sipxtapi-3.3.0~test17/0000755000175000017500000000000012321445034015374 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/build-aux/0000755000175000017500000000000012321445023017264 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/build-aux/ar-lib0000755000175000017500000001330312321250501020353 0ustar00danieldaniel00000000000000#! /bin/sh # Wrapper for Microsoft lib.exe me=ar-lib scriptversion=2012-03-01.08; # UTC # Copyright (C) 2010, 2012 Free Software Foundation, Inc. # Written by Peter Rosin . # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # This file is maintained in Automake, please report # bugs to or send patches to # . # func_error message func_error () { echo "$me: $1" 1>&2 exit 1 } file_conv= # func_file_conv build_file # Convert a $build file to $host form and store it in $file # Currently only supports Windows hosts. func_file_conv () { file=$1 case $file in / | /[!/]*) # absolute file, and not a UNC file if test -z "$file_conv"; then # lazily determine how to convert abs files case `uname -s` in MINGW*) file_conv=mingw ;; CYGWIN*) file_conv=cygwin ;; *) file_conv=wine ;; esac fi case $file_conv in mingw) file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'` ;; cygwin) file=`cygpath -m "$file" || echo "$file"` ;; wine) file=`winepath -w "$file" || echo "$file"` ;; esac ;; esac } # func_at_file at_file operation archive # Iterate over all members in AT_FILE performing OPERATION on ARCHIVE # for each of them. # When interpreting the content of the @FILE, do NOT use func_file_conv, # since the user would need to supply preconverted file names to # binutils ar, at least for MinGW. func_at_file () { operation=$2 archive=$3 at_file_contents=`cat "$1"` eval set x "$at_file_contents" shift for member do $AR -NOLOGO $operation:"$member" "$archive" || exit $? done } case $1 in '') func_error "no command. Try '$0 --help' for more information." ;; -h | --h*) cat <. # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # Originally written by Per Bothner. Please send patches (context # diff format) to and include a ChangeLog # entry. # # This script attempts to guess a canonical system name similar to # config.sub. If it succeeds, it prints the system name on stdout, and # exits with 0. Otherwise, it exits with 1. # # You can get the latest version of this script from: # http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] Output the configuration name of the system \`$me' is run on. Operation modes: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.guess ($timestamp) Originally written by Per Bothner. Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" >&2 exit 1 ;; * ) break ;; esac done if test $# != 0; then echo "$me: too many arguments$help" >&2 exit 1 fi trap 'exit 1' 1 2 15 # CC_FOR_BUILD -- compiler used by this script. Note that the use of a # compiler to aid in system detection is discouraged as it requires # temporary files to be created and, as you can see below, it is a # headache to deal with in a portable fashion. # Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still # use `HOST_CC' if defined, but it is deprecated. # Portable tmp directory creation inspired by the Autoconf team. set_cc_for_build=' trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; : ${TMPDIR=/tmp} ; { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; dummy=$tmp/dummy ; tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; case $CC_FOR_BUILD,$HOST_CC,$CC in ,,) echo "int x;" > $dummy.c ; for c in cc gcc c89 c99 ; do if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then CC_FOR_BUILD="$c"; break ; fi ; done ; if test x"$CC_FOR_BUILD" = x ; then CC_FOR_BUILD=no_compiler_found ; fi ;; ,,*) CC_FOR_BUILD=$CC ;; ,*,*) CC_FOR_BUILD=$HOST_CC ;; esac ; set_cc_for_build= ;' # This is needed to find uname on a Pyramid OSx when run in the BSD universe. # (ghazi@noc.rutgers.edu 1994-08-24) if (test -f /.attbin/uname) >/dev/null 2>&1 ; then PATH=$PATH:/.attbin ; export PATH fi UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown # Note: order is significant - the case branches are not exclusive. case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in *:NetBSD:*:*) # NetBSD (nbsd) targets should (where applicable) match one or # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*, # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently # switched to ELF, *-*-netbsd* would select the old # object file format. This provides both forward # compatibility and a consistent mechanism for selecting the # object file format. # # Note: NetBSD doesn't particularly care about the vendor # portion of the name. We always set it to "unknown". sysctl="sysctl -n hw.machine_arch" UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ /usr/sbin/$sysctl 2>/dev/null || echo unknown)` case "${UNAME_MACHINE_ARCH}" in armeb) machine=armeb-unknown ;; arm*) machine=arm-unknown ;; sh3el) machine=shl-unknown ;; sh3eb) machine=sh-unknown ;; sh5el) machine=sh5le-unknown ;; *) machine=${UNAME_MACHINE_ARCH}-unknown ;; esac # The Operating System including object format, if it has switched # to ELF recently, or will in the future. case "${UNAME_MACHINE_ARCH}" in arm*|i386|m68k|ns32k|sh3*|sparc|vax) eval $set_cc_for_build if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ELF__ then # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). # Return netbsd for either. FIX? os=netbsd else os=netbsdelf fi ;; *) os=netbsd ;; esac # The OS release # Debian GNU/NetBSD machines have a different userland, and # thus, need a distinct triplet. However, they do not need # kernel version information, so it can be replaced with a # suitable tag, in the style of linux-gnu. case "${UNAME_VERSION}" in Debian*) release='-gnu' ;; *) release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` ;; esac # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: # contains redundant information, the shorter form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. echo "${machine}-${os}${release}" exit ;; *:OpenBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} exit ;; *:ekkoBSD:*:*) echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} exit ;; *:SolidBSD:*:*) echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} exit ;; macppc:MirBSD:*:*) echo powerpc-unknown-mirbsd${UNAME_RELEASE} exit ;; *:MirBSD:*:*) echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} exit ;; alpha:OSF1:*:*) case $UNAME_RELEASE in *4.0) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` ;; *5.*) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` ;; esac # According to Compaq, /usr/sbin/psrinfo has been available on # OSF/1 and Tru64 systems produced since 1995. I hope that # covers most systems running today. This code pipes the CPU # types through head -n 1, so we only detect the type of CPU 0. ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` case "$ALPHA_CPU_TYPE" in "EV4 (21064)") UNAME_MACHINE="alpha" ;; "EV4.5 (21064)") UNAME_MACHINE="alpha" ;; "LCA4 (21066/21068)") UNAME_MACHINE="alpha" ;; "EV5 (21164)") UNAME_MACHINE="alphaev5" ;; "EV5.6 (21164A)") UNAME_MACHINE="alphaev56" ;; "EV5.6 (21164PC)") UNAME_MACHINE="alphapca56" ;; "EV5.7 (21164PC)") UNAME_MACHINE="alphapca57" ;; "EV6 (21264)") UNAME_MACHINE="alphaev6" ;; "EV6.7 (21264A)") UNAME_MACHINE="alphaev67" ;; "EV6.8CB (21264C)") UNAME_MACHINE="alphaev68" ;; "EV6.8AL (21264B)") UNAME_MACHINE="alphaev68" ;; "EV6.8CX (21264D)") UNAME_MACHINE="alphaev68" ;; "EV6.9A (21264/EV69A)") UNAME_MACHINE="alphaev69" ;; "EV7 (21364)") UNAME_MACHINE="alphaev7" ;; "EV7.9 (21364A)") UNAME_MACHINE="alphaev79" ;; esac # A Pn.n version is a patched version. # A Vn.n version is a released version. # A Tn.n version is a released field test version. # A Xn.n version is an unreleased experimental baselevel. # 1.2 uses "1.2" for uname -r. echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` # Reset EXIT trap before exiting to avoid spurious non-zero exit code. exitcode=$? trap '' 0 exit $exitcode ;; Alpha\ *:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # Should we change UNAME_MACHINE based on the output of uname instead # of the specific Alpha model? echo alpha-pc-interix exit ;; 21064:Windows_NT:50:3) echo alpha-dec-winnt3.5 exit ;; Amiga*:UNIX_System_V:4.0:*) echo m68k-unknown-sysv4 exit ;; *:[Aa]miga[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-amigaos exit ;; *:[Mm]orph[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-morphos exit ;; *:OS/390:*:*) echo i370-ibm-openedition exit ;; *:z/VM:*:*) echo s390-ibm-zvmoe exit ;; *:OS400:*:*) echo powerpc-ibm-os400 exit ;; arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) echo arm-acorn-riscix${UNAME_RELEASE} exit ;; arm:riscos:*:*|arm:RISCOS:*:*) echo arm-unknown-riscos exit ;; SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) echo hppa1.1-hitachi-hiuxmpp exit ;; Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. if test "`(/bin/universe) 2>/dev/null`" = att ; then echo pyramid-pyramid-sysv3 else echo pyramid-pyramid-bsd fi exit ;; NILE*:*:*:dcosx) echo pyramid-pyramid-svr4 exit ;; DRS?6000:unix:4.0:6*) echo sparc-icl-nx6 exit ;; DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) case `/usr/bin/uname -p` in sparc) echo sparc-icl-nx7; exit ;; esac ;; s390x:SunOS:*:*) echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4H:SunOS:5.*:*) echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) echo i386-pc-auroraux${UNAME_RELEASE} exit ;; i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) eval $set_cc_for_build SUN_ARCH="i386" # If there is a compiler, see if it is configured for 64-bit objects. # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. # This test works for both compilers. if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then SUN_ARCH="x86_64" fi fi echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:6*:*) # According to config.sub, this is the proper way to canonicalize # SunOS6. Hard to guess exactly what SunOS6 will be like, but # it's likely to be more like Solaris than SunOS4. echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:*:*) case "`/usr/bin/arch -k`" in Series*|S4*) UNAME_RELEASE=`uname -v` ;; esac # Japanese Language versions have a version number like `4.1.3-JL'. echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` exit ;; sun3*:SunOS:*:*) echo m68k-sun-sunos${UNAME_RELEASE} exit ;; sun*:*:4.2BSD:*) UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 case "`/bin/arch`" in sun3) echo m68k-sun-sunos${UNAME_RELEASE} ;; sun4) echo sparc-sun-sunos${UNAME_RELEASE} ;; esac exit ;; aushp:SunOS:*:*) echo sparc-auspex-sunos${UNAME_RELEASE} exit ;; # The situation for MiNT is a little confusing. The machine name # can be virtually everything (everything which is not # "atarist" or "atariste" at least should have a processor # > m68000). The system name ranges from "MiNT" over "FreeMiNT" # to the lowercase version "mint" (or "freemint"). Finally # the system name "TOS" denotes a system which is actually not # MiNT. But MiNT is downward compatible to TOS, so this should # be no problem. atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) echo m68k-milan-mint${UNAME_RELEASE} exit ;; hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) echo m68k-hades-mint${UNAME_RELEASE} exit ;; *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) echo m68k-unknown-mint${UNAME_RELEASE} exit ;; m68k:machten:*:*) echo m68k-apple-machten${UNAME_RELEASE} exit ;; powerpc:machten:*:*) echo powerpc-apple-machten${UNAME_RELEASE} exit ;; RISC*:Mach:*:*) echo mips-dec-mach_bsd4.3 exit ;; RISC*:ULTRIX:*:*) echo mips-dec-ultrix${UNAME_RELEASE} exit ;; VAX*:ULTRIX*:*:*) echo vax-dec-ultrix${UNAME_RELEASE} exit ;; 2020:CLIX:*:* | 2430:CLIX:*:*) echo clipper-intergraph-clix${UNAME_RELEASE} exit ;; mips:*:*:UMIPS | mips:*:*:RISCos) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #ifdef __cplusplus #include /* for printf() prototype */ int main (int argc, char *argv[]) { #else int main (argc, argv) int argc; char *argv[]; { #endif #if defined (host_mips) && defined (MIPSEB) #if defined (SYSTYPE_SYSV) printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_SVR4) printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); #endif #endif exit (-1); } EOF $CC_FOR_BUILD -o $dummy $dummy.c && dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && SYSTEM_NAME=`$dummy $dummyarg` && { echo "$SYSTEM_NAME"; exit; } echo mips-mips-riscos${UNAME_RELEASE} exit ;; Motorola:PowerMAX_OS:*:*) echo powerpc-motorola-powermax exit ;; Motorola:*:4.3:PL8-*) echo powerpc-harris-powermax exit ;; Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) echo powerpc-harris-powermax exit ;; Night_Hawk:Power_UNIX:*:*) echo powerpc-harris-powerunix exit ;; m88k:CX/UX:7*:*) echo m88k-harris-cxux7 exit ;; m88k:*:4*:R4*) echo m88k-motorola-sysv4 exit ;; m88k:*:3*:R3*) echo m88k-motorola-sysv3 exit ;; AViiON:dgux:*:*) # DG/UX returns AViiON for all architectures UNAME_PROCESSOR=`/usr/bin/uname -p` if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] then if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ [ ${TARGET_BINARY_INTERFACE}x = x ] then echo m88k-dg-dgux${UNAME_RELEASE} else echo m88k-dg-dguxbcs${UNAME_RELEASE} fi else echo i586-dg-dgux${UNAME_RELEASE} fi exit ;; M88*:DolphinOS:*:*) # DolphinOS (SVR3) echo m88k-dolphin-sysv3 exit ;; M88*:*:R3*:*) # Delta 88k system running SVR3 echo m88k-motorola-sysv3 exit ;; XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) echo m88k-tektronix-sysv3 exit ;; Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) echo m68k-tektronix-bsd exit ;; *:IRIX*:*:*) echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` exit ;; ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' i*86:AIX:*:*) echo i386-ibm-aix exit ;; ia64:AIX:*:*) if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} exit ;; *:AIX:2:3) if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include main() { if (!__power_pc()) exit(1); puts("powerpc-ibm-aix3.2.5"); exit(0); } EOF if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` then echo "$SYSTEM_NAME" else echo rs6000-ibm-aix3.2.5 fi elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then echo rs6000-ibm-aix3.2.4 else echo rs6000-ibm-aix3.2 fi exit ;; *:AIX:*:[4567]) IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then IBM_ARCH=rs6000 else IBM_ARCH=powerpc fi if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${IBM_ARCH}-ibm-aix${IBM_REV} exit ;; *:AIX:*:*) echo rs6000-ibm-aix exit ;; ibmrt:4.4BSD:*|romp-ibm:BSD:*) echo romp-ibm-bsd4.4 exit ;; ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to exit ;; # report: romp-ibm BSD 4.3 *:BOSX:*:*) echo rs6000-bull-bosx exit ;; DPX/2?00:B.O.S.:*:*) echo m68k-bull-sysv3 exit ;; 9000/[34]??:4.3bsd:1.*:*) echo m68k-hp-bsd exit ;; hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) echo m68k-hp-bsd4.4 exit ;; 9000/[34678]??:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` case "${UNAME_MACHINE}" in 9000/31? ) HP_ARCH=m68000 ;; 9000/[34]?? ) HP_ARCH=m68k ;; 9000/[678][0-9][0-9]) if [ -x /usr/bin/getconf ]; then sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` case "${sc_cpu_version}" in 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 532) # CPU_PA_RISC2_0 case "${sc_kernel_bits}" in 32) HP_ARCH="hppa2.0n" ;; 64) HP_ARCH="hppa2.0w" ;; '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 esac ;; esac fi if [ "${HP_ARCH}" = "" ]; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #define _HPUX_SOURCE #include #include int main () { #if defined(_SC_KERNEL_BITS) long bits = sysconf(_SC_KERNEL_BITS); #endif long cpu = sysconf (_SC_CPU_VERSION); switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0"); break; case CPU_PA_RISC1_1: puts ("hppa1.1"); break; case CPU_PA_RISC2_0: #if defined(_SC_KERNEL_BITS) switch (bits) { case 64: puts ("hppa2.0w"); break; case 32: puts ("hppa2.0n"); break; default: puts ("hppa2.0"); break; } break; #else /* !defined(_SC_KERNEL_BITS) */ puts ("hppa2.0"); break; #endif default: puts ("hppa1.0"); break; } exit (0); } EOF (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` test -z "$HP_ARCH" && HP_ARCH=hppa fi ;; esac if [ ${HP_ARCH} = "hppa2.0w" ] then eval $set_cc_for_build # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler # generating 64-bit code. GNU and HP use different nomenclature: # # $ CC_FOR_BUILD=cc ./config.guess # => hppa2.0w-hp-hpux11.23 # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess # => hppa64-hp-hpux11.23 if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | grep -q __LP64__ then HP_ARCH="hppa2.0w" else HP_ARCH="hppa64" fi fi echo ${HP_ARCH}-hp-hpux${HPUX_REV} exit ;; ia64:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` echo ia64-hp-hpux${HPUX_REV} exit ;; 3050*:HI-UX:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include int main () { long cpu = sysconf (_SC_CPU_VERSION); /* The order matters, because CPU_IS_HP_MC68K erroneously returns true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct results, however. */ if (CPU_IS_PA_RISC (cpu)) { switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; default: puts ("hppa-hitachi-hiuxwe2"); break; } } else if (CPU_IS_HP_MC68K (cpu)) puts ("m68k-hitachi-hiuxwe2"); else puts ("unknown-hitachi-hiuxwe2"); exit (0); } EOF $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && { echo "$SYSTEM_NAME"; exit; } echo unknown-hitachi-hiuxwe2 exit ;; 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) echo hppa1.1-hp-bsd exit ;; 9000/8??:4.3bsd:*:*) echo hppa1.0-hp-bsd exit ;; *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) echo hppa1.0-hp-mpeix exit ;; hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) echo hppa1.1-hp-osf exit ;; hp8??:OSF1:*:*) echo hppa1.0-hp-osf exit ;; i*86:OSF1:*:*) if [ -x /usr/sbin/sysversion ] ; then echo ${UNAME_MACHINE}-unknown-osf1mk else echo ${UNAME_MACHINE}-unknown-osf1 fi exit ;; parisc*:Lites*:*:*) echo hppa1.1-hp-lites exit ;; C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) echo c1-convex-bsd exit ;; C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit ;; C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) echo c34-convex-bsd exit ;; C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) echo c38-convex-bsd exit ;; C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) echo c4-convex-bsd exit ;; CRAY*Y-MP:*:*:*) echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*[A-Z]90:*:*:*) echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ -e 's/\.[^.]*$/.X/' exit ;; CRAY*TS:*:*:*) echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*T3E:*:*:*) echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*SV1:*:*:*) echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; *:UNICOS/mp:*:*) echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; 5000:UNIX_System_V:4.*:*) FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} exit ;; sparc*:BSD/OS:*:*) echo sparc-unknown-bsdi${UNAME_RELEASE} exit ;; *:BSD/OS:*:*) echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} exit ;; *:FreeBSD:*:*) UNAME_PROCESSOR=`/usr/bin/uname -p` case ${UNAME_PROCESSOR} in amd64) echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; *) echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; esac exit ;; i*:CYGWIN*:*) echo ${UNAME_MACHINE}-pc-cygwin exit ;; *:MINGW*:*) echo ${UNAME_MACHINE}-pc-mingw32 exit ;; i*:MSYS*:*) echo ${UNAME_MACHINE}-pc-msys exit ;; i*:windows32*:*) # uname -m includes "-pc" on this system. echo ${UNAME_MACHINE}-mingw32 exit ;; i*:PW*:*) echo ${UNAME_MACHINE}-pc-pw32 exit ;; *:Interix*:*) case ${UNAME_MACHINE} in x86) echo i586-pc-interix${UNAME_RELEASE} exit ;; authenticamd | genuineintel | EM64T) echo x86_64-unknown-interix${UNAME_RELEASE} exit ;; IA64) echo ia64-unknown-interix${UNAME_RELEASE} exit ;; esac ;; [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) echo i${UNAME_MACHINE}-pc-mks exit ;; 8664:Windows_NT:*) echo x86_64-pc-mks exit ;; i*:Windows_NT*:* | Pentium*:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we # UNAME_MACHINE based on the output of uname instead of i386? echo i586-pc-interix exit ;; i*:UWIN*:*) echo ${UNAME_MACHINE}-pc-uwin exit ;; amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) echo x86_64-unknown-cygwin exit ;; p*:CYGWIN*:*) echo powerpcle-unknown-cygwin exit ;; prep*:SunOS:5.*:*) echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; *:GNU:*:*) # the GNU system echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` exit ;; *:GNU/*:*:*) # other systems with GNU libc and userland echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu exit ;; i*86:Minix:*:*) echo ${UNAME_MACHINE}-pc-minix exit ;; aarch64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; aarch64_be:Linux:*:*) UNAME_MACHINE=aarch64_be echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; alpha:Linux:*:*) case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in EV5) UNAME_MACHINE=alphaev5 ;; EV56) UNAME_MACHINE=alphaev56 ;; PCA56) UNAME_MACHINE=alphapca56 ;; PCA57) UNAME_MACHINE=alphapca56 ;; EV6) UNAME_MACHINE=alphaev6 ;; EV67) UNAME_MACHINE=alphaev67 ;; EV68*) UNAME_MACHINE=alphaev68 ;; esac objdump --private-headers /bin/sh | grep -q ld.so.1 if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} exit ;; arm*:Linux:*:*) eval $set_cc_for_build if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_EABI__ then echo ${UNAME_MACHINE}-unknown-linux-gnu else if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_PCS_VFP then echo ${UNAME_MACHINE}-unknown-linux-gnueabi else echo ${UNAME_MACHINE}-unknown-linux-gnueabihf fi fi exit ;; avr32*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; cris:Linux:*:*) echo ${UNAME_MACHINE}-axis-linux-gnu exit ;; crisv32:Linux:*:*) echo ${UNAME_MACHINE}-axis-linux-gnu exit ;; frv:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; hexagon:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; i*86:Linux:*:*) LIBC=gnu eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #ifdef __dietlibc__ LIBC=dietlibc #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'` echo "${UNAME_MACHINE}-pc-linux-${LIBC}" exit ;; ia64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; m32r*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; m68*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; mips:Linux:*:* | mips64:Linux:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #undef CPU #undef ${UNAME_MACHINE} #undef ${UNAME_MACHINE}el #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) CPU=${UNAME_MACHINE}el #else #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) CPU=${UNAME_MACHINE} #else CPU= #endif #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'` test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } ;; or32:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; padre:Linux:*:*) echo sparc-unknown-linux-gnu exit ;; parisc64:Linux:*:* | hppa64:Linux:*:*) echo hppa64-unknown-linux-gnu exit ;; parisc:Linux:*:* | hppa:Linux:*:*) # Look for CPU level case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in PA7*) echo hppa1.1-unknown-linux-gnu ;; PA8*) echo hppa2.0-unknown-linux-gnu ;; *) echo hppa-unknown-linux-gnu ;; esac exit ;; ppc64:Linux:*:*) echo powerpc64-unknown-linux-gnu exit ;; ppc:Linux:*:*) echo powerpc-unknown-linux-gnu exit ;; s390:Linux:*:* | s390x:Linux:*:*) echo ${UNAME_MACHINE}-ibm-linux exit ;; sh64*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; sh*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; sparc:Linux:*:* | sparc64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; tile*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; vax:Linux:*:*) echo ${UNAME_MACHINE}-dec-linux-gnu exit ;; x86_64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; xtensa*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit ;; i*86:DYNIX/ptx:4*:*) # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. # earlier versions are messed up and put the nodename in both # sysname and nodename. echo i386-sequent-sysv4 exit ;; i*86:UNIX_SV:4.2MP:2.*) # Unixware is an offshoot of SVR4, but it has its own version # number series starting with 2... # I am not positive that other SVR4 systems won't match this, # I just have to hope. -- rms. # Use sysv4.2uw... so that sysv4* matches it. echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} exit ;; i*86:OS/2:*:*) # If we were able to find `uname', then EMX Unix compatibility # is probably installed. echo ${UNAME_MACHINE}-pc-os2-emx exit ;; i*86:XTS-300:*:STOP) echo ${UNAME_MACHINE}-unknown-stop exit ;; i*86:atheos:*:*) echo ${UNAME_MACHINE}-unknown-atheos exit ;; i*86:syllable:*:*) echo ${UNAME_MACHINE}-pc-syllable exit ;; i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) echo i386-unknown-lynxos${UNAME_RELEASE} exit ;; i*86:*DOS:*:*) echo ${UNAME_MACHINE}-pc-msdosdjgpp exit ;; i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} else echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} fi exit ;; i*86:*:5:[678]*) # UnixWare 7.x, OpenUNIX and OpenServer 6. case `/bin/uname -X | grep "^Machine"` in *486*) UNAME_MACHINE=i486 ;; *Pentium) UNAME_MACHINE=i586 ;; *Pent*|*Celeron) UNAME_MACHINE=i686 ;; esac echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} exit ;; i*86:*:3.2:*) if test -f /usr/options/cb.name; then UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ && UNAME_MACHINE=i586 (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ && UNAME_MACHINE=i686 (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ && UNAME_MACHINE=i686 echo ${UNAME_MACHINE}-pc-sco$UNAME_REL else echo ${UNAME_MACHINE}-pc-sysv32 fi exit ;; pc:*:*:*) # Left here for compatibility: # uname -m prints for DJGPP always 'pc', but it prints nothing about # the processor, so we play safe by assuming i586. # Note: whatever this is, it MUST be the same as what config.sub # prints for the "djgpp" host, or else GDB configury will decide that # this is a cross-build. echo i586-pc-msdosdjgpp exit ;; Intel:Mach:3*:*) echo i386-pc-mach3 exit ;; paragon:*:*:*) echo i860-intel-osf1 exit ;; i860:*:4.*:*) # i860-SVR4 if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 else # Add other i860-SVR4 vendors below as they are discovered. echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 fi exit ;; mini*:CTIX:SYS*5:*) # "miniframe" echo m68010-convergent-sysv exit ;; mc68k:UNIX:SYSTEM5:3.51m) echo m68k-convergent-sysv exit ;; M680?0:D-NIX:5.3:*) echo m68k-diab-dnix exit ;; M68*:*:R3V[5678]*:*) test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) OS_REL='' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4; exit; } ;; NCR*:*:4.2:* | MPRAS*:*:4.2:*) OS_REL='.3' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) echo m68k-unknown-lynxos${UNAME_RELEASE} exit ;; mc68030:UNIX_System_V:4.*:*) echo m68k-atari-sysv4 exit ;; TSUNAMI:LynxOS:2.*:*) echo sparc-unknown-lynxos${UNAME_RELEASE} exit ;; rs6000:LynxOS:2.*:*) echo rs6000-unknown-lynxos${UNAME_RELEASE} exit ;; PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) echo powerpc-unknown-lynxos${UNAME_RELEASE} exit ;; SM[BE]S:UNIX_SV:*:*) echo mips-dde-sysv${UNAME_RELEASE} exit ;; RM*:ReliantUNIX-*:*:*) echo mips-sni-sysv4 exit ;; RM*:SINIX-*:*:*) echo mips-sni-sysv4 exit ;; *:SINIX-*:*:*) if uname -p 2>/dev/null >/dev/null ; then UNAME_MACHINE=`(uname -p) 2>/dev/null` echo ${UNAME_MACHINE}-sni-sysv4 else echo ns32k-sni-sysv fi exit ;; PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort # says echo i586-unisys-sysv4 exit ;; *:UNIX_System_V:4*:FTX*) # From Gerald Hewes . # How about differentiating between stratus architectures? -djm echo hppa1.1-stratus-sysv4 exit ;; *:*:*:FTX*) # From seanf@swdc.stratus.com. echo i860-stratus-sysv4 exit ;; i*86:VOS:*:*) # From Paul.Green@stratus.com. echo ${UNAME_MACHINE}-stratus-vos exit ;; *:VOS:*:*) # From Paul.Green@stratus.com. echo hppa1.1-stratus-vos exit ;; mc68*:A/UX:*:*) echo m68k-apple-aux${UNAME_RELEASE} exit ;; news*:NEWS-OS:6*:*) echo mips-sony-newsos6 exit ;; R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) if [ -d /usr/nec ]; then echo mips-nec-sysv${UNAME_RELEASE} else echo mips-unknown-sysv${UNAME_RELEASE} fi exit ;; BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. echo powerpc-be-beos exit ;; BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. echo powerpc-apple-beos exit ;; BePC:BeOS:*:*) # BeOS running on Intel PC compatible. echo i586-pc-beos exit ;; BePC:Haiku:*:*) # Haiku running on Intel PC compatible. echo i586-pc-haiku exit ;; SX-4:SUPER-UX:*:*) echo sx4-nec-superux${UNAME_RELEASE} exit ;; SX-5:SUPER-UX:*:*) echo sx5-nec-superux${UNAME_RELEASE} exit ;; SX-6:SUPER-UX:*:*) echo sx6-nec-superux${UNAME_RELEASE} exit ;; SX-7:SUPER-UX:*:*) echo sx7-nec-superux${UNAME_RELEASE} exit ;; SX-8:SUPER-UX:*:*) echo sx8-nec-superux${UNAME_RELEASE} exit ;; SX-8R:SUPER-UX:*:*) echo sx8r-nec-superux${UNAME_RELEASE} exit ;; Power*:Rhapsody:*:*) echo powerpc-apple-rhapsody${UNAME_RELEASE} exit ;; *:Rhapsody:*:*) echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} exit ;; *:Darwin:*:*) UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown case $UNAME_PROCESSOR in i386) eval $set_cc_for_build if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then UNAME_PROCESSOR="x86_64" fi fi ;; unknown) UNAME_PROCESSOR=powerpc ;; esac echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} exit ;; *:procnto*:*:* | *:QNX:[0123456789]*:*) UNAME_PROCESSOR=`uname -p` if test "$UNAME_PROCESSOR" = "x86"; then UNAME_PROCESSOR=i386 UNAME_MACHINE=pc fi echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} exit ;; *:QNX:*:4*) echo i386-pc-qnx exit ;; NEO-?:NONSTOP_KERNEL:*:*) echo neo-tandem-nsk${UNAME_RELEASE} exit ;; NSE-?:NONSTOP_KERNEL:*:*) echo nse-tandem-nsk${UNAME_RELEASE} exit ;; NSR-?:NONSTOP_KERNEL:*:*) echo nsr-tandem-nsk${UNAME_RELEASE} exit ;; *:NonStop-UX:*:*) echo mips-compaq-nonstopux exit ;; BS2000:POSIX*:*:*) echo bs2000-siemens-sysv exit ;; DS/*:UNIX_System_V:*:*) echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} exit ;; *:Plan9:*:*) # "uname -m" is not consistent, so use $cputype instead. 386 # is converted to i386 for consistency with other x86 # operating systems. if test "$cputype" = "386"; then UNAME_MACHINE=i386 else UNAME_MACHINE="$cputype" fi echo ${UNAME_MACHINE}-unknown-plan9 exit ;; *:TOPS-10:*:*) echo pdp10-unknown-tops10 exit ;; *:TENEX:*:*) echo pdp10-unknown-tenex exit ;; KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) echo pdp10-dec-tops20 exit ;; XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) echo pdp10-xkl-tops20 exit ;; *:TOPS-20:*:*) echo pdp10-unknown-tops20 exit ;; *:ITS:*:*) echo pdp10-unknown-its exit ;; SEI:*:*:SEIUX) echo mips-sei-seiux${UNAME_RELEASE} exit ;; *:DragonFly:*:*) echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` exit ;; *:*VMS:*:*) UNAME_MACHINE=`(uname -p) 2>/dev/null` case "${UNAME_MACHINE}" in A*) echo alpha-dec-vms ; exit ;; I*) echo ia64-dec-vms ; exit ;; V*) echo vax-dec-vms ; exit ;; esac ;; *:XENIX:*:SysV) echo i386-pc-xenix exit ;; i*86:skyos:*:*) echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' exit ;; i*86:rdos:*:*) echo ${UNAME_MACHINE}-pc-rdos exit ;; i*86:AROS:*:*) echo ${UNAME_MACHINE}-pc-aros exit ;; x86_64:VMkernel:*:*) echo ${UNAME_MACHINE}-unknown-esx exit ;; esac #echo '(No uname command or uname output not recognized.)' 1>&2 #echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2 eval $set_cc_for_build cat >$dummy.c < # include #endif main () { #if defined (sony) #if defined (MIPSEB) /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, I don't know.... */ printf ("mips-sony-bsd\n"); exit (0); #else #include printf ("m68k-sony-newsos%s\n", #ifdef NEWSOS4 "4" #else "" #endif ); exit (0); #endif #endif #if defined (__arm) && defined (__acorn) && defined (__unix) printf ("arm-acorn-riscix\n"); exit (0); #endif #if defined (hp300) && !defined (hpux) printf ("m68k-hp-bsd\n"); exit (0); #endif #if defined (NeXT) #if !defined (__ARCHITECTURE__) #define __ARCHITECTURE__ "m68k" #endif int version; version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; if (version < 4) printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); else printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); exit (0); #endif #if defined (MULTIMAX) || defined (n16) #if defined (UMAXV) printf ("ns32k-encore-sysv\n"); exit (0); #else #if defined (CMU) printf ("ns32k-encore-mach\n"); exit (0); #else printf ("ns32k-encore-bsd\n"); exit (0); #endif #endif #endif #if defined (__386BSD__) printf ("i386-pc-bsd\n"); exit (0); #endif #if defined (sequent) #if defined (i386) printf ("i386-sequent-dynix\n"); exit (0); #endif #if defined (ns32000) printf ("ns32k-sequent-dynix\n"); exit (0); #endif #endif #if defined (_SEQUENT_) struct utsname un; uname(&un); if (strncmp(un.version, "V2", 2) == 0) { printf ("i386-sequent-ptx2\n"); exit (0); } if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ printf ("i386-sequent-ptx1\n"); exit (0); } printf ("i386-sequent-ptx\n"); exit (0); #endif #if defined (vax) # if !defined (ultrix) # include # if defined (BSD) # if BSD == 43 printf ("vax-dec-bsd4.3\n"); exit (0); # else # if BSD == 199006 printf ("vax-dec-bsd4.3reno\n"); exit (0); # else printf ("vax-dec-bsd\n"); exit (0); # endif # endif # else printf ("vax-dec-bsd\n"); exit (0); # endif # else printf ("vax-dec-ultrix\n"); exit (0); # endif #endif #if defined (alliant) && defined (i860) printf ("i860-alliant-bsd\n"); exit (0); #endif exit (1); } EOF $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` && { echo "$SYSTEM_NAME"; exit; } # Apollos put the system type in the environment. test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; } # Convex versions that predate uname can use getsysinfo(1) if [ -x /usr/convex/getsysinfo ] then case `getsysinfo -f cpu_type` in c1*) echo c1-convex-bsd exit ;; c2*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit ;; c34*) echo c34-convex-bsd exit ;; c38*) echo c38-convex-bsd exit ;; c4*) echo c4-convex-bsd exit ;; esac fi cat >&2 < in order to provide the needed information to handle your system. config.guess timestamp = $timestamp uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` /bin/uname -X = `(/bin/uname -X) 2>/dev/null` hostinfo = `(hostinfo) 2>/dev/null` /bin/universe = `(/bin/universe) 2>/dev/null` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` /bin/arch = `(/bin/arch) 2>/dev/null` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` UNAME_MACHINE = ${UNAME_MACHINE} UNAME_RELEASE = ${UNAME_RELEASE} UNAME_SYSTEM = ${UNAME_SYSTEM} UNAME_VERSION = ${UNAME_VERSION} EOF exit 1 # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: sipxtapi-3.3.0~test17/build-aux/config.sub0000755000175000017500000010532712321250501021252 0ustar00danieldaniel00000000000000#! /bin/sh # Configuration validation subroutine script. # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, # 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, # 2011, 2012 Free Software Foundation, Inc. timestamp='2012-04-18' # This file is (in principle) common to ALL GNU software. # The presence of a machine in this file suggests that SOME GNU software # can handle that machine. It does not imply ALL GNU software can. # # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # Please send patches to . Submit a context # diff and a properly formatted GNU ChangeLog entry. # # Configuration subroutine to validate and canonicalize a configuration type. # Supply the specified configuration type as an argument. # If it is invalid, we print an error message on stderr and exit with code 1. # Otherwise, we print the canonical config type on stdout and succeed. # You can get the latest version of this script from: # http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD # This file is supposed to be the same for all GNU packages # and recognize all the CPU types, system types and aliases # that are meaningful with *any* GNU software. # Each package is responsible for reporting which valid configurations # it does not support. The user should be able to distinguish # a failure to support a valid configuration from a meaningless # configuration. # The goal of this file is to map all the various variations of a given # machine specification into a single specification in the form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM # or in some cases, the newer four-part form: # CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM # It is wrong to echo any other type of specification. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] CPU-MFR-OPSYS $0 [OPTION] ALIAS Canonicalize a configuration name. Operation modes: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.sub ($timestamp) Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" exit 1 ;; *local*) # First pass through any local machine types. echo $1 exit ;; * ) break ;; esac done case $# in 0) echo "$me: missing argument$help" >&2 exit 1;; 1) ;; *) echo "$me: too many arguments$help" >&2 exit 1;; esac # Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). # Here we must recognize all the valid KERNEL-OS combinations. maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` case $maybe_os in nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \ linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \ knetbsd*-gnu* | netbsd*-gnu* | \ kopensolaris*-gnu* | \ storm-chaos* | os2-emx* | rtmk-nova*) os=-$maybe_os basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` ;; android-linux) os=-linux-android basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown ;; *) basic_machine=`echo $1 | sed 's/-[^-]*$//'` if [ $basic_machine != $1 ] then os=`echo $1 | sed 's/.*-/-/'` else os=; fi ;; esac ### Let's recognize common machines as not being operating systems so ### that things like config.sub decstation-3100 work. We also ### recognize some manufacturers as not being operating systems, so we ### can provide default operating systems below. case $os in -sun*os*) # Prevent following clause from handling this invalid input. ;; -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ -apple | -axis | -knuth | -cray | -microblaze) os= basic_machine=$1 ;; -bluegene*) os=-cnk ;; -sim | -cisco | -oki | -wec | -winbond) os= basic_machine=$1 ;; -scout) ;; -wrs) os=-vxworks basic_machine=$1 ;; -chorusos*) os=-chorusos basic_machine=$1 ;; -chorusrdb) os=-chorusrdb basic_machine=$1 ;; -hiux*) os=-hiuxwe2 ;; -sco6) os=-sco5v6 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco5) os=-sco3.2v5 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco4) os=-sco3.2v4 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco3.2.[4-9]*) os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco3.2v[4-9]*) # Don't forget version if it is 3.2v4 or newer. basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco5v6*) # Don't forget version if it is 3.2v4 or newer. basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco*) os=-sco3.2v2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -udk*) basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -isc) os=-isc2.2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -clix*) basic_machine=clipper-intergraph ;; -isc*) basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -lynx*178) os=-lynxos178 ;; -lynx*5) os=-lynxos5 ;; -lynx*) os=-lynxos ;; -ptx*) basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` ;; -windowsnt*) os=`echo $os | sed -e 's/windowsnt/winnt/'` ;; -psos*) os=-psos ;; -mint | -mint[0-9]*) basic_machine=m68k-atari os=-mint ;; esac # Decode aliases for certain CPU-COMPANY combinations. case $basic_machine in # Recognize the basic CPU types without company name. # Some are omitted here because they have special meanings below. 1750a | 580 \ | a29k \ | aarch64 | aarch64_be \ | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ | am33_2.0 \ | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \ | be32 | be64 \ | bfin \ | c4x | clipper \ | d10v | d30v | dlx | dsp16xx \ | epiphany \ | fido | fr30 | frv \ | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ | hexagon \ | i370 | i860 | i960 | ia64 \ | ip2k | iq2000 \ | le32 | le64 \ | lm32 \ | m32c | m32r | m32rle | m68000 | m68k | m88k \ | maxq | mb | microblaze | mcore | mep | metag \ | mips | mipsbe | mipseb | mipsel | mipsle \ | mips16 \ | mips64 | mips64el \ | mips64octeon | mips64octeonel \ | mips64orion | mips64orionel \ | mips64r5900 | mips64r5900el \ | mips64vr | mips64vrel \ | mips64vr4100 | mips64vr4100el \ | mips64vr4300 | mips64vr4300el \ | mips64vr5000 | mips64vr5000el \ | mips64vr5900 | mips64vr5900el \ | mipsisa32 | mipsisa32el \ | mipsisa32r2 | mipsisa32r2el \ | mipsisa64 | mipsisa64el \ | mipsisa64r2 | mipsisa64r2el \ | mipsisa64sb1 | mipsisa64sb1el \ | mipsisa64sr71k | mipsisa64sr71kel \ | mipstx39 | mipstx39el \ | mn10200 | mn10300 \ | moxie \ | mt \ | msp430 \ | nds32 | nds32le | nds32be \ | nios | nios2 \ | ns16k | ns32k \ | open8 \ | or32 \ | pdp10 | pdp11 | pj | pjl \ | powerpc | powerpc64 | powerpc64le | powerpcle \ | pyramid \ | rl78 | rx \ | score \ | sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \ | sh64 | sh64le \ | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \ | sparcv8 | sparcv9 | sparcv9b | sparcv9v \ | spu \ | tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \ | ubicom32 \ | v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \ | we32k \ | x86 | xc16x | xstormy16 | xtensa \ | z8k | z80) basic_machine=$basic_machine-unknown ;; c54x) basic_machine=tic54x-unknown ;; c55x) basic_machine=tic55x-unknown ;; c6x) basic_machine=tic6x-unknown ;; m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | picochip) basic_machine=$basic_machine-unknown os=-none ;; m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) ;; ms1) basic_machine=mt-unknown ;; strongarm | thumb | xscale) basic_machine=arm-unknown ;; xgate) basic_machine=$basic_machine-unknown os=-none ;; xscaleeb) basic_machine=armeb-unknown ;; xscaleel) basic_machine=armel-unknown ;; # We use `pc' rather than `unknown' # because (1) that's what they normally are, and # (2) the word "unknown" tends to confuse beginning users. i*86 | x86_64) basic_machine=$basic_machine-pc ;; # Object if more than one company name word. *-*-*) echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 exit 1 ;; # Recognize the basic CPU types with company name. 580-* \ | a29k-* \ | aarch64-* | aarch64_be-* \ | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \ | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ | avr-* | avr32-* \ | be32-* | be64-* \ | bfin-* | bs2000-* \ | c[123]* | c30-* | [cjt]90-* | c4x-* \ | clipper-* | craynv-* | cydra-* \ | d10v-* | d30v-* | dlx-* \ | elxsi-* \ | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \ | h8300-* | h8500-* \ | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ | hexagon-* \ | i*86-* | i860-* | i960-* | ia64-* \ | ip2k-* | iq2000-* \ | le32-* | le64-* \ | lm32-* \ | m32c-* | m32r-* | m32rle-* \ | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ | m88110-* | m88k-* | maxq-* | mcore-* | metag-* | microblaze-* \ | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ | mips16-* \ | mips64-* | mips64el-* \ | mips64octeon-* | mips64octeonel-* \ | mips64orion-* | mips64orionel-* \ | mips64r5900-* | mips64r5900el-* \ | mips64vr-* | mips64vrel-* \ | mips64vr4100-* | mips64vr4100el-* \ | mips64vr4300-* | mips64vr4300el-* \ | mips64vr5000-* | mips64vr5000el-* \ | mips64vr5900-* | mips64vr5900el-* \ | mipsisa32-* | mipsisa32el-* \ | mipsisa32r2-* | mipsisa32r2el-* \ | mipsisa64-* | mipsisa64el-* \ | mipsisa64r2-* | mipsisa64r2el-* \ | mipsisa64sb1-* | mipsisa64sb1el-* \ | mipsisa64sr71k-* | mipsisa64sr71kel-* \ | mipstx39-* | mipstx39el-* \ | mmix-* \ | mt-* \ | msp430-* \ | nds32-* | nds32le-* | nds32be-* \ | nios-* | nios2-* \ | none-* | np1-* | ns16k-* | ns32k-* \ | open8-* \ | orion-* \ | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \ | pyramid-* \ | rl78-* | romp-* | rs6000-* | rx-* \ | sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \ | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \ | sparclite-* \ | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \ | tahoe-* \ | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ | tile*-* \ | tron-* \ | ubicom32-* \ | v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \ | vax-* \ | we32k-* \ | x86-* | x86_64-* | xc16x-* | xps100-* \ | xstormy16-* | xtensa*-* \ | ymp-* \ | z8k-* | z80-*) ;; # Recognize the basic CPU types without company name, with glob match. xtensa*) basic_machine=$basic_machine-unknown ;; # Recognize the various machine names and aliases which stand # for a CPU type and a company and sometimes even an OS. 386bsd) basic_machine=i386-unknown os=-bsd ;; 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) basic_machine=m68000-att ;; 3b*) basic_machine=we32k-att ;; a29khif) basic_machine=a29k-amd os=-udi ;; abacus) basic_machine=abacus-unknown ;; adobe68k) basic_machine=m68010-adobe os=-scout ;; alliant | fx80) basic_machine=fx80-alliant ;; altos | altos3068) basic_machine=m68k-altos ;; am29k) basic_machine=a29k-none os=-bsd ;; amd64) basic_machine=x86_64-pc ;; amd64-*) basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` ;; amdahl) basic_machine=580-amdahl os=-sysv ;; amiga | amiga-*) basic_machine=m68k-unknown ;; amigaos | amigados) basic_machine=m68k-unknown os=-amigaos ;; amigaunix | amix) basic_machine=m68k-unknown os=-sysv4 ;; apollo68) basic_machine=m68k-apollo os=-sysv ;; apollo68bsd) basic_machine=m68k-apollo os=-bsd ;; aros) basic_machine=i386-pc os=-aros ;; aux) basic_machine=m68k-apple os=-aux ;; balance) basic_machine=ns32k-sequent os=-dynix ;; blackfin) basic_machine=bfin-unknown os=-linux ;; blackfin-*) basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; bluegene*) basic_machine=powerpc-ibm os=-cnk ;; c54x-*) basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c55x-*) basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c6x-*) basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c90) basic_machine=c90-cray os=-unicos ;; cegcc) basic_machine=arm-unknown os=-cegcc ;; convex-c1) basic_machine=c1-convex os=-bsd ;; convex-c2) basic_machine=c2-convex os=-bsd ;; convex-c32) basic_machine=c32-convex os=-bsd ;; convex-c34) basic_machine=c34-convex os=-bsd ;; convex-c38) basic_machine=c38-convex os=-bsd ;; cray | j90) basic_machine=j90-cray os=-unicos ;; craynv) basic_machine=craynv-cray os=-unicosmp ;; cr16 | cr16-*) basic_machine=cr16-unknown os=-elf ;; crds | unos) basic_machine=m68k-crds ;; crisv32 | crisv32-* | etraxfs*) basic_machine=crisv32-axis ;; cris | cris-* | etrax*) basic_machine=cris-axis ;; crx) basic_machine=crx-unknown os=-elf ;; da30 | da30-*) basic_machine=m68k-da30 ;; decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) basic_machine=mips-dec ;; decsystem10* | dec10*) basic_machine=pdp10-dec os=-tops10 ;; decsystem20* | dec20*) basic_machine=pdp10-dec os=-tops20 ;; delta | 3300 | motorola-3300 | motorola-delta \ | 3300-motorola | delta-motorola) basic_machine=m68k-motorola ;; delta88) basic_machine=m88k-motorola os=-sysv3 ;; dicos) basic_machine=i686-pc os=-dicos ;; djgpp) basic_machine=i586-pc os=-msdosdjgpp ;; dpx20 | dpx20-*) basic_machine=rs6000-bull os=-bosx ;; dpx2* | dpx2*-bull) basic_machine=m68k-bull os=-sysv3 ;; ebmon29k) basic_machine=a29k-amd os=-ebmon ;; elxsi) basic_machine=elxsi-elxsi os=-bsd ;; encore | umax | mmax) basic_machine=ns32k-encore ;; es1800 | OSE68k | ose68k | ose | OSE) basic_machine=m68k-ericsson os=-ose ;; fx2800) basic_machine=i860-alliant ;; genix) basic_machine=ns32k-ns ;; gmicro) basic_machine=tron-gmicro os=-sysv ;; go32) basic_machine=i386-pc os=-go32 ;; h3050r* | hiux*) basic_machine=hppa1.1-hitachi os=-hiuxwe2 ;; h8300hms) basic_machine=h8300-hitachi os=-hms ;; h8300xray) basic_machine=h8300-hitachi os=-xray ;; h8500hms) basic_machine=h8500-hitachi os=-hms ;; harris) basic_machine=m88k-harris os=-sysv3 ;; hp300-*) basic_machine=m68k-hp ;; hp300bsd) basic_machine=m68k-hp os=-bsd ;; hp300hpux) basic_machine=m68k-hp os=-hpux ;; hp3k9[0-9][0-9] | hp9[0-9][0-9]) basic_machine=hppa1.0-hp ;; hp9k2[0-9][0-9] | hp9k31[0-9]) basic_machine=m68000-hp ;; hp9k3[2-9][0-9]) basic_machine=m68k-hp ;; hp9k6[0-9][0-9] | hp6[0-9][0-9]) basic_machine=hppa1.0-hp ;; hp9k7[0-79][0-9] | hp7[0-79][0-9]) basic_machine=hppa1.1-hp ;; hp9k78[0-9] | hp78[0-9]) # FIXME: really hppa2.0-hp basic_machine=hppa1.1-hp ;; hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) # FIXME: really hppa2.0-hp basic_machine=hppa1.1-hp ;; hp9k8[0-9][13679] | hp8[0-9][13679]) basic_machine=hppa1.1-hp ;; hp9k8[0-9][0-9] | hp8[0-9][0-9]) basic_machine=hppa1.0-hp ;; hppa-next) os=-nextstep3 ;; hppaosf) basic_machine=hppa1.1-hp os=-osf ;; hppro) basic_machine=hppa1.1-hp os=-proelf ;; i370-ibm* | ibm*) basic_machine=i370-ibm ;; i*86v32) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv32 ;; i*86v4*) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv4 ;; i*86v) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv ;; i*86sol2) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-solaris2 ;; i386mach) basic_machine=i386-mach os=-mach ;; i386-vsta | vsta) basic_machine=i386-unknown os=-vsta ;; iris | iris4d) basic_machine=mips-sgi case $os in -irix*) ;; *) os=-irix4 ;; esac ;; isi68 | isi) basic_machine=m68k-isi os=-sysv ;; m68knommu) basic_machine=m68k-unknown os=-linux ;; m68knommu-*) basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; m88k-omron*) basic_machine=m88k-omron ;; magnum | m3230) basic_machine=mips-mips os=-sysv ;; merlin) basic_machine=ns32k-utek os=-sysv ;; microblaze) basic_machine=microblaze-xilinx ;; mingw32) basic_machine=i386-pc os=-mingw32 ;; mingw32ce) basic_machine=arm-unknown os=-mingw32ce ;; miniframe) basic_machine=m68000-convergent ;; *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) basic_machine=m68k-atari os=-mint ;; mips3*-*) basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` ;; mips3*) basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown ;; monitor) basic_machine=m68k-rom68k os=-coff ;; morphos) basic_machine=powerpc-unknown os=-morphos ;; msdos) basic_machine=i386-pc os=-msdos ;; ms1-*) basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` ;; msys) basic_machine=i386-pc os=-msys ;; mvs) basic_machine=i370-ibm os=-mvs ;; nacl) basic_machine=le32-unknown os=-nacl ;; ncr3000) basic_machine=i486-ncr os=-sysv4 ;; netbsd386) basic_machine=i386-unknown os=-netbsd ;; netwinder) basic_machine=armv4l-rebel os=-linux ;; news | news700 | news800 | news900) basic_machine=m68k-sony os=-newsos ;; news1000) basic_machine=m68030-sony os=-newsos ;; news-3600 | risc-news) basic_machine=mips-sony os=-newsos ;; necv70) basic_machine=v70-nec os=-sysv ;; next | m*-next ) basic_machine=m68k-next case $os in -nextstep* ) ;; -ns2*) os=-nextstep2 ;; *) os=-nextstep3 ;; esac ;; nh3000) basic_machine=m68k-harris os=-cxux ;; nh[45]000) basic_machine=m88k-harris os=-cxux ;; nindy960) basic_machine=i960-intel os=-nindy ;; mon960) basic_machine=i960-intel os=-mon960 ;; nonstopux) basic_machine=mips-compaq os=-nonstopux ;; np1) basic_machine=np1-gould ;; neo-tandem) basic_machine=neo-tandem ;; nse-tandem) basic_machine=nse-tandem ;; nsr-tandem) basic_machine=nsr-tandem ;; op50n-* | op60c-*) basic_machine=hppa1.1-oki os=-proelf ;; openrisc | openrisc-*) basic_machine=or32-unknown ;; os400) basic_machine=powerpc-ibm os=-os400 ;; OSE68000 | ose68000) basic_machine=m68000-ericsson os=-ose ;; os68k) basic_machine=m68k-none os=-os68k ;; pa-hitachi) basic_machine=hppa1.1-hitachi os=-hiuxwe2 ;; paragon) basic_machine=i860-intel os=-osf ;; parisc) basic_machine=hppa-unknown os=-linux ;; parisc-*) basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; pbd) basic_machine=sparc-tti ;; pbb) basic_machine=m68k-tti ;; pc532 | pc532-*) basic_machine=ns32k-pc532 ;; pc98) basic_machine=i386-pc ;; pc98-*) basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentium | p5 | k5 | k6 | nexgen | viac3) basic_machine=i586-pc ;; pentiumpro | p6 | 6x86 | athlon | athlon_*) basic_machine=i686-pc ;; pentiumii | pentium2 | pentiumiii | pentium3) basic_machine=i686-pc ;; pentium4) basic_machine=i786-pc ;; pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentiumpro-* | p6-* | 6x86-* | athlon-*) basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentium4-*) basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pn) basic_machine=pn-gould ;; power) basic_machine=power-ibm ;; ppc | ppcbe) basic_machine=powerpc-unknown ;; ppc-* | ppcbe-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppcle | powerpclittle | ppc-le | powerpc-little) basic_machine=powerpcle-unknown ;; ppcle-* | powerpclittle-*) basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppc64) basic_machine=powerpc64-unknown ;; ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppc64le | powerpc64little | ppc64-le | powerpc64-little) basic_machine=powerpc64le-unknown ;; ppc64le-* | powerpc64little-*) basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ps2) basic_machine=i386-ibm ;; pw32) basic_machine=i586-unknown os=-pw32 ;; rdos) basic_machine=i386-pc os=-rdos ;; rom68k) basic_machine=m68k-rom68k os=-coff ;; rm[46]00) basic_machine=mips-siemens ;; rtpc | rtpc-*) basic_machine=romp-ibm ;; s390 | s390-*) basic_machine=s390-ibm ;; s390x | s390x-*) basic_machine=s390x-ibm ;; sa29200) basic_machine=a29k-amd os=-udi ;; sb1) basic_machine=mipsisa64sb1-unknown ;; sb1el) basic_machine=mipsisa64sb1el-unknown ;; sde) basic_machine=mipsisa32-sde os=-elf ;; sei) basic_machine=mips-sei os=-seiux ;; sequent) basic_machine=i386-sequent ;; sh) basic_machine=sh-hitachi os=-hms ;; sh5el) basic_machine=sh5le-unknown ;; sh64) basic_machine=sh64-unknown ;; sparclite-wrs | simso-wrs) basic_machine=sparclite-wrs os=-vxworks ;; sps7) basic_machine=m68k-bull os=-sysv2 ;; spur) basic_machine=spur-unknown ;; st2000) basic_machine=m68k-tandem ;; stratus) basic_machine=i860-stratus os=-sysv4 ;; strongarm-* | thumb-*) basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'` ;; sun2) basic_machine=m68000-sun ;; sun2os3) basic_machine=m68000-sun os=-sunos3 ;; sun2os4) basic_machine=m68000-sun os=-sunos4 ;; sun3os3) basic_machine=m68k-sun os=-sunos3 ;; sun3os4) basic_machine=m68k-sun os=-sunos4 ;; sun4os3) basic_machine=sparc-sun os=-sunos3 ;; sun4os4) basic_machine=sparc-sun os=-sunos4 ;; sun4sol2) basic_machine=sparc-sun os=-solaris2 ;; sun3 | sun3-*) basic_machine=m68k-sun ;; sun4) basic_machine=sparc-sun ;; sun386 | sun386i | roadrunner) basic_machine=i386-sun ;; sv1) basic_machine=sv1-cray os=-unicos ;; symmetry) basic_machine=i386-sequent os=-dynix ;; t3e) basic_machine=alphaev5-cray os=-unicos ;; t90) basic_machine=t90-cray os=-unicos ;; tile*) basic_machine=$basic_machine-unknown os=-linux-gnu ;; tx39) basic_machine=mipstx39-unknown ;; tx39el) basic_machine=mipstx39el-unknown ;; toad1) basic_machine=pdp10-xkl os=-tops20 ;; tower | tower-32) basic_machine=m68k-ncr ;; tpf) basic_machine=s390x-ibm os=-tpf ;; udi29k) basic_machine=a29k-amd os=-udi ;; ultra3) basic_machine=a29k-nyu os=-sym1 ;; v810 | necv810) basic_machine=v810-nec os=-none ;; vaxv) basic_machine=vax-dec os=-sysv ;; vms) basic_machine=vax-dec os=-vms ;; vpp*|vx|vx-*) basic_machine=f301-fujitsu ;; vxworks960) basic_machine=i960-wrs os=-vxworks ;; vxworks68) basic_machine=m68k-wrs os=-vxworks ;; vxworks29k) basic_machine=a29k-wrs os=-vxworks ;; w65*) basic_machine=w65-wdc os=-none ;; w89k-*) basic_machine=hppa1.1-winbond os=-proelf ;; xbox) basic_machine=i686-pc os=-mingw32 ;; xps | xps100) basic_machine=xps100-honeywell ;; xscale-* | xscalee[bl]-*) basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'` ;; ymp) basic_machine=ymp-cray os=-unicos ;; z8k-*-coff) basic_machine=z8k-unknown os=-sim ;; z80-*-coff) basic_machine=z80-unknown os=-sim ;; none) basic_machine=none-none os=-none ;; # Here we handle the default manufacturer of certain CPU types. It is in # some cases the only manufacturer, in others, it is the most popular. w89k) basic_machine=hppa1.1-winbond ;; op50n) basic_machine=hppa1.1-oki ;; op60c) basic_machine=hppa1.1-oki ;; romp) basic_machine=romp-ibm ;; mmix) basic_machine=mmix-knuth ;; rs6000) basic_machine=rs6000-ibm ;; vax) basic_machine=vax-dec ;; pdp10) # there are many clones, so DEC is not a safe bet basic_machine=pdp10-unknown ;; pdp11) basic_machine=pdp11-dec ;; we32k) basic_machine=we32k-att ;; sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele) basic_machine=sh-unknown ;; sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) basic_machine=sparc-sun ;; cydra) basic_machine=cydra-cydrome ;; orion) basic_machine=orion-highlevel ;; orion105) basic_machine=clipper-highlevel ;; mac | mpw | mac-mpw) basic_machine=m68k-apple ;; pmac | pmac-mpw) basic_machine=powerpc-apple ;; *-unknown) # Make sure to match an already-canonicalized machine name. ;; *) echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 exit 1 ;; esac # Here we canonicalize certain aliases for manufacturers. case $basic_machine in *-digital*) basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` ;; *-commodore*) basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` ;; *) ;; esac # Decode manufacturer-specific aliases for certain operating systems. if [ x"$os" != x"" ] then case $os in # First match some system type aliases # that might get confused with valid system types. # -solaris* is a basic system type, with this one exception. -auroraux) os=-auroraux ;; -solaris1 | -solaris1.*) os=`echo $os | sed -e 's|solaris1|sunos4|'` ;; -solaris) os=-solaris2 ;; -svr4*) os=-sysv4 ;; -unixware*) os=-sysv4.2uw ;; -gnu/linux*) os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` ;; # First accept the basic system types. # The portable systems comes first. # Each alternative MUST END IN A *, to match a version number. # -sysv* is not here because it comes later, after sysvr4. -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\ | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \ | -sym* | -kopensolaris* \ | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ | -aos* | -aros* \ | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ | -openbsd* | -solidbsd* \ | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ | -chorusos* | -chorusrdb* | -cegcc* \ | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ | -mingw32* | -linux-gnu* | -linux-android* \ | -linux-newlib* | -linux-uclibc* \ | -uxpv* | -beos* | -mpeix* | -udk* \ | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*) # Remember, each alternative MUST END IN *, to match a version number. ;; -qnx*) case $basic_machine in x86-* | i*86-*) ;; *) os=-nto$os ;; esac ;; -nto-qnx*) ;; -nto*) os=`echo $os | sed -e 's|nto|nto-qnx|'` ;; -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \ | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) ;; -mac*) os=`echo $os | sed -e 's|mac|macos|'` ;; -linux-dietlibc) os=-linux-dietlibc ;; -linux*) os=`echo $os | sed -e 's|linux|linux-gnu|'` ;; -sunos5*) os=`echo $os | sed -e 's|sunos5|solaris2|'` ;; -sunos6*) os=`echo $os | sed -e 's|sunos6|solaris3|'` ;; -opened*) os=-openedition ;; -os400*) os=-os400 ;; -wince*) os=-wince ;; -osfrose*) os=-osfrose ;; -osf*) os=-osf ;; -utek*) os=-bsd ;; -dynix*) os=-bsd ;; -acis*) os=-aos ;; -atheos*) os=-atheos ;; -syllable*) os=-syllable ;; -386bsd) os=-bsd ;; -ctix* | -uts*) os=-sysv ;; -nova*) os=-rtmk-nova ;; -ns2 ) os=-nextstep2 ;; -nsk*) os=-nsk ;; # Preserve the version number of sinix5. -sinix5.*) os=`echo $os | sed -e 's|sinix|sysv|'` ;; -sinix*) os=-sysv4 ;; -tpf*) os=-tpf ;; -triton*) os=-sysv3 ;; -oss*) os=-sysv3 ;; -svr4) os=-sysv4 ;; -svr3) os=-sysv3 ;; -sysvr4) os=-sysv4 ;; # This must come after -sysvr4. -sysv*) ;; -ose*) os=-ose ;; -es1800*) os=-ose ;; -xenix) os=-xenix ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) os=-mint ;; -aros*) os=-aros ;; -kaos*) os=-kaos ;; -zvmoe) os=-zvmoe ;; -dicos*) os=-dicos ;; -nacl*) ;; -none) ;; *) # Get rid of the `-' at the beginning of $os. os=`echo $os | sed 's/[^-]*-//'` echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 exit 1 ;; esac else # Here we handle the default operating systems that come with various machines. # The value should be what the vendor currently ships out the door with their # machine or put another way, the most popular os provided with the machine. # Note that if you're going to try to match "-MANUFACTURER" here (say, # "-sun"), then you have to tell the case statement up towards the top # that MANUFACTURER isn't an operating system. Otherwise, code above # will signal an error saying that MANUFACTURER isn't an operating # system, and we'll never get to this point. case $basic_machine in score-*) os=-elf ;; spu-*) os=-elf ;; *-acorn) os=-riscix1.2 ;; arm*-rebel) os=-linux ;; arm*-semi) os=-aout ;; c4x-* | tic4x-*) os=-coff ;; hexagon-*) os=-elf ;; tic54x-*) os=-coff ;; tic55x-*) os=-coff ;; tic6x-*) os=-coff ;; # This must come before the *-dec entry. pdp10-*) os=-tops20 ;; pdp11-*) os=-none ;; *-dec | vax-*) os=-ultrix4.2 ;; m68*-apollo) os=-domain ;; i386-sun) os=-sunos4.0.2 ;; m68000-sun) os=-sunos3 ;; m68*-cisco) os=-aout ;; mep-*) os=-elf ;; mips*-cisco) os=-elf ;; mips*-*) os=-elf ;; or32-*) os=-coff ;; *-tti) # must be before sparc entry or we get the wrong os. os=-sysv3 ;; sparc-* | *-sun) os=-sunos4.1.1 ;; *-be) os=-beos ;; *-haiku) os=-haiku ;; *-ibm) os=-aix ;; *-knuth) os=-mmixware ;; *-wec) os=-proelf ;; *-winbond) os=-proelf ;; *-oki) os=-proelf ;; *-hp) os=-hpux ;; *-hitachi) os=-hiux ;; i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) os=-sysv ;; *-cbm) os=-amigaos ;; *-dg) os=-dgux ;; *-dolphin) os=-sysv3 ;; m68k-ccur) os=-rtu ;; m88k-omron*) os=-luna ;; *-next ) os=-nextstep ;; *-sequent) os=-ptx ;; *-crds) os=-unos ;; *-ns) os=-genix ;; i370-*) os=-mvs ;; *-next) os=-nextstep3 ;; *-gould) os=-sysv ;; *-highlevel) os=-bsd ;; *-encore) os=-bsd ;; *-sgi) os=-irix ;; *-siemens) os=-sysv4 ;; *-masscomp) os=-rtu ;; f30[01]-fujitsu | f700-fujitsu) os=-uxpv ;; *-rom68k) os=-coff ;; *-*bug) os=-coff ;; *-apple) os=-macos ;; *-atari*) os=-mint ;; *) os=-none ;; esac fi # Here we handle the case where we know the os, and the CPU type, but not the # manufacturer. We pick the logical manufacturer. vendor=unknown case $basic_machine in *-unknown) case $os in -riscix*) vendor=acorn ;; -sunos*) vendor=sun ;; -cnk*|-aix*) vendor=ibm ;; -beos*) vendor=be ;; -hpux*) vendor=hp ;; -mpeix*) vendor=hp ;; -hiux*) vendor=hitachi ;; -unos*) vendor=crds ;; -dgux*) vendor=dg ;; -luna*) vendor=omron ;; -genix*) vendor=ns ;; -mvs* | -opened*) vendor=ibm ;; -os400*) vendor=ibm ;; -ptx*) vendor=sequent ;; -tpf*) vendor=ibm ;; -vxsim* | -vxworks* | -windiss*) vendor=wrs ;; -aux*) vendor=apple ;; -hms*) vendor=hitachi ;; -mpw* | -macos*) vendor=apple ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) vendor=atari ;; -vos*) vendor=stratus ;; esac basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` ;; esac echo $basic_machine$os exit # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: sipxtapi-3.3.0~test17/build-aux/depcomp0000755000175000017500000005064312321250507020652 0ustar00danieldaniel00000000000000#! /bin/sh # depcomp - compile a program generating dependencies as side-effects scriptversion=2012-03-27.16; # UTC # Copyright (C) 1999, 2000, 2003, 2004, 2005, 2006, 2007, 2009, 2010, # 2011, 2012 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # Originally written by Alexandre Oliva . case $1 in '') echo "$0: No command. Try '$0 --help' for more information." 1>&2 exit 1; ;; -h | --h*) cat <<\EOF Usage: depcomp [--help] [--version] PROGRAM [ARGS] Run PROGRAMS ARGS to compile a file, generating dependencies as side-effects. Environment variables: depmode Dependency tracking mode. source Source file read by 'PROGRAMS ARGS'. object Object file output by 'PROGRAMS ARGS'. DEPDIR directory where to store dependencies. depfile Dependency file to output. tmpdepfile Temporary file to use when outputting dependencies. libtool Whether libtool is used (yes/no). Report bugs to . EOF exit $? ;; -v | --v*) echo "depcomp $scriptversion" exit $? ;; esac # A tabulation character. tab=' ' # A newline character. nl=' ' if test -z "$depmode" || test -z "$source" || test -z "$object"; then echo "depcomp: Variables source, object and depmode must be set" 1>&2 exit 1 fi # Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po. depfile=${depfile-`echo "$object" | sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`} tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`} rm -f "$tmpdepfile" # Some modes work just like other modes, but use different flags. We # parameterize here, but still list the modes in the big case below, # to make depend.m4 easier to write. Note that we *cannot* use a case # here, because this file can only contain one case statement. if test "$depmode" = hp; then # HP compiler uses -M and no extra arg. gccflag=-M depmode=gcc fi if test "$depmode" = dashXmstdout; then # This is just like dashmstdout with a different argument. dashmflag=-xM depmode=dashmstdout fi cygpath_u="cygpath -u -f -" if test "$depmode" = msvcmsys; then # This is just like msvisualcpp but w/o cygpath translation. # Just convert the backslash-escaped backslashes to single forward # slashes to satisfy depend.m4 cygpath_u='sed s,\\\\,/,g' depmode=msvisualcpp fi if test "$depmode" = msvc7msys; then # This is just like msvc7 but w/o cygpath translation. # Just convert the backslash-escaped backslashes to single forward # slashes to satisfy depend.m4 cygpath_u='sed s,\\\\,/,g' depmode=msvc7 fi if test "$depmode" = xlc; then # IBM C/C++ Compilers xlc/xlC can output gcc-like dependency informations. gccflag=-qmakedep=gcc,-MF depmode=gcc fi case "$depmode" in gcc3) ## gcc 3 implements dependency tracking that does exactly what ## we want. Yay! Note: for some reason libtool 1.4 doesn't like ## it if -MD -MP comes after the -MF stuff. Hmm. ## Unfortunately, FreeBSD c89 acceptance of flags depends upon ## the command line argument order; so add the flags where they ## appear in depend2.am. Note that the slowdown incurred here ## affects only configure: in makefiles, %FASTDEP% shortcuts this. for arg do case $arg in -c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;; *) set fnord "$@" "$arg" ;; esac shift # fnord shift # $arg done "$@" stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile" exit $stat fi mv "$tmpdepfile" "$depfile" ;; gcc) ## There are various ways to get dependency output from gcc. Here's ## why we pick this rather obscure method: ## - Don't want to use -MD because we'd like the dependencies to end ## up in a subdir. Having to rename by hand is ugly. ## (We might end up doing this anyway to support other compilers.) ## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like ## -MM, not -M (despite what the docs say). ## - Using -M directly means running the compiler twice (even worse ## than renaming). if test -z "$gccflag"; then gccflag=-MD, fi "$@" -Wp,"$gccflag$tmpdepfile" stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" echo "$object : \\" > "$depfile" alpha=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ## The second -e expression handles DOS-style file names with drive letters. sed -e 's/^[^:]*: / /' \ -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile" ## This next piece of magic avoids the "deleted header file" problem. ## The problem is that when a header file which appears in a .P file ## is deleted, the dependency causes make to die (because there is ## typically no way to rebuild the header). We avoid this by adding ## dummy dependencies for each header file. Too bad gcc doesn't do ## this for us directly. tr ' ' "$nl" < "$tmpdepfile" | ## Some versions of gcc put a space before the ':'. On the theory ## that the space means something, we add a space to the output as ## well. hp depmode also adds that space, but also prefixes the VPATH ## to the object. Take care to not repeat it in the output. ## Some versions of the HPUX 10.20 sed can't process this invocation ## correctly. Breaking it into two sed invocations is a workaround. sed -e 's/^\\$//' -e '/^$/d' -e "s|.*$object$||" -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; hp) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; sgi) if test "$libtool" = yes; then "$@" "-Wp,-MDupdate,$tmpdepfile" else "$@" -MDupdate "$tmpdepfile" fi stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files echo "$object : \\" > "$depfile" # Clip off the initial element (the dependent). Don't try to be # clever and replace this with sed code, as IRIX sed won't handle # lines with more than a fixed number of characters (4096 in # IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines; # the IRIX cc adds comments like '#:fec' to the end of the # dependency line. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' | \ tr "$nl" ' ' >> "$depfile" echo >> "$depfile" # The second pass generates a dummy entry for each header file. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \ >> "$depfile" else # The sourcefile does not contain any dependencies, so just # store a dummy comment line, to avoid errors with the Makefile # "include basename.Plo" scheme. echo "#dummy" > "$depfile" fi rm -f "$tmpdepfile" ;; xlc) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; aix) # The C for AIX Compiler uses -M and outputs the dependencies # in a .u file. In older versions, this file always lives in the # current directory. Also, the AIX compiler puts '$object:' at the # start of each line; $object doesn't have directory information. # Version 6 uses the directory in both cases. dir=`echo "$object" | sed -e 's|/[^/]*$|/|'` test "x$dir" = "x$object" && dir= base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'` if test "$libtool" = yes; then tmpdepfile1=$dir$base.u tmpdepfile2=$base.u tmpdepfile3=$dir.libs/$base.u "$@" -Wc,-M else tmpdepfile1=$dir$base.u tmpdepfile2=$dir$base.u tmpdepfile3=$dir$base.u "$@" -M fi stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" do test -f "$tmpdepfile" && break done if test -f "$tmpdepfile"; then # Each line is of the form 'foo.o: dependent.h'. # Do two passes, one to just change these to # '$object: dependent.h' and one to simply 'dependent.h:'. sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile" sed -e 's,^.*\.[a-z]*:['"$tab"' ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile" else # The sourcefile does not contain any dependencies, so just # store a dummy comment line, to avoid errors with the Makefile # "include basename.Plo" scheme. echo "#dummy" > "$depfile" fi rm -f "$tmpdepfile" ;; icc) # Intel's C compiler anf tcc (Tiny C Compiler) understand '-MD -MF file'. # However on # $CC -MD -MF foo.d -c -o sub/foo.o sub/foo.c # ICC 7.0 will fill foo.d with something like # foo.o: sub/foo.c # foo.o: sub/foo.h # which is wrong. We want # sub/foo.o: sub/foo.c # sub/foo.o: sub/foo.h # sub/foo.c: # sub/foo.h: # ICC 7.1 will output # foo.o: sub/foo.c sub/foo.h # and will wrap long lines using '\': # foo.o: sub/foo.c ... \ # sub/foo.h ... \ # ... # tcc 0.9.26 (FIXME still under development at the moment of writing) # will emit a similar output, but also prepend the continuation lines # with horizontal tabulation characters. "$@" -MD -MF "$tmpdepfile" stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" # Each line is of the form 'foo.o: dependent.h', # or 'foo.o: dep1.h dep2.h \', or ' dep3.h dep4.h \'. # Do two passes, one to just change these to # '$object: dependent.h' and one to simply 'dependent.h:'. sed -e "s/^[ $tab][ $tab]*/ /" -e "s,^[^:]*:,$object :," \ < "$tmpdepfile" > "$depfile" sed ' s/[ '"$tab"'][ '"$tab"']*/ /g s/^ *// s/ *\\*$// s/^[^:]*: *// /^$/d /:$/d s/$/ :/ ' < "$tmpdepfile" >> "$depfile" rm -f "$tmpdepfile" ;; hp2) # The "hp" stanza above does not work with aCC (C++) and HP's ia64 # compilers, which have integrated preprocessors. The correct option # to use with these is +Maked; it writes dependencies to a file named # 'foo.d', which lands next to the object file, wherever that # happens to be. # Much of this is similar to the tru64 case; see comments there. dir=`echo "$object" | sed -e 's|/[^/]*$|/|'` test "x$dir" = "x$object" && dir= base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'` if test "$libtool" = yes; then tmpdepfile1=$dir$base.d tmpdepfile2=$dir.libs/$base.d "$@" -Wc,+Maked else tmpdepfile1=$dir$base.d tmpdepfile2=$dir$base.d "$@" +Maked fi stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile1" "$tmpdepfile2" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" do test -f "$tmpdepfile" && break done if test -f "$tmpdepfile"; then sed -e "s,^.*\.[a-z]*:,$object:," "$tmpdepfile" > "$depfile" # Add 'dependent.h:' lines. sed -ne '2,${ s/^ *// s/ \\*$// s/$/:/ p }' "$tmpdepfile" >> "$depfile" else echo "#dummy" > "$depfile" fi rm -f "$tmpdepfile" "$tmpdepfile2" ;; tru64) # The Tru64 compiler uses -MD to generate dependencies as a side # effect. 'cc -MD -o foo.o ...' puts the dependencies into 'foo.o.d'. # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put # dependencies in 'foo.d' instead, so we check for that too. # Subdirectories are respected. dir=`echo "$object" | sed -e 's|/[^/]*$|/|'` test "x$dir" = "x$object" && dir= base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'` if test "$libtool" = yes; then # With Tru64 cc, shared objects can also be used to make a # static library. This mechanism is used in libtool 1.4 series to # handle both shared and static libraries in a single compilation. # With libtool 1.4, dependencies were output in $dir.libs/$base.lo.d. # # With libtool 1.5 this exception was removed, and libtool now # generates 2 separate objects for the 2 libraries. These two # compilations output dependencies in $dir.libs/$base.o.d and # in $dir$base.o.d. We have to check for both files, because # one of the two compilations can be disabled. We should prefer # $dir$base.o.d over $dir.libs/$base.o.d because the latter is # automatically cleaned when .libs/ is deleted, while ignoring # the former would cause a distcleancheck panic. tmpdepfile1=$dir.libs/$base.lo.d # libtool 1.4 tmpdepfile2=$dir$base.o.d # libtool 1.5 tmpdepfile3=$dir.libs/$base.o.d # libtool 1.5 tmpdepfile4=$dir.libs/$base.d # Compaq CCC V6.2-504 "$@" -Wc,-MD else tmpdepfile1=$dir$base.o.d tmpdepfile2=$dir$base.d tmpdepfile3=$dir$base.d tmpdepfile4=$dir$base.d "$@" -MD fi stat=$? if test $stat -eq 0; then : else rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4" do test -f "$tmpdepfile" && break done if test -f "$tmpdepfile"; then sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile" sed -e 's,^.*\.[a-z]*:['"$tab"' ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile" else echo "#dummy" > "$depfile" fi rm -f "$tmpdepfile" ;; msvc7) if test "$libtool" = yes; then showIncludes=-Wc,-showIncludes else showIncludes=-showIncludes fi "$@" $showIncludes > "$tmpdepfile" stat=$? grep -v '^Note: including file: ' "$tmpdepfile" if test "$stat" = 0; then : else rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" echo "$object : \\" > "$depfile" # The first sed program below extracts the file names and escapes # backslashes for cygpath. The second sed program outputs the file # name when reading, but also accumulates all include files in the # hold buffer in order to output them again at the end. This only # works with sed implementations that can handle large buffers. sed < "$tmpdepfile" -n ' /^Note: including file: *\(.*\)/ { s//\1/ s/\\/\\\\/g p }' | $cygpath_u | sort -u | sed -n ' s/ /\\ /g s/\(.*\)/'"$tab"'\1 \\/p s/.\(.*\) \\/\1:/ H $ { s/.*/'"$tab"'/ G p }' >> "$depfile" rm -f "$tmpdepfile" ;; msvc7msys) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; #nosideeffect) # This comment above is used by automake to tell side-effect # dependency tracking mechanisms from slower ones. dashmstdout) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout, regardless of -o. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # Remove '-o $object'. IFS=" " for arg do case $arg in -o) shift ;; $object) shift ;; *) set fnord "$@" "$arg" shift # fnord shift # $arg ;; esac done test -z "$dashmflag" && dashmflag=-M # Require at least two characters before searching for ':' # in the target name. This is to cope with DOS-style filenames: # a dependency such as 'c:/foo/bar' could be seen as target 'c' otherwise. "$@" $dashmflag | sed 's:^['"$tab"' ]*[^:'"$tab"' ][^:][^:]*\:['"$tab"' ]*:'"$object"'\: :' > "$tmpdepfile" rm -f "$depfile" cat < "$tmpdepfile" > "$depfile" tr ' ' "$nl" < "$tmpdepfile" | \ ## Some versions of the HPUX 10.20 sed can't process this invocation ## correctly. Breaking it into two sed invocations is a workaround. sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; dashXmstdout) # This case only exists to satisfy depend.m4. It is never actually # run, as this mode is specially recognized in the preamble. exit 1 ;; makedepend) "$@" || exit $? # Remove any Libtool call if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # X makedepend shift cleared=no eat=no for arg do case $cleared in no) set ""; shift cleared=yes ;; esac if test $eat = yes; then eat=no continue fi case "$arg" in -D*|-I*) set fnord "$@" "$arg"; shift ;; # Strip any option that makedepend may not understand. Remove # the object too, otherwise makedepend will parse it as a source file. -arch) eat=yes ;; -*|$object) ;; *) set fnord "$@" "$arg"; shift ;; esac done obj_suffix=`echo "$object" | sed 's/^.*\././'` touch "$tmpdepfile" ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@" rm -f "$depfile" # makedepend may prepend the VPATH from the source file name to the object. # No need to regex-escape $object, excess matching of '.' is harmless. sed "s|^.*\($object *:\)|\1|" "$tmpdepfile" > "$depfile" sed '1,2d' "$tmpdepfile" | tr ' ' "$nl" | \ ## Some versions of the HPUX 10.20 sed can't process this invocation ## correctly. Breaking it into two sed invocations is a workaround. sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" "$tmpdepfile".bak ;; cpp) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # Remove '-o $object'. IFS=" " for arg do case $arg in -o) shift ;; $object) shift ;; *) set fnord "$@" "$arg" shift # fnord shift # $arg ;; esac done "$@" -E | sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ -e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' | sed '$ s: \\$::' > "$tmpdepfile" rm -f "$depfile" echo "$object : \\" > "$depfile" cat < "$tmpdepfile" >> "$depfile" sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; msvisualcpp) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi IFS=" " for arg do case "$arg" in -o) shift ;; $object) shift ;; "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI") set fnord "$@" shift shift ;; *) set fnord "$@" "$arg" shift shift ;; esac done "$@" -E 2>/dev/null | sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile" rm -f "$depfile" echo "$object : \\" > "$depfile" sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::'"$tab"'\1 \\:p' >> "$depfile" echo "$tab" >> "$depfile" sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile" rm -f "$tmpdepfile" ;; msvcmsys) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; none) exec "$@" ;; *) echo "Unknown depmode $depmode" 1>&2 exit 1 ;; esac exit 0 # Local Variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: sipxtapi-3.3.0~test17/build-aux/install-sh0000755000175000017500000003325612321250501021274 0ustar00danieldaniel00000000000000#!/bin/sh # install - install a program, script, or datafile scriptversion=2011-01-19.21; # UTC # This originates from X11R5 (mit/util/scripts/install.sh), which was # later released in X11R6 (xc/config/util/install.sh) with the # following copyright and license. # # Copyright (C) 1994 X Consortium # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN # AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- # TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # Except as contained in this notice, the name of the X Consortium shall not # be used in advertising or otherwise to promote the sale, use or other deal- # ings in this Software without prior written authorization from the X Consor- # tium. # # # FSF changes to this file are in the public domain. # # Calling this script install-sh is preferred over install.sh, to prevent # `make' implicit rules from creating a file called install from it # when there is no Makefile. # # This script is compatible with the BSD install script, but was written # from scratch. nl=' ' IFS=" "" $nl" # set DOITPROG to echo to test this script # Don't use :- since 4.3BSD and earlier shells don't like it. doit=${DOITPROG-} if test -z "$doit"; then doit_exec=exec else doit_exec=$doit fi # Put in absolute file names if you don't have them in your path; # or use environment vars. chgrpprog=${CHGRPPROG-chgrp} chmodprog=${CHMODPROG-chmod} chownprog=${CHOWNPROG-chown} cmpprog=${CMPPROG-cmp} cpprog=${CPPROG-cp} mkdirprog=${MKDIRPROG-mkdir} mvprog=${MVPROG-mv} rmprog=${RMPROG-rm} stripprog=${STRIPPROG-strip} posix_glob='?' initialize_posix_glob=' test "$posix_glob" != "?" || { if (set -f) 2>/dev/null; then posix_glob= else posix_glob=: fi } ' posix_mkdir= # Desired mode of installed file. mode=0755 chgrpcmd= chmodcmd=$chmodprog chowncmd= mvcmd=$mvprog rmcmd="$rmprog -f" stripcmd= src= dst= dir_arg= dst_arg= copy_on_change=false no_target_directory= usage="\ Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE or: $0 [OPTION]... SRCFILES... DIRECTORY or: $0 [OPTION]... -t DIRECTORY SRCFILES... or: $0 [OPTION]... -d DIRECTORIES... In the 1st form, copy SRCFILE to DSTFILE. In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. In the 4th, create DIRECTORIES. Options: --help display this help and exit. --version display version info and exit. -c (ignored) -C install only if different (preserve the last data modification time) -d create directories instead of installing files. -g GROUP $chgrpprog installed files to GROUP. -m MODE $chmodprog installed files to MODE. -o USER $chownprog installed files to USER. -s $stripprog installed files. -t DIRECTORY install into DIRECTORY. -T report an error if DSTFILE is a directory. Environment variables override the default commands: CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG " while test $# -ne 0; do case $1 in -c) ;; -C) copy_on_change=true;; -d) dir_arg=true;; -g) chgrpcmd="$chgrpprog $2" shift;; --help) echo "$usage"; exit $?;; -m) mode=$2 case $mode in *' '* | *' '* | *' '* | *'*'* | *'?'* | *'['*) echo "$0: invalid mode: $mode" >&2 exit 1;; esac shift;; -o) chowncmd="$chownprog $2" shift;; -s) stripcmd=$stripprog;; -t) dst_arg=$2 # Protect names problematic for `test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac shift;; -T) no_target_directory=true;; --version) echo "$0 $scriptversion"; exit $?;; --) shift break;; -*) echo "$0: invalid option: $1" >&2 exit 1;; *) break;; esac shift done if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then # When -d is used, all remaining arguments are directories to create. # When -t is used, the destination is already specified. # Otherwise, the last argument is the destination. Remove it from $@. for arg do if test -n "$dst_arg"; then # $@ is not empty: it contains at least $arg. set fnord "$@" "$dst_arg" shift # fnord fi shift # arg dst_arg=$arg # Protect names problematic for `test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac done fi if test $# -eq 0; then if test -z "$dir_arg"; then echo "$0: no input file specified." >&2 exit 1 fi # It's OK to call `install-sh -d' without argument. # This can happen when creating conditional directories. exit 0 fi if test -z "$dir_arg"; then do_exit='(exit $ret); exit $ret' trap "ret=129; $do_exit" 1 trap "ret=130; $do_exit" 2 trap "ret=141; $do_exit" 13 trap "ret=143; $do_exit" 15 # Set umask so as not to create temps with too-generous modes. # However, 'strip' requires both read and write access to temps. case $mode in # Optimize common cases. *644) cp_umask=133;; *755) cp_umask=22;; *[0-7]) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw='% 200' fi cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; *) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw=,u+rw fi cp_umask=$mode$u_plus_rw;; esac fi for src do # Protect names problematic for `test' and other utilities. case $src in -* | [=\(\)!]) src=./$src;; esac if test -n "$dir_arg"; then dst=$src dstdir=$dst test -d "$dstdir" dstdir_status=$? else # Waiting for this to be detected by the "$cpprog $src $dsttmp" command # might cause directories to be created, which would be especially bad # if $src (and thus $dsttmp) contains '*'. if test ! -f "$src" && test ! -d "$src"; then echo "$0: $src does not exist." >&2 exit 1 fi if test -z "$dst_arg"; then echo "$0: no destination specified." >&2 exit 1 fi dst=$dst_arg # If destination is a directory, append the input filename; won't work # if double slashes aren't ignored. if test -d "$dst"; then if test -n "$no_target_directory"; then echo "$0: $dst_arg: Is a directory" >&2 exit 1 fi dstdir=$dst dst=$dstdir/`basename "$src"` dstdir_status=0 else # Prefer dirname, but fall back on a substitute if dirname fails. dstdir=` (dirname "$dst") 2>/dev/null || expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$dst" : 'X\(//\)[^/]' \| \ X"$dst" : 'X\(//\)$' \| \ X"$dst" : 'X\(/\)' \| . 2>/dev/null || echo X"$dst" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q' ` test -d "$dstdir" dstdir_status=$? fi fi obsolete_mkdir_used=false if test $dstdir_status != 0; then case $posix_mkdir in '') # Create intermediate dirs using mode 755 as modified by the umask. # This is like FreeBSD 'install' as of 1997-10-28. umask=`umask` case $stripcmd.$umask in # Optimize common cases. *[2367][2367]) mkdir_umask=$umask;; .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;; *[0-7]) mkdir_umask=`expr $umask + 22 \ - $umask % 100 % 40 + $umask % 20 \ - $umask % 10 % 4 + $umask % 2 `;; *) mkdir_umask=$umask,go-w;; esac # With -d, create the new directory with the user-specified mode. # Otherwise, rely on $mkdir_umask. if test -n "$dir_arg"; then mkdir_mode=-m$mode else mkdir_mode= fi posix_mkdir=false case $umask in *[123567][0-7][0-7]) # POSIX mkdir -p sets u+wx bits regardless of umask, which # is incompatible with FreeBSD 'install' when (umask & 300) != 0. ;; *) tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0 if (umask $mkdir_umask && exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1 then if test -z "$dir_arg" || { # Check for POSIX incompatibilities with -m. # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or # other-writeable bit of parent directory when it shouldn't. # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. ls_ld_tmpdir=`ls -ld "$tmpdir"` case $ls_ld_tmpdir in d????-?r-*) different_mode=700;; d????-?--*) different_mode=755;; *) false;; esac && $mkdirprog -m$different_mode -p -- "$tmpdir" && { ls_ld_tmpdir_1=`ls -ld "$tmpdir"` test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" } } then posix_mkdir=: fi rmdir "$tmpdir/d" "$tmpdir" else # Remove any dirs left behind by ancient mkdir implementations. rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null fi trap '' 0;; esac;; esac if $posix_mkdir && ( umask $mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" ) then : else # The umask is ridiculous, or mkdir does not conform to POSIX, # or it failed possibly due to a race condition. Create the # directory the slow way, step by step, checking for races as we go. case $dstdir in /*) prefix='/';; [-=\(\)!]*) prefix='./';; *) prefix='';; esac eval "$initialize_posix_glob" oIFS=$IFS IFS=/ $posix_glob set -f set fnord $dstdir shift $posix_glob set +f IFS=$oIFS prefixes= for d do test X"$d" = X && continue prefix=$prefix$d if test -d "$prefix"; then prefixes= else if $posix_mkdir; then (umask=$mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break # Don't fail if two instances are running concurrently. test -d "$prefix" || exit 1 else case $prefix in *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; *) qprefix=$prefix;; esac prefixes="$prefixes '$qprefix'" fi fi prefix=$prefix/ done if test -n "$prefixes"; then # Don't fail if two instances are running concurrently. (umask $mkdir_umask && eval "\$doit_exec \$mkdirprog $prefixes") || test -d "$dstdir" || exit 1 obsolete_mkdir_used=true fi fi fi if test -n "$dir_arg"; then { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 else # Make a couple of temp file names in the proper directory. dsttmp=$dstdir/_inst.$$_ rmtmp=$dstdir/_rm.$$_ # Trap to clean up those temp files at exit. trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 # Copy the file name to the temp name. (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") && # and set any options; do chmod last to preserve setuid bits. # # If any of these fail, we abort the whole thing. If we want to # ignore errors from any of these, just make sure not to ignore # errors from the above "$doit $cpprog $src $dsttmp" command. # { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } && { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && # If -C, don't bother to copy if it wouldn't change the file. if $copy_on_change && old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` && new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` && eval "$initialize_posix_glob" && $posix_glob set -f && set X $old && old=:$2:$4:$5:$6 && set X $new && new=:$2:$4:$5:$6 && $posix_glob set +f && test "$old" = "$new" && $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1 then rm -f "$dsttmp" else # Rename the file to the real destination. $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null || # The rename failed, perhaps because mv can't rename something else # to itself, or perhaps because mv is so ancient that it does not # support -f. { # Now remove or move aside any old file at destination location. # We try this two ways since rm can't unlink itself on some # systems and the destination file might be busy for other # reasons. In this case, the final cleanup might fail but the new # file should still install successfully. { test ! -f "$dst" || $doit $rmcmd -f "$dst" 2>/dev/null || { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null && { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; } } || { echo "$0: cannot unlink or rename $dst" >&2 (exit 1); exit 1 } } && # Now rename the file to the real destination. $doit $mvcmd "$dsttmp" "$dst" } fi || exit 1 trap '' 0 fi done # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: sipxtapi-3.3.0~test17/build-aux/ltmain.sh0000644000175000017500000105202612321250471021113 0ustar00danieldaniel00000000000000 # libtool (GNU libtool) 2.4.2 # Written by Gordon Matzigkeit , 1996 # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, # 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, # or obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Usage: $progname [OPTION]... [MODE-ARG]... # # Provide generalized library-building support services. # # --config show all configuration variables # --debug enable verbose shell tracing # -n, --dry-run display commands without modifying any files # --features display basic configuration information and exit # --mode=MODE use operation mode MODE # --preserve-dup-deps don't remove duplicate dependency libraries # --quiet, --silent don't print informational messages # --no-quiet, --no-silent # print informational messages (default) # --no-warn don't display warning messages # --tag=TAG use configuration variables from tag TAG # -v, --verbose print more informational messages than default # --no-verbose don't print the extra informational messages # --version print version information # -h, --help, --help-all print short, long, or detailed help message # # MODE must be one of the following: # # clean remove files from the build directory # compile compile a source file into a libtool object # execute automatically set library path, then run a program # finish complete the installation of libtool libraries # install install libraries or executables # link create a library or an executable # uninstall remove libraries from an installed directory # # MODE-ARGS vary depending on the MODE. When passed as first option, # `--mode=MODE' may be abbreviated as `MODE' or a unique abbreviation of that. # Try `$progname --help --mode=MODE' for a more detailed description of MODE. # # When reporting a bug, please describe a test case to reproduce it and # include the following information: # # host-triplet: $host # shell: $SHELL # compiler: $LTCC # compiler flags: $LTCFLAGS # linker: $LD (gnu? $with_gnu_ld) # $progname: (GNU libtool) 2.4.2 Debian-2.4.2-1.1 # automake: $automake_version # autoconf: $autoconf_version # # Report bugs to . # GNU libtool home page: . # General help using GNU software: . PROGRAM=libtool PACKAGE=libtool VERSION="2.4.2 Debian-2.4.2-1.1" TIMESTAMP="" package_revision=1.3337 # Be Bourne compatible if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } # NLS nuisances: We save the old values to restore during execute mode. lt_user_locale= lt_safe_locale= for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${$lt_var+set}\" = set; then save_$lt_var=\$$lt_var $lt_var=C export $lt_var lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\" lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\" fi" done LC_ALL=C LANGUAGE=C export LANGUAGE LC_ALL $lt_unset CDPATH # Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh # is ksh but when the shell is invoked as "sh" and the current value of # the _XPG environment variable is not equal to 1 (one), the special # positional parameter $0, within a function call, is the name of the # function. progpath="$0" : ${CP="cp -f"} test "${ECHO+set}" = set || ECHO=${as_echo-'printf %s\n'} : ${MAKE="make"} : ${MKDIR="mkdir"} : ${MV="mv -f"} : ${RM="rm -f"} : ${SHELL="${CONFIG_SHELL-/bin/sh}"} : ${Xsed="$SED -e 1s/^X//"} # Global variables: EXIT_SUCCESS=0 EXIT_FAILURE=1 EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. exit_status=$EXIT_SUCCESS # Make sure IFS has a sensible default lt_nl=' ' IFS=" $lt_nl" dirname="s,/[^/]*$,," basename="s,^.*/,," # func_dirname file append nondir_replacement # Compute the dirname of FILE. If nonempty, add APPEND to the result, # otherwise set result to NONDIR_REPLACEMENT. func_dirname () { func_dirname_result=`$ECHO "${1}" | $SED "$dirname"` if test "X$func_dirname_result" = "X${1}"; then func_dirname_result="${3}" else func_dirname_result="$func_dirname_result${2}" fi } # func_dirname may be replaced by extended shell implementation # func_basename file func_basename () { func_basename_result=`$ECHO "${1}" | $SED "$basename"` } # func_basename may be replaced by extended shell implementation # func_dirname_and_basename file append nondir_replacement # perform func_basename and func_dirname in a single function # call: # dirname: Compute the dirname of FILE. If nonempty, # add APPEND to the result, otherwise set result # to NONDIR_REPLACEMENT. # value returned in "$func_dirname_result" # basename: Compute filename of FILE. # value retuned in "$func_basename_result" # Implementation must be kept synchronized with func_dirname # and func_basename. For efficiency, we do not delegate to # those functions but instead duplicate the functionality here. func_dirname_and_basename () { # Extract subdirectory from the argument. func_dirname_result=`$ECHO "${1}" | $SED -e "$dirname"` if test "X$func_dirname_result" = "X${1}"; then func_dirname_result="${3}" else func_dirname_result="$func_dirname_result${2}" fi func_basename_result=`$ECHO "${1}" | $SED -e "$basename"` } # func_dirname_and_basename may be replaced by extended shell implementation # func_stripname prefix suffix name # strip PREFIX and SUFFIX off of NAME. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). # func_strip_suffix prefix name func_stripname () { case ${2} in .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;; *) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;; esac } # func_stripname may be replaced by extended shell implementation # These SED scripts presuppose an absolute path with a trailing slash. pathcar='s,^/\([^/]*\).*$,\1,' pathcdr='s,^/[^/]*,,' removedotparts=':dotsl s@/\./@/@g t dotsl s,/\.$,/,' collapseslashes='s@/\{1,\}@/@g' finalslash='s,/*$,/,' # func_normal_abspath PATH # Remove doubled-up and trailing slashes, "." path components, # and cancel out any ".." path components in PATH after making # it an absolute path. # value returned in "$func_normal_abspath_result" func_normal_abspath () { # Start from root dir and reassemble the path. func_normal_abspath_result= func_normal_abspath_tpath=$1 func_normal_abspath_altnamespace= case $func_normal_abspath_tpath in "") # Empty path, that just means $cwd. func_stripname '' '/' "`pwd`" func_normal_abspath_result=$func_stripname_result return ;; # The next three entries are used to spot a run of precisely # two leading slashes without using negated character classes; # we take advantage of case's first-match behaviour. ///*) # Unusual form of absolute path, do nothing. ;; //*) # Not necessarily an ordinary path; POSIX reserves leading '//' # and for example Cygwin uses it to access remote file shares # over CIFS/SMB, so we conserve a leading double slash if found. func_normal_abspath_altnamespace=/ ;; /*) # Absolute path, do nothing. ;; *) # Relative path, prepend $cwd. func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath ;; esac # Cancel out all the simple stuff to save iterations. We also want # the path to end with a slash for ease of parsing, so make sure # there is one (and only one) here. func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$removedotparts" -e "$collapseslashes" -e "$finalslash"` while :; do # Processed it all yet? if test "$func_normal_abspath_tpath" = / ; then # If we ascended to the root using ".." the result may be empty now. if test -z "$func_normal_abspath_result" ; then func_normal_abspath_result=/ fi break fi func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$pathcar"` func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$pathcdr"` # Figure out what to do with it case $func_normal_abspath_tcomponent in "") # Trailing empty path component, ignore it. ;; ..) # Parent dir; strip last assembled component from result. func_dirname "$func_normal_abspath_result" func_normal_abspath_result=$func_dirname_result ;; *) # Actual path component, append it. func_normal_abspath_result=$func_normal_abspath_result/$func_normal_abspath_tcomponent ;; esac done # Restore leading double-slash if one was found on entry. func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result } # func_relative_path SRCDIR DSTDIR # generates a relative path from SRCDIR to DSTDIR, with a trailing # slash if non-empty, suitable for immediately appending a filename # without needing to append a separator. # value returned in "$func_relative_path_result" func_relative_path () { func_relative_path_result= func_normal_abspath "$1" func_relative_path_tlibdir=$func_normal_abspath_result func_normal_abspath "$2" func_relative_path_tbindir=$func_normal_abspath_result # Ascend the tree starting from libdir while :; do # check if we have found a prefix of bindir case $func_relative_path_tbindir in $func_relative_path_tlibdir) # found an exact match func_relative_path_tcancelled= break ;; $func_relative_path_tlibdir*) # found a matching prefix func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir" func_relative_path_tcancelled=$func_stripname_result if test -z "$func_relative_path_result"; then func_relative_path_result=. fi break ;; *) func_dirname $func_relative_path_tlibdir func_relative_path_tlibdir=${func_dirname_result} if test "x$func_relative_path_tlibdir" = x ; then # Have to descend all the way to the root! func_relative_path_result=../$func_relative_path_result func_relative_path_tcancelled=$func_relative_path_tbindir break fi func_relative_path_result=../$func_relative_path_result ;; esac done # Now calculate path; take care to avoid doubling-up slashes. func_stripname '' '/' "$func_relative_path_result" func_relative_path_result=$func_stripname_result func_stripname '/' '/' "$func_relative_path_tcancelled" if test "x$func_stripname_result" != x ; then func_relative_path_result=${func_relative_path_result}/${func_stripname_result} fi # Normalisation. If bindir is libdir, return empty string, # else relative path ending with a slash; either way, target # file name can be directly appended. if test ! -z "$func_relative_path_result"; then func_stripname './' '' "$func_relative_path_result/" func_relative_path_result=$func_stripname_result fi } # The name of this program: func_dirname_and_basename "$progpath" progname=$func_basename_result # Make sure we have an absolute path for reexecution: case $progpath in [\\/]*|[A-Za-z]:\\*) ;; *[\\/]*) progdir=$func_dirname_result progdir=`cd "$progdir" && pwd` progpath="$progdir/$progname" ;; *) save_IFS="$IFS" IFS=${PATH_SEPARATOR-:} for progdir in $PATH; do IFS="$save_IFS" test -x "$progdir/$progname" && break done IFS="$save_IFS" test -n "$progdir" || progdir=`pwd` progpath="$progdir/$progname" ;; esac # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. Xsed="${SED}"' -e 1s/^X//' sed_quote_subst='s/\([`"$\\]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution that turns a string into a regex matching for the # string literally. sed_make_literal_regex='s,[].[^$\\*\/],\\&,g' # Sed substitution that converts a w32 file name or path # which contains forward slashes, into one that contains # (escaped) backslashes. A very naive implementation. lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' # Re-`\' parameter expansions in output of double_quote_subst that were # `\'-ed in input to the same. If an odd number of `\' preceded a '$' # in input to double_quote_subst, that '$' was protected from expansion. # Since each input `\' is now two `\'s, look for any number of runs of # four `\'s followed by two `\'s and then a '$'. `\' that '$'. bs='\\' bs2='\\\\' bs4='\\\\\\\\' dollar='\$' sed_double_backslash="\ s/$bs4/&\\ /g s/^$bs2$dollar/$bs&/ s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g s/\n//g" # Standard options: opt_dry_run=false opt_help=false opt_quiet=false opt_verbose=false opt_warning=: # func_echo arg... # Echo program name prefixed message, along with the current mode # name if it has been set yet. func_echo () { $ECHO "$progname: ${opt_mode+$opt_mode: }$*" } # func_verbose arg... # Echo program name prefixed message in verbose mode only. func_verbose () { $opt_verbose && func_echo ${1+"$@"} # A bug in bash halts the script if the last line of a function # fails when set -e is in force, so we need another command to # work around that: : } # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "$*" } # func_error arg... # Echo program name prefixed message to standard error. func_error () { $ECHO "$progname: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2 } # func_warning arg... # Echo program name prefixed warning message to standard error. func_warning () { $opt_warning && $ECHO "$progname: ${opt_mode+$opt_mode: }warning: "${1+"$@"} 1>&2 # bash bug again: : } # func_fatal_error arg... # Echo program name prefixed message to standard error, and exit. func_fatal_error () { func_error ${1+"$@"} exit $EXIT_FAILURE } # func_fatal_help arg... # Echo program name prefixed message to standard error, followed by # a help hint, and exit. func_fatal_help () { func_error ${1+"$@"} func_fatal_error "$help" } help="Try \`$progname --help' for more information." ## default # func_grep expression filename # Check whether EXPRESSION matches any line of FILENAME, without output. func_grep () { $GREP "$1" "$2" >/dev/null 2>&1 } # func_mkdir_p directory-path # Make sure the entire path to DIRECTORY-PATH is available. func_mkdir_p () { my_directory_path="$1" my_dir_list= if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then # Protect directory names starting with `-' case $my_directory_path in -*) my_directory_path="./$my_directory_path" ;; esac # While some portion of DIR does not yet exist... while test ! -d "$my_directory_path"; do # ...make a list in topmost first order. Use a colon delimited # list incase some portion of path contains whitespace. my_dir_list="$my_directory_path:$my_dir_list" # If the last portion added has no slash in it, the list is done case $my_directory_path in */*) ;; *) break ;; esac # ...otherwise throw away the child directory and loop my_directory_path=`$ECHO "$my_directory_path" | $SED -e "$dirname"` done my_dir_list=`$ECHO "$my_dir_list" | $SED 's,:*$,,'` save_mkdir_p_IFS="$IFS"; IFS=':' for my_dir in $my_dir_list; do IFS="$save_mkdir_p_IFS" # mkdir can fail with a `File exist' error if two processes # try to create one of the directories concurrently. Don't # stop in that case! $MKDIR "$my_dir" 2>/dev/null || : done IFS="$save_mkdir_p_IFS" # Bail out if we (or some other process) failed to create a directory. test -d "$my_directory_path" || \ func_fatal_error "Failed to create \`$1'" fi } # func_mktempdir [string] # Make a temporary directory that won't clash with other running # libtool processes, and avoids race conditions if possible. If # given, STRING is the basename for that directory. func_mktempdir () { my_template="${TMPDIR-/tmp}/${1-$progname}" if test "$opt_dry_run" = ":"; then # Return a directory name, but don't create it in dry-run mode my_tmpdir="${my_template}-$$" else # If mktemp works, use that first and foremost my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null` if test ! -d "$my_tmpdir"; then # Failing that, at least try and use $RANDOM to avoid a race my_tmpdir="${my_template}-${RANDOM-0}$$" save_mktempdir_umask=`umask` umask 0077 $MKDIR "$my_tmpdir" umask $save_mktempdir_umask fi # If we're not in dry-run mode, bomb out on failure test -d "$my_tmpdir" || \ func_fatal_error "cannot create temporary directory \`$my_tmpdir'" fi $ECHO "$my_tmpdir" } # func_quote_for_eval arg # Aesthetically quote ARG to be evaled later. # This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT # is double-quoted, suitable for a subsequent eval, whereas # FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters # which are still active within double quotes backslashified. func_quote_for_eval () { case $1 in *[\\\`\"\$]*) func_quote_for_eval_unquoted_result=`$ECHO "$1" | $SED "$sed_quote_subst"` ;; *) func_quote_for_eval_unquoted_result="$1" ;; esac case $func_quote_for_eval_unquoted_result in # Double-quote args containing shell metacharacters to delay # word splitting, command substitution and and variable # expansion for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\"" ;; *) func_quote_for_eval_result="$func_quote_for_eval_unquoted_result" esac } # func_quote_for_expand arg # Aesthetically quote ARG to be evaled later; same as above, # but do not quote variable references. func_quote_for_expand () { case $1 in *[\\\`\"]*) my_arg=`$ECHO "$1" | $SED \ -e "$double_quote_subst" -e "$sed_double_backslash"` ;; *) my_arg="$1" ;; esac case $my_arg in # Double-quote args containing shell metacharacters to delay # word splitting and command substitution for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") my_arg="\"$my_arg\"" ;; esac func_quote_for_expand_result="$my_arg" } # func_show_eval cmd [fail_exp] # Unless opt_silent is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. func_show_eval () { my_cmd="$1" my_fail_exp="${2-:}" ${opt_silent-false} || { func_quote_for_expand "$my_cmd" eval "func_echo $func_quote_for_expand_result" } if ${opt_dry_run-false}; then :; else eval "$my_cmd" my_status=$? if test "$my_status" -eq 0; then :; else eval "(exit $my_status); $my_fail_exp" fi fi } # func_show_eval_locale cmd [fail_exp] # Unless opt_silent is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. Use the saved locale for evaluation. func_show_eval_locale () { my_cmd="$1" my_fail_exp="${2-:}" ${opt_silent-false} || { func_quote_for_expand "$my_cmd" eval "func_echo $func_quote_for_expand_result" } if ${opt_dry_run-false}; then :; else eval "$lt_user_locale $my_cmd" my_status=$? eval "$lt_safe_locale" if test "$my_status" -eq 0; then :; else eval "(exit $my_status); $my_fail_exp" fi fi } # func_tr_sh # Turn $1 into a string suitable for a shell variable name. # Result is stored in $func_tr_sh_result. All characters # not in the set a-zA-Z0-9_ are replaced with '_'. Further, # if $1 begins with a digit, a '_' is prepended as well. func_tr_sh () { case $1 in [0-9]* | *[!a-zA-Z0-9_]*) func_tr_sh_result=`$ECHO "$1" | $SED 's/^\([0-9]\)/_\1/; s/[^a-zA-Z0-9_]/_/g'` ;; * ) func_tr_sh_result=$1 ;; esac } # func_version # Echo version message to standard output and exit. func_version () { $opt_debug $SED -n '/(C)/!b go :more /\./!{ N s/\n# / / b more } :go /^# '$PROGRAM' (GNU /,/# warranty; / { s/^# // s/^# *$// s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/ p }' < "$progpath" exit $? } # func_usage # Echo short help message to standard output and exit. func_usage () { $opt_debug $SED -n '/^# Usage:/,/^# *.*--help/ { s/^# // s/^# *$// s/\$progname/'$progname'/ p }' < "$progpath" echo $ECHO "run \`$progname --help | more' for full usage" exit $? } # func_help [NOEXIT] # Echo long help message to standard output and exit, # unless 'noexit' is passed as argument. func_help () { $opt_debug $SED -n '/^# Usage:/,/# Report bugs to/ { :print s/^# // s/^# *$// s*\$progname*'$progname'* s*\$host*'"$host"'* s*\$SHELL*'"$SHELL"'* s*\$LTCC*'"$LTCC"'* s*\$LTCFLAGS*'"$LTCFLAGS"'* s*\$LD*'"$LD"'* s/\$with_gnu_ld/'"$with_gnu_ld"'/ s/\$automake_version/'"`(${AUTOMAKE-automake} --version) 2>/dev/null |$SED 1q`"'/ s/\$autoconf_version/'"`(${AUTOCONF-autoconf} --version) 2>/dev/null |$SED 1q`"'/ p d } /^# .* home page:/b print /^# General help using/b print ' < "$progpath" ret=$? if test -z "$1"; then exit $ret fi } # func_missing_arg argname # Echo program name prefixed message to standard error and set global # exit_cmd. func_missing_arg () { $opt_debug func_error "missing argument for $1." exit_cmd=exit } # func_split_short_opt shortopt # Set func_split_short_opt_name and func_split_short_opt_arg shell # variables after splitting SHORTOPT after the 2nd character. func_split_short_opt () { my_sed_short_opt='1s/^\(..\).*$/\1/;q' my_sed_short_rest='1s/^..\(.*\)$/\1/;q' func_split_short_opt_name=`$ECHO "$1" | $SED "$my_sed_short_opt"` func_split_short_opt_arg=`$ECHO "$1" | $SED "$my_sed_short_rest"` } # func_split_short_opt may be replaced by extended shell implementation # func_split_long_opt longopt # Set func_split_long_opt_name and func_split_long_opt_arg shell # variables after splitting LONGOPT at the `=' sign. func_split_long_opt () { my_sed_long_opt='1s/^\(--[^=]*\)=.*/\1/;q' my_sed_long_arg='1s/^--[^=]*=//' func_split_long_opt_name=`$ECHO "$1" | $SED "$my_sed_long_opt"` func_split_long_opt_arg=`$ECHO "$1" | $SED "$my_sed_long_arg"` } # func_split_long_opt may be replaced by extended shell implementation exit_cmd=: magic="%%%MAGIC variable%%%" magic_exe="%%%MAGIC EXE variable%%%" # Global variables. nonopt= preserve_args= lo2o="s/\\.lo\$/.${objext}/" o2lo="s/\\.${objext}\$/.lo/" extracted_archives= extracted_serial=0 # If this variable is set in any of the actions, the command in it # will be execed at the end. This prevents here-documents from being # left over by shells. exec_cmd= # func_append var value # Append VALUE to the end of shell variable VAR. func_append () { eval "${1}=\$${1}\${2}" } # func_append may be replaced by extended shell implementation # func_append_quoted var value # Quote VALUE and append to the end of shell variable VAR, separated # by a space. func_append_quoted () { func_quote_for_eval "${2}" eval "${1}=\$${1}\\ \$func_quote_for_eval_result" } # func_append_quoted may be replaced by extended shell implementation # func_arith arithmetic-term... func_arith () { func_arith_result=`expr "${@}"` } # func_arith may be replaced by extended shell implementation # func_len string # STRING may not start with a hyphen. func_len () { func_len_result=`expr "${1}" : ".*" 2>/dev/null || echo $max_cmd_len` } # func_len may be replaced by extended shell implementation # func_lo2o object func_lo2o () { func_lo2o_result=`$ECHO "${1}" | $SED "$lo2o"` } # func_lo2o may be replaced by extended shell implementation # func_xform libobj-or-source func_xform () { func_xform_result=`$ECHO "${1}" | $SED 's/\.[^.]*$/.lo/'` } # func_xform may be replaced by extended shell implementation # func_fatal_configuration arg... # Echo program name prefixed message to standard error, followed by # a configuration failure hint, and exit. func_fatal_configuration () { func_error ${1+"$@"} func_error "See the $PACKAGE documentation for more information." func_fatal_error "Fatal configuration error." } # func_config # Display the configuration for all the tags in this script. func_config () { re_begincf='^# ### BEGIN LIBTOOL' re_endcf='^# ### END LIBTOOL' # Default configuration. $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath" # Now print the configurations for the tags. for tagname in $taglist; do $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath" done exit $? } # func_features # Display the features supported by this script. func_features () { echo "host: $host" if test "$build_libtool_libs" = yes; then echo "enable shared libraries" else echo "disable shared libraries" fi if test "$build_old_libs" = yes; then echo "enable static libraries" else echo "disable static libraries" fi exit $? } # func_enable_tag tagname # Verify that TAGNAME is valid, and either flag an error and exit, or # enable the TAGNAME tag. We also add TAGNAME to the global $taglist # variable here. func_enable_tag () { # Global variable: tagname="$1" re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$" re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$" sed_extractcf="/$re_begincf/,/$re_endcf/p" # Validate tagname. case $tagname in *[!-_A-Za-z0-9,/]*) func_fatal_error "invalid tag name: $tagname" ;; esac # Don't test for the "default" C tag, as we know it's # there but not specially marked. case $tagname in CC) ;; *) if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then taglist="$taglist $tagname" # Evaluate the configuration. Be careful to quote the path # and the sed script, to avoid splitting on whitespace, but # also don't use non-portable quotes within backquotes within # quotes we have to do it in 2 steps: extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` eval "$extractedcf" else func_error "ignoring unknown tag $tagname" fi ;; esac } # func_check_version_match # Ensure that we are using m4 macros, and libtool script from the same # release of libtool. func_check_version_match () { if test "$package_revision" != "$macro_revision"; then if test "$VERSION" != "$macro_version"; then if test -z "$macro_version"; then cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from an older release. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from $PACKAGE $macro_version. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF fi else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, $progname: but the definition of this LT_INIT comes from revision $macro_revision. $progname: You should recreate aclocal.m4 with macros from revision $package_revision $progname: of $PACKAGE $VERSION and run autoconf again. _LT_EOF fi exit $EXIT_MISMATCH fi } # Shorthand for --mode=foo, only valid as the first argument case $1 in clean|clea|cle|cl) shift; set dummy --mode clean ${1+"$@"}; shift ;; compile|compil|compi|comp|com|co|c) shift; set dummy --mode compile ${1+"$@"}; shift ;; execute|execut|execu|exec|exe|ex|e) shift; set dummy --mode execute ${1+"$@"}; shift ;; finish|finis|fini|fin|fi|f) shift; set dummy --mode finish ${1+"$@"}; shift ;; install|instal|insta|inst|ins|in|i) shift; set dummy --mode install ${1+"$@"}; shift ;; link|lin|li|l) shift; set dummy --mode link ${1+"$@"}; shift ;; uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) shift; set dummy --mode uninstall ${1+"$@"}; shift ;; esac # Option defaults: opt_debug=: opt_dry_run=false opt_config=false opt_preserve_dup_deps=false opt_features=false opt_finish=false opt_help=false opt_help_all=false opt_silent=: opt_warning=: opt_verbose=: opt_silent=false opt_verbose=false # Parse options once, thoroughly. This comes as soon as possible in the # script to make things like `--version' happen as quickly as we can. { # this just eases exit handling while test $# -gt 0; do opt="$1" shift case $opt in --debug|-x) opt_debug='set -x' func_echo "enabling shell trace mode" $opt_debug ;; --dry-run|--dryrun|-n) opt_dry_run=: ;; --config) opt_config=: func_config ;; --dlopen|-dlopen) optarg="$1" opt_dlopen="${opt_dlopen+$opt_dlopen }$optarg" shift ;; --preserve-dup-deps) opt_preserve_dup_deps=: ;; --features) opt_features=: func_features ;; --finish) opt_finish=: set dummy --mode finish ${1+"$@"}; shift ;; --help) opt_help=: ;; --help-all) opt_help_all=: opt_help=': help-all' ;; --mode) test $# = 0 && func_missing_arg $opt && break optarg="$1" opt_mode="$optarg" case $optarg in # Valid mode arguments: clean|compile|execute|finish|install|link|relink|uninstall) ;; # Catch anything else as an error *) func_error "invalid argument for $opt" exit_cmd=exit break ;; esac shift ;; --no-silent|--no-quiet) opt_silent=false func_append preserve_args " $opt" ;; --no-warning|--no-warn) opt_warning=false func_append preserve_args " $opt" ;; --no-verbose) opt_verbose=false func_append preserve_args " $opt" ;; --silent|--quiet) opt_silent=: func_append preserve_args " $opt" opt_verbose=false ;; --verbose|-v) opt_verbose=: func_append preserve_args " $opt" opt_silent=false ;; --tag) test $# = 0 && func_missing_arg $opt && break optarg="$1" opt_tag="$optarg" func_append preserve_args " $opt $optarg" func_enable_tag "$optarg" shift ;; -\?|-h) func_usage ;; --help) func_help ;; --version) func_version ;; # Separate optargs to long options: --*=*) func_split_long_opt "$opt" set dummy "$func_split_long_opt_name" "$func_split_long_opt_arg" ${1+"$@"} shift ;; # Separate non-argument short options: -\?*|-h*|-n*|-v*) func_split_short_opt "$opt" set dummy "$func_split_short_opt_name" "-$func_split_short_opt_arg" ${1+"$@"} shift ;; --) break ;; -*) func_fatal_help "unrecognized option \`$opt'" ;; *) set dummy "$opt" ${1+"$@"}; shift; break ;; esac done # Validate options: # save first non-option argument if test "$#" -gt 0; then nonopt="$opt" shift fi # preserve --debug test "$opt_debug" = : || func_append preserve_args " --debug" case $host in *cygwin* | *mingw* | *pw32* | *cegcc*) # don't eliminate duplications in $postdeps and $predeps opt_duplicate_compiler_generated_deps=: ;; *) opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps ;; esac $opt_help || { # Sanity checks first: func_check_version_match if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then func_fatal_configuration "not configured to build any kind of library" fi # Darwin sucks eval std_shrext=\"$shrext_cmds\" # Only execute mode is allowed to have -dlopen flags. if test -n "$opt_dlopen" && test "$opt_mode" != execute; then func_error "unrecognized option \`-dlopen'" $ECHO "$help" 1>&2 exit $EXIT_FAILURE fi # Change the help message to a mode-specific one. generic_help="$help" help="Try \`$progname --help --mode=$opt_mode' for more information." } # Bail if the options were screwed $exit_cmd $EXIT_FAILURE } ## ----------- ## ## Main. ## ## ----------- ## # func_lalib_p file # True iff FILE is a libtool `.la' library or `.lo' object file. # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_lalib_p () { test -f "$1" && $SED -e 4q "$1" 2>/dev/null \ | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 } # func_lalib_unsafe_p file # True iff FILE is a libtool `.la' library or `.lo' object file. # This function implements the same check as func_lalib_p without # resorting to external programs. To this end, it redirects stdin and # closes it afterwards, without saving the original file descriptor. # As a safety measure, use it only where a negative result would be # fatal anyway. Works if `file' does not exist. func_lalib_unsafe_p () { lalib_p=no if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then for lalib_p_l in 1 2 3 4 do read lalib_p_line case "$lalib_p_line" in \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; esac done exec 0<&5 5<&- fi test "$lalib_p" = yes } # func_ltwrapper_script_p file # True iff FILE is a libtool wrapper script # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_script_p () { func_lalib_p "$1" } # func_ltwrapper_executable_p file # True iff FILE is a libtool wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_executable_p () { func_ltwrapper_exec_suffix= case $1 in *.exe) ;; *) func_ltwrapper_exec_suffix=.exe ;; esac $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 } # func_ltwrapper_scriptname file # Assumes file is an ltwrapper_executable # uses $file to determine the appropriate filename for a # temporary ltwrapper_script. func_ltwrapper_scriptname () { func_dirname_and_basename "$1" "" "." func_stripname '' '.exe' "$func_basename_result" func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper" } # func_ltwrapper_p file # True iff FILE is a libtool wrapper script or wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_p () { func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" } # func_execute_cmds commands fail_cmd # Execute tilde-delimited COMMANDS. # If FAIL_CMD is given, eval that upon failure. # FAIL_CMD may read-access the current command in variable CMD! func_execute_cmds () { $opt_debug save_ifs=$IFS; IFS='~' for cmd in $1; do IFS=$save_ifs eval cmd=\"$cmd\" func_show_eval "$cmd" "${2-:}" done IFS=$save_ifs } # func_source file # Source FILE, adding directory component if necessary. # Note that it is not necessary on cygwin/mingw to append a dot to # FILE even if both FILE and FILE.exe exist: automatic-append-.exe # behavior happens only for exec(3), not for open(2)! Also, sourcing # `FILE.' does not work on cygwin managed mounts. func_source () { $opt_debug case $1 in */* | *\\*) . "$1" ;; *) . "./$1" ;; esac } # func_resolve_sysroot PATH # Replace a leading = in PATH with a sysroot. Store the result into # func_resolve_sysroot_result func_resolve_sysroot () { func_resolve_sysroot_result=$1 case $func_resolve_sysroot_result in =*) func_stripname '=' '' "$func_resolve_sysroot_result" func_resolve_sysroot_result=$lt_sysroot$func_stripname_result ;; esac } # func_replace_sysroot PATH # If PATH begins with the sysroot, replace it with = and # store the result into func_replace_sysroot_result. func_replace_sysroot () { case "$lt_sysroot:$1" in ?*:"$lt_sysroot"*) func_stripname "$lt_sysroot" '' "$1" func_replace_sysroot_result="=$func_stripname_result" ;; *) # Including no sysroot. func_replace_sysroot_result=$1 ;; esac } # func_infer_tag arg # Infer tagged configuration to use if any are available and # if one wasn't chosen via the "--tag" command line option. # Only attempt this if the compiler in the base compile # command doesn't match the default compiler. # arg is usually of the form 'gcc ...' func_infer_tag () { $opt_debug if test -n "$available_tags" && test -z "$tagname"; then CC_quoted= for arg in $CC; do func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case $@ in # Blanks in the command may have been stripped by the calling shell, # but not from the CC environment variable when configure was run. " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;; # Blanks at the start of $base_compile will cause this to fail # if we don't check for them as well. *) for z in $available_tags; do if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then # Evaluate the configuration. eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" CC_quoted= for arg in $CC; do # Double-quote args containing other shell metacharacters. func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case "$@ " in " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) # The compiler in the base compile command matches # the one in the tagged configuration. # Assume this is the tagged configuration we want. tagname=$z break ;; esac fi done # If $tagname still isn't set, then no tagged configuration # was found and let the user know that the "--tag" command # line option must be used. if test -z "$tagname"; then func_echo "unable to infer tagged configuration" func_fatal_error "specify a tag with \`--tag'" # else # func_verbose "using $tagname tagged configuration" fi ;; esac fi } # func_write_libtool_object output_name pic_name nonpic_name # Create a libtool object file (analogous to a ".la" file), # but don't create it if we're doing a dry run. func_write_libtool_object () { write_libobj=${1} if test "$build_libtool_libs" = yes; then write_lobj=\'${2}\' else write_lobj=none fi if test "$build_old_libs" = yes; then write_oldobj=\'${3}\' else write_oldobj=none fi $opt_dry_run || { cat >${write_libobj}T </dev/null` if test "$?" -eq 0 && test -n "${func_convert_core_file_wine_to_w32_tmp}"; then func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" | $SED -e "$lt_sed_naive_backslashify"` else func_convert_core_file_wine_to_w32_result= fi fi } # end: func_convert_core_file_wine_to_w32 # func_convert_core_path_wine_to_w32 ARG # Helper function used by path conversion functions when $build is *nix, and # $host is mingw, cygwin, or some other w32 environment. Relies on a correctly # configured wine environment available, with the winepath program in $build's # $PATH. Assumes ARG has no leading or trailing path separator characters. # # ARG is path to be converted from $build format to win32. # Result is available in $func_convert_core_path_wine_to_w32_result. # Unconvertible file (directory) names in ARG are skipped; if no directory names # are convertible, then the result may be empty. func_convert_core_path_wine_to_w32 () { $opt_debug # unfortunately, winepath doesn't convert paths, only file names func_convert_core_path_wine_to_w32_result="" if test -n "$1"; then oldIFS=$IFS IFS=: for func_convert_core_path_wine_to_w32_f in $1; do IFS=$oldIFS func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f" if test -n "$func_convert_core_file_wine_to_w32_result" ; then if test -z "$func_convert_core_path_wine_to_w32_result"; then func_convert_core_path_wine_to_w32_result="$func_convert_core_file_wine_to_w32_result" else func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result" fi fi done IFS=$oldIFS fi } # end: func_convert_core_path_wine_to_w32 # func_cygpath ARGS... # Wrapper around calling the cygpath program via LT_CYGPATH. This is used when # when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2) # $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or # (2), returns the Cygwin file name or path in func_cygpath_result (input # file name or path is assumed to be in w32 format, as previously converted # from $build's *nix or MSYS format). In case (3), returns the w32 file name # or path in func_cygpath_result (input file name or path is assumed to be in # Cygwin format). Returns an empty string on error. # # ARGS are passed to cygpath, with the last one being the file name or path to # be converted. # # Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH # environment variable; do not put it in $PATH. func_cygpath () { $opt_debug if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null` if test "$?" -ne 0; then # on failure, ensure result is empty func_cygpath_result= fi else func_cygpath_result= func_error "LT_CYGPATH is empty or specifies non-existent file: \`$LT_CYGPATH'" fi } #end: func_cygpath # func_convert_core_msys_to_w32 ARG # Convert file name or path ARG from MSYS format to w32 format. Return # result in func_convert_core_msys_to_w32_result. func_convert_core_msys_to_w32 () { $opt_debug # awkward: cmd appends spaces to result func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null | $SED -e 's/[ ]*$//' -e "$lt_sed_naive_backslashify"` } #end: func_convert_core_msys_to_w32 # func_convert_file_check ARG1 ARG2 # Verify that ARG1 (a file name in $build format) was converted to $host # format in ARG2. Otherwise, emit an error message, but continue (resetting # func_to_host_file_result to ARG1). func_convert_file_check () { $opt_debug if test -z "$2" && test -n "$1" ; then func_error "Could not determine host file name corresponding to" func_error " \`$1'" func_error "Continuing, but uninstalled executables may not work." # Fallback: func_to_host_file_result="$1" fi } # end func_convert_file_check # func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH # Verify that FROM_PATH (a path in $build format) was converted to $host # format in TO_PATH. Otherwise, emit an error message, but continue, resetting # func_to_host_file_result to a simplistic fallback value (see below). func_convert_path_check () { $opt_debug if test -z "$4" && test -n "$3"; then func_error "Could not determine the host path corresponding to" func_error " \`$3'" func_error "Continuing, but uninstalled executables may not work." # Fallback. This is a deliberately simplistic "conversion" and # should not be "improved". See libtool.info. if test "x$1" != "x$2"; then lt_replace_pathsep_chars="s|$1|$2|g" func_to_host_path_result=`echo "$3" | $SED -e "$lt_replace_pathsep_chars"` else func_to_host_path_result="$3" fi fi } # end func_convert_path_check # func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG # Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT # and appending REPL if ORIG matches BACKPAT. func_convert_path_front_back_pathsep () { $opt_debug case $4 in $1 ) func_to_host_path_result="$3$func_to_host_path_result" ;; esac case $4 in $2 ) func_append func_to_host_path_result "$3" ;; esac } # end func_convert_path_front_back_pathsep ################################################## # $build to $host FILE NAME CONVERSION FUNCTIONS # ################################################## # invoked via `$to_host_file_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # Result will be available in $func_to_host_file_result. # func_to_host_file ARG # Converts the file name ARG from $build format to $host format. Return result # in func_to_host_file_result. func_to_host_file () { $opt_debug $to_host_file_cmd "$1" } # end func_to_host_file # func_to_tool_file ARG LAZY # converts the file name ARG from $build format to toolchain format. Return # result in func_to_tool_file_result. If the conversion in use is listed # in (the comma separated) LAZY, no conversion takes place. func_to_tool_file () { $opt_debug case ,$2, in *,"$to_tool_file_cmd",*) func_to_tool_file_result=$1 ;; *) $to_tool_file_cmd "$1" func_to_tool_file_result=$func_to_host_file_result ;; esac } # end func_to_tool_file # func_convert_file_noop ARG # Copy ARG to func_to_host_file_result. func_convert_file_noop () { func_to_host_file_result="$1" } # end func_convert_file_noop # func_convert_file_msys_to_w32 ARG # Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_file_result. func_convert_file_msys_to_w32 () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_to_host_file_result="$func_convert_core_msys_to_w32_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_w32 # func_convert_file_cygwin_to_w32 ARG # Convert file name ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_file_cygwin_to_w32 () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then # because $build is cygwin, we call "the" cygpath in $PATH; no need to use # LT_CYGPATH in this case. func_to_host_file_result=`cygpath -m "$1"` fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_cygwin_to_w32 # func_convert_file_nix_to_w32 ARG # Convert file name ARG from *nix to w32 format. Requires a wine environment # and a working winepath. Returns result in func_to_host_file_result. func_convert_file_nix_to_w32 () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then func_convert_core_file_wine_to_w32 "$1" func_to_host_file_result="$func_convert_core_file_wine_to_w32_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_w32 # func_convert_file_msys_to_cygwin ARG # Convert file name ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_file_msys_to_cygwin () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_cygpath -u "$func_convert_core_msys_to_w32_result" func_to_host_file_result="$func_cygpath_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_cygwin # func_convert_file_nix_to_cygwin ARG # Convert file name ARG from *nix to Cygwin format. Requires Cygwin installed # in a wine environment, working winepath, and LT_CYGPATH set. Returns result # in func_to_host_file_result. func_convert_file_nix_to_cygwin () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then # convert from *nix to w32, then use cygpath to convert from w32 to cygwin. func_convert_core_file_wine_to_w32 "$1" func_cygpath -u "$func_convert_core_file_wine_to_w32_result" func_to_host_file_result="$func_cygpath_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_cygwin ############################################# # $build to $host PATH CONVERSION FUNCTIONS # ############################################# # invoked via `$to_host_path_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # The result will be available in $func_to_host_path_result. # # Path separators are also converted from $build format to $host format. If # ARG begins or ends with a path separator character, it is preserved (but # converted to $host format) on output. # # All path conversion functions are named using the following convention: # file name conversion function : func_convert_file_X_to_Y () # path conversion function : func_convert_path_X_to_Y () # where, for any given $build/$host combination the 'X_to_Y' value is the # same. If conversion functions are added for new $build/$host combinations, # the two new functions must follow this pattern, or func_init_to_host_path_cmd # will break. # func_init_to_host_path_cmd # Ensures that function "pointer" variable $to_host_path_cmd is set to the # appropriate value, based on the value of $to_host_file_cmd. to_host_path_cmd= func_init_to_host_path_cmd () { $opt_debug if test -z "$to_host_path_cmd"; then func_stripname 'func_convert_file_' '' "$to_host_file_cmd" to_host_path_cmd="func_convert_path_${func_stripname_result}" fi } # func_to_host_path ARG # Converts the path ARG from $build format to $host format. Return result # in func_to_host_path_result. func_to_host_path () { $opt_debug func_init_to_host_path_cmd $to_host_path_cmd "$1" } # end func_to_host_path # func_convert_path_noop ARG # Copy ARG to func_to_host_path_result. func_convert_path_noop () { func_to_host_path_result="$1" } # end func_convert_path_noop # func_convert_path_msys_to_w32 ARG # Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_path_result. func_convert_path_msys_to_w32 () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # Remove leading and trailing path separator characters from ARG. MSYS # behavior is inconsistent here; cygpath turns them into '.;' and ';.'; # and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result="$func_convert_core_msys_to_w32_result" func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_msys_to_w32 # func_convert_path_cygwin_to_w32 ARG # Convert path ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_path_cygwin_to_w32 () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"` func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_cygwin_to_w32 # func_convert_path_nix_to_w32 ARG # Convert path ARG from *nix to w32 format. Requires a wine environment and # a working winepath. Returns result in func_to_host_file_result. func_convert_path_nix_to_w32 () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result="$func_convert_core_path_wine_to_w32_result" func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_nix_to_w32 # func_convert_path_msys_to_cygwin ARG # Convert path ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_path_msys_to_cygwin () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_msys_to_w32_result" func_to_host_path_result="$func_cygpath_result" func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_msys_to_cygwin # func_convert_path_nix_to_cygwin ARG # Convert path ARG from *nix to Cygwin format. Requires Cygwin installed in a # a wine environment, working winepath, and LT_CYGPATH set. Returns result in # func_to_host_file_result. func_convert_path_nix_to_cygwin () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # Remove leading and trailing path separator characters from # ARG. msys behavior is inconsistent here, cygpath turns them # into '.;' and ';.', and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result" func_to_host_path_result="$func_cygpath_result" func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_nix_to_cygwin # func_mode_compile arg... func_mode_compile () { $opt_debug # Get the compilation command and the source file. base_compile= srcfile="$nonopt" # always keep a non-empty value in "srcfile" suppress_opt=yes suppress_output= arg_mode=normal libobj= later= pie_flag= for arg do case $arg_mode in arg ) # do not "continue". Instead, add this to base_compile lastarg="$arg" arg_mode=normal ;; target ) libobj="$arg" arg_mode=normal continue ;; normal ) # Accept any command-line options. case $arg in -o) test -n "$libobj" && \ func_fatal_error "you cannot specify \`-o' more than once" arg_mode=target continue ;; -pie | -fpie | -fPIE) func_append pie_flag " $arg" continue ;; -shared | -static | -prefer-pic | -prefer-non-pic) func_append later " $arg" continue ;; -no-suppress) suppress_opt=no continue ;; -Xcompiler) arg_mode=arg # the next one goes into the "base_compile" arg list continue # The current "srcfile" will either be retained or ;; # replaced later. I would guess that would be a bug. -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result lastarg= save_ifs="$IFS"; IFS=',' for arg in $args; do IFS="$save_ifs" func_append_quoted lastarg "$arg" done IFS="$save_ifs" func_stripname ' ' '' "$lastarg" lastarg=$func_stripname_result # Add the arguments to base_compile. func_append base_compile " $lastarg" continue ;; *) # Accept the current argument as the source file. # The previous "srcfile" becomes the current argument. # lastarg="$srcfile" srcfile="$arg" ;; esac # case $arg ;; esac # case $arg_mode # Aesthetically quote the previous argument. func_append_quoted base_compile "$lastarg" done # for arg case $arg_mode in arg) func_fatal_error "you must specify an argument for -Xcompile" ;; target) func_fatal_error "you must specify a target with \`-o'" ;; *) # Get the name of the library object. test -z "$libobj" && { func_basename "$srcfile" libobj="$func_basename_result" } ;; esac # Recognize several different file suffixes. # If the user specifies -o file.o, it is replaced with file.lo case $libobj in *.[cCFSifmso] | \ *.ada | *.adb | *.ads | *.asm | \ *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \ *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup) func_xform "$libobj" libobj=$func_xform_result ;; esac case $libobj in *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;; *) func_fatal_error "cannot determine name of library object from \`$libobj'" ;; esac func_infer_tag $base_compile for arg in $later; do case $arg in -shared) test "$build_libtool_libs" != yes && \ func_fatal_configuration "can not build a shared library" build_old_libs=no continue ;; -static) build_libtool_libs=no build_old_libs=yes continue ;; -prefer-pic) pic_mode=yes continue ;; -prefer-non-pic) pic_mode=no continue ;; esac done func_quote_for_eval "$libobj" test "X$libobj" != "X$func_quote_for_eval_result" \ && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"' &()|`$[]' \ && func_warning "libobj name \`$libobj' may not contain shell special characters." func_dirname_and_basename "$obj" "/" "" objname="$func_basename_result" xdir="$func_dirname_result" lobj=${xdir}$objdir/$objname test -z "$base_compile" && \ func_fatal_help "you must specify a compilation command" # Delete any leftover library objects. if test "$build_old_libs" = yes; then removelist="$obj $lobj $libobj ${libobj}T" else removelist="$lobj $libobj ${libobj}T" fi # On Cygwin there's no "real" PIC flag so we must build both object types case $host_os in cygwin* | mingw* | pw32* | os2* | cegcc*) pic_mode=default ;; esac if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then # non-PIC code in shared libraries is not supported pic_mode=default fi # Calculate the filename of the output object if compiler does # not support -o with -c if test "$compiler_c_o" = no; then output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.${objext} lockfile="$output_obj.lock" else output_obj= need_locks=no lockfile= fi # Lock this critical section if it is needed # We use this script file to make the link, it avoids creating a new file if test "$need_locks" = yes; then until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done elif test "$need_locks" = warn; then if test -f "$lockfile"; then $ECHO "\ *** ERROR, $lockfile exists and contains: `cat $lockfile 2>/dev/null` This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi func_append removelist " $output_obj" $ECHO "$srcfile" > "$lockfile" fi $opt_dry_run || $RM $removelist func_append removelist " $lockfile" trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 func_to_tool_file "$srcfile" func_convert_file_msys_to_w32 srcfile=$func_to_tool_file_result func_quote_for_eval "$srcfile" qsrcfile=$func_quote_for_eval_result # Only build a PIC object if we are building libtool libraries. if test "$build_libtool_libs" = yes; then # Without this assignment, base_compile gets emptied. fbsd_hideous_sh_bug=$base_compile if test "$pic_mode" != no; then command="$base_compile $qsrcfile $pic_flag" else # Don't build PIC code command="$base_compile $qsrcfile" fi func_mkdir_p "$xdir$objdir" if test -z "$output_obj"; then # Place PIC objects in $objdir func_append command " -o $lobj" fi func_show_eval_locale "$command" \ 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' if test "$need_locks" = warn && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed, then go on to compile the next one if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then func_show_eval '$MV "$output_obj" "$lobj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi # Allow error messages only from the first compilation. if test "$suppress_opt" = yes; then suppress_output=' >/dev/null 2>&1' fi fi # Only build a position-dependent object if we build old libraries. if test "$build_old_libs" = yes; then if test "$pic_mode" != yes; then # Don't build PIC code command="$base_compile $qsrcfile$pie_flag" else command="$base_compile $qsrcfile $pic_flag" fi if test "$compiler_c_o" = yes; then func_append command " -o $obj" fi # Suppress compiler output if we already did a PIC compilation. func_append command "$suppress_output" func_show_eval_locale "$command" \ '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' if test "$need_locks" = warn && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then func_show_eval '$MV "$output_obj" "$obj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi fi $opt_dry_run || { func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" # Unlock the critical section if it was locked if test "$need_locks" != no; then removelist=$lockfile $RM "$lockfile" fi } exit $EXIT_SUCCESS } $opt_help || { test "$opt_mode" = compile && func_mode_compile ${1+"$@"} } func_mode_help () { # We need to display help for each of the modes. case $opt_mode in "") # Generic help is extracted from the usage comments # at the start of this file. func_help ;; clean) $ECHO \ "Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... Remove files from the build directory. RM is the name of the program to use to delete files associated with each FILE (typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed to RM. If FILE is a libtool library, object or program, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; compile) $ECHO \ "Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE Compile a source file into a libtool library object. This mode accepts the following additional options: -o OUTPUT-FILE set the output file name to OUTPUT-FILE -no-suppress do not suppress compiler output for multiple passes -prefer-pic try to build PIC objects only -prefer-non-pic try to build non-PIC objects only -shared do not build a \`.o' file suitable for static linking -static only build a \`.o' file suitable for static linking -Wc,FLAG pass FLAG directly to the compiler COMPILE-COMMAND is a command to be used in creating a \`standard' object file from the given SOURCEFILE. The output file name is determined by removing the directory component from SOURCEFILE, then substituting the C source code suffix \`.c' with the library object suffix, \`.lo'." ;; execute) $ECHO \ "Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... Automatically set library path, then run a program. This mode accepts the following additional options: -dlopen FILE add the directory containing FILE to the library path This mode sets the library path environment variable according to \`-dlopen' flags. If any of the ARGS are libtool executable wrappers, then they are translated into their corresponding uninstalled binary, and any of their required library directories are added to the library path. Then, COMMAND is executed, with ARGS as arguments." ;; finish) $ECHO \ "Usage: $progname [OPTION]... --mode=finish [LIBDIR]... Complete the installation of libtool libraries. Each LIBDIR is a directory that contains libtool libraries. The commands that this mode executes may require superuser privileges. Use the \`--dry-run' option if you just want to see what would be executed." ;; install) $ECHO \ "Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... Install executables or libraries. INSTALL-COMMAND is the installation command. The first component should be either the \`install' or \`cp' program. The following components of INSTALL-COMMAND are treated specially: -inst-prefix-dir PREFIX-DIR Use PREFIX-DIR as a staging area for installation The rest of the components are interpreted as arguments to that command (only BSD-compatible install options are recognized)." ;; link) $ECHO \ "Usage: $progname [OPTION]... --mode=link LINK-COMMAND... Link object files or libraries together to form another library, or to create an executable program. LINK-COMMAND is a command using the C compiler that you would use to create a program from several object files. The following components of LINK-COMMAND are treated specially: -all-static do not do any dynamic linking at all -avoid-version do not add a version suffix if possible -bindir BINDIR specify path to binaries directory (for systems where libraries must be found in the PATH setting at runtime) -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) -export-symbols SYMFILE try to export only the symbols listed in SYMFILE -export-symbols-regex REGEX try to export only the symbols matching REGEX -LLIBDIR search LIBDIR for required installed libraries -lNAME OUTPUT-FILE requires the installed library libNAME -module build a library that can dlopened -no-fast-install disable the fast-install mode -no-install link a not-installable executable -no-undefined declare that a library does not refer to external symbols -o OUTPUT-FILE create OUTPUT-FILE from the specified objects -objectlist FILE Use a list of object files found in FILE to specify objects -precious-files-regex REGEX don't remove output files matching REGEX -release RELEASE specify package release information -rpath LIBDIR the created library will eventually be installed in LIBDIR -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries -shared only do dynamic linking of libtool libraries -shrext SUFFIX override the standard shared library file extension -static do not do any dynamic linking of uninstalled libtool libraries -static-libtool-libs do not do any dynamic linking of libtool libraries -version-info CURRENT[:REVISION[:AGE]] specify library version info [each variable defaults to 0] -weak LIBNAME declare that the target provides the LIBNAME interface -Wc,FLAG -Xcompiler FLAG pass linker-specific FLAG directly to the compiler -Wl,FLAG -Xlinker FLAG pass linker-specific FLAG directly to the linker -XCClinker FLAG pass link-specific FLAG to the compiler driver (CC) All other options (arguments beginning with \`-') are ignored. Every other argument is treated as a filename. Files ending in \`.la' are treated as uninstalled libtool libraries, other files are standard or library object files. If the OUTPUT-FILE ends in \`.la', then a libtool library is created, only library objects (\`.lo' files) may be specified, and \`-rpath' is required, except when creating a convenience library. If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created using \`ar' and \`ranlib', or on Windows using \`lib'. If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file is created, otherwise an executable program is created." ;; uninstall) $ECHO \ "Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... Remove libraries from an installation directory. RM is the name of the program to use to delete files associated with each FILE (typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed to RM. If FILE is a libtool library, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; *) func_fatal_help "invalid operation mode \`$opt_mode'" ;; esac echo $ECHO "Try \`$progname --help' for more information about other modes." } # Now that we've collected a possible --mode arg, show help if necessary if $opt_help; then if test "$opt_help" = :; then func_mode_help else { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do func_mode_help done } | sed -n '1p; 2,$s/^Usage:/ or: /p' { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do echo func_mode_help done } | sed '1d /^When reporting/,/^Report/{ H d } $x /information about other modes/d /more detailed .*MODE/d s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/' fi exit $? fi # func_mode_execute arg... func_mode_execute () { $opt_debug # The first argument is the command name. cmd="$nonopt" test -z "$cmd" && \ func_fatal_help "you must specify a COMMAND" # Handle -dlopen flags immediately. for file in $opt_dlopen; do test -f "$file" \ || func_fatal_help "\`$file' is not a file" dir= case $file in *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "\`$lib' is not a valid libtool archive" # Read the libtool library. dlname= library_names= func_source "$file" # Skip this library if it cannot be dlopened. if test -z "$dlname"; then # Warn if it was a shared library. test -n "$library_names" && \ func_warning "\`$file' was not linked with \`-export-dynamic'" continue fi func_dirname "$file" "" "." dir="$func_dirname_result" if test -f "$dir/$objdir/$dlname"; then func_append dir "/$objdir" else if test ! -f "$dir/$dlname"; then func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" fi fi ;; *.lo) # Just add the directory containing the .lo file. func_dirname "$file" "" "." dir="$func_dirname_result" ;; *) func_warning "\`-dlopen' is ignored for non-libtool libraries and objects" continue ;; esac # Get the absolute pathname. absdir=`cd "$dir" && pwd` test -n "$absdir" && dir="$absdir" # Now add the directory to shlibpath_var. if eval "test -z \"\$$shlibpath_var\""; then eval "$shlibpath_var=\"\$dir\"" else eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" fi done # This variable tells wrapper scripts just to set shlibpath_var # rather than running their programs. libtool_execute_magic="$magic" # Check if any of the arguments is a wrapper script. args= for file do case $file in -* | *.la | *.lo ) ;; *) # Do a test to see if this is really a libtool program. if func_ltwrapper_script_p "$file"; then func_source "$file" # Transform arg to wrapped name. file="$progdir/$program" elif func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" func_source "$func_ltwrapper_scriptname_result" # Transform arg to wrapped name. file="$progdir/$program" fi ;; esac # Quote arguments (to preserve shell metacharacters). func_append_quoted args "$file" done if test "X$opt_dry_run" = Xfalse; then if test -n "$shlibpath_var"; then # Export the shlibpath_var. eval "export $shlibpath_var" fi # Restore saved environment variables for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${save_$lt_var+set}\" = set; then $lt_var=\$save_$lt_var; export $lt_var else $lt_unset $lt_var fi" done # Now prepare to actually exec the command. exec_cmd="\$cmd$args" else # Display what would be done. if test -n "$shlibpath_var"; then eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" echo "export $shlibpath_var" fi $ECHO "$cmd$args" exit $EXIT_SUCCESS fi } test "$opt_mode" = execute && func_mode_execute ${1+"$@"} # func_mode_finish arg... func_mode_finish () { $opt_debug libs= libdirs= admincmds= for opt in "$nonopt" ${1+"$@"} do if test -d "$opt"; then func_append libdirs " $opt" elif test -f "$opt"; then if func_lalib_unsafe_p "$opt"; then func_append libs " $opt" else func_warning "\`$opt' is not a valid libtool archive" fi else func_fatal_error "invalid argument \`$opt'" fi done if test -n "$libs"; then if test -n "$lt_sysroot"; then sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"` sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;" else sysroot_cmd= fi # Remove sysroot references if $opt_dry_run; then for lib in $libs; do echo "removing references to $lt_sysroot and \`=' prefixes from $lib" done else tmpdir=`func_mktempdir` for lib in $libs; do sed -e "${sysroot_cmd} s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \ > $tmpdir/tmp-la mv -f $tmpdir/tmp-la $lib done ${RM}r "$tmpdir" fi fi if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then for libdir in $libdirs; do if test -n "$finish_cmds"; then # Do each command in the finish commands. func_execute_cmds "$finish_cmds" 'admincmds="$admincmds '"$cmd"'"' fi if test -n "$finish_eval"; then # Do the single finish_eval. eval cmds=\"$finish_eval\" $opt_dry_run || eval "$cmds" || func_append admincmds " $cmds" fi done fi # Exit here if they wanted silent mode. $opt_silent && exit $EXIT_SUCCESS if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then echo "----------------------------------------------------------------------" echo "Libraries have been installed in:" for libdir in $libdirs; do $ECHO " $libdir" done echo echo "If you ever happen to want to link against installed libraries" echo "in a given directory, LIBDIR, you must either use libtool, and" echo "specify the full pathname of the library, or use the \`-LLIBDIR'" echo "flag during linking and do at least one of the following:" if test -n "$shlibpath_var"; then echo " - add LIBDIR to the \`$shlibpath_var' environment variable" echo " during execution" fi if test -n "$runpath_var"; then echo " - add LIBDIR to the \`$runpath_var' environment variable" echo " during linking" fi if test -n "$hardcode_libdir_flag_spec"; then libdir=LIBDIR eval flag=\"$hardcode_libdir_flag_spec\" $ECHO " - use the \`$flag' linker flag" fi if test -n "$admincmds"; then $ECHO " - have your system administrator run these commands:$admincmds" fi if test -f /etc/ld.so.conf; then echo " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'" fi echo echo "See any operating system documentation about shared libraries for" case $host in solaris2.[6789]|solaris2.1[0-9]) echo "more information, such as the ld(1), crle(1) and ld.so(8) manual" echo "pages." ;; *) echo "more information, such as the ld(1) and ld.so(8) manual pages." ;; esac echo "----------------------------------------------------------------------" fi exit $EXIT_SUCCESS } test "$opt_mode" = finish && func_mode_finish ${1+"$@"} # func_mode_install arg... func_mode_install () { $opt_debug # There may be an optional sh(1) argument at the beginning of # install_prog (especially on Windows NT). if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh || # Allow the use of GNU shtool's install command. case $nonopt in *shtool*) :;; *) false;; esac; then # Aesthetically quote it. func_quote_for_eval "$nonopt" install_prog="$func_quote_for_eval_result " arg=$1 shift else install_prog= arg=$nonopt fi # The real first argument should be the name of the installation program. # Aesthetically quote it. func_quote_for_eval "$arg" func_append install_prog "$func_quote_for_eval_result" install_shared_prog=$install_prog case " $install_prog " in *[\\\ /]cp\ *) install_cp=: ;; *) install_cp=false ;; esac # We need to accept at least all the BSD install flags. dest= files= opts= prev= install_type= isdir=no stripme= no_mode=: for arg do arg2= if test -n "$dest"; then func_append files " $dest" dest=$arg continue fi case $arg in -d) isdir=yes ;; -f) if $install_cp; then :; else prev=$arg fi ;; -g | -m | -o) prev=$arg ;; -s) stripme=" -s" continue ;; -*) ;; *) # If the previous option needed an argument, then skip it. if test -n "$prev"; then if test "x$prev" = x-m && test -n "$install_override_mode"; then arg2=$install_override_mode no_mode=false fi prev= else dest=$arg continue fi ;; esac # Aesthetically quote the argument. func_quote_for_eval "$arg" func_append install_prog " $func_quote_for_eval_result" if test -n "$arg2"; then func_quote_for_eval "$arg2" fi func_append install_shared_prog " $func_quote_for_eval_result" done test -z "$install_prog" && \ func_fatal_help "you must specify an install program" test -n "$prev" && \ func_fatal_help "the \`$prev' option requires an argument" if test -n "$install_override_mode" && $no_mode; then if $install_cp; then :; else func_quote_for_eval "$install_override_mode" func_append install_shared_prog " -m $func_quote_for_eval_result" fi fi if test -z "$files"; then if test -z "$dest"; then func_fatal_help "no file or destination specified" else func_fatal_help "you must specify a destination" fi fi # Strip any trailing slash from the destination. func_stripname '' '/' "$dest" dest=$func_stripname_result # Check to see that the destination is a directory. test -d "$dest" && isdir=yes if test "$isdir" = yes; then destdir="$dest" destname= else func_dirname_and_basename "$dest" "" "." destdir="$func_dirname_result" destname="$func_basename_result" # Not a directory, so check to see that there is only one file specified. set dummy $files; shift test "$#" -gt 1 && \ func_fatal_help "\`$dest' is not a directory" fi case $destdir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) for file in $files; do case $file in *.lo) ;; *) func_fatal_help "\`$destdir' must be an absolute directory name" ;; esac done ;; esac # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic="$magic" staticlibs= future_libdirs= current_libdirs= for file in $files; do # Do each installation. case $file in *.$libext) # Do the static libraries later. func_append staticlibs " $file" ;; *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "\`$file' is not a valid libtool archive" library_names= old_library= relink_command= func_source "$file" # Add the libdir to current_libdirs if it is the destination. if test "X$destdir" = "X$libdir"; then case "$current_libdirs " in *" $libdir "*) ;; *) func_append current_libdirs " $libdir" ;; esac else # Note the libdir as a future libdir. case "$future_libdirs " in *" $libdir "*) ;; *) func_append future_libdirs " $libdir" ;; esac fi func_dirname "$file" "/" "" dir="$func_dirname_result" func_append dir "$objdir" if test -n "$relink_command"; then # Determine the prefix the user has applied to our future dir. inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"` # Don't allow the user to place us outside of our expected # location b/c this prevents finding dependent libraries that # are installed to the same prefix. # At present, this check doesn't affect windows .dll's that # are installed into $libdir/../bin (currently, that works fine) # but it's something to keep an eye on. test "$inst_prefix_dir" = "$destdir" && \ func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir" if test -n "$inst_prefix_dir"; then # Stick the inst_prefix_dir data into the link command. relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` else relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"` fi func_warning "relinking \`$file'" func_show_eval "$relink_command" \ 'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"' fi # See the names of the shared library. set dummy $library_names; shift if test -n "$1"; then realname="$1" shift srcname="$realname" test -n "$relink_command" && srcname="$realname"T # Install the shared library and build the symlinks. func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \ 'exit $?' tstripme="$stripme" case $host_os in cygwin* | mingw* | pw32* | cegcc*) case $realname in *.dll.a) tstripme="" ;; esac ;; esac if test -n "$tstripme" && test -n "$striplib"; then func_show_eval "$striplib $destdir/$realname" 'exit $?' fi if test "$#" -gt 0; then # Delete the old symlinks, and create new ones. # Try `ln -sf' first, because the `ln' binary might depend on # the symlink we replace! Solaris /bin/ln does not understand -f, # so we also need to try rm && ln -s. for linkname do test "$linkname" != "$realname" \ && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" done fi # Do each command in the postinstall commands. lib="$destdir/$realname" func_execute_cmds "$postinstall_cmds" 'exit $?' fi # Install the pseudo-library for information purposes. func_basename "$file" name="$func_basename_result" instname="$dir/$name"i func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' # Maybe install the static library, too. test -n "$old_library" && func_append staticlibs " $dir/$old_library" ;; *.lo) # Install (i.e. copy) a libtool object. # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile="$destdir/$destname" else func_basename "$file" destfile="$func_basename_result" destfile="$destdir/$destfile" fi # Deduce the name of the destination old-style object file. case $destfile in *.lo) func_lo2o "$destfile" staticdest=$func_lo2o_result ;; *.$objext) staticdest="$destfile" destfile= ;; *) func_fatal_help "cannot copy a libtool object to \`$destfile'" ;; esac # Install the libtool object if requested. test -n "$destfile" && \ func_show_eval "$install_prog $file $destfile" 'exit $?' # Install the old object if enabled. if test "$build_old_libs" = yes; then # Deduce the name of the old-style object file. func_lo2o "$file" staticobj=$func_lo2o_result func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' fi exit $EXIT_SUCCESS ;; *) # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile="$destdir/$destname" else func_basename "$file" destfile="$func_basename_result" destfile="$destdir/$destfile" fi # If the file is missing, and there is a .exe on the end, strip it # because it is most likely a libtool script we actually want to # install stripped_ext="" case $file in *.exe) if test ! -f "$file"; then func_stripname '' '.exe' "$file" file=$func_stripname_result stripped_ext=".exe" fi ;; esac # Do a test to see if this is really a libtool program. case $host in *cygwin* | *mingw*) if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" wrapper=$func_ltwrapper_scriptname_result else func_stripname '' '.exe' "$file" wrapper=$func_stripname_result fi ;; *) wrapper=$file ;; esac if func_ltwrapper_script_p "$wrapper"; then notinst_deplibs= relink_command= func_source "$wrapper" # Check the variables that should have been set. test -z "$generated_by_libtool_version" && \ func_fatal_error "invalid libtool wrapper script \`$wrapper'" finalize=yes for lib in $notinst_deplibs; do # Check to see that each library is installed. libdir= if test -f "$lib"; then func_source "$lib" fi libfile="$libdir/"`$ECHO "$lib" | $SED 's%^.*/%%g'` ### testsuite: skip nested quoting test if test -n "$libdir" && test ! -f "$libfile"; then func_warning "\`$lib' has not been installed in \`$libdir'" finalize=no fi done relink_command= func_source "$wrapper" outputname= if test "$fast_install" = no && test -n "$relink_command"; then $opt_dry_run || { if test "$finalize" = yes; then tmpdir=`func_mktempdir` func_basename "$file$stripped_ext" file="$func_basename_result" outputname="$tmpdir/$file" # Replace the output file specification. relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'` $opt_silent || { func_quote_for_expand "$relink_command" eval "func_echo $func_quote_for_expand_result" } if eval "$relink_command"; then : else func_error "error: relink \`$file' with the above command before installing it" $opt_dry_run || ${RM}r "$tmpdir" continue fi file="$outputname" else func_warning "cannot relink \`$file'" fi } else # Install the binary that we compiled earlier. file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"` fi fi # remove .exe since cygwin /usr/bin/install will append another # one anyway case $install_prog,$host in */usr/bin/install*,*cygwin*) case $file:$destfile in *.exe:*.exe) # this is ok ;; *.exe:*) destfile=$destfile.exe ;; *:*.exe) func_stripname '' '.exe' "$destfile" destfile=$func_stripname_result ;; esac ;; esac func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' $opt_dry_run || if test -n "$outputname"; then ${RM}r "$tmpdir" fi ;; esac done for file in $staticlibs; do func_basename "$file" name="$func_basename_result" # Set up the ranlib parameters. oldlib="$destdir/$name" func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result func_show_eval "$install_prog \$file \$oldlib" 'exit $?' if test -n "$stripme" && test -n "$old_striplib"; then func_show_eval "$old_striplib $tool_oldlib" 'exit $?' fi # Do each command in the postinstall commands. func_execute_cmds "$old_postinstall_cmds" 'exit $?' done test -n "$future_libdirs" && \ func_warning "remember to run \`$progname --finish$future_libdirs'" if test -n "$current_libdirs"; then # Maybe just do a dry run. $opt_dry_run && current_libdirs=" -n$current_libdirs" exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs' else exit $EXIT_SUCCESS fi } test "$opt_mode" = install && func_mode_install ${1+"$@"} # func_generate_dlsyms outputname originator pic_p # Extract symbols from dlprefiles and create ${outputname}S.o with # a dlpreopen symbol table. func_generate_dlsyms () { $opt_debug my_outputname="$1" my_originator="$2" my_pic_p="${3-no}" my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'` my_dlsyms= if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then if test -n "$NM" && test -n "$global_symbol_pipe"; then my_dlsyms="${my_outputname}S.c" else func_error "not configured to extract global symbols from dlpreopened files" fi fi if test -n "$my_dlsyms"; then case $my_dlsyms in "") ;; *.c) # Discover the nlist of each of the dlfiles. nlist="$output_objdir/${my_outputname}.nm" func_show_eval "$RM $nlist ${nlist}S ${nlist}T" # Parse the name list into a source file. func_verbose "creating $output_objdir/$my_dlsyms" $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ /* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */ /* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */ #ifdef __cplusplus extern \"C\" { #endif #if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4)) #pragma GCC diagnostic ignored \"-Wstrict-prototypes\" #endif /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) /* DATA imports from DLLs on WIN32 con't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined(__osf__) /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif /* External symbol declarations for the compiler. */\ " if test "$dlself" = yes; then func_verbose "generating symbol list for \`$output'" $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" # Add our own program objects to the symbol list. progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP` for progfile in $progfiles; do func_to_tool_file "$progfile" func_convert_file_msys_to_w32 func_verbose "extracting global C symbols from \`$func_to_tool_file_result'" $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'" done if test -n "$exclude_expsyms"; then $opt_dry_run || { eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi if test -n "$export_symbols_regex"; then $opt_dry_run || { eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi # Prepare the list of exported symbols if test -z "$export_symbols"; then export_symbols="$output_objdir/$outputname.exp" $opt_dry_run || { $RM $export_symbols eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' ;; esac } else $opt_dry_run || { eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' ;; esac } fi fi for dlprefile in $dlprefiles; do func_verbose "extracting global C symbols from \`$dlprefile'" func_basename "$dlprefile" name="$func_basename_result" case $host in *cygwin* | *mingw* | *cegcc* ) # if an import library, we need to obtain dlname if func_win32_import_lib_p "$dlprefile"; then func_tr_sh "$dlprefile" eval "curr_lafile=\$libfile_$func_tr_sh_result" dlprefile_dlbasename="" if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then # Use subshell, to avoid clobbering current variable values dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"` if test -n "$dlprefile_dlname" ; then func_basename "$dlprefile_dlname" dlprefile_dlbasename="$func_basename_result" else # no lafile. user explicitly requested -dlpreopen . $sharedlib_from_linklib_cmd "$dlprefile" dlprefile_dlbasename=$sharedlib_from_linklib_result fi fi $opt_dry_run || { if test -n "$dlprefile_dlbasename" ; then eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"' else func_warning "Could not compute DLL name from $name" eval '$ECHO ": $name " >> "$nlist"' fi func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" } else # not an import lib $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } fi ;; *) $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } ;; esac done $opt_dry_run || { # Make sure we have at least an empty file. test -f "$nlist" || : > "$nlist" if test -n "$exclude_expsyms"; then $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T $MV "$nlist"T "$nlist" fi # Try sorting and uniquifying the output. if $GREP -v "^: " < "$nlist" | if sort -k 3 /dev/null 2>&1; then sort -k 3 else sort +2 fi | uniq > "$nlist"S; then : else $GREP -v "^: " < "$nlist" > "$nlist"S fi if test -f "$nlist"S; then eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' else echo '/* NONE */' >> "$output_objdir/$my_dlsyms" fi echo >> "$output_objdir/$my_dlsyms" "\ /* The mapping between symbol names and symbols. */ typedef struct { const char *name; void *address; } lt_dlsymlist; extern LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[]; LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[] = {\ { \"$my_originator\", (void *) 0 }," case $need_lib_prefix in no) eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; *) eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; esac echo >> "$output_objdir/$my_dlsyms" "\ {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt_${my_prefix}_LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif\ " } # !$opt_dry_run pic_flag_for_symtable= case "$compile_command " in *" -static "*) ;; *) case $host in # compiling the symbol table file with pic_flag works around # a FreeBSD bug that causes programs to crash when -lm is # linked before any other PIC object. But we must not use # pic_flag when linking with -static. The problem exists in # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; *-*-hpux*) pic_flag_for_symtable=" $pic_flag" ;; *) if test "X$my_pic_p" != Xno; then pic_flag_for_symtable=" $pic_flag" fi ;; esac ;; esac symtab_cflags= for arg in $LTCFLAGS; do case $arg in -pie | -fpie | -fPIE) ;; *) func_append symtab_cflags " $arg" ;; esac done # Now compile the dynamic symbol file. func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' # Clean up the generated files. func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"' # Transform the symbol file into the correct name. symfileobj="$output_objdir/${my_outputname}S.$objext" case $host in *cygwin* | *mingw* | *cegcc* ) if test -f "$output_objdir/$my_outputname.def"; then compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` else compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` fi ;; *) compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` ;; esac ;; *) func_fatal_error "unknown suffix for \`$my_dlsyms'" ;; esac else # We keep going just in case the user didn't refer to # lt_preloaded_symbols. The linker will fail if global_symbol_pipe # really was required. # Nullify the symbol file. compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"` finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"` fi } # func_win32_libid arg # return the library type of file 'arg' # # Need a lot of goo to handle *both* DLLs and import libs # Has to be a shell function in order to 'eat' the argument # that is supplied when $file_magic_command is called. # Despite the name, also deal with 64 bit binaries. func_win32_libid () { $opt_debug win32_libid_type="unknown" win32_fileres=`file -L $1 2>/dev/null` case $win32_fileres in *ar\ archive\ import\ library*) # definitely import win32_libid_type="x86 archive import" ;; *ar\ archive*) # could be an import, or static # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD. if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then func_to_tool_file "$1" func_convert_file_msys_to_w32 win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" | $SED -n -e ' 1,100{ / I /{ s,.*,import, p q } }'` case $win32_nmres in import*) win32_libid_type="x86 archive import";; *) win32_libid_type="x86 archive static";; esac fi ;; *DLL*) win32_libid_type="x86 DLL" ;; *executable*) # but shell scripts are "executable" too... case $win32_fileres in *MS\ Windows\ PE\ Intel*) win32_libid_type="x86 DLL" ;; esac ;; esac $ECHO "$win32_libid_type" } # func_cygming_dll_for_implib ARG # # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib () { $opt_debug sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"` } # func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs # # The is the core of a fallback implementation of a # platform-specific function to extract the name of the # DLL associated with the specified import library LIBNAME. # # SECTION_NAME is either .idata$6 or .idata$7, depending # on the platform and compiler that created the implib. # # Echos the name of the DLL associated with the # specified import library. func_cygming_dll_for_implib_fallback_core () { $opt_debug match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"` $OBJDUMP -s --section "$1" "$2" 2>/dev/null | $SED '/^Contents of section '"$match_literal"':/{ # Place marker at beginning of archive member dllname section s/.*/====MARK====/ p d } # These lines can sometimes be longer than 43 characters, but # are always uninteresting /:[ ]*file format pe[i]\{,1\}-/d /^In archive [^:]*:/d # Ensure marker is printed /^====MARK====/p # Remove all lines with less than 43 characters /^.\{43\}/!d # From remaining lines, remove first 43 characters s/^.\{43\}//' | $SED -n ' # Join marker and all lines until next marker into a single line /^====MARK====/ b para H $ b para b :para x s/\n//g # Remove the marker s/^====MARK====// # Remove trailing dots and whitespace s/[\. \t]*$// # Print /./p' | # we now have a list, one entry per line, of the stringified # contents of the appropriate section of all members of the # archive which possess that section. Heuristic: eliminate # all those which have a first or second character that is # a '.' (that is, objdump's representation of an unprintable # character.) This should work for all archives with less than # 0x302f exports -- but will fail for DLLs whose name actually # begins with a literal '.' or a single character followed by # a '.'. # # Of those that remain, print the first one. $SED -e '/^\./d;/^.\./d;q' } # func_cygming_gnu_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is a GNU/binutils-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_gnu_implib_p () { $opt_debug func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'` test -n "$func_cygming_gnu_implib_tmp" } # func_cygming_ms_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is an MS-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_ms_implib_p () { $opt_debug func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'` test -n "$func_cygming_ms_implib_tmp" } # func_cygming_dll_for_implib_fallback ARG # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # # This fallback implementation is for use when $DLLTOOL # does not support the --identify-strict option. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib_fallback () { $opt_debug if func_cygming_gnu_implib_p "$1" ; then # binutils import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"` elif func_cygming_ms_implib_p "$1" ; then # ms-generated import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"` else # unknown sharedlib_from_linklib_result="" fi } # func_extract_an_archive dir oldlib func_extract_an_archive () { $opt_debug f_ex_an_ar_dir="$1"; shift f_ex_an_ar_oldlib="$1" if test "$lock_old_archive_extraction" = yes; then lockfile=$f_ex_an_ar_oldlib.lock until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done fi func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \ 'stat=$?; rm -f "$lockfile"; exit $stat' if test "$lock_old_archive_extraction" = yes; then $opt_dry_run || rm -f "$lockfile" fi if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then : else func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" fi } # func_extract_archives gentop oldlib ... func_extract_archives () { $opt_debug my_gentop="$1"; shift my_oldlibs=${1+"$@"} my_oldobjs="" my_xlib="" my_xabs="" my_xdir="" for my_xlib in $my_oldlibs; do # Extract the objects. case $my_xlib in [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;; *) my_xabs=`pwd`"/$my_xlib" ;; esac func_basename "$my_xlib" my_xlib="$func_basename_result" my_xlib_u=$my_xlib while :; do case " $extracted_archives " in *" $my_xlib_u "*) func_arith $extracted_serial + 1 extracted_serial=$func_arith_result my_xlib_u=lt$extracted_serial-$my_xlib ;; *) break ;; esac done extracted_archives="$extracted_archives $my_xlib_u" my_xdir="$my_gentop/$my_xlib_u" func_mkdir_p "$my_xdir" case $host in *-darwin*) func_verbose "Extracting $my_xabs" # Do not bother doing anything if just a dry run $opt_dry_run || { darwin_orig_dir=`pwd` cd $my_xdir || exit $? darwin_archive=$my_xabs darwin_curdir=`pwd` darwin_base_archive=`basename "$darwin_archive"` darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` if test -n "$darwin_arches"; then darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` darwin_arch= func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" for darwin_arch in $darwin_arches ; do func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}" $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}" cd "unfat-$$/${darwin_base_archive}-${darwin_arch}" func_extract_an_archive "`pwd`" "${darwin_base_archive}" cd "$darwin_curdir" $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" done # $darwin_arches ## Okay now we've a bunch of thin objects, gotta fatten them up :) darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u` darwin_file= darwin_files= for darwin_file in $darwin_filelist; do darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP` $LIPO -create -output "$darwin_file" $darwin_files done # $darwin_filelist $RM -rf unfat-$$ cd "$darwin_orig_dir" else cd $darwin_orig_dir func_extract_an_archive "$my_xdir" "$my_xabs" fi # $darwin_arches } # !$opt_dry_run ;; *) func_extract_an_archive "$my_xdir" "$my_xabs" ;; esac my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP` done func_extract_archives_result="$my_oldobjs" } # func_emit_wrapper [arg=no] # # Emit a libtool wrapper script on stdout. # Don't directly open a file because we may want to # incorporate the script contents within a cygwin/mingw # wrapper executable. Must ONLY be called from within # func_mode_link because it depends on a number of variables # set therein. # # ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR # variable will take. If 'yes', then the emitted script # will assume that the directory in which it is stored is # the $objdir directory. This is a cygwin/mingw-specific # behavior. func_emit_wrapper () { func_emit_wrapper_arg1=${1-no} $ECHO "\ #! $SHELL # $output - temporary wrapper script for $objdir/$outputname # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # The $output program cannot be directly executed until all the libtool # libraries that it depends on are installed. # # This wrapper script should never be moved out of the build directory. # If it is, it will not operate correctly. # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. sed_quote_subst='$sed_quote_subst' # Be Bourne compatible if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH relink_command=\"$relink_command\" # This environment variable determines our operation mode. if test \"\$libtool_install_magic\" = \"$magic\"; then # install mode needs the following variables: generated_by_libtool_version='$macro_version' notinst_deplibs='$notinst_deplibs' else # When we are sourced in execute mode, \$file and \$ECHO are already set. if test \"\$libtool_execute_magic\" != \"$magic\"; then file=\"\$0\"" qECHO=`$ECHO "$ECHO" | $SED "$sed_quote_subst"` $ECHO "\ # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } ECHO=\"$qECHO\" fi # Very basic option parsing. These options are (a) specific to # the libtool wrapper, (b) are identical between the wrapper # /script/ and the wrapper /executable/ which is used only on # windows platforms, and (c) all begin with the string "--lt-" # (application programs are unlikely to have options which match # this pattern). # # There are only two supported options: --lt-debug and # --lt-dump-script. There is, deliberately, no --lt-help. # # The first argument to this parsing function should be the # script's $0 value, followed by "$@". lt_option_debug= func_parse_lt_options () { lt_script_arg0=\$0 shift for lt_opt do case \"\$lt_opt\" in --lt-debug) lt_option_debug=1 ;; --lt-dump-script) lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\` test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=. lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\` cat \"\$lt_dump_D/\$lt_dump_F\" exit 0 ;; --lt-*) \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2 exit 1 ;; esac done # Print the debug banner immediately: if test -n \"\$lt_option_debug\"; then echo \"${outputname}:${output}:\${LINENO}: libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\" 1>&2 fi } # Used when --lt-debug. Prints its arguments to stdout # (redirection is the responsibility of the caller) func_lt_dump_args () { lt_dump_args_N=1; for lt_arg do \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[\$lt_dump_args_N]: \$lt_arg\" lt_dump_args_N=\`expr \$lt_dump_args_N + 1\` done } # Core function for launching the target application func_exec_program_core () { " case $host in # Backslashes separate directories on plain windows *-*-mingw | *-*-os2* | *-cegcc*) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir\\\\\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} " ;; *) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir/\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir/\$program\" \${1+\"\$@\"} " ;; esac $ECHO "\ \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 exit 1 } # A function to encapsulate launching the target application # Strips options in the --lt-* namespace from \$@ and # launches target application with the remaining arguments. func_exec_program () { case \" \$* \" in *\\ --lt-*) for lt_wr_arg do case \$lt_wr_arg in --lt-*) ;; *) set x \"\$@\" \"\$lt_wr_arg\"; shift;; esac shift done ;; esac func_exec_program_core \${1+\"\$@\"} } # Parse options func_parse_lt_options \"\$0\" \${1+\"\$@\"} # Find the directory that this script lives in. thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\` test \"x\$thisdir\" = \"x\$file\" && thisdir=. # Follow symbolic links until we get to the real thisdir. file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\` while test -n \"\$file\"; do destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\` # If there was a directory component, then change thisdir. if test \"x\$destdir\" != \"x\$file\"; then case \"\$destdir\" in [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; *) thisdir=\"\$thisdir/\$destdir\" ;; esac fi file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\` file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\` done # Usually 'no', except on cygwin/mingw when embedded into # the cwrapper. WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1 if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then # special case for '.' if test \"\$thisdir\" = \".\"; then thisdir=\`pwd\` fi # remove .libs from thisdir case \"\$thisdir\" in *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;; $objdir ) thisdir=. ;; esac fi # Try to get the absolute directory name. absdir=\`cd \"\$thisdir\" && pwd\` test -n \"\$absdir\" && thisdir=\"\$absdir\" " if test "$fast_install" = yes; then $ECHO "\ program=lt-'$outputname'$exeext progdir=\"\$thisdir/$objdir\" if test ! -f \"\$progdir/\$program\" || { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\ test \"X\$file\" != \"X\$progdir/\$program\"; }; then file=\"\$\$-\$program\" if test ! -d \"\$progdir\"; then $MKDIR \"\$progdir\" else $RM \"\$progdir/\$file\" fi" $ECHO "\ # relink executable if necessary if test -n \"\$relink_command\"; then if relink_command_output=\`eval \$relink_command 2>&1\`; then : else $ECHO \"\$relink_command_output\" >&2 $RM \"\$progdir/\$file\" exit 1 fi fi $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || { $RM \"\$progdir/\$program\"; $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } $RM \"\$progdir/\$file\" fi" else $ECHO "\ program='$outputname' progdir=\"\$thisdir/$objdir\" " fi $ECHO "\ if test -f \"\$progdir/\$program\"; then" # fixup the dll searchpath if we need to. # # Fix the DLL searchpath if we need to. Do this before prepending # to shlibpath, because on Windows, both are PATH and uninstalled # libraries must come first. if test -n "$dllsearchpath"; then $ECHO "\ # Add the dll search path components to the executable PATH PATH=$dllsearchpath:\$PATH " fi # Export our shlibpath_var if we have one. if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then $ECHO "\ # Add our own library path to $shlibpath_var $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" # Some systems cannot cope with colon-terminated $shlibpath_var # The second colon is a workaround for a bug in BeOS R4 sed $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\` export $shlibpath_var " fi $ECHO "\ if test \"\$libtool_execute_magic\" != \"$magic\"; then # Run the actual program with our arguments. func_exec_program \${1+\"\$@\"} fi else # The program doesn't exist. \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2 \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 exit 1 fi fi\ " } # func_emit_cwrapperexe_src # emit the source code for a wrapper executable on stdout # Must ONLY be called from within func_mode_link because # it depends on a number of variable set therein. func_emit_cwrapperexe_src () { cat < #include #ifdef _MSC_VER # include # include # include #else # include # include # ifdef __CYGWIN__ # include # endif #endif #include #include #include #include #include #include #include #include /* declarations of non-ANSI functions */ #if defined(__MINGW32__) # ifdef __STRICT_ANSI__ int _putenv (const char *); # endif #elif defined(__CYGWIN__) # ifdef __STRICT_ANSI__ char *realpath (const char *, char *); int putenv (char *); int setenv (const char *, const char *, int); # endif /* #elif defined (other platforms) ... */ #endif /* portability defines, excluding path handling macros */ #if defined(_MSC_VER) # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv # define S_IXUSR _S_IEXEC # ifndef _INTPTR_T_DEFINED # define _INTPTR_T_DEFINED # define intptr_t int # endif #elif defined(__MINGW32__) # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv #elif defined(__CYGWIN__) # define HAVE_SETENV # define FOPEN_WB "wb" /* #elif defined (other platforms) ... */ #endif #if defined(PATH_MAX) # define LT_PATHMAX PATH_MAX #elif defined(MAXPATHLEN) # define LT_PATHMAX MAXPATHLEN #else # define LT_PATHMAX 1024 #endif #ifndef S_IXOTH # define S_IXOTH 0 #endif #ifndef S_IXGRP # define S_IXGRP 0 #endif /* path handling portability macros */ #ifndef DIR_SEPARATOR # define DIR_SEPARATOR '/' # define PATH_SEPARATOR ':' #endif #if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \ defined (__OS2__) # define HAVE_DOS_BASED_FILE_SYSTEM # define FOPEN_WB "wb" # ifndef DIR_SEPARATOR_2 # define DIR_SEPARATOR_2 '\\' # endif # ifndef PATH_SEPARATOR_2 # define PATH_SEPARATOR_2 ';' # endif #endif #ifndef DIR_SEPARATOR_2 # define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) #else /* DIR_SEPARATOR_2 */ # define IS_DIR_SEPARATOR(ch) \ (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) #endif /* DIR_SEPARATOR_2 */ #ifndef PATH_SEPARATOR_2 # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) #else /* PATH_SEPARATOR_2 */ # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) #endif /* PATH_SEPARATOR_2 */ #ifndef FOPEN_WB # define FOPEN_WB "w" #endif #ifndef _O_BINARY # define _O_BINARY 0 #endif #define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) #define XFREE(stale) do { \ if (stale) { free ((void *) stale); stale = 0; } \ } while (0) #if defined(LT_DEBUGWRAPPER) static int lt_debug = 1; #else static int lt_debug = 0; #endif const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */ void *xmalloc (size_t num); char *xstrdup (const char *string); const char *base_name (const char *name); char *find_executable (const char *wrapper); char *chase_symlinks (const char *pathspec); int make_executable (const char *path); int check_executable (const char *path); char *strendzap (char *str, const char *pat); void lt_debugprintf (const char *file, int line, const char *fmt, ...); void lt_fatal (const char *file, int line, const char *message, ...); static const char *nonnull (const char *s); static const char *nonempty (const char *s); void lt_setenv (const char *name, const char *value); char *lt_extend_str (const char *orig_value, const char *add, int to_end); void lt_update_exe_path (const char *name, const char *value); void lt_update_lib_path (const char *name, const char *value); char **prepare_spawn (char **argv); void lt_dump_script (FILE *f); EOF cat <= 0) && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return 1; else return 0; } int make_executable (const char *path) { int rval = 0; struct stat st; lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n", nonempty (path)); if ((!path) || (!*path)) return 0; if (stat (path, &st) >= 0) { rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); } return rval; } /* Searches for the full path of the wrapper. Returns newly allocated full path name if found, NULL otherwise Does not chase symlinks, even on platforms that support them. */ char * find_executable (const char *wrapper) { int has_slash = 0; const char *p; const char *p_next; /* static buffer for getcwd */ char tmp[LT_PATHMAX + 1]; int tmp_len; char *concat_name; lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n", nonempty (wrapper)); if ((wrapper == NULL) || (*wrapper == '\0')) return NULL; /* Absolute path? */ #if defined (HAVE_DOS_BASED_FILE_SYSTEM) if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } else { #endif if (IS_DIR_SEPARATOR (wrapper[0])) { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } #if defined (HAVE_DOS_BASED_FILE_SYSTEM) } #endif for (p = wrapper; *p; p++) if (*p == '/') { has_slash = 1; break; } if (!has_slash) { /* no slashes; search PATH */ const char *path = getenv ("PATH"); if (path != NULL) { for (p = path; *p; p = p_next) { const char *q; size_t p_len; for (q = p; *q; q++) if (IS_PATH_SEPARATOR (*q)) break; p_len = q - p; p_next = (*q == '\0' ? q : q + 1); if (p_len == 0) { /* empty path: current directory */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); } else { concat_name = XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, p, p_len); concat_name[p_len] = '/'; strcpy (concat_name + p_len + 1, wrapper); } if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } } /* not found in PATH; assume curdir */ } /* Relative path | not found in path: prepend cwd */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); return NULL; } char * chase_symlinks (const char *pathspec) { #ifndef S_ISLNK return xstrdup (pathspec); #else char buf[LT_PATHMAX]; struct stat s; char *tmp_pathspec = xstrdup (pathspec); char *p; int has_symlinks = 0; while (strlen (tmp_pathspec) && !has_symlinks) { lt_debugprintf (__FILE__, __LINE__, "checking path component for symlinks: %s\n", tmp_pathspec); if (lstat (tmp_pathspec, &s) == 0) { if (S_ISLNK (s.st_mode) != 0) { has_symlinks = 1; break; } /* search backwards for last DIR_SEPARATOR */ p = tmp_pathspec + strlen (tmp_pathspec) - 1; while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) p--; if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) { /* no more DIR_SEPARATORS left */ break; } *p = '\0'; } else { lt_fatal (__FILE__, __LINE__, "error accessing file \"%s\": %s", tmp_pathspec, nonnull (strerror (errno))); } } XFREE (tmp_pathspec); if (!has_symlinks) { return xstrdup (pathspec); } tmp_pathspec = realpath (pathspec, buf); if (tmp_pathspec == 0) { lt_fatal (__FILE__, __LINE__, "could not follow symlinks for %s", pathspec); } return xstrdup (tmp_pathspec); #endif } char * strendzap (char *str, const char *pat) { size_t len, patlen; assert (str != NULL); assert (pat != NULL); len = strlen (str); patlen = strlen (pat); if (patlen <= len) { str += len - patlen; if (strcmp (str, pat) == 0) *str = '\0'; } return str; } void lt_debugprintf (const char *file, int line, const char *fmt, ...) { va_list args; if (lt_debug) { (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line); va_start (args, fmt); (void) vfprintf (stderr, fmt, args); va_end (args); } } static void lt_error_core (int exit_status, const char *file, int line, const char *mode, const char *message, va_list ap) { fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode); vfprintf (stderr, message, ap); fprintf (stderr, ".\n"); if (exit_status >= 0) exit (exit_status); } void lt_fatal (const char *file, int line, const char *message, ...) { va_list ap; va_start (ap, message); lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap); va_end (ap); } static const char * nonnull (const char *s) { return s ? s : "(null)"; } static const char * nonempty (const char *s) { return (s && !*s) ? "(empty)" : nonnull (s); } void lt_setenv (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_setenv) setting '%s' to '%s'\n", nonnull (name), nonnull (value)); { #ifdef HAVE_SETENV /* always make a copy, for consistency with !HAVE_SETENV */ char *str = xstrdup (value); setenv (name, str, 1); #else int len = strlen (name) + 1 + strlen (value) + 1; char *str = XMALLOC (char, len); sprintf (str, "%s=%s", name, value); if (putenv (str) != EXIT_SUCCESS) { XFREE (str); } #endif } } char * lt_extend_str (const char *orig_value, const char *add, int to_end) { char *new_value; if (orig_value && *orig_value) { int orig_value_len = strlen (orig_value); int add_len = strlen (add); new_value = XMALLOC (char, add_len + orig_value_len + 1); if (to_end) { strcpy (new_value, orig_value); strcpy (new_value + orig_value_len, add); } else { strcpy (new_value, add); strcpy (new_value + add_len, orig_value); } } else { new_value = xstrdup (add); } return new_value; } void lt_update_exe_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_exe_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); /* some systems can't cope with a ':'-terminated path #' */ int len = strlen (new_value); while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1])) { new_value[len-1] = '\0'; } lt_setenv (name, new_value); XFREE (new_value); } } void lt_update_lib_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_lib_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); lt_setenv (name, new_value); XFREE (new_value); } } EOF case $host_os in mingw*) cat <<"EOF" /* Prepares an argument vector before calling spawn(). Note that spawn() does not by itself call the command interpreter (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") : ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&v); v.dwPlatformId == VER_PLATFORM_WIN32_NT; }) ? "cmd.exe" : "command.com"). Instead it simply concatenates the arguments, separated by ' ', and calls CreateProcess(). We must quote the arguments since Win32 CreateProcess() interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a special way: - Space and tab are interpreted as delimiters. They are not treated as delimiters if they are surrounded by double quotes: "...". - Unescaped double quotes are removed from the input. Their only effect is that within double quotes, space and tab are treated like normal characters. - Backslashes not followed by double quotes are not special. - But 2*n+1 backslashes followed by a double quote become n backslashes followed by a double quote (n >= 0): \" -> " \\\" -> \" \\\\\" -> \\" */ #define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" #define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" char ** prepare_spawn (char **argv) { size_t argc; char **new_argv; size_t i; /* Count number of arguments. */ for (argc = 0; argv[argc] != NULL; argc++) ; /* Allocate new argument vector. */ new_argv = XMALLOC (char *, argc + 1); /* Put quoted arguments into the new argument vector. */ for (i = 0; i < argc; i++) { const char *string = argv[i]; if (string[0] == '\0') new_argv[i] = xstrdup ("\"\""); else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL) { int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL); size_t length; unsigned int backslashes; const char *s; char *quoted_string; char *p; length = 0; backslashes = 0; if (quote_around) length++; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') length += backslashes + 1; length++; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) length += backslashes + 1; quoted_string = XMALLOC (char, length + 1); p = quoted_string; backslashes = 0; if (quote_around) *p++ = '"'; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') { unsigned int j; for (j = backslashes + 1; j > 0; j--) *p++ = '\\'; } *p++ = c; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) { unsigned int j; for (j = backslashes; j > 0; j--) *p++ = '\\'; *p++ = '"'; } *p = '\0'; new_argv[i] = quoted_string; } else new_argv[i] = (char *) string; } new_argv[argc] = NULL; return new_argv; } EOF ;; esac cat <<"EOF" void lt_dump_script (FILE* f) { EOF func_emit_wrapper yes | $SED -n -e ' s/^\(.\{79\}\)\(..*\)/\1\ \2/ h s/\([\\"]\)/\\\1/g s/$/\\n/ s/\([^\n]*\).*/ fputs ("\1", f);/p g D' cat <<"EOF" } EOF } # end: func_emit_cwrapperexe_src # func_win32_import_lib_p ARG # True if ARG is an import lib, as indicated by $file_magic_cmd func_win32_import_lib_p () { $opt_debug case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in *import*) : ;; *) false ;; esac } # func_mode_link arg... func_mode_link () { $opt_debug case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) # It is impossible to link a dll without this setting, and # we shouldn't force the makefile maintainer to figure out # which system we are compiling for in order to pass an extra # flag for every libtool invocation. # allow_undefined=no # FIXME: Unfortunately, there are problems with the above when trying # to make a dll which has undefined symbols, in which case not # even a static library is built. For now, we need to specify # -no-undefined on the libtool link line when we can be certain # that all symbols are satisfied, otherwise we get a static library. allow_undefined=yes ;; *) allow_undefined=yes ;; esac libtool_args=$nonopt base_compile="$nonopt $@" compile_command=$nonopt finalize_command=$nonopt compile_rpath= finalize_rpath= compile_shlibpath= finalize_shlibpath= convenience= old_convenience= deplibs= old_deplibs= compiler_flags= linker_flags= dllsearchpath= lib_search_path=`pwd` inst_prefix_dir= new_inherited_linker_flags= avoid_version=no bindir= dlfiles= dlprefiles= dlself=no export_dynamic=no export_symbols= export_symbols_regex= generated= libobjs= ltlibs= module=no no_install=no objs= non_pic_objects= precious_files_regex= prefer_static_libs=no preload=no prev= prevarg= release= rpath= xrpath= perm_rpath= temp_rpath= thread_safe=no vinfo= vinfo_number=no weak_libs= single_module="${wl}-single_module" func_infer_tag $base_compile # We need to know -static, to get the right output filenames. for arg do case $arg in -shared) test "$build_libtool_libs" != yes && \ func_fatal_configuration "can not build a shared library" build_old_libs=no break ;; -all-static | -static | -static-libtool-libs) case $arg in -all-static) if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then func_warning "complete static linking is impossible in this configuration" fi if test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; -static) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=built ;; -static-libtool-libs) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; esac build_libtool_libs=no build_old_libs=yes break ;; esac done # See if our shared archives depend on static archives. test -n "$old_archive_from_new_cmds" && build_old_libs=yes # Go through the arguments, transforming them on the way. while test "$#" -gt 0; do arg="$1" shift func_quote_for_eval "$arg" qarg=$func_quote_for_eval_unquoted_result func_append libtool_args " $func_quote_for_eval_result" # If the previous option needs an argument, assign it. if test -n "$prev"; then case $prev in output) func_append compile_command " @OUTPUT@" func_append finalize_command " @OUTPUT@" ;; esac case $prev in bindir) bindir="$arg" prev= continue ;; dlfiles|dlprefiles) if test "$preload" = no; then # Add the symbol object into the linking commands. func_append compile_command " @SYMFILE@" func_append finalize_command " @SYMFILE@" preload=yes fi case $arg in *.la | *.lo) ;; # We handle these cases below. force) if test "$dlself" = no; then dlself=needless export_dynamic=yes fi prev= continue ;; self) if test "$prev" = dlprefiles; then dlself=yes elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then dlself=yes else dlself=needless export_dynamic=yes fi prev= continue ;; *) if test "$prev" = dlfiles; then func_append dlfiles " $arg" else func_append dlprefiles " $arg" fi prev= continue ;; esac ;; expsyms) export_symbols="$arg" test -f "$arg" \ || func_fatal_error "symbol file \`$arg' does not exist" prev= continue ;; expsyms_regex) export_symbols_regex="$arg" prev= continue ;; framework) case $host in *-*-darwin*) case "$deplibs " in *" $qarg.ltframework "*) ;; *) func_append deplibs " $qarg.ltframework" # this is fixed later ;; esac ;; esac prev= continue ;; inst_prefix) inst_prefix_dir="$arg" prev= continue ;; objectlist) if test -f "$arg"; then save_arg=$arg moreargs= for fil in `cat "$save_arg"` do # func_append moreargs " $fil" arg=$fil # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test "$pic_object" = none && test "$non_pic_object" = none; then func_fatal_error "cannot find name of object for \`$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" if test "$pic_object" != none; then # Prepend the subdirectory the object is found in. pic_object="$xdir$pic_object" if test "$prev" = dlfiles; then if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test "$prev" = dlprefiles; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg="$pic_object" fi # Non-PIC object. if test "$non_pic_object" != none; then # Prepend the subdirectory the object is found in. non_pic_object="$xdir$non_pic_object" # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test "$pic_object" = none ; then arg="$non_pic_object" fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object="$pic_object" func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "\`$arg' is not a valid libtool object" fi fi done else func_fatal_error "link input file \`$arg' does not exist" fi arg=$save_arg prev= continue ;; precious_regex) precious_files_regex="$arg" prev= continue ;; release) release="-$arg" prev= continue ;; rpath | xrpath) # We need an absolute path. case $arg in [\\/]* | [A-Za-z]:[\\/]*) ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac if test "$prev" = rpath; then case "$rpath " in *" $arg "*) ;; *) func_append rpath " $arg" ;; esac else case "$xrpath " in *" $arg "*) ;; *) func_append xrpath " $arg" ;; esac fi prev= continue ;; shrext) shrext_cmds="$arg" prev= continue ;; weak) func_append weak_libs " $arg" prev= continue ;; xcclinker) func_append linker_flags " $qarg" func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xcompiler) func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xlinker) func_append linker_flags " $qarg" func_append compiler_flags " $wl$qarg" prev= func_append compile_command " $wl$qarg" func_append finalize_command " $wl$qarg" continue ;; *) eval "$prev=\"\$arg\"" prev= continue ;; esac fi # test -n "$prev" prevarg="$arg" case $arg in -all-static) if test -n "$link_static_flag"; then # See comment for -static flag below, for more details. func_append compile_command " $link_static_flag" func_append finalize_command " $link_static_flag" fi continue ;; -allow-undefined) # FIXME: remove this flag sometime in the future. func_fatal_error "\`-allow-undefined' must not be used because it is the default" ;; -avoid-version) avoid_version=yes continue ;; -bindir) prev=bindir continue ;; -dlopen) prev=dlfiles continue ;; -dlpreopen) prev=dlprefiles continue ;; -export-dynamic) export_dynamic=yes continue ;; -export-symbols | -export-symbols-regex) if test -n "$export_symbols" || test -n "$export_symbols_regex"; then func_fatal_error "more than one -exported-symbols argument is not allowed" fi if test "X$arg" = "X-export-symbols"; then prev=expsyms else prev=expsyms_regex fi continue ;; -framework) prev=framework continue ;; -inst-prefix-dir) prev=inst_prefix continue ;; # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* # so, if we see these flags be careful not to treat them like -L -L[A-Z][A-Z]*:*) case $with_gcc/$host in no/*-*-irix* | /*-*-irix*) func_append compile_command " $arg" func_append finalize_command " $arg" ;; esac continue ;; -L*) func_stripname "-L" '' "$arg" if test -z "$func_stripname_result"; then if test "$#" -gt 0; then func_fatal_error "require no space between \`-L' and \`$1'" else func_fatal_error "need path for \`-L' option" fi fi func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) absdir=`cd "$dir" && pwd` test -z "$absdir" && \ func_fatal_error "cannot determine absolute directory name of \`$dir'" dir="$absdir" ;; esac case "$deplibs " in *" -L$dir "* | *" $arg "*) # Will only happen for absolute or sysroot arguments ;; *) # Preserve sysroot, but never include relative directories case $dir in [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;; *) func_append deplibs " -L$dir" ;; esac func_append lib_search_path " $dir" ;; esac case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'` case :$dllsearchpath: in *":$dir:"*) ;; ::) dllsearchpath=$dir;; *) func_append dllsearchpath ":$dir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac continue ;; -l*) if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) # These systems don't actually have a C or math library (as such) continue ;; *-*-os2*) # These systems don't actually have a C library (as such) test "X$arg" = "X-lc" && continue ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. test "X$arg" = "X-lc" && continue ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C and math libraries are in the System framework func_append deplibs " System.ltframework" continue ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype test "X$arg" = "X-lc" && continue ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work test "X$arg" = "X-lc" && continue ;; esac elif test "X$arg" = "X-lc_r"; then case $host in *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc_r directly, use -pthread flag. continue ;; esac fi func_append deplibs " $arg" continue ;; -module) module=yes continue ;; # Tru64 UNIX uses -model [arg] to determine the layout of C++ # classes, name mangling, and exception handling. # Darwin uses the -arch flag to determine output architecture. -model|-arch|-isysroot|--sysroot) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" prev=xcompiler continue ;; -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" case "$new_inherited_linker_flags " in *" $arg "*) ;; * ) func_append new_inherited_linker_flags " $arg" ;; esac continue ;; -multi_module) single_module="${wl}-multi_module" continue ;; -no-fast-install) fast_install=no continue ;; -no-install) case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) # The PATH hackery in wrapper scripts is required on Windows # and Darwin in order for the loader to find any dlls it needs. func_warning "\`-no-install' is ignored for $host" func_warning "assuming \`-no-fast-install' instead" fast_install=no ;; *) no_install=yes ;; esac continue ;; -no-undefined) allow_undefined=no continue ;; -objectlist) prev=objectlist continue ;; -o) prev=output ;; -precious-files-regex) prev=precious_regex continue ;; -release) prev=release continue ;; -rpath) prev=rpath continue ;; -R) prev=xrpath continue ;; -R*) func_stripname '-R' '' "$arg" dir=$func_stripname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; =*) func_stripname '=' '' "$dir" dir=$lt_sysroot$func_stripname_result ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac continue ;; -shared) # The effects of -shared are defined in a previous loop. continue ;; -shrext) prev=shrext continue ;; -static | -static-libtool-libs) # The effects of -static are defined in a previous loop. # We used to do the same as -all-static on platforms that # didn't have a PIC flag, but the assumption that the effects # would be equivalent was wrong. It would break on at least # Digital Unix and AIX. continue ;; -thread-safe) thread_safe=yes continue ;; -version-info) prev=vinfo continue ;; -version-number) prev=vinfo vinfo_number=yes continue ;; -weak) prev=weak continue ;; -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result arg= save_ifs="$IFS"; IFS=',' for flag in $args; do IFS="$save_ifs" func_quote_for_eval "$flag" func_append arg " $func_quote_for_eval_result" func_append compiler_flags " $func_quote_for_eval_result" done IFS="$save_ifs" func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Wl,*) func_stripname '-Wl,' '' "$arg" args=$func_stripname_result arg= save_ifs="$IFS"; IFS=',' for flag in $args; do IFS="$save_ifs" func_quote_for_eval "$flag" func_append arg " $wl$func_quote_for_eval_result" func_append compiler_flags " $wl$func_quote_for_eval_result" func_append linker_flags " $func_quote_for_eval_result" done IFS="$save_ifs" func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Xcompiler) prev=xcompiler continue ;; -Xlinker) prev=xlinker continue ;; -XCClinker) prev=xcclinker continue ;; # -msg_* for osf cc -msg_*) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; # Flags to be passed through unchanged, with rationale: # -64, -mips[0-9] enable 64-bit mode for the SGI compiler # -r[0-9][0-9]* specify processor for the SGI compiler # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler # +DA*, +DD* enable 64-bit mode for the HP compiler # -q* compiler args for the IBM compiler # -m*, -t[45]*, -txscale* architecture-specific flags for GCC # -F/path path to uninstalled frameworks, gcc on darwin # -p, -pg, --coverage, -fprofile-* profiling flags for GCC # @file GCC response files # -tp=* Portland pgcc target processor selection # --sysroot=* for sysroot support # -O*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \ -O*|-flto*|-fwhopr*|-fuse-linker-plugin) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" func_append compile_command " $arg" func_append finalize_command " $arg" func_append compiler_flags " $arg" continue ;; # Some other compiler flag. -* | +*) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; *.$objext) # A standard object. func_append objs " $arg" ;; *.lo) # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test "$pic_object" = none && test "$non_pic_object" = none; then func_fatal_error "cannot find name of object for \`$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" if test "$pic_object" != none; then # Prepend the subdirectory the object is found in. pic_object="$xdir$pic_object" if test "$prev" = dlfiles; then if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test "$prev" = dlprefiles; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg="$pic_object" fi # Non-PIC object. if test "$non_pic_object" != none; then # Prepend the subdirectory the object is found in. non_pic_object="$xdir$non_pic_object" # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test "$pic_object" = none ; then arg="$non_pic_object" fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object="$pic_object" func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "\`$arg' is not a valid libtool object" fi fi ;; *.$libext) # An archive. func_append deplibs " $arg" func_append old_deplibs " $arg" continue ;; *.la) # A libtool-controlled library. func_resolve_sysroot "$arg" if test "$prev" = dlfiles; then # This library was specified with -dlopen. func_append dlfiles " $func_resolve_sysroot_result" prev= elif test "$prev" = dlprefiles; then # The library was specified with -dlpreopen. func_append dlprefiles " $func_resolve_sysroot_result" prev= else func_append deplibs " $func_resolve_sysroot_result" fi continue ;; # Some other compiler argument. *) # Unknown arguments in both finalize_command and compile_command need # to be aesthetically quoted because they are evaled later. func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; esac # arg # Now actually substitute the argument into the commands. if test -n "$arg"; then func_append compile_command " $arg" func_append finalize_command " $arg" fi done # argument parsing loop test -n "$prev" && \ func_fatal_help "the \`$prevarg' option requires an argument" if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then eval arg=\"$export_dynamic_flag_spec\" func_append compile_command " $arg" func_append finalize_command " $arg" fi oldlibs= # calculate the name of the file, without its directory func_basename "$output" outputname="$func_basename_result" libobjs_save="$libobjs" if test -n "$shlibpath_var"; then # get the directories listed in $shlibpath_var eval shlib_search_path=\`\$ECHO \"\${$shlibpath_var}\" \| \$SED \'s/:/ /g\'\` else shlib_search_path= fi eval sys_lib_search_path=\"$sys_lib_search_path_spec\" eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" func_dirname "$output" "/" "" output_objdir="$func_dirname_result$objdir" func_to_tool_file "$output_objdir/" tool_output_objdir=$func_to_tool_file_result # Create the object directory. func_mkdir_p "$output_objdir" # Determine the type of output case $output in "") func_fatal_help "you must specify an output file" ;; *.$libext) linkmode=oldlib ;; *.lo | *.$objext) linkmode=obj ;; *.la) linkmode=lib ;; *) linkmode=prog ;; # Anything else should be a program. esac specialdeplibs= libs= # Find all interdependent deplibs by searching for libraries # that are linked more than once (e.g. -la -lb -la) for deplib in $deplibs; do if $opt_preserve_dup_deps ; then case "$libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append libs " $deplib" done if test "$linkmode" = lib; then libs="$predeps $libs $compiler_lib_search_path $postdeps" # Compute libraries that are listed more than once in $predeps # $postdeps and mark them as special (i.e., whose duplicates are # not to be eliminated). pre_post_deps= if $opt_duplicate_compiler_generated_deps; then for pre_post_dep in $predeps $postdeps; do case "$pre_post_deps " in *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;; esac func_append pre_post_deps " $pre_post_dep" done fi pre_post_deps= fi deplibs= newdependency_libs= newlib_search_path= need_relink=no # whether we're linking any uninstalled libtool libraries notinst_deplibs= # not-installed libtool libraries notinst_path= # paths that contain not-installed libtool libraries case $linkmode in lib) passes="conv dlpreopen link" for file in $dlfiles $dlprefiles; do case $file in *.la) ;; *) func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file" ;; esac done ;; prog) compile_deplibs= finalize_deplibs= alldeplibs=no newdlfiles= newdlprefiles= passes="conv scan dlopen dlpreopen link" ;; *) passes="conv" ;; esac for pass in $passes; do # The preopen pass in lib mode reverses $deplibs; put it back here # so that -L comes before libs that need it for instance... if test "$linkmode,$pass" = "lib,link"; then ## FIXME: Find the place where the list is rebuilt in the wrong ## order, and fix it there properly tmp_deplibs= for deplib in $deplibs; do tmp_deplibs="$deplib $tmp_deplibs" done deplibs="$tmp_deplibs" fi if test "$linkmode,$pass" = "lib,link" || test "$linkmode,$pass" = "prog,scan"; then libs="$deplibs" deplibs= fi if test "$linkmode" = prog; then case $pass in dlopen) libs="$dlfiles" ;; dlpreopen) libs="$dlprefiles" ;; link) libs="$deplibs %DEPLIBS%" test "X$link_all_deplibs" != Xno && libs="$libs $dependency_libs" ;; esac fi if test "$linkmode,$pass" = "lib,dlpreopen"; then # Collect and forward deplibs of preopened libtool libs for lib in $dlprefiles; do # Ignore non-libtool-libs dependency_libs= func_resolve_sysroot "$lib" case $lib in *.la) func_source "$func_resolve_sysroot_result" ;; esac # Collect preopened libtool deplibs, except any this library # has declared as weak libs for deplib in $dependency_libs; do func_basename "$deplib" deplib_base=$func_basename_result case " $weak_libs " in *" $deplib_base "*) ;; *) func_append deplibs " $deplib" ;; esac done done libs="$dlprefiles" fi if test "$pass" = dlopen; then # Collect dlpreopened libraries save_deplibs="$deplibs" deplibs= fi for deplib in $libs; do lib= found=no case $deplib in -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append compiler_flags " $deplib" if test "$linkmode" = lib ; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -l*) if test "$linkmode" != lib && test "$linkmode" != prog; then func_warning "\`-l' is ignored for archives/objects" continue fi func_stripname '-l' '' "$deplib" name=$func_stripname_result if test "$linkmode" = lib; then searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" else searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" fi for searchdir in $searchdirs; do for search_ext in .la $std_shrext .so .a; do # Search the libtool library lib="$searchdir/lib${name}${search_ext}" if test -f "$lib"; then if test "$search_ext" = ".la"; then found=yes else found=no fi break 2 fi done done if test "$found" != yes; then # deplib doesn't seem to be a libtool library if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" fi continue else # deplib is a libtool library # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, # We need to do some special things here, and not later. if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $deplib "*) if func_lalib_p "$lib"; then library_names= old_library= func_source "$lib" for l in $old_library $library_names; do ll="$l" done if test "X$ll" = "X$old_library" ; then # only static version available found=no func_dirname "$lib" "" "." ladir="$func_dirname_result" lib=$ladir/$old_library if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" fi continue fi fi ;; *) ;; esac fi fi ;; # -l *.ltframework) if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" if test "$linkmode" = lib ; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -L*) case $linkmode in lib) deplibs="$deplib $deplibs" test "$pass" = conv && continue newdependency_libs="$deplib $newdependency_libs" func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; prog) if test "$pass" = conv; then deplibs="$deplib $deplibs" continue fi if test "$pass" = scan; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; *) func_warning "\`-L' is ignored for archives/objects" ;; esac # linkmode continue ;; # -L -R*) if test "$pass" = link; then func_stripname '-R' '' "$deplib" func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # Make sure the xrpath contains only unique directories. case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac fi deplibs="$deplib $deplibs" continue ;; *.la) func_resolve_sysroot "$deplib" lib=$func_resolve_sysroot_result ;; *.$libext) if test "$pass" = conv; then deplibs="$deplib $deplibs" continue fi case $linkmode in lib) # Linking convenience modules into shared libraries is allowed, # but linking other static libraries is non-portable. case " $dlpreconveniencelibs " in *" $deplib "*) ;; *) valid_a_lib=no case $deplibs_check_method in match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \ | $EGREP "$match_pattern_regex" > /dev/null; then valid_a_lib=yes fi ;; pass_all) valid_a_lib=yes ;; esac if test "$valid_a_lib" != yes; then echo $ECHO "*** Warning: Trying to link with static lib archive $deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because the file extensions .$libext of this argument makes me believe" echo "*** that it is just a static archive that I should not use here." else echo $ECHO "*** Warning: Linking the shared library $output against the" $ECHO "*** static library $deplib is not portable!" deplibs="$deplib $deplibs" fi ;; esac continue ;; prog) if test "$pass" != link; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi continue ;; esac # linkmode ;; # *.$libext *.lo | *.$objext) if test "$pass" = conv; then deplibs="$deplib $deplibs" elif test "$linkmode" = prog; then if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then # If there is no dlopen support or we're linking statically, # we need to preload. func_append newdlprefiles " $deplib" compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append newdlfiles " $deplib" fi fi continue ;; %DEPLIBS%) alldeplibs=yes continue ;; esac # case $deplib if test "$found" = yes || test -f "$lib"; then : else func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'" fi # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$lib" \ || func_fatal_error "\`$lib' is not a valid libtool archive" func_dirname "$lib" "" "." ladir="$func_dirname_result" dlname= dlopen= dlpreopen= libdir= library_names= old_library= inherited_linker_flags= # If the library was installed with an old release of libtool, # it will not redefine variables installed, or shouldnotlink installed=yes shouldnotlink=no avoidtemprpath= # Read the .la file func_source "$lib" # Convert "-framework foo" to "foo.ltframework" if test -n "$inherited_linker_flags"; then tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'` for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do case " $new_inherited_linker_flags " in *" $tmp_inherited_linker_flag "*) ;; *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";; esac done fi dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` if test "$linkmode,$pass" = "lib,link" || test "$linkmode,$pass" = "prog,scan" || { test "$linkmode" != prog && test "$linkmode" != lib; }; then test -n "$dlopen" && func_append dlfiles " $dlopen" test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen" fi if test "$pass" = conv; then # Only check for convenience libraries deplibs="$lib $deplibs" if test -z "$libdir"; then if test -z "$old_library"; then func_fatal_error "cannot find name of link library for \`$lib'" fi # It is a libtool convenience library, so add in its objects. func_append convenience " $ladir/$objdir/$old_library" func_append old_convenience " $ladir/$objdir/$old_library" tmp_libs= for deplib in $dependency_libs; do deplibs="$deplib $deplibs" if $opt_preserve_dup_deps ; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done elif test "$linkmode" != prog && test "$linkmode" != lib; then func_fatal_error "\`$lib' is not a convenience library" fi continue fi # $pass = conv # Get the name of the library we link against. linklib= if test -n "$old_library" && { test "$prefer_static_libs" = yes || test "$prefer_static_libs,$installed" = "built,no"; }; then linklib=$old_library else for l in $old_library $library_names; do linklib="$l" done fi if test -z "$linklib"; then func_fatal_error "cannot find name of link library for \`$lib'" fi # This library was specified with -dlopen. if test "$pass" = dlopen; then if test -z "$libdir"; then func_fatal_error "cannot -dlopen a convenience library: \`$lib'" fi if test -z "$dlname" || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then # If there is no dlname, no dlopen support or we're linking # statically, we need to preload. We also need to preload any # dependent libraries so libltdl's deplib preloader doesn't # bomb out in the load deplibs phase. func_append dlprefiles " $lib $dependency_libs" else func_append newdlfiles " $lib" fi continue fi # $pass = dlopen # We need an absolute path. case $ladir in [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; *) abs_ladir=`cd "$ladir" && pwd` if test -z "$abs_ladir"; then func_warning "cannot determine absolute directory name of \`$ladir'" func_warning "passing it literally to the linker, although it might fail" abs_ladir="$ladir" fi ;; esac func_basename "$lib" laname="$func_basename_result" # Find the relevant object directory and library name. if test "X$installed" = Xyes; then if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then func_warning "library \`$lib' was moved." dir="$ladir" absdir="$abs_ladir" libdir="$abs_ladir" else dir="$lt_sysroot$libdir" absdir="$lt_sysroot$libdir" fi test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes else if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then dir="$ladir" absdir="$abs_ladir" # Remove this search path later func_append notinst_path " $abs_ladir" else dir="$ladir/$objdir" absdir="$abs_ladir/$objdir" # Remove this search path later func_append notinst_path " $abs_ladir" fi fi # $installed = yes func_stripname 'lib' '.la' "$laname" name=$func_stripname_result # This library was specified with -dlpreopen. if test "$pass" = dlpreopen; then if test -z "$libdir" && test "$linkmode" = prog; then func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'" fi case "$host" in # special handling for platforms with PE-DLLs. *cygwin* | *mingw* | *cegcc* ) # Linker will automatically link against shared library if both # static and shared are present. Therefore, ensure we extract # symbols from the import library if a shared library is present # (otherwise, the dlopen module name will be incorrect). We do # this by putting the import library name into $newdlprefiles. # We recover the dlopen module name by 'saving' the la file # name in a special purpose variable, and (later) extracting the # dlname from the la file. if test -n "$dlname"; then func_tr_sh "$dir/$linklib" eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname" func_append newdlprefiles " $dir/$linklib" else func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" fi ;; * ) # Prefer using a static library (so that no silly _DYNAMIC symbols # are required to link). if test -n "$old_library"; then func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" # Otherwise, use the dlname, so that lt_dlopen finds it. elif test -n "$dlname"; then func_append newdlprefiles " $dir/$dlname" else func_append newdlprefiles " $dir/$linklib" fi ;; esac fi # $pass = dlpreopen if test -z "$libdir"; then # Link the convenience library if test "$linkmode" = lib; then deplibs="$dir/$old_library $deplibs" elif test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$dir/$old_library $compile_deplibs" finalize_deplibs="$dir/$old_library $finalize_deplibs" else deplibs="$lib $deplibs" # used for prog,scan pass fi continue fi if test "$linkmode" = prog && test "$pass" != link; then func_append newlib_search_path " $ladir" deplibs="$lib $deplibs" linkalldeplibs=no if test "$link_all_deplibs" != no || test -z "$library_names" || test "$build_libtool_libs" = no; then linkalldeplibs=yes fi tmp_libs= for deplib in $dependency_libs; do case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; esac # Need to link against all dependency_libs? if test "$linkalldeplibs" = yes; then deplibs="$deplib $deplibs" else # Need to hardcode shared library paths # or/and link against static libraries newdependency_libs="$deplib $newdependency_libs" fi if $opt_preserve_dup_deps ; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done # for deplib continue fi # $linkmode = prog... if test "$linkmode,$pass" = "prog,link"; then if test -n "$library_names" && { { test "$prefer_static_libs" = no || test "$prefer_static_libs,$installed" = "built,yes"; } || test -z "$old_library"; }; then # We need to hardcode the library path if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then # Make sure the rpath contains only unique directories. case "$temp_rpath:" in *"$absdir:"*) ;; *) func_append temp_rpath "$absdir:" ;; esac fi # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi # $linkmode,$pass = prog,link... if test "$alldeplibs" = yes && { test "$deplibs_check_method" = pass_all || { test "$build_libtool_libs" = yes && test -n "$library_names"; }; }; then # We only need to search for static libraries continue fi fi link_static=no # Whether the deplib will be linked statically use_static_libs=$prefer_static_libs if test "$use_static_libs" = built && test "$installed" = yes; then use_static_libs=no fi if test -n "$library_names" && { test "$use_static_libs" = no || test -z "$old_library"; }; then case $host in *cygwin* | *mingw* | *cegcc*) # No point in relinking DLLs because paths are not encoded func_append notinst_deplibs " $lib" need_relink=no ;; *) if test "$installed" = no; then func_append notinst_deplibs " $lib" need_relink=yes fi ;; esac # This is a shared library # Warn about portability, can't link against -module's on some # systems (darwin). Don't bleat about dlopened modules though! dlopenmodule="" for dlpremoduletest in $dlprefiles; do if test "X$dlpremoduletest" = "X$lib"; then dlopenmodule="$dlpremoduletest" break fi done if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then echo if test "$linkmode" = prog; then $ECHO "*** Warning: Linking the executable $output against the loadable module" else $ECHO "*** Warning: Linking the shared library $output against the loadable module" fi $ECHO "*** $linklib is not portable!" fi if test "$linkmode" = lib && test "$hardcode_into_libs" = yes; then # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi if test -n "$old_archive_from_expsyms_cmds"; then # figure out the soname set dummy $library_names shift realname="$1" shift libname=`eval "\\$ECHO \"$libname_spec\""` # use dlname if we got it. it's perfectly good, no? if test -n "$dlname"; then soname="$dlname" elif test -n "$soname_spec"; then # bleh windows case $host in *cygwin* | mingw* | *cegcc*) func_arith $current - $age major=$func_arith_result versuffix="-$major" ;; esac eval soname=\"$soname_spec\" else soname="$realname" fi # Make a new name for the extract_expsyms_cmds to use soroot="$soname" func_basename "$soroot" soname="$func_basename_result" func_stripname 'lib' '.dll' "$soname" newlib=libimp-$func_stripname_result.a # If the library has no export list, then create one now if test -f "$output_objdir/$soname-def"; then : else func_verbose "extracting exported symbol list from \`$soname'" func_execute_cmds "$extract_expsyms_cmds" 'exit $?' fi # Create $newlib if test -f "$output_objdir/$newlib"; then :; else func_verbose "generating import library for \`$soname'" func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' fi # make sure the library variables are pointing to the new library dir=$output_objdir linklib=$newlib fi # test -n "$old_archive_from_expsyms_cmds" if test "$linkmode" = prog || test "$opt_mode" != relink; then add_shlibpath= add_dir= add= lib_linked=yes case $hardcode_action in immediate | unsupported) if test "$hardcode_direct" = no; then add="$dir/$linklib" case $host in *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;; *-*-sysv4*uw2*) add_dir="-L$dir" ;; *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ *-*-unixware7*) add_dir="-L$dir" ;; *-*-darwin* ) # if the lib is a (non-dlopened) module then we can not # link against it, someone is ignoring the earlier warnings if /usr/bin/file -L $add 2> /dev/null | $GREP ": [^:]* bundle" >/dev/null ; then if test "X$dlopenmodule" != "X$lib"; then $ECHO "*** Warning: lib $linklib is a module, not a shared library" if test -z "$old_library" ; then echo echo "*** And there doesn't seem to be a static archive available" echo "*** The link will probably fail, sorry" else add="$dir/$old_library" fi elif test -n "$old_library"; then add="$dir/$old_library" fi fi esac elif test "$hardcode_minus_L" = no; then case $host in *-*-sunos*) add_shlibpath="$dir" ;; esac add_dir="-L$dir" add="-l$name" elif test "$hardcode_shlibpath_var" = no; then add_shlibpath="$dir" add="-l$name" else lib_linked=no fi ;; relink) if test "$hardcode_direct" = yes && test "$hardcode_direct_absolute" = no; then add="$dir/$linklib" elif test "$hardcode_minus_L" = yes; then add_dir="-L$absdir" # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add="-l$name" elif test "$hardcode_shlibpath_var" = yes; then add_shlibpath="$dir" add="-l$name" else lib_linked=no fi ;; *) lib_linked=no ;; esac if test "$lib_linked" != yes; then func_fatal_configuration "unsupported hardcode properties" fi if test -n "$add_shlibpath"; then case :$compile_shlibpath: in *":$add_shlibpath:"*) ;; *) func_append compile_shlibpath "$add_shlibpath:" ;; esac fi if test "$linkmode" = prog; then test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" test -n "$add" && compile_deplibs="$add $compile_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" if test "$hardcode_direct" != yes && test "$hardcode_minus_L" != yes && test "$hardcode_shlibpath_var" = yes; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac fi fi fi if test "$linkmode" = prog || test "$opt_mode" = relink; then add_shlibpath= add_dir= add= # Finalize command for both is simple: just hardcode it. if test "$hardcode_direct" = yes && test "$hardcode_direct_absolute" = no; then add="$libdir/$linklib" elif test "$hardcode_minus_L" = yes; then add_dir="-L$libdir" add="-l$name" elif test "$hardcode_shlibpath_var" = yes; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac add="-l$name" elif test "$hardcode_automatic" = yes; then if test -n "$inst_prefix_dir" && test -f "$inst_prefix_dir$libdir/$linklib" ; then add="$inst_prefix_dir$libdir/$linklib" else add="$libdir/$linklib" fi else # We cannot seem to hardcode it, guess we'll fake it. add_dir="-L$libdir" # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add="-l$name" fi if test "$linkmode" = prog; then test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" test -n "$add" && finalize_deplibs="$add $finalize_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" fi fi elif test "$linkmode" = prog; then # Here we assume that one of hardcode_direct or hardcode_minus_L # is not unsupported. This is valid on all known static and # shared platforms. if test "$hardcode_direct" != unsupported; then test -n "$old_library" && linklib="$old_library" compile_deplibs="$dir/$linklib $compile_deplibs" finalize_deplibs="$dir/$linklib $finalize_deplibs" else compile_deplibs="-l$name -L$dir $compile_deplibs" finalize_deplibs="-l$name -L$dir $finalize_deplibs" fi elif test "$build_libtool_libs" = yes; then # Not a shared library if test "$deplibs_check_method" != pass_all; then # We're trying link a shared library against a static one # but the system doesn't support it. # Just print a warning and add the library to dependency_libs so # that the program can be linked against the static library. echo $ECHO "*** Warning: This system can not link to static lib archive $lib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have." if test "$module" = yes; then echo "*** But as you try to build a module library, libtool will still create " echo "*** a static module, that should work as long as the dlopening application" echo "*** is linked with the -dlopen flag to resolve symbols at runtime." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using \`nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** \`nm' from GNU binutils and a full rebuild may help." fi if test "$build_old_libs" = no; then build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi else deplibs="$dir/$old_library $deplibs" link_static=yes fi fi # link shared/static library? if test "$linkmode" = lib; then if test -n "$dependency_libs" && { test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes || test "$link_static" = yes; }; then # Extract -R from dependency_libs temp_deplibs= for libdir in $dependency_libs; do case $libdir in -R*) func_stripname '-R' '' "$libdir" temp_xrpath=$func_stripname_result case " $xrpath " in *" $temp_xrpath "*) ;; *) func_append xrpath " $temp_xrpath";; esac;; *) func_append temp_deplibs " $libdir";; esac done dependency_libs="$temp_deplibs" fi func_append newlib_search_path " $absdir" # Link against this library test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs" # ... and its dependency_libs tmp_libs= for deplib in $dependency_libs; do newdependency_libs="$deplib $newdependency_libs" case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result";; *) func_resolve_sysroot "$deplib" ;; esac if $opt_preserve_dup_deps ; then case "$tmp_libs " in *" $func_resolve_sysroot_result "*) func_append specialdeplibs " $func_resolve_sysroot_result" ;; esac fi func_append tmp_libs " $func_resolve_sysroot_result" done if test "$link_all_deplibs" != no; then # Add the search paths of all dependency libraries for deplib in $dependency_libs; do path= case $deplib in -L*) path="$deplib" ;; *.la) func_resolve_sysroot "$deplib" deplib=$func_resolve_sysroot_result func_dirname "$deplib" "" "." dir=$func_dirname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;; *) absdir=`cd "$dir" && pwd` if test -z "$absdir"; then func_warning "cannot determine absolute directory name of \`$dir'" absdir="$dir" fi ;; esac if $GREP "^installed=no" $deplib > /dev/null; then case $host in *-*-darwin*) depdepl= eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` if test -n "$deplibrary_names" ; then for tmp in $deplibrary_names ; do depdepl=$tmp done if test -f "$absdir/$objdir/$depdepl" ; then depdepl="$absdir/$objdir/$depdepl" darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` if test -z "$darwin_install_name"; then darwin_install_name=`${OTOOL64} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` fi func_append compiler_flags " ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}" func_append linker_flags " -dylib_file ${darwin_install_name}:${depdepl}" path= fi fi ;; *) path="-L$absdir/$objdir" ;; esac else eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` test -z "$libdir" && \ func_fatal_error "\`$deplib' is not a valid libtool archive" test "$absdir" != "$libdir" && \ func_warning "\`$deplib' seems to be moved" path="-L$absdir" fi ;; esac case " $deplibs " in *" $path "*) ;; *) deplibs="$path $deplibs" ;; esac done fi # link_all_deplibs != no fi # linkmode = lib done # for deplib in $libs if test "$pass" = link; then if test "$linkmode" = "prog"; then compile_deplibs="$new_inherited_linker_flags $compile_deplibs" finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" else compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` fi fi dependency_libs="$newdependency_libs" if test "$pass" = dlpreopen; then # Link the dlpreopened libraries before other libraries for deplib in $save_deplibs; do deplibs="$deplib $deplibs" done fi if test "$pass" != dlopen; then if test "$pass" != conv; then # Make sure lib_search_path contains only unique directories. lib_search_path= for dir in $newlib_search_path; do case "$lib_search_path " in *" $dir "*) ;; *) func_append lib_search_path " $dir" ;; esac done newlib_search_path= fi if test "$linkmode,$pass" != "prog,link"; then vars="deplibs" else vars="compile_deplibs finalize_deplibs" fi for var in $vars dependency_libs; do # Add libraries to $var in reverse order eval tmp_libs=\"\$$var\" new_libs= for deplib in $tmp_libs; do # FIXME: Pedantically, this is the right thing to do, so # that some nasty dependency loop isn't accidentally # broken: #new_libs="$deplib $new_libs" # Pragmatically, this seems to cause very few problems in # practice: case $deplib in -L*) new_libs="$deplib $new_libs" ;; -R*) ;; *) # And here is the reason: when a library appears more # than once as an explicit dependence of a library, or # is implicitly linked in more than once by the # compiler, it is considered special, and multiple # occurrences thereof are not removed. Compare this # with having the same library being listed as a # dependency of multiple other libraries: in this case, # we know (pedantically, we assume) the library does not # need to be listed more than once, so we keep only the # last copy. This is not always right, but it is rare # enough that we require users that really mean to play # such unportable linking tricks to link the library # using -Wl,-lname, so that libtool does not consider it # for duplicate removal. case " $specialdeplibs " in *" $deplib "*) new_libs="$deplib $new_libs" ;; *) case " $new_libs " in *" $deplib "*) ;; *) new_libs="$deplib $new_libs" ;; esac ;; esac ;; esac done tmp_libs= for deplib in $new_libs; do case $deplib in -L*) case " $tmp_libs " in *" $deplib "*) ;; *) func_append tmp_libs " $deplib" ;; esac ;; *) func_append tmp_libs " $deplib" ;; esac done eval $var=\"$tmp_libs\" done # for var fi # Last step: remove runtime libs from dependency_libs # (they stay in deplibs) tmp_libs= for i in $dependency_libs ; do case " $predeps $postdeps $compiler_lib_search_path " in *" $i "*) i="" ;; esac if test -n "$i" ; then func_append tmp_libs " $i" fi done dependency_libs=$tmp_libs done # for pass if test "$linkmode" = prog; then dlfiles="$newdlfiles" fi if test "$linkmode" = prog || test "$linkmode" = lib; then dlprefiles="$newdlprefiles" fi case $linkmode in oldlib) if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then func_warning "\`-dlopen' is ignored for archives" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "\`-l' and \`-L' are ignored for archives" ;; esac test -n "$rpath" && \ func_warning "\`-rpath' is ignored for archives" test -n "$xrpath" && \ func_warning "\`-R' is ignored for archives" test -n "$vinfo" && \ func_warning "\`-version-info/-version-number' is ignored for archives" test -n "$release" && \ func_warning "\`-release' is ignored for archives" test -n "$export_symbols$export_symbols_regex" && \ func_warning "\`-export-symbols' is ignored for archives" # Now set the variables for building old libraries. build_libtool_libs=no oldlibs="$output" func_append objs "$old_deplibs" ;; lib) # Make sure we only generate libraries of the form `libNAME.la'. case $outputname in lib*) func_stripname 'lib' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" ;; *) test "$module" = no && \ func_fatal_help "libtool library \`$output' must begin with \`lib'" if test "$need_lib_prefix" != no; then # Add the "lib" prefix for modules if required func_stripname '' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" else func_stripname '' '.la' "$outputname" libname=$func_stripname_result fi ;; esac if test -n "$objs"; then if test "$deplibs_check_method" != pass_all; then func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs" else echo $ECHO "*** Warning: Linking the shared library $output against the non-libtool" $ECHO "*** objects $objs is not portable!" func_append libobjs " $objs" fi fi test "$dlself" != no && \ func_warning "\`-dlopen self' is ignored for libtool libraries" set dummy $rpath shift test "$#" -gt 1 && \ func_warning "ignoring multiple \`-rpath's for a libtool library" install_libdir="$1" oldlibs= if test -z "$rpath"; then if test "$build_libtool_libs" = yes; then # Building a libtool convenience library. # Some compilers have problems with a `.al' extension so # convenience libraries should have the same extension an # archive normally would. oldlibs="$output_objdir/$libname.$libext $oldlibs" build_libtool_libs=convenience build_old_libs=yes fi test -n "$vinfo" && \ func_warning "\`-version-info/-version-number' is ignored for convenience libraries" test -n "$release" && \ func_warning "\`-release' is ignored for convenience libraries" else # Parse the version information argument. save_ifs="$IFS"; IFS=':' set dummy $vinfo 0 0 0 shift IFS="$save_ifs" test -n "$7" && \ func_fatal_help "too many parameters to \`-version-info'" # convert absolute version numbers to libtool ages # this retains compatibility with .la files and attempts # to make the code below a bit more comprehensible case $vinfo_number in yes) number_major="$1" number_minor="$2" number_revision="$3" # # There are really only two kinds -- those that # use the current revision as the major version # and those that subtract age and use age as # a minor version. But, then there is irix # which has an extra 1 added just for fun # case $version_type in # correct linux to gnu/linux during the next big refactor darwin|linux|osf|windows|none) func_arith $number_major + $number_minor current=$func_arith_result age="$number_minor" revision="$number_revision" ;; freebsd-aout|freebsd-elf|qnx|sunos) current="$number_major" revision="$number_minor" age="0" ;; irix|nonstopux) func_arith $number_major + $number_minor current=$func_arith_result age="$number_minor" revision="$number_minor" lt_irix_increment=no ;; *) func_fatal_configuration "$modename: unknown library version type \`$version_type'" ;; esac ;; no) current="$1" revision="$2" age="$3" ;; esac # Check that each of the things are valid numbers. case $current in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "CURRENT \`$current' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac case $revision in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "REVISION \`$revision' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac case $age in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "AGE \`$age' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac if test "$age" -gt "$current"; then func_error "AGE \`$age' is greater than the current interface number \`$current'" func_fatal_error "\`$vinfo' is not valid version information" fi # Calculate the version variables. major= versuffix= verstring= case $version_type in none) ;; darwin) # Like Linux, but with the current version available in # verstring for coding it into the library header func_arith $current - $age major=.$func_arith_result versuffix="$major.$age.$revision" # Darwin ld doesn't like 0 for these options... func_arith $current + 1 minor_current=$func_arith_result xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision" verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" ;; freebsd-aout) major=".$current" versuffix=".$current.$revision"; ;; freebsd-elf) major=".$current" versuffix=".$current" ;; irix | nonstopux) if test "X$lt_irix_increment" = "Xno"; then func_arith $current - $age else func_arith $current - $age + 1 fi major=$func_arith_result case $version_type in nonstopux) verstring_prefix=nonstopux ;; *) verstring_prefix=sgi ;; esac verstring="$verstring_prefix$major.$revision" # Add in all the interfaces that we are compatible with. loop=$revision while test "$loop" -ne 0; do func_arith $revision - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring="$verstring_prefix$major.$iface:$verstring" done # Before this point, $major must not contain `.'. major=.$major versuffix="$major.$revision" ;; linux) # correct to gnu/linux during the next big refactor func_arith $current - $age major=.$func_arith_result versuffix="$major.$age.$revision" ;; osf) func_arith $current - $age major=.$func_arith_result versuffix=".$current.$age.$revision" verstring="$current.$age.$revision" # Add in all the interfaces that we are compatible with. loop=$age while test "$loop" -ne 0; do func_arith $current - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring="$verstring:${iface}.0" done # Make executables depend on our current version. func_append verstring ":${current}.0" ;; qnx) major=".$current" versuffix=".$current" ;; sunos) major=".$current" versuffix=".$current.$revision" ;; windows) # Use '-' rather than '.', since we only want one # extension on DOS 8.3 filesystems. func_arith $current - $age major=$func_arith_result versuffix="-$major" ;; *) func_fatal_configuration "unknown library version type \`$version_type'" ;; esac # Clear the version info if we defaulted, and they specified a release. if test -z "$vinfo" && test -n "$release"; then major= case $version_type in darwin) # we can't check for "0.0" in archive_cmds due to quoting # problems, so we reset it completely verstring= ;; *) verstring="0.0" ;; esac if test "$need_version" = no; then versuffix= else versuffix=".0.0" fi fi # Remove version info from name if versioning should be avoided if test "$avoid_version" = yes && test "$need_version" = no; then major= versuffix= verstring="" fi # Check to see if the archive will have undefined symbols. if test "$allow_undefined" = yes; then if test "$allow_undefined_flag" = unsupported; then func_warning "undefined symbols not allowed in $host shared libraries" build_libtool_libs=no build_old_libs=yes fi else # Don't allow undefined symbols. allow_undefined_flag="$no_undefined_flag" fi fi func_generate_dlsyms "$libname" "$libname" "yes" func_append libobjs " $symfileobj" test "X$libobjs" = "X " && libobjs= if test "$opt_mode" != relink; then # Remove our outputs, but don't remove object files since they # may have been created when compiling PIC objects. removelist= tempremovelist=`$ECHO "$output_objdir/*"` for p in $tempremovelist; do case $p in *.$objext | *.gcno) ;; $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*) if test "X$precious_files_regex" != "X"; then if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 then continue fi fi func_append removelist " $p" ;; *) ;; esac done test -n "$removelist" && \ func_show_eval "${RM}r \$removelist" fi # Now set the variables for building old libraries. if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then func_append oldlibs " $output_objdir/$libname.$libext" # Transform .lo files to .o files. oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; $lo2o" | $NL2SP` fi # Eliminate all temporary directories. #for path in $notinst_path; do # lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"` # deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"` # dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"` #done if test -n "$xrpath"; then # If the user specified any rpath flags, then add them. temp_xrpath= for libdir in $xrpath; do func_replace_sysroot "$libdir" func_append temp_xrpath " -R$func_replace_sysroot_result" case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then dependency_libs="$temp_xrpath $dependency_libs" fi fi # Make sure dlfiles contains only unique files that won't be dlpreopened old_dlfiles="$dlfiles" dlfiles= for lib in $old_dlfiles; do case " $dlprefiles $dlfiles " in *" $lib "*) ;; *) func_append dlfiles " $lib" ;; esac done # Make sure dlprefiles contains only unique files old_dlprefiles="$dlprefiles" dlprefiles= for lib in $old_dlprefiles; do case "$dlprefiles " in *" $lib "*) ;; *) func_append dlprefiles " $lib" ;; esac done if test "$build_libtool_libs" = yes; then if test -n "$rpath"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*) # these systems don't actually have a c library (as such)! ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C library is in the System framework func_append deplibs " System.ltframework" ;; *-*-netbsd*) # Don't link with libc until the a.out ld.so is fixed. ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work ;; *) # Add libc to deplibs on all other systems if necessary. if test "$build_libtool_need_lc" = "yes"; then func_append deplibs " -lc" fi ;; esac fi # Transform deplibs into only deplibs that can be linked in shared. name_save=$name libname_save=$libname release_save=$release versuffix_save=$versuffix major_save=$major # I'm not sure if I'm treating the release correctly. I think # release should show up in the -l (ie -lgmp5) so we don't want to # add it in twice. Is that correct? release="" versuffix="" major="" newdeplibs= droppeddeps=no case $deplibs_check_method in pass_all) # Don't check for shared/static. Everything works. # This might be a little naive. We might want to check # whether the library exists or not. But this is on # osf3 & osf4 and I'm not really sure... Just # implementing what was already the behavior. newdeplibs=$deplibs ;; test_compile) # This code stresses the "libraries are programs" paradigm to its # limits. Maybe even breaks it. We compile a program, linking it # against the deplibs as a proxy for the library. Then we can check # whether they linked in statically or dynamically with ldd. $opt_dry_run || $RM conftest.c cat > conftest.c </dev/null` $nocaseglob else potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null` fi for potent_lib in $potential_libs; do # Follow soft links. if ls -lLd "$potent_lib" 2>/dev/null | $GREP " -> " >/dev/null; then continue fi # The statement above tries to avoid entering an # endless loop below, in case of cyclic links. # We might still enter an endless loop, since a link # loop can be closed while we follow links, # but so what? potlib="$potent_lib" while test -h "$potlib" 2>/dev/null; do potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'` case $potliblink in [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";; *) potlib=`$ECHO "$potlib" | $SED 's,[^/]*$,,'`"$potliblink";; esac done if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | $SED -e 10q | $EGREP "$file_magic_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib="" break 2 fi done done fi if test -n "$a_deplib" ; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib" ; then $ECHO "*** with $libname but no candidates were found. (...for file magic test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a file magic. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` for a_deplib in $deplibs; do case $a_deplib in -l*) func_stripname -l '' "$a_deplib" name=$func_stripname_result if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $a_deplib "*) func_append newdeplibs " $a_deplib" a_deplib="" ;; esac fi if test -n "$a_deplib" ; then libname=`eval "\\$ECHO \"$libname_spec\""` for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do potential_libs=`ls $i/$libname[.-]* 2>/dev/null` for potent_lib in $potential_libs; do potlib="$potent_lib" # see symlink-check above in file_magic test if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \ $EGREP "$match_pattern_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib="" break 2 fi done done fi if test -n "$a_deplib" ; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib" ; then $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a regex pattern. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; none | unknown | *) newdeplibs="" tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'` if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then for i in $predeps $postdeps ; do # can't use Xsed below, because $i might contain '/' tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s,$i,,"` done fi case $tmp_deplibs in *[!\ \ ]*) echo if test "X$deplibs_check_method" = "Xnone"; then echo "*** Warning: inter-library dependencies are not supported in this platform." else echo "*** Warning: inter-library dependencies are not known to be supported." fi echo "*** All declared inter-library dependencies are being dropped." droppeddeps=yes ;; esac ;; esac versuffix=$versuffix_save major=$major_save release=$release_save libname=$libname_save name=$name_save case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library with the System framework newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac if test "$droppeddeps" = yes; then if test "$module" = yes; then echo echo "*** Warning: libtool could not satisfy all declared inter-library" $ECHO "*** dependencies of module $libname. Therefore, libtool will create" echo "*** a static module, that should work as long as the dlopening" echo "*** application is linked with the -dlopen flag." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using \`nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** \`nm' from GNU binutils and a full rebuild may help." fi if test "$build_old_libs" = no; then oldlibs="$output_objdir/$libname.$libext" build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi else echo "*** The inter-library dependencies that have been dropped here will be" echo "*** automatically added whenever a program is linked with this library" echo "*** or is declared to -dlopen it." if test "$allow_undefined" = no; then echo echo "*** Since this library must not contain undefined symbols," echo "*** because either the platform does not support them or" echo "*** it was explicitly requested with -no-undefined," echo "*** libtool will only create a static version of it." if test "$build_old_libs" = no; then oldlibs="$output_objdir/$libname.$libext" build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi fi fi # Done checking deplibs! deplibs=$newdeplibs fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" case $host in *-*-darwin*) newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done deplibs="$new_libs" # All the library-specific variables (install_libdir is set above). library_names= old_library= dlname= # Test again, we may have decided not to build it any more if test "$build_libtool_libs" = yes; then # Remove ${wl} instances when linking with ld. # FIXME: should test the right _cmds variable. case $archive_cmds in *\$LD\ *) wl= ;; esac if test "$hardcode_into_libs" = yes; then # Hardcode the library paths hardcode_libdirs= dep_rpath= rpath="$finalize_rpath" test "$opt_mode" != relink && rpath="$compile_rpath$rpath" for libdir in $rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then func_replace_sysroot "$libdir" libdir=$func_replace_sysroot_result if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append dep_rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval "dep_rpath=\"$hardcode_libdir_flag_spec\"" fi if test -n "$runpath_var" && test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" fi test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" fi shlibpath="$finalize_shlibpath" test "$opt_mode" != relink && shlibpath="$compile_shlibpath$shlibpath" if test -n "$shlibpath"; then eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" fi # Get the real and link names of the library. eval shared_ext=\"$shrext_cmds\" eval library_names=\"$library_names_spec\" set dummy $library_names shift realname="$1" shift if test -n "$soname_spec"; then eval soname=\"$soname_spec\" else soname="$realname" fi if test -z "$dlname"; then dlname=$soname fi lib="$output_objdir/$realname" linknames= for link do func_append linknames " $link" done # Use standard objects if they are pic test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP` test "X$libobjs" = "X " && libobjs= delfiles= if test -n "$export_symbols" && test -n "$include_expsyms"; then $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" export_symbols="$output_objdir/$libname.uexp" func_append delfiles " $export_symbols" fi orig_export_symbols= case $host_os in cygwin* | mingw* | cegcc*) if test -n "$export_symbols" && test -z "$export_symbols_regex"; then # exporting using user supplied symfile if test "x`$SED 1q $export_symbols`" != xEXPORTS; then # and it's NOT already a .def file. Must figure out # which of the given symbols are data symbols and tag # them as such. So, trigger use of export_symbols_cmds. # export_symbols gets reassigned inside the "prepare # the list of exported symbols" if statement, so the # include_expsyms logic still works. orig_export_symbols="$export_symbols" export_symbols= always_export_symbols=yes fi fi ;; esac # Prepare the list of exported symbols if test -z "$export_symbols"; then if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then func_verbose "generating symbol list for \`$libname.la'" export_symbols="$output_objdir/$libname.exp" $opt_dry_run || $RM $export_symbols cmds=$export_symbols_cmds save_ifs="$IFS"; IFS='~' for cmd1 in $cmds; do IFS="$save_ifs" # Take the normal branch if the nm_file_list_spec branch # doesn't work or if tool conversion is not needed. case $nm_file_list_spec~$to_tool_file_cmd in *~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*) try_normal_branch=yes eval cmd=\"$cmd1\" func_len " $cmd" len=$func_len_result ;; *) try_normal_branch=no ;; esac if test "$try_normal_branch" = yes \ && { test "$len" -lt "$max_cmd_len" \ || test "$max_cmd_len" -le -1; } then func_show_eval "$cmd" 'exit $?' skipped_export=false elif test -n "$nm_file_list_spec"; then func_basename "$output" output_la=$func_basename_result save_libobjs=$libobjs save_output=$output output=${output_objdir}/${output_la}.nm func_to_tool_file "$output" libobjs=$nm_file_list_spec$func_to_tool_file_result func_append delfiles " $output" func_verbose "creating $NM input file list: $output" for obj in $save_libobjs; do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > "$output" eval cmd=\"$cmd1\" func_show_eval "$cmd" 'exit $?' output=$save_output libobjs=$save_libobjs skipped_export=false else # The command line is too long to execute in one step. func_verbose "using reloadable object file for export list..." skipped_export=: # Break out early, otherwise skipped_export may be # set to false by a later but shorter cmd. break fi done IFS="$save_ifs" if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi fi if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols="$export_symbols" test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi tmp_deplibs= for test_deplib in $deplibs; do case " $convenience " in *" $test_deplib "*) ;; *) func_append tmp_deplibs " $test_deplib" ;; esac done deplibs="$tmp_deplibs" if test -n "$convenience"; then if test -n "$whole_archive_flag_spec" && test "$compiler_needs_object" = yes && test -z "$libobjs"; then # extract the archives, so we have objects to list. # TODO: could optimize this to just extract one archive. whole_archive_flag_spec= fi if test -n "$whole_archive_flag_spec"; then save_libobjs=$libobjs eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= else gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_extract_archives $gentop $convenience func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi fi if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then eval flag=\"$thread_safe_flag_spec\" func_append linker_flags " $flag" fi # Make a backup of the uninstalled library when relinking if test "$opt_mode" = relink; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? fi # Do each of the archive commands. if test "$module" = yes && test -n "$module_cmds" ; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then eval test_cmds=\"$module_expsym_cmds\" cmds=$module_expsym_cmds else eval test_cmds=\"$module_cmds\" cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then eval test_cmds=\"$archive_expsym_cmds\" cmds=$archive_expsym_cmds else eval test_cmds=\"$archive_cmds\" cmds=$archive_cmds fi fi if test "X$skipped_export" != "X:" && func_len " $test_cmds" && len=$func_len_result && test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then : else # The command line is too long to link in one step, link piecewise # or, if using GNU ld and skipped_export is not :, use a linker # script. # Save the value of $output and $libobjs because we want to # use them later. If we have whole_archive_flag_spec, we # want to use save_libobjs as it was before # whole_archive_flag_spec was expanded, because we can't # assume the linker understands whole_archive_flag_spec. # This may have to be revisited, in case too many # convenience libraries get linked in and end up exceeding # the spec. if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then save_libobjs=$libobjs fi save_output=$output func_basename "$output" output_la=$func_basename_result # Clear the reloadable object creation command queue and # initialize k to one. test_cmds= concat_cmds= objlist= last_robj= k=1 if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then output=${output_objdir}/${output_la}.lnkscript func_verbose "creating GNU ld script: $output" echo 'INPUT (' > $output for obj in $save_libobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done echo ')' >> $output func_append delfiles " $output" func_to_tool_file "$output" output=$func_to_tool_file_result elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then output=${output_objdir}/${output_la}.lnk func_verbose "creating linker input file list: $output" : > $output set x $save_libobjs shift firstobj= if test "$compiler_needs_object" = yes; then firstobj="$1 " shift fi for obj do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done func_append delfiles " $output" func_to_tool_file "$output" output=$firstobj\"$file_list_spec$func_to_tool_file_result\" else if test -n "$save_libobjs"; then func_verbose "creating reloadable object files..." output=$output_objdir/$output_la-${k}.$objext eval test_cmds=\"$reload_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 # Loop over the list of objects to be linked. for obj in $save_libobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result if test "X$objlist" = X || test "$len" -lt "$max_cmd_len"; then func_append objlist " $obj" else # The command $test_cmds is almost too long, add a # command to the queue. if test "$k" -eq 1 ; then # The first file doesn't have a previous command to add. reload_objs=$objlist eval concat_cmds=\"$reload_cmds\" else # All subsequent reloadable object files will link in # the last one created. reload_objs="$objlist $last_robj" eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\" fi last_robj=$output_objdir/$output_la-${k}.$objext func_arith $k + 1 k=$func_arith_result output=$output_objdir/$output_la-${k}.$objext objlist=" $obj" func_len " $last_robj" func_arith $len0 + $func_len_result len=$func_arith_result fi done # Handle the remaining objects by creating one last # reloadable object file. All subsequent reloadable object # files will link in the last one created. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ reload_objs="$objlist $last_robj" eval concat_cmds=\"\${concat_cmds}$reload_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\" fi func_append delfiles " $output" else output= fi if ${skipped_export-false}; then func_verbose "generating symbol list for \`$libname.la'" export_symbols="$output_objdir/$libname.exp" $opt_dry_run || $RM $export_symbols libobjs=$output # Append the command to create the export file. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi fi test -n "$save_libobjs" && func_verbose "creating a temporary reloadable object file: $output" # Loop through the commands generated above and execute them. save_ifs="$IFS"; IFS='~' for cmd in $concat_cmds; do IFS="$save_ifs" $opt_silent || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test "$opt_mode" = relink; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS="$save_ifs" if test -n "$export_symbols_regex" && ${skipped_export-false}; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi if ${skipped_export-false}; then if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols="$export_symbols" test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi fi libobjs=$output # Restore the value of output. output=$save_output if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= fi # Expand the library linking commands again to reset the # value of $libobjs for piecewise linking. # Do each of the archive commands. if test "$module" = yes && test -n "$module_cmds" ; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then cmds=$module_expsym_cmds else cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then cmds=$archive_expsym_cmds else cmds=$archive_cmds fi fi fi if test -n "$delfiles"; then # Append the command to remove temporary files to $cmds. eval cmds=\"\$cmds~\$RM $delfiles\" fi # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi save_ifs="$IFS"; IFS='~' for cmd in $cmds; do IFS="$save_ifs" eval cmd=\"$cmd\" $opt_silent || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test "$opt_mode" = relink; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS="$save_ifs" # Restore the uninstalled library and exit if test "$opt_mode" = relink; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? if test -n "$convenience"; then if test -z "$whole_archive_flag_spec"; then func_show_eval '${RM}r "$gentop"' fi fi exit $EXIT_SUCCESS fi # Create links to the real library. for linkname in $linknames; do if test "$realname" != "$linkname"; then func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' fi done # If -module or -export-dynamic was specified, set the dlname. if test "$module" = yes || test "$export_dynamic" = yes; then # On all known operating systems, these are identical. dlname="$soname" fi fi ;; obj) if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then func_warning "\`-dlopen' is ignored for objects" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "\`-l' and \`-L' are ignored for objects" ;; esac test -n "$rpath" && \ func_warning "\`-rpath' is ignored for objects" test -n "$xrpath" && \ func_warning "\`-R' is ignored for objects" test -n "$vinfo" && \ func_warning "\`-version-info' is ignored for objects" test -n "$release" && \ func_warning "\`-release' is ignored for objects" case $output in *.lo) test -n "$objs$old_deplibs" && \ func_fatal_error "cannot build library object \`$output' from non-libtool objects" libobj=$output func_lo2o "$libobj" obj=$func_lo2o_result ;; *) libobj= obj="$output" ;; esac # Delete the old objects. $opt_dry_run || $RM $obj $libobj # Objects from convenience libraries. This assumes # single-version convenience libraries. Whenever we create # different ones for PIC/non-PIC, this we'll have to duplicate # the extraction. reload_conv_objs= gentop= # reload_cmds runs $LD directly, so let us get rid of # -Wl from whole_archive_flag_spec and hope we can get by with # turning comma into space.. wl= if test -n "$convenience"; then if test -n "$whole_archive_flag_spec"; then eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" reload_conv_objs=$reload_objs\ `$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'` else gentop="$output_objdir/${obj}x" func_append generated " $gentop" func_extract_archives $gentop $convenience reload_conv_objs="$reload_objs $func_extract_archives_result" fi fi # If we're not building shared, we need to use non_pic_objs test "$build_libtool_libs" != yes && libobjs="$non_pic_objects" # Create the old-style object. reload_objs="$objs$old_deplibs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; /\.lib$/d; $lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test output="$obj" func_execute_cmds "$reload_cmds" 'exit $?' # Exit if we aren't doing a library object file. if test -z "$libobj"; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS fi if test "$build_libtool_libs" != yes; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi # Create an invalid libtool object if no PIC, so that we don't # accidentally link it into a program. # $show "echo timestamp > $libobj" # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? exit $EXIT_SUCCESS fi if test -n "$pic_flag" || test "$pic_mode" != default; then # Only do commands if we really have different PIC objects. reload_objs="$libobjs $reload_conv_objs" output="$libobj" func_execute_cmds "$reload_cmds" 'exit $?' fi if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS ;; prog) case $host in *cygwin*) func_stripname '' '.exe' "$output" output=$func_stripname_result.exe;; esac test -n "$vinfo" && \ func_warning "\`-version-info' is ignored for programs" test -n "$release" && \ func_warning "\`-release' is ignored for programs" test "$preload" = yes \ && test "$dlopen_support" = unknown \ && test "$dlopen_self" = unknown \ && test "$dlopen_self_static" = unknown && \ func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support." case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library is the System framework compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac case $host in *-*-darwin*) # Don't allow lazy linking, it breaks C++ global constructors # But is supposedly fixed on 10.4 or later (yay!). if test "$tagname" = CXX ; then case ${MACOSX_DEPLOYMENT_TARGET-10.0} in 10.[0123]) func_append compile_command " ${wl}-bind_at_load" func_append finalize_command " ${wl}-bind_at_load" ;; esac fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $compile_deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $compile_deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done compile_deplibs="$new_libs" func_append compile_command " $compile_deplibs" func_append finalize_command " $finalize_deplibs" if test -n "$rpath$xrpath"; then # If the user specified any rpath flags, then add them. for libdir in $rpath $xrpath; do # This is the magic to use -rpath. case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done fi # Now hardcode the library paths rpath= hardcode_libdirs= for libdir in $compile_rpath $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'` case :$dllsearchpath: in *":$libdir:"*) ;; ::) dllsearchpath=$libdir;; *) func_append dllsearchpath ":$libdir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval rpath=\" $hardcode_libdir_flag_spec\" fi compile_rpath="$rpath" rpath= hardcode_libdirs= for libdir in $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$finalize_perm_rpath " in *" $libdir "*) ;; *) func_append finalize_perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval rpath=\" $hardcode_libdir_flag_spec\" fi finalize_rpath="$rpath" if test -n "$libobjs" && test "$build_old_libs" = yes; then # Transform all the library objects into standard objects. compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP` finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP` fi func_generate_dlsyms "$outputname" "@PROGRAM@" "no" # template prelinking step if test -n "$prelink_cmds"; then func_execute_cmds "$prelink_cmds" 'exit $?' fi wrappers_required=yes case $host in *cegcc* | *mingw32ce*) # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway. wrappers_required=no ;; *cygwin* | *mingw* ) if test "$build_libtool_libs" != yes; then wrappers_required=no fi ;; *) if test "$need_relink" = no || test "$build_libtool_libs" != yes; then wrappers_required=no fi ;; esac if test "$wrappers_required" = no; then # Replace the output file specification. compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'` link_command="$compile_command$compile_rpath" # We have no uninstalled library dependencies, so finalize right now. exit_status=0 func_show_eval "$link_command" 'exit_status=$?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Delete the generated files. if test -f "$output_objdir/${outputname}S.${objext}"; then func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"' fi exit $exit_status fi if test -n "$compile_shlibpath$finalize_shlibpath"; then compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" fi if test -n "$finalize_shlibpath"; then finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" fi compile_var= finalize_var= if test -n "$runpath_var"; then if test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done compile_var="$runpath_var=\"$rpath\$$runpath_var\" " fi if test -n "$finalize_perm_rpath"; then # We should set the runpath_var. rpath= for dir in $finalize_perm_rpath; do func_append rpath "$dir:" done finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " fi fi if test "$no_install" = yes; then # We don't need to create a wrapper script. link_command="$compile_var$compile_command$compile_rpath" # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'` # Delete the old output file. $opt_dry_run || $RM $output # Link the executable and exit func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi exit $EXIT_SUCCESS fi if test "$hardcode_action" = relink; then # Fast installation is not supported link_command="$compile_var$compile_command$compile_rpath" relink_command="$finalize_var$finalize_command$finalize_rpath" func_warning "this platform does not like uninstalled shared libraries" func_warning "\`$output' will be relinked during installation" else if test "$fast_install" != no; then link_command="$finalize_var$compile_command$finalize_rpath" if test "$fast_install" = yes; then relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'` else # fast_install is set to needless relink_command= fi else link_command="$compile_var$compile_command$compile_rpath" relink_command="$finalize_var$finalize_command$finalize_rpath" fi fi # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` # Delete the old output files. $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output_objdir/$outputname" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Now create the wrapper script. func_verbose "creating $output" # Quote the relink command for shipping. if test -n "$relink_command"; then # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done relink_command="(cd `pwd`; $relink_command)" relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` fi # Only actually do things if not in dry run mode. $opt_dry_run || { # win32 will think the script is a binary if it has # a .exe suffix, so we strip it off here. case $output in *.exe) func_stripname '' '.exe' "$output" output=$func_stripname_result ;; esac # test for cygwin because mv fails w/o .exe extensions case $host in *cygwin*) exeext=.exe func_stripname '' '.exe' "$outputname" outputname=$func_stripname_result ;; *) exeext= ;; esac case $host in *cygwin* | *mingw* ) func_dirname_and_basename "$output" "" "." output_name=$func_basename_result output_path=$func_dirname_result cwrappersource="$output_path/$objdir/lt-$output_name.c" cwrapper="$output_path/$output_name.exe" $RM $cwrappersource $cwrapper trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 func_emit_cwrapperexe_src > $cwrappersource # The wrapper executable is built using the $host compiler, # because it contains $host paths and files. If cross- # compiling, it, like the target executable, must be # executed on the $host or under an emulation environment. $opt_dry_run || { $LTCC $LTCFLAGS -o $cwrapper $cwrappersource $STRIP $cwrapper } # Now, create the wrapper script for func_source use: func_ltwrapper_scriptname $cwrapper $RM $func_ltwrapper_scriptname_result trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 $opt_dry_run || { # note: this script will not be executed, so do not chmod. if test "x$build" = "x$host" ; then $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result else func_emit_wrapper no > $func_ltwrapper_scriptname_result fi } ;; * ) $RM $output trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 func_emit_wrapper no > $output chmod +x $output ;; esac } exit $EXIT_SUCCESS ;; esac # See if we need to build an old-fashioned archive. for oldlib in $oldlibs; do if test "$build_libtool_libs" = convenience; then oldobjs="$libobjs_save $symfileobj" addlibs="$convenience" build_libtool_libs=no else if test "$build_libtool_libs" = module; then oldobjs="$libobjs_save" build_libtool_libs=no else oldobjs="$old_deplibs $non_pic_objects" if test "$preload" = yes && test -f "$symfileobj"; then func_append oldobjs " $symfileobj" fi fi addlibs="$old_convenience" fi if test -n "$addlibs"; then gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_extract_archives $gentop $addlibs func_append oldobjs " $func_extract_archives_result" fi # Do each command in the archive commands. if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then cmds=$old_archive_from_new_cmds else # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append oldobjs " $func_extract_archives_result" fi # POSIX demands no paths to be encoded in archives. We have # to avoid creating archives with duplicate basenames if we # might have to extract them afterwards, e.g., when creating a # static archive out of a convenience library, or when linking # the entirety of a libtool archive into another (currently # not supported by libtool). if (for obj in $oldobjs do func_basename "$obj" $ECHO "$func_basename_result" done | sort | sort -uc >/dev/null 2>&1); then : else echo "copying selected object files to avoid basename conflicts..." gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_mkdir_p "$gentop" save_oldobjs=$oldobjs oldobjs= counter=1 for obj in $save_oldobjs do func_basename "$obj" objbase="$func_basename_result" case " $oldobjs " in " ") oldobjs=$obj ;; *[\ /]"$objbase "*) while :; do # Make sure we don't pick an alternate name that also # overlaps. newobj=lt$counter-$objbase func_arith $counter + 1 counter=$func_arith_result case " $oldobjs " in *[\ /]"$newobj "*) ;; *) if test ! -f "$gentop/$newobj"; then break; fi ;; esac done func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" func_append oldobjs " $gentop/$newobj" ;; *) func_append oldobjs " $obj" ;; esac done fi func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result eval cmds=\"$old_archive_cmds\" func_len " $cmds" len=$func_len_result if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then cmds=$old_archive_cmds elif test -n "$archiver_list_spec"; then func_verbose "using command file archive linking..." for obj in $oldobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > $output_objdir/$libname.libcmd func_to_tool_file "$output_objdir/$libname.libcmd" oldobjs=" $archiver_list_spec$func_to_tool_file_result" cmds=$old_archive_cmds else # the command line is too long to link in one step, link in parts func_verbose "using piecewise archive linking..." save_RANLIB=$RANLIB RANLIB=: objlist= concat_cmds= save_oldobjs=$oldobjs oldobjs= # Is there a better way of finding the last object in the list? for obj in $save_oldobjs do last_oldobj=$obj done eval test_cmds=\"$old_archive_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 for obj in $save_oldobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result func_append objlist " $obj" if test "$len" -lt "$max_cmd_len"; then : else # the above command should be used before it gets too long oldobjs=$objlist if test "$obj" = "$last_oldobj" ; then RANLIB=$save_RANLIB fi test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\" objlist= len=$len0 fi done RANLIB=$save_RANLIB oldobjs=$objlist if test "X$oldobjs" = "X" ; then eval cmds=\"\$concat_cmds\" else eval cmds=\"\$concat_cmds~\$old_archive_cmds\" fi fi fi func_execute_cmds "$cmds" 'exit $?' done test -n "$generated" && \ func_show_eval "${RM}r$generated" # Now create the libtool archive. case $output in *.la) old_library= test "$build_old_libs" = yes && old_library="$libname.$libext" func_verbose "creating $output" # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done # Quote the link command for shipping. relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` if test "$hardcode_automatic" = yes ; then relink_command= fi # Only create the output if not a dry run. $opt_dry_run || { for installed in no yes; do if test "$installed" = yes; then if test -z "$install_libdir"; then break fi output="$output_objdir/$outputname"i # Replace all uninstalled libtool libraries with the installed ones newdependency_libs= for deplib in $dependency_libs; do case $deplib in *.la) func_basename "$deplib" name="$func_basename_result" func_resolve_sysroot "$deplib" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result` test -z "$libdir" && \ func_fatal_error "\`$deplib' is not a valid libtool archive" func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name" ;; -L*) func_stripname -L '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -L$func_replace_sysroot_result" ;; -R*) func_stripname -R '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -R$func_replace_sysroot_result" ;; *) func_append newdependency_libs " $deplib" ;; esac done dependency_libs="$newdependency_libs" newdlfiles= for lib in $dlfiles; do case $lib in *.la) func_basename "$lib" name="$func_basename_result" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "\`$lib' is not a valid libtool archive" func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name" ;; *) func_append newdlfiles " $lib" ;; esac done dlfiles="$newdlfiles" newdlprefiles= for lib in $dlprefiles; do case $lib in *.la) # Only pass preopened files to the pseudo-archive (for # eventual linking with the app. that links it) if we # didn't already link the preopened objects directly into # the library: func_basename "$lib" name="$func_basename_result" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "\`$lib' is not a valid libtool archive" func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name" ;; esac done dlprefiles="$newdlprefiles" else newdlfiles= for lib in $dlfiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlfiles " $abs" done dlfiles="$newdlfiles" newdlprefiles= for lib in $dlprefiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlprefiles " $abs" done dlprefiles="$newdlprefiles" fi $RM $output # place dlname in correct position for cygwin # In fact, it would be nice if we could use this code for all target # systems that can't hard-code library paths into their executables # and that have no shared library path variable independent of PATH, # but it turns out we can't easily determine that from inspecting # libtool variables, so we have to hard-code the OSs to which it # applies here; at the moment, that means platforms that use the PE # object format with DLL files. See the long comment at the top of # tests/bindir.at for full details. tdlname=$dlname case $host,$output,$installed,$module,$dlname in *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) # If a -bindir argument was supplied, place the dll there. if test "x$bindir" != x ; then func_relative_path "$install_libdir" "$bindir" tdlname=$func_relative_path_result$dlname else # Otherwise fall back on heuristic. tdlname=../bin/$dlname fi ;; esac $ECHO > $output "\ # $outputname - a libtool library file # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # Please DO NOT delete this file! # It is necessary for linking the library. # The name that we can dlopen(3). dlname='$tdlname' # Names of this library. library_names='$library_names' # The name of the static archive. old_library='$old_library' # Linker flags that can not go in dependency_libs. inherited_linker_flags='$new_inherited_linker_flags' # Libraries that this one depends upon. dependency_libs='$dependency_libs' # Names of additional weak libraries provided by this library weak_library_names='$weak_libs' # Version information for $libname. current=$current age=$age revision=$revision # Is this an already installed library? installed=$installed # Should we warn about portability when linking against -modules? shouldnotlink=$module # Files to dlopen/dlpreopen dlopen='$dlfiles' dlpreopen='$dlprefiles' # Directory that this library needs to be installed in: libdir='$install_libdir'" if test "$installed" = no && test "$need_relink" = yes; then $ECHO >> $output "\ relink_command=\"$relink_command\"" fi done } # Do a symbolic link so that the libtool archive can be found in # LD_LIBRARY_PATH before the program is installed. func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' ;; esac exit $EXIT_SUCCESS } { test "$opt_mode" = link || test "$opt_mode" = relink; } && func_mode_link ${1+"$@"} # func_mode_uninstall arg... func_mode_uninstall () { $opt_debug RM="$nonopt" files= rmforce= exit_status=0 # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic="$magic" for arg do case $arg in -f) func_append RM " $arg"; rmforce=yes ;; -*) func_append RM " $arg" ;; *) func_append files " $arg" ;; esac done test -z "$RM" && \ func_fatal_help "you must specify an RM program" rmdirs= for file in $files; do func_dirname "$file" "" "." dir="$func_dirname_result" if test "X$dir" = X.; then odir="$objdir" else odir="$dir/$objdir" fi func_basename "$file" name="$func_basename_result" test "$opt_mode" = uninstall && odir="$dir" # Remember odir for removal later, being careful to avoid duplicates if test "$opt_mode" = clean; then case " $rmdirs " in *" $odir "*) ;; *) func_append rmdirs " $odir" ;; esac fi # Don't error if the file doesn't exist and rm -f was used. if { test -L "$file"; } >/dev/null 2>&1 || { test -h "$file"; } >/dev/null 2>&1 || test -f "$file"; then : elif test -d "$file"; then exit_status=1 continue elif test "$rmforce" = yes; then continue fi rmfiles="$file" case $name in *.la) # Possibly a libtool archive, so verify it. if func_lalib_p "$file"; then func_source $dir/$name # Delete the libtool libraries and symlinks. for n in $library_names; do func_append rmfiles " $odir/$n" done test -n "$old_library" && func_append rmfiles " $odir/$old_library" case "$opt_mode" in clean) case " $library_names " in *" $dlname "*) ;; *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;; esac test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i" ;; uninstall) if test -n "$library_names"; then # Do each command in the postuninstall commands. func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' fi if test -n "$old_library"; then # Do each command in the old_postuninstall commands. func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' fi # FIXME: should reinstall the best remaining shared library. ;; esac fi ;; *.lo) # Possibly a libtool object, so verify it. if func_lalib_p "$file"; then # Read the .lo file func_source $dir/$name # Add PIC object to the list of files to remove. if test -n "$pic_object" && test "$pic_object" != none; then func_append rmfiles " $dir/$pic_object" fi # Add non-PIC object to the list of files to remove. if test -n "$non_pic_object" && test "$non_pic_object" != none; then func_append rmfiles " $dir/$non_pic_object" fi fi ;; *) if test "$opt_mode" = clean ; then noexename=$name case $file in *.exe) func_stripname '' '.exe' "$file" file=$func_stripname_result func_stripname '' '.exe' "$name" noexename=$func_stripname_result # $file with .exe has already been added to rmfiles, # add $file without .exe func_append rmfiles " $file" ;; esac # Do a test to see if this is a libtool program. if func_ltwrapper_p "$file"; then if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" relink_command= func_source $func_ltwrapper_scriptname_result func_append rmfiles " $func_ltwrapper_scriptname_result" else relink_command= func_source $dir/$noexename fi # note $name still contains .exe if it was in $file originally # as does the version of $file that was added into $rmfiles func_append rmfiles " $odir/$name $odir/${name}S.${objext}" if test "$fast_install" = yes && test -n "$relink_command"; then func_append rmfiles " $odir/lt-$name" fi if test "X$noexename" != "X$name" ; then func_append rmfiles " $odir/lt-${noexename}.c" fi fi fi ;; esac func_show_eval "$RM $rmfiles" 'exit_status=1' done # Try to remove the ${objdir}s in the directories where we deleted files for dir in $rmdirs; do if test -d "$dir"; then func_show_eval "rmdir $dir >/dev/null 2>&1" fi done exit $exit_status } { test "$opt_mode" = uninstall || test "$opt_mode" = clean; } && func_mode_uninstall ${1+"$@"} test -z "$opt_mode" && { help="$generic_help" func_fatal_help "you must specify a MODE" } test -z "$exec_cmd" && \ func_fatal_help "invalid operation mode \`$opt_mode'" if test -n "$exec_cmd"; then eval exec "$exec_cmd" exit $EXIT_FAILURE fi exit $exit_status # The TAGs below are defined such that we never get into a situation # in which we disable both kinds of libraries. Given conflicting # choices, we go for a static library, that is the most portable, # since we can't tell whether shared libraries were disabled because # the user asked for that or because the platform doesn't support # them. This is particularly important on AIX, because we don't # support having both static and shared libraries enabled at the same # time on that platform, so we default to a shared-only configuration. # If a disable-shared tag is given, we'll fallback to a static-only # configuration. But we'll never go from static-only to shared-only. # ### BEGIN LIBTOOL TAG CONFIG: disable-shared build_libtool_libs=no build_old_libs=yes # ### END LIBTOOL TAG CONFIG: disable-shared # ### BEGIN LIBTOOL TAG CONFIG: disable-static build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` # ### END LIBTOOL TAG CONFIG: disable-static # Local Variables: # mode:shell-script # sh-indentation:2 # End: # vi:sw=2 sipxtapi-3.3.0~test17/build-aux/missing0000755000175000017500000002415212321250501020662 0ustar00danieldaniel00000000000000#! /bin/sh # Common stub for a few missing GNU programs while installing. scriptversion=2012-01-06.13; # UTC # Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003, 2004, 2005, 2006, # 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc. # Originally by Fran,cois Pinard , 1996. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. if test $# -eq 0; then echo 1>&2 "Try \`$0 --help' for more information" exit 1 fi run=: sed_output='s/.* --output[ =]\([^ ]*\).*/\1/p' sed_minuso='s/.* -o \([^ ]*\).*/\1/p' # In the cases where this matters, `missing' is being run in the # srcdir already. if test -f configure.ac; then configure_ac=configure.ac else configure_ac=configure.in fi msg="missing on your system" case $1 in --run) # Try to run requested program, and just exit if it succeeds. run= shift "$@" && exit 0 # Exit code 63 means version mismatch. This often happens # when the user try to use an ancient version of a tool on # a file that requires a minimum version. In this case we # we should proceed has if the program had been absent, or # if --run hadn't been passed. if test $? = 63; then run=: msg="probably too old" fi ;; -h|--h|--he|--hel|--help) echo "\ $0 [OPTION]... PROGRAM [ARGUMENT]... Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an error status if there is no known handling for PROGRAM. Options: -h, --help display this help and exit -v, --version output version information and exit --run try to run the given command, and emulate it if it fails Supported PROGRAM values: aclocal touch file \`aclocal.m4' autoconf touch file \`configure' autoheader touch file \`config.h.in' autom4te touch the output file, or create a stub one automake touch all \`Makefile.in' files bison create \`y.tab.[ch]', if possible, from existing .[ch] flex create \`lex.yy.c', if possible, from existing .c help2man touch the output file lex create \`lex.yy.c', if possible, from existing .c makeinfo touch the output file yacc create \`y.tab.[ch]', if possible, from existing .[ch] Version suffixes to PROGRAM as well as the prefixes \`gnu-', \`gnu', and \`g' are ignored when checking the name. Send bug reports to ." exit $? ;; -v|--v|--ve|--ver|--vers|--versi|--versio|--version) echo "missing $scriptversion (GNU Automake)" exit $? ;; -*) echo 1>&2 "$0: Unknown \`$1' option" echo 1>&2 "Try \`$0 --help' for more information" exit 1 ;; esac # normalize program name to check for. program=`echo "$1" | sed ' s/^gnu-//; t s/^gnu//; t s/^g//; t'` # Now exit if we have it, but it failed. Also exit now if we # don't have it and --version was passed (most likely to detect # the program). This is about non-GNU programs, so use $1 not # $program. case $1 in lex*|yacc*) # Not GNU programs, they don't have --version. ;; *) if test -z "$run" && ($1 --version) > /dev/null 2>&1; then # We have it, but it failed. exit 1 elif test "x$2" = "x--version" || test "x$2" = "x--help"; then # Could not run --version or --help. This is probably someone # running `$TOOL --version' or `$TOOL --help' to check whether # $TOOL exists and not knowing $TOOL uses missing. exit 1 fi ;; esac # If it does not exist, or fails to run (possibly an outdated version), # try to emulate it. case $program in aclocal*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified \`acinclude.m4' or \`${configure_ac}'. You might want to install the \`Automake' and \`Perl' packages. Grab them from any GNU archive site." touch aclocal.m4 ;; autoconf*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified \`${configure_ac}'. You might want to install the \`Autoconf' and \`GNU m4' packages. Grab them from any GNU archive site." touch configure ;; autoheader*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified \`acconfig.h' or \`${configure_ac}'. You might want to install the \`Autoconf' and \`GNU m4' packages. Grab them from any GNU archive site." files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' ${configure_ac}` test -z "$files" && files="config.h" touch_files= for f in $files; do case $f in *:*) touch_files="$touch_files "`echo "$f" | sed -e 's/^[^:]*://' -e 's/:.*//'`;; *) touch_files="$touch_files $f.in";; esac done touch $touch_files ;; automake*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'. You might want to install the \`Automake' and \`Perl' packages. Grab them from any GNU archive site." find . -type f -name Makefile.am -print | sed 's/\.am$/.in/' | while read f; do touch "$f"; done ;; autom4te*) echo 1>&2 "\ WARNING: \`$1' is needed, but is $msg. You might have modified some files without having the proper tools for further handling them. You can get \`$1' as part of \`Autoconf' from any GNU archive site." file=`echo "$*" | sed -n "$sed_output"` test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` if test -f "$file"; then touch $file else test -z "$file" || exec >$file echo "#! /bin/sh" echo "# Created by GNU Automake missing as a replacement of" echo "# $ $@" echo "exit 0" chmod +x $file exit 1 fi ;; bison*|yacc*) echo 1>&2 "\ WARNING: \`$1' $msg. You should only need it if you modified a \`.y' file. You may need the \`Bison' package in order for those modifications to take effect. You can get \`Bison' from any GNU archive site." rm -f y.tab.c y.tab.h if test $# -ne 1; then eval LASTARG=\${$#} case $LASTARG in *.y) SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'` if test -f "$SRCFILE"; then cp "$SRCFILE" y.tab.c fi SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'` if test -f "$SRCFILE"; then cp "$SRCFILE" y.tab.h fi ;; esac fi if test ! -f y.tab.h; then echo >y.tab.h fi if test ! -f y.tab.c; then echo 'main() { return 0; }' >y.tab.c fi ;; lex*|flex*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified a \`.l' file. You may need the \`Flex' package in order for those modifications to take effect. You can get \`Flex' from any GNU archive site." rm -f lex.yy.c if test $# -ne 1; then eval LASTARG=\${$#} case $LASTARG in *.l) SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'` if test -f "$SRCFILE"; then cp "$SRCFILE" lex.yy.c fi ;; esac fi if test ! -f lex.yy.c; then echo 'main() { return 0; }' >lex.yy.c fi ;; help2man*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified a dependency of a manual page. You may need the \`Help2man' package in order for those modifications to take effect. You can get \`Help2man' from any GNU archive site." file=`echo "$*" | sed -n "$sed_output"` test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` if test -f "$file"; then touch $file else test -z "$file" || exec >$file echo ".ab help2man is required to generate this page" exit $? fi ;; makeinfo*) echo 1>&2 "\ WARNING: \`$1' is $msg. You should only need it if you modified a \`.texi' or \`.texinfo' file, or any other file indirectly affecting the aspect of the manual. The spurious call might also be the consequence of using a buggy \`make' (AIX, DU, IRIX). You might want to install the \`Texinfo' package or the \`GNU make' package. Grab either from any GNU archive site." # The file to touch is that specified with -o ... file=`echo "$*" | sed -n "$sed_output"` test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` if test -z "$file"; then # ... or it is the one specified with @setfilename ... infile=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'` file=`sed -n ' /^@setfilename/{ s/.* \([^ ]*\) *$/\1/ p q }' $infile` # ... or it is derived from the source name (dir/f.texi becomes f.info) test -z "$file" && file=`echo "$infile" | sed 's,.*/,,;s,.[^.]*$,,'`.info fi # If the file does not exist, the user really needs makeinfo; # let's fail without touching anything. test -f $file || exit 1 touch $file ;; *) echo 1>&2 "\ WARNING: \`$1' is needed, and is $msg. You might have modified some files without having the proper tools for further handling them. Check the \`README' file, it often tells you about the needed prerequisites for installing this package. You may also peek at any GNU archive site, in case some other package would contain this missing \`$1' program." exit 1 ;; esac exit 0 # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: sipxtapi-3.3.0~test17/config/0000755000175000017500000000000012321445023016637 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/config/sipXcommon.am.inc0000644000175000017500000000504112205613305022063 0ustar00danieldaniel00000000000000# -*-makefile-*- ConfigureArgs=$(shell sed \ -e '/^ *\$$ .*\/configure/!d' \ -e 's/^ *\$$ .*\/configure *//' \ $(top_builddir)/config.log \ ) LocalizeSipXconfig = sed \ -e 's,@PACKAGE\@,@PACKAGE@,g' \ -e 's,@VERSION\@,@VERSION@,g' \ -e 's,@abs_builddir\@,@abs_builddir@,g' \ -e 's,@abs_srcdir\@,@abs_srcdir@,g' \ -e 's,@abs_top_srcdir\@,@abs_top_srcdir@,g' \ -e 's,@sipx_abs_srcdir\@,@sipx_abs_srcdir@,g' \ -e 's!@CONFIGURE_OPTIONS@!$(ConfigureArgs)!g' \ -e 's,@bindir\@,$(bindir),g' \ -e 's,@datadir\@,$(datadir),g' \ -e 's,@htmldir\@,@htmldir@,g' \ -e 's,@INSTALL\@,@INSTALL@,g' \ -e 's,@install_sh\@,@install_sh@,g' \ -e 's,@libdir\@,$(libdir),g' \ -e 's,@localstatedir\@,$(localstatedir),g' \ -e 's,@pkgdatadir\@,@pkgdatadir@,g' \ -e 's,@prefix\@,$(prefix),g' \ -e 's,@profiledir\@,@profiledir@,g' \ -e 's,@wwwdir\@,@wwwdir@,g' \ -e 's,@host\@,@host@,g' \ -e 's,@PERL\@,@PERL@,g' \ -e 's,@APACHE2_HTTPD\@,@APACHE2_HTTPD@,g' \ -e 's,@APACHE2_MOD\@,@APACHE2_MOD@,g' \ -e 's,@CLOVER_HOME\@,@CLOVER_HOME@,g' \ -e 's,@JAVAC_DEBUG\@,@JAVAC_DEBUG@,g' \ -e 's,@JAVAC_OPTIMIZED\@,@JAVAC_OPTIMIZED@,g' \ -e 's,@JAVA\@,@JAVA@,g' \ -e 's,@JAVA_HOME\@,@JAVA_HOME@,g' \ -e 's,@JBOSS_HOME\@,@JBOSS_HOME@,g' \ -e 's,@JBOSS_SERVER_CONF\@,@JBOSS_SERVER_CONF@,g' \ -e 's,@SIPFOUNDRY_ORG\@,@SIPFOUNDRY_ORG@,g' \ -e 's,@SIPXCONFIG_LIBDIR\@,@SIPXCONFIG_LIBDIR@,g' \ -e 's,@SIPXPBXUSER\@,@SIPXPBXUSER@,g' \ -e 's,@SIPX_BINDIR\@,@SIPX_BINDIR@,g' \ -e 's,@SIPX_CONFDIR\@,@SIPX_CONFDIR@,g' \ -e 's,@SIPX_CONFIGPHONEDIR\@,@SIPX_CONFIGPHONEDIR@,g' \ -e 's,@SIPX_BACKUPDIR\@,@SIPX_BACKUPDIR@,g' \ -e 's,@SIPX_DATADIR\@,@SIPX_DATADIR@,g' \ -e 's,@SIPX_DBDIR\@,@SIPX_DBDIR@,g' \ -e 's,@SIPX_DOCDIR\@,@SIPX_DOCDIR@,g' \ -e 's,@SIPX_LOGDIR\@,@SIPX_LOGDIR@,g' \ -e 's,@SIPX_RUNDIR\@,@SIPX_RUNDIR@,g' \ -e 's,@SIPX_TMPDIR\@,@SIPX_TMPDIR@,g' \ -e 's,@SIPX_INCDIR\@,@SIPX_INCDIR@,g' \ -e 's,@SIPX_LIBDIR\@,@SIPX_LIBDIR@,g' \ -e 's,@SIPX_SCHEMADIR\@,@SIPX_SCHEMADIR@,g' \ -e 's,@SIPX_VXMLDATADIR\@,@SIPX_VXMLDATADIR@,g' \ -e 's,@SIPX_PARKMUSICDIR\@,@SIPX_PARKMUSICDIR@,g' \ -e 's,@SPRING_HOME\@,@SPRING_HOME@,g' \ -e 's,@XPRESSA_BUILD_NUMBER\@,@XPRESSA_BUILD_NUMBER@,g' \ -e 's,@XPRESSA_BUILD_COMMENT\@,@XPRESSA_BUILD_COMMENT@,g' \ -e 's,@SIPXPHONELIB\@,@SIPXPHONELIB@,g' \ -e 's,@SIPXPHONEDATA\@,@SIPXPHONEDATA@,g' \ -e 's,@SIPXPHONECONF\@,@SIPXPHONECONF@,g' \ -e 's,@NAMED_PROGRAM\@,@NAMED_PROGRAM@,g' sipxtapi-3.3.0~test17/config/sipXpkgtop.mak0000644000175000017500000000266012205613305021506 0ustar00danieldaniel00000000000000## Makefile components common to the top level of the package source tree ## BUILDSTAMP records the subversion revision, date/time, and host of the build ## it also creates the cpp file config/sipX-buildstamp.cpp with the same information. all: BUILDSTAMP ## The SVN-VERSION file is created to record the version ## in the distribution tarball; it is not used in a subversion working copy ## (see the BUILDSTAMP rule below). SVN-VERSION: svnversion @top_srcdir@ > SVN-VERSION .PHONY: BUILDSTAMP BUILDSTAMP: if test -d @top_srcdir@/.svn \ ;then \ sipxSvnVersion=`svnversion @top_srcdir@` \ ;elif test -f @top_srcdir@/SVN-VERSION \ ;then \ sipxSvnVersion=`cat @top_srcdir@/SVN-VERSION` \ ;fi \ ;if test -z "$${sipxSvnVersion}" -o "export" = "$${sipxSvnVersion}" \ ;then \ sipxSvnVersion="SVN-UNKNOWN" \ ;fi \ ;sipxBuildTime=`date -u --iso-8601=seconds | sed 's/+0000//'` \ ;sipxBuildHost=`hostname --short` \ ;SIPX_BUILDSTAMP="r$${sipxSvnVersion} $${sipxBuildTime} $${sipxBuildHost}" \ ;echo "$${SIPX_BUILDSTAMP}" > BUILDSTAMP \ ;${LocalizeSipXconfig} \ -e "s/@SIPX_BUILDSTAMP\@/$${SIPX_BUILDSTAMP}/" \ -e "s/sipx/SipX/" \ $(srcdir)/config/sipX-buildstamp.cpp.in \ > config/@PACKAGE@-buildstamp.cpp \ ;${LocalizeSipXconfig} \ -e "s/@SIPX_BUILDSTAMP\@/$${SIPX_BUILDSTAMP}/" \ -e "s/sipx/SipX/" \ $(srcdir)/config/sipX-buildstamp.h.in \ > config/@PACKAGE@-buildstamp.h sipxtapi-3.3.0~test17/config/sipX-config.in0000644000175000017500000000550512205613256021370 0ustar00danieldaniel00000000000000#! /bin/sh ## ## @PACKAGE@-config ## ## Copyright (C) 2004 SIPfoundry Inc. ## Licensed by SIPfoundry under the LGPL license. ## ## Copyright (C) 2004, 2005 Pingtel Corp. ## ## Action=PRINT Info="" prefix=@prefix@ exec_prefix=@exec_prefix@ includedir=@includedir@ libdir=@libdir@ while [ $# -ne 0 ] do case ${1} in --bin) Info="${Info} @SIPX_BINDIR@" ;; --include) Info="${Info} @SIPX_INCDIR@" ;; --lib) Info="${Info} @SIPX_LIBDIR@" ;; --host) Info="${Info} @host@" ;; --version) Info="${Info} @VERSION@" ;; --build) Info="${Info} @SIPX_BUILDSTAMP@" ;; --conf) Info="${Info} @SIPX_CONFDIR@" ;; --data) Info="${Info} @SIPX_DATADIR@" ;; --log) Info="${Info} @SIPX_LOGDIR@" ;; --run) Info="${Info} @SIPX_RUNDIR@" ;; --db) Info="${Info} @SIPX_DBDIR@" ;; --all) Action=ALL break ;; --configopts) Info="${Info} @CONFIGURE_OPTIONS@" ;; --help) Action=USAGE break ;; ## ## handle an unknown switch ## -*) echo "Unknown switch '${1}'" 1>&2 Action=USAGE ;; esac shift # always consume 1 done if [ "${Action}" = "PRINT" -a "${Info}" = "" ] then Action=USAGE fi case ${Action} in USAGE) cat < /dev/null | head -n 1` for dir in $JAVA_HOME $JDK_HOME /usr/local/jdk /usr/local/java $TRY_JAVA_HOME; do AC_PATH_PROG(jar, dt.jar, ,$dir/lib) if test x$jar != x; then found_jdk="yes"; JAVA_HOME=$dir break; fi done if test x_$found_jdk != x_yes; then AC_MSG_ERROR([Cannot find dt.jar in expected location. You may try setting the JAVA_HOME environment variable if you haven't already done so]) fi AC_SUBST(JAVA, [$JAVA_HOME/jre/bin/java]) AC_ARG_VAR(JAVAC_OPTIMIZED, [Java compiler option for faster performance. Default is on]) test -z $JAVAC_OPTIMIZED && JAVAC_OPTIMIZED=on AC_ARG_VAR(JAVAC_DEBUG, [Java compiler option to reduce code size. Default is off]) test -z $JAVAC_DEBUG && JAVAC_DEBUG=off ]) # ============ J N I ======================= AC_DEFUN([CHECK_JNI], [ CHECK_JDK JAVA_HOME_INCL=$JAVA_HOME/include AC_CHECK_FILE([$JAVA_HOME_INCL/jni.h], [ XFLAGS="-I$JAVA_HOME_INCL -I$JAVA_HOME_INCL/linux"; CFLAGS="$XFLAGS $CFLAGS"; CXXFLAGS="$XFLAGS $CXXFLAGS"; ## i386 is a big assumption, TODO: make smarter JAVA_LIB_DIR="$JAVA_HOME/jre/lib/i386"; ## Effectively LD_LIBRARY_PATH for JVM for unittests or anything else AC_SUBST(JAVA_LIB_PATH, [$JAVA_LIB_DIR:$JAVA_LIB_DIR/client]) LDFLAGS="$LDFLAGS -L$JAVA_LIB_DIR -ljava -lverify" ## Use client flags as only call for this is phone. config server ## should use jre/lib/i386/server, but not a big deal LDFLAGS="$LDFLAGS -L$JAVA_LIB_DIR/client -ljvm" ], AC_MSG_ERROR([Cannot find or validate header file $JAVA_HOME_INCL/jni.h])) ]) # ============ A N T ================== AC_DEFUN([CHECK_ANT], [ AC_REQUIRE([AC_EXEEXT]) AC_ARG_VAR(ANT, [Ant program]) test -z $ANT_HOME || ANT_HOME_BIN=$ANT_HOME/bin for dir in $ANT_HOME_BIN $PATH /usr/local/ant/bin; do # only works because unix does not use ant.sh AC_PATH_PROG(ANT, ant$EXEEXT ant.bat, ,$dir) if test x$ANT != x; then found_ant="yes"; break; fi done if test x_$found_ant != x_yes; then AC_MSG_ERROR([Cannot find ant program. Try setting ANT_HOME environment variable or use 'configure ANT=]) fi ]) # ============ O P E N S S L ================== # # OpenSSL is required # AC_DEFUN([CHECK_SSL], [ AC_CHECK_HEADER( [openssl/ssl.h],, [ AC_CHECK_HEADER( [openssl/ssl.h],, [ AC_CHECK_HEADER( [ssl.h],, [ AC_CHECK_HEADER( [ssl.h],, [ AC_MSG_ERROR([Failed to find OpenSSL (ssl.h)]) ], [krb5.h] ) ] ) ], [krb5.h] ) ] ) CPPFLAGS="${CPPFLAGS} -DHAVE_SSL" ]) # ============ C O R E A U D I O ======================= AC_DEFUN([CHECK_COREAUDIO], [ AC_MSG_CHECKING([for CoreAudio]) if test "`uname`" == "Darwin"; then AC_SUBST(CA_LIBS,"-framework CoreAudio -framework AudioToolbox") AC_MSG_RESULT([yes]) AM_CONDITIONAL([COREAUDIO_DRIVERS], [true]) else AC_SUBST(CA_LIBS,"") AC_MSG_RESULT([not needed]) AM_CONDITIONAL([COREAUDIO_DRIVERS], [false]) fi ]) # ============ C A R B O N ================== AC_DEFUN([CHECK_CARBON], [ AC_MSG_CHECKING([for Carbon]) if test "`uname`" == "Darwin"; then AC_SUBST(CARBON_LIBS,"-framework Carbon") AC_MSG_RESULT([yes]) else AC_SUBST(CARBON_LIBS,"") AC_MSG_RESULT([not needed]) fi ]) # ==================== C G I C C ========================= AC_DEFUN([CHECK_CGICC], [ AC_MSG_CHECKING([for cgicc]) AC_ARG_WITH(cgicc, [--with-cgicc=PATH to cgicc library], [cgicc_path=$withval], [ AC_PATH_PROG([CGICC_CONFIG],cgicc-config) if test "x_$CGICC_CONFIG" != "x_"; then cgicc_path=`$CGICC_CONFIG --prefix` else cgicc_path="/usr/local/cgicc /usr/local /usr" fi ] ) found_cgicc="no"; for cgicc_dir in $cgicc_path; do if test -f "$cgicc_dir/lib/libcgicc.so" -a -f "$cgicc_dir/include/cgicc/Cgicc.h" then found_cgicc="yes"; break; fi done if test x_$found_cgicc = x_yes then AC_MSG_RESULT($cgicc_dir) AC_SUBST(CGICC_CFLAGS,"-I$cgicc_dir/include") AC_SUBST(CGICC_LIBS,"$cgicc_dir/lib/libcgicc.la") else AC_MSG_ERROR([cgicc not found - looked for lib/libcgicc.so and include/cgicc/Cgicc.h in $cgicc_path]) fi ])dnl # ============ L I B W W W ================== AC_DEFUN([CHECK_LIBWWW], [ AC_MSG_CHECKING([for libwww]) AC_ARG_WITH(libwww, [--with-libwww=PATH to libwww source directory], ) for dir in $withval /usr/local/w3c-libwww /usr/lib/w3c-libwww /usr/w3c-libwww /usr/pkg /usr/local /usr; do lwwwdir="$dir" if test -f "$dir/include/w3c-libwww/WWWLib.h"; then found_www="yes"; LIBWWW_CFLAGS="-I$lwwwdir/include/w3c-libwww"; LIBWWW_CXXFLAGS="-I$lwwwdir/include/w3c-libwww"; break; fi if test -f "$dir/include/WWWLib.h"; then found_www="yes"; LIBWWW_CFLAGS="-I$lwwwdir/include"; LIBWWW_CXXFLAGS="-I$lwwwdir/include "; break; fi done if test x_$found_www != x_yes; then AC_MSG_ERROR(not found; 'include/w3c-libwww/WWWLib.h' and 'include/WWWLib.h' not in any of: $withval /usr/local/w3c-libwww /usr/lib/w3c-libwww /usr/w3c-libwww /usr/pkg /usr/local /usr) fi if test ! -e "$dir/lib/libwwwapp.so";then AC_MSG_ERROR(not found; 'libwwwapps.so' not in: $dir/lib) fi if test ! -e "$dir/lib/libwwwssl.so";then AC_MSG_ERROR(not found; 'libwwwssl.so' not in: $dir/lib) fi if test x_$found_www = x_yes; then AC_MSG_RESULT($lwwwdir) AC_SUBST(LIBWWW_CFLAGS) AC_SUBST(LIBWWW_CXXFLAGS) LIBWWW_LIBS="-lwwwapp -lwwwfile -lwwwhttp -lwwwssl -lwwwcore"; LIBWWW_LIBS="$LIBWWW_LIBS -lwwwinit -lwwwapp -lwwwhttp -lwwwcache -lwwwcore"; LIBWWW_LIBS="$LIBWWW_LIBS -lwwwfile -lwwwutils -lwwwmime -lwwwstream -lmd5"; LIBWWW_LIBS="$LIBWWW_LIBS -lpics -lwwwnews -lwwwdir -lwwwtelnet -lwwwftp"; LIBWWW_LIBS="$LIBWWW_LIBS -lwwwmux -lwwwhtml -lwwwgopher -lwwwtrans -lwwwzip"; LIBWWW_LIBS="$LIBWWW_LIBS -lwwwssl -lwwwxml -lxmlparse -lxmltok"; AC_SUBST(LIBWWW_LIBS) LIBWWW_LDFLAGS="-L$lwwwdir/lib"; AC_SUBST(LIBWWW_LDFLAGS) fi ]) # ============ P C R E ================== AC_DEFUN([CHECK_PCRE], [ AC_MSG_CHECKING([for pcre >= 4.5]) # Process the --with-pcre argument which gives the pcre base directory. AC_ARG_WITH(pcre, [ --with-pcre=PATH path to pcre install directory], ) homeval=$withval # Have to unset withval so we can tell if --with-pcre-includedir was # specified, as AC_ARG_WITH will not unset withval if the option is not # there! withval= # Process the --with-pcre-includedir argument which gives the pcre include # directory. AC_ARG_WITH(pcre-includedir, [ --with-pcre-includedir=PATH path to pcre include directory (containing pcre.h)], ) # If withval is set, use that. If not and homeval is set, use # $homeval/include. If neither, use null. includeval=${withval:-${homeval:+$homeval/include}} withval= # Process the --with-pcre-libdir argument which gives the pcre library # directory. AC_ARG_WITH(pcre-libdir, [ --with-pcre-libdir=PATH path to pcre lib directory (containing libpcre.{so,a})], ) libval=${withval:-${homeval:+$homeval/lib}} # Check for pcre.h in the specified include directory if any, and a number # of other likely places. for dir in $includeval /usr/local/include /usr/local/pcre/include /usr/include /usr/include/pcre /sw/include /opt/local/include; do if test -f "$dir/pcre.h"; then found_pcre_include="yes"; includeval=$dir break; fi done # Check for libpcre.{so,a} in the specified lib directory if any, and a # number of other likely places. for dir in $libval /usr/local/lib /usr/local/pcre/lib /usr/lib /usr/lib64 /opt/local/lib /sw/lib; do if test -f "$dir/libpcre.so" -o -f "$dir/libpcre.a"; then found_pcre_lib="yes"; libval=$dir break; fi done # Test that we've been able to find both directories, and set the various # makefile variables. if test x_$found_pcre_include != x_yes; then AC_MSG_ERROR(Cannot find pcre.h - looked in $includeval) else if test x_$found_pcre_lib != x_yes; then AC_MSG_ERROR(Cannot find libpcre.so or libpcre.a libraries - looked in $libval) else ## Test for version pcre_ver=`pcre-config --version` AX_COMPARE_VERSION([$pcre_ver],[ge],[4.2]) if test "x_$ax_compare_version" = "x_false"; then AC_MSG_ERROR(Found pcre version $pcre_ver) else AC_MSG_RESULT($pcre_ver is ok) fi AC_MSG_RESULT($includeval and $libval) PCRE_CFLAGS="-I$includeval" PCRE_CXXFLAGS="-I$includeval" AC_SUBST(PCRE_CFLAGS) AC_SUBST(PCRE_CXXFLAGS) AC_SUBST(PCRE_LIBS, "-lpcre" ) AC_SUBST(PCRE_LDFLAGS, "-L$libval") fi fi ])dnl # ============ G S M ================== AC_DEFUN([AM_PATH_GSM], [ # Unset withval, as AC_ARG_WITH does not unset it withval= # Process the --with-gsm argument which gives the libgsm base directory. AC_ARG_WITH(gsm, [AS_HELP_STRING([--with-gsm=PATH], [path to libgsm install directory])], [], [with_gsm=] ) homeval=$withval # Have to unset withval so we can tell if --with-gsm-includedir was # specified, as AC_ARG_WITH will not unset withval if the option is not # there! withval= # Process the --with-gsm-includedir argument which gives the libgsm include # directory. AC_ARG_WITH(gsm-includedir, [AS_HELP_STRING([--with-gsm-includedir=PATH], [path to libgsm include directory (containing gsm.h)])], ) # If withval is set, use that. If not and homeval is set, use # $homeval/include. If neither, use null. includeval=${withval:-${homeval:+$homeval/inc}} withval= # Process the --with-gsm-libdir argument which gives the libgsm library # directory. AC_ARG_WITH(gsm-libdir, [AS_HELP_STRING([--with-gsm-libdir=PATH], [path to libgsm lib directory (containing libgsm.{so,a})])], ) libval=${withval:-${homeval:+$homeval/lib}} # Check for gsm.h in the specified include directory if any, and a number # of other likely places. for dir in $includeval /usr/local/include /usr/local/gsm/inc /usr/include /usr/include/gsm /sw/include; do if test -f "$dir/gsm.h"; then found_gsm_include="yes"; includeval=$dir break; fi done # Check for libgsm.{so,a} in the specified lib directory if any, and a # number of other likely places. for dir in $libval /usr/local/lib /usr/local/gsm/lib /usr/lib /usr/lib64 /sw/lib; do if test -f "$dir/libgsm.so" -o -f "$dir/libgsm.a"; then found_gsm_lib="yes"; libval=$dir break; fi done # Test that we've been able to find both directories, and set the various # makefile variables. if test x_$found_gsm_include != x_yes -o x_$found_gsm_lib != x_yes; then AC_MSG_RESULT(not found) else ## Test for version gsm_major_version=`grep "GSM_MAJOR" $includeval/gsm.h | \ sed 's/^#define[ \t]\+GSM_MAJOR[ \t]\+\([0-9]\+\)/\1/'` gsm_minor_version=`grep "GSM_MINOR" $includeval/gsm.h | \ sed 's/^#define[ \t]\+GSM_MINOR[ \t]\+\([0-9]\+\)/\1/'` gsm_patchlevel_version=`grep "GSM_PATCHLEVEL" $includeval/gsm.h | \ sed 's/^#define[ \t]\+GSM_PATCHLEVEL[ \t]\+\([0-9]\+\)/\1/'` gsm_ver="$gsm_major_version.$gsm_minor_version.$gsm_patchlevel_version" AX_COMPARE_VERSION([$gsm_ver],[ge],[1.0.10]) if test "x_$ax_compare_version" = "x_false"; then AC_MSG_RESULT(too old (found version $gsm_ver)) else AC_MSG_RESULT($gsm_ver is ok) # Enable this when we begin using config.h #AC_DEFINE(HAVE_GSM, [1], [Defined if libgsm is present]) CFLAGS="${CFLAGS} -DHAVE_GSM" CXXFLAGS="${CXXFLAGS} -DHAVE_GSM" GSM_CFLAGS="-I$includeval" GSM_CXXFLAGS="-I$includeval" GSM_LIBS="-lgsm" GSM_LDFLAGS="-L$libval" GSM_TARGET="plggsm" PLUGINS="${PLUGINS} GSM" fi fi AC_SUBST(GSM_TARGET) AC_SUBST(GSM_CFLAGS) AC_SUBST(GSM_CXXFLAGS) AC_SUBST(GSM_LIBS) AC_SUBST(GSM_LDFLAGS) ])dnl AC_DEFUN([CHECK_GSM], [ AC_MSG_CHECKING([for libgsm >= 1.0.10]) AC_ARG_ENABLE(codec-gsm, [AS_HELP_STRING([--enable-codec-gsm], [Enable support for GSM codec @<:@default=auto@:>@])], [ case "${enableval}" in auto) AM_PATH_GSM ;; yes) AM_PATH_GSM ;; no) AC_MSG_RESULT(disabled) ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-codec-gsm) ;; esac], [AM_PATH_GSM]) AM_CONDITIONAL([BUILD_CODEC_GSM], [test ! -z "$GSM_TARGET"]) ])dnl # ============ S P E E X ================== dnl dnl Enables use of speex dsp specific code within the project. dnl Callers of this macro need to check the contrib_speex_enabled shell variable dnl and supply the AC_CONFIG_SUBDIRS line that configures the dnl sipXmediaLib/contrib/libspeex package. dnl See CHECK_SPEEX for more information. AC_DEFUN([ENABLE_SPEEX_DSP], [ AC_MSG_CHECKING([if speex dsp usage is enabled]) speex_dsp_enabled=no; AC_ARG_ENABLE([speex-dsp], [AS_HELP_STRING([--enable-speex-dsp], [Enable SPEEX dsp library usage @<:@default=no@:>@])], [ case "${enableval}" in yes) AC_MSG_RESULT(yes); speex_dsp_enabled=yes ;; no) AC_MSG_RESULT(no) ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-speex-dsp) ;; esac], [AC_MSG_RESULT(no)]) # Check to see if speex dsp was selected, and speex usage has not been # checked and configured if test "x$speex_dsp_enabled" == "xyes" -a "x$speex_detected" == "x"; then CHECK_SPEEX fi dnl now the important part of this macro... if test "x$speex_dsp_enabled" == "xyes"; then # Specify to enable speex dsp code CFLAGS="${CFLAGS} -DHAVE_SPEEX" ; CXXFLAGS="${CXXFLAGS} -DHAVE_SPEEX" fi ])dnl AC_DEFUN([CHECH_DYNEXT], [ AC_MSG_CHECKING([for default shared object extenetion]) case ${host} in *-apple-darwin*) DYNEXT=".dylib" ;; *) DYNEXT=".so" ;; esac AC_MSG_RESULT( ${DYNEXT} ) AC_SUBST(DYNEXT) ])dnl dnl dnl Enables the speex codec plugin to be built and linked to in sipXmediaLib. dnl Callers of this macro need to check the contrib_speex_enabled shell variable dnl and supply the AC_CONFIG_SUBDIRS line that configures the dnl sipXmediaLib/contrib/libspeex package. dnl See CHECK_SPEEX for more information. AC_DEFUN([AM_SET_STATIC_SPEEX], [ CODEC_SPEEX_STATIC=true AM_SET_SPEEX AC_DEFINE(CODEC_SPEEX_STATIC, [1], [Select SPEEX codecs for static link]) STATIC_CODEC_LIBS="${STATIC_CODEC_LIBS} mp/codecs/plgspeex/codec_speex.la" AC_SUBST(STATIC_CODEC_LIBS) ])dnl AC_DEFUN([AM_SET_SPEEX], [ # Check to see if speex dsp was selected, and speex usage has not been # checked and configured if test "x$codec_speex_enabled" == "xyes" -a "x$speex_detected" == "x"; then CHECK_SPEEX fi PLUGINS="${PLUGINS} SPEEX" SPEEX_TARGET="plgspeex" AC_SUBST(SPEEX_TARGET) ])dnl AC_DEFUN([ENABLE_CODEC_SPEEX], [ AC_ARG_ENABLE([codec-speex], [AS_HELP_STRING([--enable-codec-speex], [Enable support for SPEEX codec @<:@default=no@:>@])], [ case "${enableval}" in static) AM_SET_STATIC_SPEEX ;; yes) AM_SET_SPEEX ;; no) ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-codec-speex) ;; esac]) AM_CONDITIONAL([BUILD_CODEC_SPEEX], [test ! -z "$SPEEX_TARGET"]) AM_CONDITIONAL(SPEEX_STATIC, test "$CODEC_SPEEX_STATIC" = true) ])dnl dnl dnl Enables speex support, checks to make sure that it is present, dnl or needs to be built. If it needs to be built, then the user that dnl calls this needs to check the contrib_speex_enabled shell variable dnl and supply the AC_CONFIG_SUBDIRS line that configures the dnl sipXmediaLib/contrib/libspeex package. This cannot be done within dnl CHECK_SPEEX because it can only be specified once, and CHECK_SPEEX has the dnl possibility of being specified more than once (and does in sipXmediaLib). AC_DEFUN([CHECK_SPEEX], [ AC_MSG_CHECKING([for libspeex >= 1.2rc1]) # Check if the user wished to force usage of contrib version of speex contrib_speex_enabled=no; AC_ARG_ENABLE([contrib-speex], [AS_HELP_STRING([--enable-contrib-speex], [Ignore any installed SPEEX libraries. Instead, build and use the ones in the contrib directory. @<:@default=no@:>@])], [ case "${enableval}" in yes) contrib_speex_enabled=yes ;; no) contrib_speex_enabled=no ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-contrib-speex) ;; esac], [contrib_speex_enabled=no]) # Detect if speex is installed. speex_detected=no; if test "x$contrib_speex_enabled" == "xno"; then PKG_CHECK_MODULES([SPEEX], [speex >= 1.2rc1], PKG_CHECK_MODULES([SPEEXDSP], [speexdsp >= 1.2rc1], speex_detected=yes, speex_detected=no; contrib_speex_enabled=yes), speex_detected=no; contrib_speex_enabled=yes) pkg_failed=no _PKG_CONFIG([SPEEX_LIBDIR], [variable=libdir], [speex >= 1.2rc1]) if test "x$pkg_failed" = "xuntried"; then AC_MSG_ERROR(Failed to get the speex library directory from pkg-config!) else SPEEX_STATIC_LIB=${SPEEX_LIBDIR}/libspeex.a SPEEXDSP_STATIC_LIB=${SPEEX_LIBDIR}/libspeexdsp.a fi fi # if contrib speex is selected, use it. if test "x$contrib_speex_enabled" == "xyes" ; then AC_MSG_RESULT([using svn version]) SPEEX_ROOT='${top_srcdir}/../sipXmediaLib/contrib/libspeex' SPEEX_CFLAGS="-I${SPEEX_ROOT}/include" SPEEX_CFLAGS+=' -I${top_builddir}/sipXmediaLib/contrib/libspeex/include' SPEEX_STATIC_LIB='${top_builddir}/sipXmediaLib/contrib/libspeex/libspeex/.libs/libspeex.a' SPEEX_LIBS=${SPEEX_STATIC_LIB} SPEEXDSP_STATIC_LIB='${top_builddir}/sipXmediaLib/contrib/libspeex/libspeex/.libs/libspeexdsp.a' SPEEXDSP_LIBS=${SPEEXDSP_STATIC_LIB} AC_SUBST(SPEEX_ROOT) AC_SUBST(SPEEX_CFLAGS) AC_SUBST(SPEEX_LIBS) AC_SUBST(SPEEX_STATIC_LIB) AC_SUBST(SPEEXDSP_STATIC_LIB) AC_SUBST(SPEEXDSP_LIBS) elif test "x$speex_detected" == "xyes"; then AC_MSG_RESULT([ok]) AC_SUBST(SPEEX_CFLAGS) AC_SUBST(SPEEX_LIBS) AC_SUBST(SPEEX_STATIC_LIB) AC_SUBST(SPEEXDSP_STATIC_LIB) AC_SUBST(SPEEXDSP_LIBS) else AC_MSG_ERROR([No speex found!]) fi ])dnl # ========== P C M A P C M U ================= AC_DEFUN([AM_SET_STATIC_PCMA_PCMU], [ CODEC_PCMAPCMU_STATIC=true AM_SET_PCMA_PCMU AC_DEFINE(CODEC_PCMA_PCMU_STATIC, [1], [Select PCMA and PCMU codecs for static link]) STATIC_CODEC_LIBS="${STATIC_CODEC_LIBS} mp/codecs/plgpcmapcmu/codec_pcmapcmu.la" AC_SUBST(STATIC_CODEC_LIBS) ])dnl AC_DEFUN([AM_SET_PCMA_PCMU], [ PLUGINS="${PLUGINS} PCMA_PCMU" PCMAPCMU_TARGET="plgpcmapcmu" AC_SUBST(PCMAPCMU_TARGET) ])dnl AC_DEFUN([CHECK_PCMA_PCMU], [ AC_ARG_ENABLE([codec-pcmapcmu], [AS_HELP_STRING([--enable-codec-pcmapcmu], [Enable support for PCMA and PCMU codecs @<:@default=yes@:>@])], [ case "${enableval}" in static) AM_SET_STATIC_PCMA_PCMU ;; auto) AM_SET_PCMA_PCMU ;; yes) AM_SET_PCMA_PCMU ;; no) AC_MSG_RESULT(Codecs PCMA & PCMU was disabled) ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-codec-pcmapcmu) ;; esac], [AM_SET_PCMA_PCMU]) AM_CONDITIONAL([BUILD_CODEC_PCMAPCMU], [test ! -z "$PCMAPCMU_TARGET"]) AM_CONDITIONAL(PCMAPCMU_STATIC, test "$CODEC_PCMAPCMU_STATIC" = true) ])dnl # ============== T O N E S ================== AC_DEFUN([AM_SET_STATIC_TONES], [ CODEC_TONES_STATIC=true AM_SET_TONES AC_DEFINE(CODEC_TONES_STATIC, [1], [Select tones for static link]) STATIC_CODEC_LIBS="${STATIC_CODEC_LIBS} mp/codecs/plgtones/codec_tones.la" AC_SUBST(STATIC_CODEC_LIBS) ])dnl AC_DEFUN([AM_SET_TONES], [ PLUGINS="${PLUGINS} TONES" TONES_TARGET="plgtones" AC_SUBST(TONES_TARGET) ])dnl AC_DEFUN([CHECK_TONES], [ AC_ARG_ENABLE([codec-tones], [AS_HELP_STRING([--enable-codec-tones], [Enable support for Tones codec @<:@default=yes@:>@])], [ case "${enableval}" in static) AM_SET_STATIC_TONES ;; auto) AM_SET_TONES ;; yes) AM_SET_TONES ;; no) AC_MSG_RESULT(Codec Tones was disabled) ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-codec-tones) ;; esac], [AM_SET_TONES]) AM_CONDITIONAL([BUILD_CODEC_TONES], [test ! -z "$TONES_TARGET"]) AM_CONDITIONAL(TONES_STATIC, test "$CODEC_TONES_STATIC" = true) ])dnl # ============== L 1 6 ================== AC_DEFUN([AM_SET_STATIC_L16], [ CODEC_L16_STATIC=true AM_SET_L16 AC_DEFINE(CODEC_L16_STATIC, [1], [Select l16 for static link]) STATIC_CODEC_LIBS="${STATIC_CODEC_LIBS} mp/codecs/plgl16/codec_l16.la" AC_SUBST(STATIC_CODEC_LIBS) ])dnl AC_DEFUN([AM_SET_L16], [ PLUGINS="${PLUGINS} L16" L16_TARGET="plgl16" AC_SUBST(L16_TARGET) ])dnl AC_DEFUN([CHECK_L16], [ AC_ARG_ENABLE([codec-l16], [AS_HELP_STRING([--enable-codec-l16], [Enable support for L16 codec @<:@default=no@:>@])], [ case "${enableval}" in static) AM_SET_STATIC_L16 ;; auto) AC_MSG_RESULT(Codec L16 was disabled) ;; yes) AM_SET_L16 ;; no) AC_MSG_RESULT(Codec L16 was disabled) ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-codec-l16) ;; esac], [AM_SET_L16]) AM_CONDITIONAL([BUILD_CODEC_L16], [test ! -z "$L16_TARGET"]) AM_CONDITIONAL(L16_STATIC, test "$CODEC_L16_STATIC" = true) ])dnl # =============== I L B C ===================== AC_DEFUN([AM_SET_ILBC], [ # Currently only iLBC in contrib supported PLUGINS="${PLUGINS} iLBC" ILBC_INCLUDE="-I${PWD}/sipXmediaLib/contrib/libilbc/include" ILBC_LIB_ROOT="${PWD}/sipXmediaLib/contrib/libilbc/" ILBC_LIB_TARGET="lib/libilbc.a" ILBC_TARGET="plgilbc" AC_SUBST(ILBC_INCLUDE) AC_SUBST(ILBC_LIB_ROOT) AC_SUBST(ILBC_LIB_TARGET) AC_SUBST(ILBC_TARGET) ])dnl AC_DEFUN([CHECK_ILBC], [ AC_ARG_ENABLE([codec-ilbc], [AS_HELP_STRING([--enable-codec-ilbc], [Enable support for ilbc codec @<:@default=yes@:>@])], [ case "${enableval}" in auto) AM_SET_ILBC ;; yes) AM_SET_ILBC ;; no) AC_MSG_RESULT(Codec iLBC was disabled) ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-codec-ilbc) ;; esac], [AM_SET_ILBC]) AM_CONDITIONAL([BUILD_CODEC_ILBC], [test ! -z "$ILBC_TARGET"]) ])dnl # == D E C L A R E _ C O D E C S _ S T A F F == AC_DEFUN([DECLARE_CODECS_STAFF], [ AC_SUBST([codeclibdir], ['${pkglibdir}/codecs']) CPPFLAGS="${CPPFLAGS} -DDEFAULT_CODECS_PATH='\"${codeclibdir}\"' " ])dnl AC_DEFUN([CHECK_SPANDSP], [ AC_MSG_CHECKING([for libspandsp >= 0.0.2pre26]) # Unset withval, as AC_ARG_WITH does not unset it withval= AC_ARG_WITH(spandsp-includedir, [AS_HELP_STRING([--with-spandsp-includedir=PATH], [path to libspandsp include directory (containing spandsp.h)])], ) # If withval is set, use that. If not and homeval is set, use # $homeval/include. If neither, use null. includeval=${withval} withval= # Process the --with-spansdp-libdir argument which gives the libgsm library # directory. AC_ARG_WITH(spandsp-libdir, [AS_HELP_STRING([--with-spandsp-libdir=PATH], [path to libspandsp lib directory (containing libspandsp.{so,la})])], ) libval=${withval} # Check for spansdp.h in the specified include directory if any, and a number # of other likely places. for dir in $includeval /usr/local/include /usr/include /sw/include; do if test -f "$dir/spandsp.h"; then found_spandsp_include="yes"; includeval=$dir break; fi done # Check for libspansdp.{so,a} in the specified lib directory if any, and a # number of other likely places. for dir in $libval /usr/local/lib /usr/lib /usr/lib64 /sw/lib; do if test -f "$dir/libspandsp.so" -o -f "$dir/libspandsp.la"; then found_spandsp_lib="yes"; libval=$dir break; fi done # Test that we've been able to find both directories, and set the various # makefile variables. if test x_$found_spandsp_include != x_yes -o x_$found_spandsp_lib != x_yes; then AC_MSG_RESULT(not found) else # testing for proper version ac_spandsp_ok=false ac_spandsp_new=false ac_spandsp_g726valid=false if test -f "$includeval/spandsp/g722.h" -o -f "$includeval/spandsp/g726.h"; then OLD_CFLAGS=$CFLAGS OLD_LDFLAGS=$LDFLAGS CFLAGS+=" -I$includeval" LDFLAGS+=" -L$libval -lspandsp" AC_TRY_COMPILE([ #include #include #include #include ],[ void* p = g726_init(0, 16000, G726_ENCODING_LINEAR, G726_PACKING_LEFT); void* q = g722_encode_init(0, 64000, 0); return p!=q; ], ac_libspandsp_newstyle=true, ac_libspandsp_newstyle=false) if test "$ac_libspandsp_newstyle" = false; then AC_TRY_COMPILE([ #include #include #include #include ],[ void* p = g726_init(0, 16000, G726_ENCODING_LINEAR, G726_PACKING_LEFT); void* q = g722_encode_init(0, 64000, 0); return p!=q; ], ac_libspandsp_newstyle=true, ac_libspandsp_newstyle=false) fi CFLAGS=$OLD_CFLAGS LDFLAGS=$OLD_LDFLAGS if test "$ac_libspandsp_newstyle" = false; then AC_MSG_WARN(ac_libspandsp_newstyle == false) OLD_CFLAGS=$CFLAGS OLD_LDFLAGS=$LDFLAGS CFLAGS+=" -I$includeval" LDFLAGS+=" -L$libval -lspandsp" AC_TRY_COMPILE([ #include #include #include ],[ void* p = g726_init(0, 16000, G726_ENCODING_LINEAR, 1); void* q = g722_encode_init(0, 64000, 0); return p!=q; ], ac_libspandsp_oldstyle=true, ac_libspandsp_oldstyle=false) CFLAGS=$OLD_CFLAGS LDFLAGS=$OLD_LDFLAGS AC_MSG_WARN(ac_libspandsp_oldstyle = $ac_libspandsp_oldstyle) if test "$ac_libspandsp_oldstyle" = true; then AC_DEFINE(HAVE_OLD_LIBSPANDSP, [1], [Have old version of libspandsp]) ac_spandsp_ok=true fi else ac_spandsp_ok=true fi fi if test "$ac_spandsp_ok" = true -a "$ac_libspandsp_newstyle" = true; then ac_spandsp_new=true ac_spandsp_g726valid=true fi if test "$ac_spandsp_ok" = true; then if test "$ac_spandsp_new" = true; then AC_MSG_RESULT(ok) else AC_MSG_RESULT(old version of libspandsp) fi SPANDSP_CFLAGS="-I$includeval" SPANDSP_CXXFLAGS="-I$includeval" SPANDSP_LIBS="-lspandsp" SPANDSP_LDFLAGS="-L$libval" else AC_MSG_ERROR(invalid version of spandsplib) fi if test "$ac_spandsp_ok" = true -a "$ac_spandsp_new" = false; then withval= AC_ARG_WITH(spandsp-validg726, [AS_HELP_STRING([--with-spandsp-validg726=VAL], [Set VAL to 'yes' or 'ok' to use G726 with old libspandsp (where packing mode parameter compiled in library)])], ) if test "$withval" = "yes" -o "$withval" = "ok" ; then ac_spandsp_g726valid=true else # Need to check G726 packing AC_MSG_CHECKING([for libspandsp G726 packing]) OLD_CFLAGS=$CFLAGS OLD_LDFLAGS=$LDFLAGS CFLAGS+=" $SPANDSP_CFLAGS" LDFLAGS+=" $SPANDSP_LDFLAGS $SPANDSP_LIBS" AC_TRY_RUN([ #include #include #include int main() { void* p = g726_init(0, 16000, G726_ENCODING_LINEAR, 1); uint16_t data[16]; const uint16_t vdata[4] = {0xc, 0xc, 0xc, 0x3c}; uint8_t packed[4] = {1, 54}; int len, i; len = g726_decode(p, data, packed, 2); for (i = 0; i < 4; i++) { if ( data[i] != vdata[i] ) return -1; } return 0; } ], ac_spandsp_g726valid=true, ac_spandsp_g726valid=false, ac_spandsp_g726valid=false) CFLAGS=$OLD_CFLAGS LDFLAGS=$OLD_LDFLAGS if test "$ac_spandsp_g726valid" = true; then AC_MSG_RESULT(ok) else AC_MSG_RESULT(incorrect) fi fi fi fi AC_SUBST(SPANDSP_CFLAGS) AC_SUBST(SPANDSP_CXXFLAGS) AC_SUBST(SPANDSP_LIBS) AC_SUBST(SPANDSP_LDFLAGS) ])dnl AC_DEFUN([EXTERNAL_EXTENITIONS], [ # RTL Lib RTL_LDFLAGS="" RTL_CXXFLAGS="" # RtlAudio withval= AC_ARG_WITH(rtllibaudio, [AS_HELP_STRING([--with-rtllibaudio=library], [Use specified library for RtlAudio])], ) ac_external_rtlaudio=${withval} if test x${ac_external_rtlaudio} != x; then RTL_LDFLAGS+=" -l${ac_external_rtlaudio} " fi withval= AC_ARG_WITH(rtllibaudio-path, [AS_HELP_STRING([--with-rtllibaudio-path=PATH], [Add path for RtlAudio])], ) ac_external_rtlaudio_path=${withval} if test x${ac_external_rtlaudio_path} != x; then RTL_LDFLAGS+=" -L${ac_external_rtlaudio_path} -Wl,--rpath -Wl,${ac_external_rtlaudio_path} " fi withval= AC_ARG_WITH(rtllibaudio-inc-path, [AS_HELP_STRING([--with-rtllibaudio-inc-path=PATH], [Add path for headers for RtlAudio])], ) ac_external_rtlaudio_inc_path=${withval} if test x${ac_external_rtlaudio_inc_path} != x; then RTL_CXXFLAGS+=" -I${ac_external_rtlaudio_inc_path} " fi # Rtl withval= AC_ARG_WITH(rtllib, [AS_HELP_STRING([--with-rtllib=library], [Use specified library for Rtl])], ) ac_external_rtl=${withval} if test x${ac_external_rtl} != x; then RTL_LDFLAGS+=" -l${ac_external_rtl} " fi withval= AC_ARG_WITH(rtllib-path, [AS_HELP_STRING([--with-rtllib-path=PATH], [Add path for Rtl])], ) ac_external_rtl_path=${withval} if test x${ac_external_rtl_path} != x; then RTL_LDFLAGS+=" -L${ac_external_rtl_path} -Wl,--rpath -Wl,${ac_external_rtl_path} " fi withval= AC_ARG_WITH(rtllib-inc-path, [AS_HELP_STRING([--with-rtllib-inc-path=PATH], [Add path for headers for Rtl])], ) ac_external_rtl_inc_path=${withval} if test x${ac_external_rtl_inc_path} != x; then RTL_CXXFLAGS+=" -I${ac_external_rtl_inc_path} " fi # Rtl Defines AC_ARG_ENABLE([external-rtl-init], [AS_HELP_STRING([--enable-external-rtl-init], [Initialize external RTL collector to log to sipXmediaLib internal one @<:@default=no@:>@])], [ case "${enableval}" in yes) ac_do_rtinit_define=true ;; no) ac_do_rtinit_define=false ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-external-rtl-init) ;; esac], [ac_do_rtinit_define=false ]) if test x${ac_do_rtinit_define} != xfalse; then AC_DEFINE(INIT_EXTERNAL_RTL_COLLECTOR, [1], [Initialize external RTL collector with sipXmediaLib s internal one]) RTL_CXXFLAGS+=" -DINIT_EXTERNAL_RTL_COLLECTOR " fi AC_ARG_ENABLE([rtl], [AS_HELP_STRING([--enable-rtl], [Enable RTL for the whole library @<:@default=no@:>@])], [ case "${enableval}" in yes) ac_do_rtl_define=true ;; no) ac_do_rtl_define=false ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-rtl) ;; esac], [ac_do_rtl_define=false ]) if test x${ac_do_rtl_define} != xfalse; then AC_DEFINE(RTL_ENABLED, [1], [Enable RTL for the whole library]) RTL_CXXFLAGS+=" -DRTL_ENABLED " fi AC_ARG_ENABLE([rtlaudio], [AS_HELP_STRING([--enable-rtlaudio], [Enable RTL_AUDIO for the whole library @<:@default=no@:>@])], [ case "${enableval}" in yes) ac_do_rtlaudio_define=true ;; no) ac_do_rtlaudio_define=false ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-rtlaudio) ;; esac], [ac_do_rtlaudio_define=false ]) if test x${ac_do_rtlaudio_define} != xfalse; then AC_DEFINE(RTL_AUDIO_ENABLED, [1], [Enable RTL_AUDIO for the whole library]) RTL_CXXFLAGS+=" -DRTL_AUDIO_ENABLED " fi ])dnl AC_DEFUN([EXTERNAL_EXTENITIONS_MEDIA], [ # VAD withval= AC_ARG_WITH(external-vad, [AS_HELP_STRING([--with-external-vad=library], [Use external library for VAD])], ) ac_external_vad=${withval} withval= AC_ARG_WITH(external-vad-path, [AS_HELP_STRING([--with-external-vad-path=PATH], [Add path for searching external library for VAD])], ) ac_external_vad_path=${withval} if test x${ac_external_vad} != x; then AC_DEFINE(EXTERNAL_VAD, [1], [Use external library for VAD]) EVAD_LDFLAGS="-l${ac_external_vad} " if test x${ac_external_vad_path} != x; then EVAD_LDFLAGS+=" -L${ac_external_vad_path} -Wl,--rpath -Wl,${ac_external_vad_path} " fi LDFLAGS+=" $EVAD_LDFLAGS " CXXFLAGS+=" -DEXTERNAL_VAD " fi AC_SUBST(EVAD_LDFLAGS) # PLC withval= AC_ARG_WITH(external-plc, [AS_HELP_STRING([--with-external-plc=library], [Use external library for PLC])], ) ac_external_plc=${withval} withval= AC_ARG_WITH(external-plc-path, [AS_HELP_STRING([--with-external-plc-path=PATH], [Add path for searching external library for PLC])], ) ac_external_plc_path=${withval} if test x${ac_external_plc} != x; then AC_DEFINE(EXTERNAL_PLC, [1], [Use external library for PLC]) EPLC_LDFLAGS="-l${ac_external_plc} " if test x${ac_external_plc_path} != x; then EPLC_LDFLAGS+=" -L${ac_external_plc_path} -Wl,--rpath -Wl,${ac_external_plc_path} " fi LDFLAGS+=" $EPLC_LDFLAGS " CXXFLAGS+=" -DEXTERNAL_PLC " fi AC_SUBST(EPLC_LDFLAGS) # Jitter buffer estimation withval= AC_ARG_WITH(external-jbe, [AS_HELP_STRING([--with-external-jbe=library], [Use external library for Jitter buffer estimation])], ) ac_external_jbe=${withval} withval= AC_ARG_WITH(external-jbe-path, [AS_HELP_STRING([--with-external-jbe-path=PATH], [Add path for searching external library for JBE])], ) ac_external_jbe_path=${withval} if test x${ac_external_jbe} != x; then AC_DEFINE(EXTERNAL_JB_ESTIMATION, [1], [Use external library for jitter buffer estimation]) EJBE_LDFLAGS="-l${ac_external_jbe} " if test x${ac_external_jbe_path} != x; then EJBE_LDFLAGS+=" -L${ac_external_jbe_path} -Wl,--rpath -Wl,${ac_external_jbe_path} " fi LDFLAGS+=" $EJBE_LDFLAGS " CXXFLAGS+=" -DEXTERNAL_JB_ESTIMATION " fi AC_SUBST(EJBE_LDFLAGS) # AGC withval= AC_ARG_WITH(external-agc, [AS_HELP_STRING([--with-external-agc=library], [Use external library for AGC])], ) ac_external_agc=${withval} withval= AC_ARG_WITH(external-agc-path, [AS_HELP_STRING([--with-external-agc-path=PATH], [Add path for searching external library for AGC])], ) ac_external_agc_path=${withval} if test x${ac_external_agc} != x; then AC_DEFINE(EXTERNAL_AGC, [1], [Use external library for AGC]) EAGC_LDFLAGS="-l${ac_external_agc} " if test x${ac_external_agc_path} != x; then EAGC_LDFLAGS+=" -L${ac_external_agc_path} -Wl,--rpath -Wl,${ac_external_agc_path} " fi LDFLAGS+=" $EAGC_LDFLAGS " CXXFLAGS+=" -DEXTERNAL_AGC " fi AC_SUBST(EAGC_LDFLAGS) # Speaker selection withval= AC_ARG_WITH(external-ss, [AS_HELP_STRING([--with-external-ss=library], [Use external library for speaker selection])], ) ac_external_ss=${withval} withval= AC_ARG_WITH(external-ss-path, [AS_HELP_STRING([--with-external-ss-path=PATH], [Add path for searching external library for SS])], ) ac_external_ss_path=${withval} if test x${ac_external_ss} != x; then AC_DEFINE(EXTERNAL_SS, [1], [Use external library for speaker selection]) SS_LDFLAGS="-l${ac_external_ss} " if test x${ac_external_ss_path} != x; then SS_LDFLAGS+=" -L${ac_external_ss_path} -Wl,--rpath -Wl,${ac_external_ss_path} " fi LDFLAGS+=" $SS_LDFLAGS " CXXFLAGS+=" -DEXTERNAL_SS " fi AC_SUBST(SS_LDFLAGS) CXXFLAGS+=" $RTL_CXXFLAGS " LDFLAGS+=" ${RTL_LDFLAGS} " AC_SUBST(RTL_CXXFLAGS) AC_SUBST(RTL_LDFLAGS) ])dnl AC_DEFUN([SPEACKER_SELECTION_CHECK], [ # Speaker selection enable AC_ARG_ENABLE([speaker-selection], [AS_HELP_STRING([--enable-speaker-selection], [Enable Speaker Selection resource in flowgraph @<:@default=no@:>@])], [ case "${enableval}" in yes) ac_enable_speaker_selection=true ;; no) ac_enable_speaker_selection=false ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-speaker-selection) ;; esac], [ac_enable_speaker_selection=false ]) if test x${ac_enable_speaker_selection} != xfalse; then AC_DEFINE(INSERT_SPEAKER_SELECTOR, [1], [Enable Sepaker Selection resource in flowgraph]) CXXFLAGS+=" -DINSERT_SPEAKER_SELECTOR " fi ])dnl # =============== G726 ===================== AC_DEFUN([AM_SET_STATIC_G726], [ CODEC_G726_STATIC=true AM_SET_G726 if test "$G726_TARGET" != ""; then AC_DEFINE(CODEC_G726_STATIC, [1], [Select G726 for static link]) LDFLAGS="$LDFLAGS $SPANDSP_LDFLAGS $SPANDSP_LIBS" STATIC_CODEC_LIBS="${STATIC_CODEC_LIBS} mp/codecs/plgg726/codec_g726.la" AC_SUBST(STATIC_CODEC_LIBS) fi ])dnl AC_DEFUN([AM_SET_G726], [ if test x_$SPANDSP_CFLAGS != x_ -a "$ac_spandsp_g726valid" = true; then PLUGINS="${PLUGINS} G.726" G726_TARGET="plgg726" fi AC_SUBST(G726_TARGET) ])dnl AC_DEFUN([CHECK_G726], [ AC_ARG_ENABLE([codec-g726], [AS_HELP_STRING([--enable-codec-g726], [Enable support for g726 codec @<:@default=yes@:>@])], [ case "${enableval}" in static) AM_SET_STATIC_G726 ;; auto) AM_SET_G726 ;; yes) AM_SET_G726 ;; no) AC_MSG_RESULT(Codec G.726 was disabled) ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-codec-g726) ;; esac], [AM_SET_G726]) AM_CONDITIONAL([BUILD_CODEC_G726], [test ! -z "$G726_TARGET"]) AM_CONDITIONAL(G726_STATIC, test "$CODEC_G726_STATIC" = true) ])dnl # =============== G722 ===================== AC_DEFUN([AM_SET_STATIC_G722], [ CODEC_G722_STATIC=true AM_SET_G722 if test "$G722_TARGET" != ""; then AC_DEFINE(CODEC_G722_STATIC, [1], [Select G722 for static link]) LDFLAGS="$LDFLAGS $SPANDSP_LDFLAGS $SPANDSP_LIBS" STATIC_CODEC_LIBS="${STATIC_CODEC_LIBS} mp/codecs/plgg722/codec_g722.la" AC_SUBST(STATIC_CODEC_LIBS) fi ])dnl AC_DEFUN([AM_SET_G722], [ # Currently only iLBC in contrib supported if test x_$SPANDSP_CFLAGS != x_; then PLUGINS="${PLUGINS} G.722" G722_TARGET="plgg722" fi AC_SUBST(G722_TARGET) ])dnl AC_DEFUN([CHECK_G722], [ AC_ARG_ENABLE([codec-g722], [AS_HELP_STRING([--enable-codec-g722], [Enable support for g722 codec @<:@default=yes@:>@])], [ case "${enableval}" in static) AM_SET_STATIC_G722 ;; auto) AM_SET_G722 ;; yes) AM_SET_G722 ;; no) AC_MSG_RESULT(Codec G.722 was disabled) ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-codec-g722) ;; esac], [AM_SET_G722]) AM_CONDITIONAL([BUILD_CODEC_G722], [test ! -z "$G722_TARGET"]) AM_CONDITIONAL(G722_STATIC, test "$CODEC_G722_STATIC" = true) ])dnl AC_DEFUN([CHECK_GRAPH_INTERFACE], [ AC_ARG_ENABLE([topology-graph], [AC_HELP_STRING([--enable-topology-graph], [Enable toplogy graph as default processing @<:@default=no@:>@])], [ case "${enableval}" in yes) INTERFACE_FLAGS=" -DENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY " INTERFACE_FLAGS+="-DDISABLE_DEFAULT_PHONE_MEDIA_INTERFACE_FACTORY " ;; no) INTERFACE_FLAGS=" " ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-topology-graph) ;; esac], [ enableval= ]) AC_SUBST(INTERFACE_FLAGS) ])dnl # === CHECK_OPUS AC_DEFUN([AM_SET_STATIC_OPUS], [ CODEC_OPUS_STATIC=true AM_SET_OPUS if test "$OPUS_TARGET" != ""; then AC_DEFINE(CODEC_OPUS_STATIC, [1], [Select Opus for static link]) LDFLAGS="$LDFLAGS" STATIC_CODEC_LIBS="${STATIC_CODEC_LIBS} mp/codecs/plgopus/codec_opus.la" AC_SUBST(STATIC_CODEC_LIBS) fi ])dnl AC_DEFUN([AM_SET_OPUS], [ PLUGINS="${PLUGINS} OPUS" OPUS_TARGET="plgopus" AC_SUBST(OPUS_TARGET) OPUS_CFLAGS="-I/usr/include/opus" OPUS_LIBS="-lopus" AC_SUBST(OPUS_CFLAGS) AC_SUBST(OPUS_LIBS) ])dnl AC_DEFUN([CHECK_OPUS], [ AC_ARG_ENABLE([codec-opus], [AS_HELP_STRING([--enable-codec-opus], [Enable support for Opus codec @<:@default=yes@:>@])], [ case "${enableval}" in static) AM_SET_STATIC_OPUS ;; auto) AM_SET_OPUS ;; yes) AM_SET_OPUS ;; no) AC_MSG_RESULT(Codec Opus was disabled) ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-codec-opus) ;; esac], [AM_SET_OPUS]) AM_CONDITIONAL([BUILD_CODEC_OPUS], [test ! -z "$OPUS_TARGET"]) AM_CONDITIONAL(OPUS_STATIC, test "$CODEC_OPUS_STATIC" = true) ])dnl # === CHECK_STREAM_PLAYER AC_DEFUN([CHECK_STREAM_PLAYER], [ AC_ARG_ENABLE([stream-player], [AC_HELP_STRING([--disable-stream-player], [Disable stream player (removes sipXtack dependency on media layer) @<:@default=no@:>@])], [ case "${enableval}" in no) disable_stream_player=true ;; yes) disable_stream_player=false ;; *) AC_MSG_ERROR(bad value ${enableval} for --disable-media-player) ;; esac], [ disable_stream_player=false ]) AM_CONDITIONAL(DISABLE_STREAM_PLAYER, test x$disable_stream_player = xtrue) ])dnl # === AMR AMR_WB AC_DEFUN([AM_SET_AMR], [ # Currently only iLBC in contrib supported PLUGINS="${PLUGINS} AMR" AMR_TARGET="plgamr" AMRNB_INCLUDE="-I${PWD}/sipXmediaLib/contrib/libamrnb/" AMRNB_LIB_ROOT="${PWD}/sipXmediaLib/contrib/libamrnb/" AC_SUBST(AMR_TARGET) AC_SUBST(AMRNB_INCLUDE) AC_SUBST(AMRNB_LIB_ROOT) # amr narrowband codec has it's own configure, # so be sure to call it. AC_CONFIG_SUBDIRS([sipXmediaLib/contrib/libamrnb/]) ])dnl AC_DEFUN([AM_SET_AMRWB], [ # Currently only iLBC in contrib supported PLUGINS="${PLUGINS} AMR-WB" AMRWB_TARGET="plgamrwb" AMRWB_INCLUDE="-I${PWD}/sipXmediaLib/contrib/libamrwb/" AMRWB_LIB_ROOT="${PWD}/sipXmediaLib/contrib/libamrwb/" AC_SUBST(AMRWB_TARGET) AC_SUBST(AMRWB_INCLUDE) AC_SUBST(AMRWB_LIB_ROOT) # amr wideband codec has it's own configure, # so be sure to call it. AC_CONFIG_SUBDIRS([sipXmediaLib/contrib/libamrwb/]) ])dnl AC_DEFUN([CHECK_AMR_AMRWB], [ amr_enable=false; AC_ARG_ENABLE([codec-amr], [AS_HELP_STRING([--enable-codec-amr], [Enable support for amr codec @<:@default=no@:>@])], [ if test ${enableval} = yes; then amr_enable=true; else if test ${enableval} = no; then AC_MSG_RESULT(Codec AMR was disabled) else AC_MSG_ERROR(bad value ${enableval} for --enable-codec-amr) fi fi], amr_enable=false) if (test "x$amr_enable" = "xtrue"); then AM_SET_AMR fi AM_CONDITIONAL(AMRNB, [test "x$amr_enable" == "xtrue"]) amrwb_enable=false; AC_ARG_ENABLE([codec-amrwb], [AS_HELP_STRING([--enable-codec-amrwb], [Enable support for amrwb codec @<:@default=no@:>@])], [ if test ${enableval} = yes; then amrwb_enable=true; else if test ${enableval} = no; then AC_MSG_RESULT(Codec AMRWB was disabled) else AC_MSG_ERROR(bad value ${enableval} for --enable-codec-amrwb) fi fi], amrwb_enable=false) if (test "x$amrwb_enable" = "xtrue"); then AM_SET_AMRWB fi AM_CONDITIONAL(AMRWB, [test "x$amrwb_enable" == "xtrue"]) ])dnl # ============ D O X Y G E N ================== # Originaly from CppUnit BB_ENABLE_DOXYGEN AC_DEFUN([ENABLE_DOXYGEN], [ AC_ARG_ENABLE(doxygen, [ --enable-doxygen enable documentation generation with doxygen (yes)], [], [ enable_doxygen=yes]) AC_ARG_ENABLE(dot, [ --enable-dot use 'dot' to generate graphs in doxygen (auto)]) AC_ARG_ENABLE(html-docs, [ --enable-html-docs enable HTML generation with doxygen (yes)], [], [ enable_html_docs=yes]) AC_ARG_ENABLE(latex-docs, [ --enable-latex-docs enable LaTeX documentation generation with doxygen (no)], [], [ enable_latex_docs=no]) if test "x$enable_doxygen" = xno; then enable_doc=no else AC_MSG_CHECKING([for doxygen documentation processor]) AC_PATH_PROG(DOXYGEN, doxygen, , $PATH) if test "x$DOXYGEN" = x; then AC_MSG_WARN([could not find doxygen - disabled]) enable_doxygen=no enable_doc=no else enable_doc=yes AC_PATH_PROG(DOT, dot, , $PATH) fi fi if test x$DOT = x; then if test "x$enable_dot" = xyes; then AC_MSG_ERROR([could not find dot]) fi enable_dot=no else enable_dot=yes fi AC_SUBST(enable_dot) AC_SUBST(enable_html_docs) AC_SUBST(enable_latex_docs) ]) dnl @synopsis AX_COMPARE_VERSION(VERSION_A, OP, VERSION_B, [ACTION-IF-TRUE], [ACTION-IF-FALSE]) dnl dnl This macro compares two version strings. It is used heavily in the dnl macro _AX_PATH_BDB for library checking. Due to the various number dnl of minor-version numbers that can exist, and the fact that string dnl comparisons are not compatible with numeric comparisons, this is dnl not necessarily trivial to do in a autoconf script. This macro makes dnl doing these comparisons easy. dnl dnl The six basic comparisons are available, as well as checking dnl equality limited to a certain number of minor-version levels. dnl dnl The operator OP determines what type of comparison to do, and dnl can be one of: dnl eq - equal (test A == B) dnl ne - not equal (test A != B) dnl le - less than or equal (test A <= B) dnl ge - greater than or equal (test A >= B) dnl lt - less than (test A < B) dnl gt - greater than (test A > B) dnl dnl Additionally, the eq and ne operator can have a number after it dnl to limit the test to that number of minor versions. dnl eq0 - equal up to the length of the shorter version dnl ne0 - not equal up to the length of the shorter version dnl eqN - equal up to N sub-version levels dnl neN - not equal up to N sub-version levels dnl dnl When the condition is true, shell commands ACTION-IF-TRUE are run, dnl otherwise shell commands ACTION-IF-FALSE are run. The environment dnl variable 'ax_compare_version' is always set to either 'true' or 'false' dnl as well. dnl dnl Examples: dnl AX_COMPARE_VERSION([3.15.7],[lt],[3.15.8]) dnl AX_COMPARE_VERSION([3.15],[lt],[3.15.8]) dnl would both be true. dnl dnl AX_COMPARE_VERSION([3.15.7],[eq],[3.15.8]) dnl AX_COMPARE_VERSION([3.15],[gt],[3.15.8]) dnl would both be false. dnl dnl AX_COMPARE_VERSION([3.15.7],[eq2],[3.15.8]) dnl would be true because it is only comparing two minor versions. dnl AX_COMPARE_VERSION([3.15.7],[eq0],[3.15]) dnl would be true because it is only comparing the lesser number of dnl minor versions of the two values. dnl dnl Note: The characters that separate the version numbers do not dnl matter. An empty string is the same as version 0. OP is evaluated dnl by autoconf, not configure, so must be a string, not a variable. dnl dnl The author would like to acknowledge Guido Draheim whose advice about dnl the m4_case and m4_ifvaln functions make this macro only include dnl the portions necessary to perform the specific comparison specified dnl by the OP argument in the final configure script. dnl dnl @version $Id: ax_compare_version.m4,v 1.1 2004/03/01 19:14:43 guidod Exp $ dnl @author Tim Toolan dnl dnl ######################################################################### AC_DEFUN([AX_COMPARE_VERSION], [ # Used to indicate true or false condition ax_compare_version=false # Convert the two version strings to be compared into a format that # allows a simple string comparison. The end result is that a version # string of the form 1.12.5-r617 will be converted to the form # 0001001200050617. In other words, each number is zero padded to four # digits, and non digits are removed. AS_VAR_PUSHDEF([A],[ax_compare_version_A]) A=`echo "$1" | sed -e 's/\([[0-9]]*\)/Z\1Z/g' \ -e 's/Z\([[0-9]]\)Z/Z0\1Z/g' \ -e 's/Z\([[0-9]][[0-9]]\)Z/Z0\1Z/g' \ -e 's/Z\([[0-9]][[0-9]][[0-9]]\)Z/Z0\1Z/g' \ -e 's/[[^0-9]]//g'` AS_VAR_PUSHDEF([B],[ax_compare_version_B]) B=`echo "$3" | sed -e 's/\([[0-9]]*\)/Z\1Z/g' \ -e 's/Z\([[0-9]]\)Z/Z0\1Z/g' \ -e 's/Z\([[0-9]][[0-9]]\)Z/Z0\1Z/g' \ -e 's/Z\([[0-9]][[0-9]][[0-9]]\)Z/Z0\1Z/g' \ -e 's/[[^0-9]]//g'` dnl # In the case of le, ge, lt, and gt, the strings are sorted as necessary dnl # then the first line is used to determine if the condition is true. dnl # The sed right after the echo is to remove any indented white space. m4_case(m4_tolower($2), [lt],[ ax_compare_version=`echo "x$A x$B" | sed 's/^ *//' | sort -r | sed "s/x${A}/false/;s/x${B}/true/;1q"` ], [gt],[ ax_compare_version=`echo "x$A x$B" | sed 's/^ *//' | sort | sed "s/x${A}/false/;s/x${B}/true/;1q"` ], [le],[ ax_compare_version=`echo "x$A x$B" | sed 's/^ *//' | sort | sed "s/x${A}/true/;s/x${B}/false/;1q"` ], [ge],[ ax_compare_version=`echo "x$A x$B" | sed 's/^ *//' | sort -r | sed "s/x${A}/true/;s/x${B}/false/;1q"` ],[ dnl Split the operator from the subversion count if present. m4_bmatch(m4_substr($2,2), [0],[ # A count of zero means use the length of the shorter version. # Determine the number of characters in A and B. ax_compare_version_len_A=`echo "$A" | awk '{print(length)}'` ax_compare_version_len_B=`echo "$B" | awk '{print(length)}'` # Set A to no more than B's length and B to no more than A's length. A=`echo "$A" | sed "s/\(.\{$ax_compare_version_len_B\}\).*/\1/"` B=`echo "$B" | sed "s/\(.\{$ax_compare_version_len_A\}\).*/\1/"` ], [[0-9]+],[ # A count greater than zero means use only that many subversions A=`echo "$A" | sed "s/\(\([[0-9]]\{4\}\)\{m4_substr($2,2)\}\).*/\1/"` B=`echo "$B" | sed "s/\(\([[0-9]]\{4\}\)\{m4_substr($2,2)\}\).*/\1/"` ], [.+],[ AC_WARNING( [illegal OP numeric parameter: $2]) ],[]) # Pad zeros at end of numbers to make same length. ax_compare_version_tmp_A="$A`echo $B | sed 's/./0/g'`" B="$B`echo $A | sed 's/./0/g'`" A="$ax_compare_version_tmp_A" # Check for equality or inequality as necessary. m4_case(m4_tolower(m4_substr($2,0,2)), [eq],[ test "x$A" = "x$B" && ax_compare_version=true ], [ne],[ test "x$A" != "x$B" && ax_compare_version=true ],[ AC_WARNING([illegal OP parameter: $2]) ]) ]) AS_VAR_POPDEF([A])dnl AS_VAR_POPDEF([B])dnl dnl # Execute ACTION-IF-TRUE / ACTION-IF-FALSE. if test "$ax_compare_version" = "true" ; then m4_ifvaln([$4],[$4],[:])dnl m4_ifvaln([$5],[else $5])dnl fi ]) dnl AX_COMPARE_VERSION # ============ Test the nature of the va_list type. ================== AC_DEFUN([CHECK_VA_LIST], [ # Check to see how the compiler defines va_list, as pointer or array. AC_MSG_CHECKING(whether va_lists can be copied by value) AC_CACHE_VAL(ac_cv_valistisarray,[ AC_TRY_RUN([ #include void f(int i, ...) { va_list args1, args2; va_start(args1, i); args2 = args1; if (va_arg(args2, int) != 42 || va_arg(args1, int) != 42) exit(1); va_end(args1); va_end(args2); } int main() { f(0, 42); return(0); }], ac_cv_valistisarray=false, ac_cv_valistisarray=true, ac_cv_valistisarray=false ) ]) if test "$ac_cv_valistisarray" = true ; then AC_DEFINE(HAVE_VA_LIST_AS_ARRAY, [1], [Define if va_list is defined as an array]) AC_MSG_RESULT(yes) else AC_MSG_RESULT(no) fi ]) # ==================== wxWidgets ========================= AC_DEFUN([CHECK_WXWIDGETS], [ AC_MSG_CHECKING([for wxWidgets]) AC_PATH_PROG([WXWIDGETS_CONFIG],wx-config) if test "x_$WXWIDGETS_CONFIG" != "x_" then wxCflags=`$WXWIDGETS_CONFIG --cflags` AC_SUBST(WXWIDGETS_CFLAGS,$wxCflags) wxCXXflags=`$WXWIDGETS_CONFIG --cxxflags` AC_SUBST(WXWIDGETS_CXXFLAGS,$wxCXXflags) wxlibs=`$WXWIDGETS_CONFIG --libs` AC_SUBST(WXWIDGETS_LIBS,$wxlibs) wxver=`$WXWIDGETS_CONFIG --version` AC_MSG_CHECKING([wxWidgets revision]) AC_MSG_RESULT([found version $wxver]) enable_wxwidgets=yes else enable_wxwidgets=no AC_MSG_WARN([no wx-config found - wxWidgets disabled]) fi ])dnl # ==================== named ==================== # Find the installed executable of named/bind. AC_DEFUN([CHECK_NAMED], [ AC_ARG_WITH(named, [--with-named=PATH the named/bind executable], [named_program=$withval], [named_program=""], ) if test x_$named_program != x_; then AC_MSG_RESULT([Using named from --with-named $named_program]) AC_SUBST(NAMED_PROGRAM, $named_program) else AC_PATH_PROG([NAMED_PROGRAM], [named], [named], [$PATH:/sbin:/usr/sbin:/usr/local/sbin] ) fi if ! test -x $NAMED_PROGRAM; then AC_MSG_WARN([Cannot execute $NAMED_PROGRAM. Tests that require it will not be executed.]) NAMED_PROGRAM="" fi ]) sipxtapi-3.3.0~test17/m4/libtool.m40000644000175000017500000105754212321250471017637 0ustar00danieldaniel00000000000000# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*- # # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, # 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. m4_define([_LT_COPYING], [dnl # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, # 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is part of GNU Libtool. # # GNU Libtool is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, or # obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ]) # serial 57 LT_INIT # LT_PREREQ(VERSION) # ------------------ # Complain and exit if this libtool version is less that VERSION. m4_defun([LT_PREREQ], [m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1, [m4_default([$3], [m4_fatal([Libtool version $1 or higher is required], 63)])], [$2])]) # _LT_CHECK_BUILDDIR # ------------------ # Complain if the absolute build directory name contains unusual characters m4_defun([_LT_CHECK_BUILDDIR], [case `pwd` in *\ * | *\ *) AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;; esac ]) # LT_INIT([OPTIONS]) # ------------------ AC_DEFUN([LT_INIT], [AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl AC_BEFORE([$0], [LT_LANG])dnl AC_BEFORE([$0], [LT_OUTPUT])dnl AC_BEFORE([$0], [LTDL_INIT])dnl m4_require([_LT_CHECK_BUILDDIR])dnl dnl Autoconf doesn't catch unexpanded LT_ macros by default: m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4 dnl unless we require an AC_DEFUNed macro: AC_REQUIRE([LTOPTIONS_VERSION])dnl AC_REQUIRE([LTSUGAR_VERSION])dnl AC_REQUIRE([LTVERSION_VERSION])dnl AC_REQUIRE([LTOBSOLETE_VERSION])dnl m4_require([_LT_PROG_LTMAIN])dnl _LT_SHELL_INIT([SHELL=${CONFIG_SHELL-/bin/sh}]) dnl Parse OPTIONS _LT_SET_OPTIONS([$0], [$1]) # This can be used to rebuild libtool when needed LIBTOOL_DEPS="$ltmain" # Always use our own libtool. LIBTOOL='$(SHELL) $(top_builddir)/libtool' AC_SUBST(LIBTOOL)dnl _LT_SETUP # Only expand once: m4_define([LT_INIT]) ])# LT_INIT # Old names: AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT]) AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_PROG_LIBTOOL], []) dnl AC_DEFUN([AM_PROG_LIBTOOL], []) # _LT_CC_BASENAME(CC) # ------------------- # Calculate cc_basename. Skip known compiler wrappers and cross-prefix. m4_defun([_LT_CC_BASENAME], [for cc_temp in $1""; do case $cc_temp in compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;; distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;; \-*) ;; *) break;; esac done cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` ]) # _LT_FILEUTILS_DEFAULTS # ---------------------- # It is okay to use these file commands and assume they have been set # sensibly after `m4_require([_LT_FILEUTILS_DEFAULTS])'. m4_defun([_LT_FILEUTILS_DEFAULTS], [: ${CP="cp -f"} : ${MV="mv -f"} : ${RM="rm -f"} ])# _LT_FILEUTILS_DEFAULTS # _LT_SETUP # --------- m4_defun([_LT_SETUP], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl AC_REQUIRE([_LT_PREPARE_SED_QUOTE_VARS])dnl AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl _LT_DECL([], [PATH_SEPARATOR], [1], [The PATH separator for the build system])dnl dnl _LT_DECL([], [host_alias], [0], [The host system])dnl _LT_DECL([], [host], [0])dnl _LT_DECL([], [host_os], [0])dnl dnl _LT_DECL([], [build_alias], [0], [The build system])dnl _LT_DECL([], [build], [0])dnl _LT_DECL([], [build_os], [0])dnl dnl AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([LT_PATH_LD])dnl AC_REQUIRE([LT_PATH_NM])dnl dnl AC_REQUIRE([AC_PROG_LN_S])dnl test -z "$LN_S" && LN_S="ln -s" _LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl dnl AC_REQUIRE([LT_CMD_MAX_LEN])dnl _LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl _LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_CHECK_SHELL_FEATURES])dnl m4_require([_LT_PATH_CONVERSION_FUNCTIONS])dnl m4_require([_LT_CMD_RELOAD])dnl m4_require([_LT_CHECK_MAGIC_METHOD])dnl m4_require([_LT_CHECK_SHAREDLIB_FROM_LINKLIB])dnl m4_require([_LT_CMD_OLD_ARCHIVE])dnl m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl m4_require([_LT_WITH_SYSROOT])dnl _LT_CONFIG_LIBTOOL_INIT([ # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes INIT. if test -n "\${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi ]) if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi _LT_CHECK_OBJDIR m4_require([_LT_TAG_COMPILER])dnl case $host_os in aix3*) # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi ;; esac # Global variables: ofile=libtool can_build_shared=yes # All known linkers require a `.a' archive for static linking (except MSVC, # which needs '.lib'). libext=a with_gnu_ld="$lt_cv_prog_gnu_ld" old_CC="$CC" old_CFLAGS="$CFLAGS" # Set sane defaults for various variables test -z "$CC" && CC=cc test -z "$LTCC" && LTCC=$CC test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS test -z "$LD" && LD=ld test -z "$ac_objext" && ac_objext=o _LT_CC_BASENAME([$compiler]) # Only perform the check for file, if the check method requires it test -z "$MAGIC_CMD" && MAGIC_CMD=file case $deplibs_check_method in file_magic*) if test "$file_magic_cmd" = '$MAGIC_CMD'; then _LT_PATH_MAGIC fi ;; esac # Use C for the default configuration in the libtool script LT_SUPPORTED_TAG([CC]) _LT_LANG_C_CONFIG _LT_LANG_DEFAULT_CONFIG _LT_CONFIG_COMMANDS ])# _LT_SETUP # _LT_PREPARE_SED_QUOTE_VARS # -------------------------- # Define a few sed substitution that help us do robust quoting. m4_defun([_LT_PREPARE_SED_QUOTE_VARS], [# Backslashify metacharacters that are still active within # double-quoted strings. sed_quote_subst='s/\([["`$\\]]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\([["`\\]]\)/\\\1/g' # Sed substitution to delay expansion of an escaped shell variable in a # double_quote_subst'ed string. delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' # Sed substitution to delay expansion of an escaped single quote. delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' # Sed substitution to avoid accidental globbing in evaled expressions no_glob_subst='s/\*/\\\*/g' ]) # _LT_PROG_LTMAIN # --------------- # Note that this code is called both from `configure', and `config.status' # now that we use AC_CONFIG_COMMANDS to generate libtool. Notably, # `config.status' has no value for ac_aux_dir unless we are using Automake, # so we pass a copy along to make sure it has a sensible value anyway. m4_defun([_LT_PROG_LTMAIN], [m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl _LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir']) ltmain="$ac_aux_dir/ltmain.sh" ])# _LT_PROG_LTMAIN ## ------------------------------------- ## ## Accumulate code for creating libtool. ## ## ------------------------------------- ## # So that we can recreate a full libtool script including additional # tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS # in macros and then make a single call at the end using the `libtool' # label. # _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS]) # ---------------------------------------- # Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later. m4_define([_LT_CONFIG_LIBTOOL_INIT], [m4_ifval([$1], [m4_append([_LT_OUTPUT_LIBTOOL_INIT], [$1 ])])]) # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_INIT]) # _LT_CONFIG_LIBTOOL([COMMANDS]) # ------------------------------ # Register COMMANDS to be passed to AC_CONFIG_COMMANDS later. m4_define([_LT_CONFIG_LIBTOOL], [m4_ifval([$1], [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS], [$1 ])])]) # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS]) # _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS]) # ----------------------------------------------------- m4_defun([_LT_CONFIG_SAVE_COMMANDS], [_LT_CONFIG_LIBTOOL([$1]) _LT_CONFIG_LIBTOOL_INIT([$2]) ]) # _LT_FORMAT_COMMENT([COMMENT]) # ----------------------------- # Add leading comment marks to the start of each line, and a trailing # full-stop to the whole comment if one is not present already. m4_define([_LT_FORMAT_COMMENT], [m4_ifval([$1], [ m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])], [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.]) )]) ## ------------------------ ## ## FIXME: Eliminate VARNAME ## ## ------------------------ ## # _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?]) # ------------------------------------------------------------------- # CONFIGNAME is the name given to the value in the libtool script. # VARNAME is the (base) name used in the configure script. # VALUE may be 0, 1 or 2 for a computed quote escaped value based on # VARNAME. Any other value will be used directly. m4_define([_LT_DECL], [lt_if_append_uniq([lt_decl_varnames], [$2], [, ], [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name], [m4_ifval([$1], [$1], [$2])]) lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3]) m4_ifval([$4], [lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])]) lt_dict_add_subkey([lt_decl_dict], [$2], [tagged?], [m4_ifval([$5], [yes], [no])])]) ]) # _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION]) # -------------------------------------------------------- m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])]) # lt_decl_tag_varnames([SEPARATOR], [VARNAME1...]) # ------------------------------------------------ m4_define([lt_decl_tag_varnames], [_lt_decl_filter([tagged?], [yes], $@)]) # _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..]) # --------------------------------------------------------- m4_define([_lt_decl_filter], [m4_case([$#], [0], [m4_fatal([$0: too few arguments: $#])], [1], [m4_fatal([$0: too few arguments: $#: $1])], [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)], [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)], [lt_dict_filter([lt_decl_dict], $@)])[]dnl ]) # lt_decl_quote_varnames([SEPARATOR], [VARNAME1...]) # -------------------------------------------------- m4_define([lt_decl_quote_varnames], [_lt_decl_filter([value], [1], $@)]) # lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...]) # --------------------------------------------------- m4_define([lt_decl_dquote_varnames], [_lt_decl_filter([value], [2], $@)]) # lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...]) # --------------------------------------------------- m4_define([lt_decl_varnames_tagged], [m4_assert([$# <= 2])dnl _$0(m4_quote(m4_default([$1], [[, ]])), m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]), m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))]) m4_define([_lt_decl_varnames_tagged], [m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])]) # lt_decl_all_varnames([SEPARATOR], [VARNAME1...]) # ------------------------------------------------ m4_define([lt_decl_all_varnames], [_$0(m4_quote(m4_default([$1], [[, ]])), m4_if([$2], [], m4_quote(lt_decl_varnames), m4_quote(m4_shift($@))))[]dnl ]) m4_define([_lt_decl_all_varnames], [lt_join($@, lt_decl_varnames_tagged([$1], lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl ]) # _LT_CONFIG_STATUS_DECLARE([VARNAME]) # ------------------------------------ # Quote a variable value, and forward it to `config.status' so that its # declaration there will have the same value as in `configure'. VARNAME # must have a single quote delimited value for this to work. m4_define([_LT_CONFIG_STATUS_DECLARE], [$1='`$ECHO "$][$1" | $SED "$delay_single_quote_subst"`']) # _LT_CONFIG_STATUS_DECLARATIONS # ------------------------------ # We delimit libtool config variables with single quotes, so when # we write them to config.status, we have to be sure to quote all # embedded single quotes properly. In configure, this macro expands # each variable declared with _LT_DECL (and _LT_TAGDECL) into: # # ='`$ECHO "$" | $SED "$delay_single_quote_subst"`' m4_defun([_LT_CONFIG_STATUS_DECLARATIONS], [m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames), [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])]) # _LT_LIBTOOL_TAGS # ---------------- # Output comment and list of tags supported by the script m4_defun([_LT_LIBTOOL_TAGS], [_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl available_tags="_LT_TAGS"dnl ]) # _LT_LIBTOOL_DECLARE(VARNAME, [TAG]) # ----------------------------------- # Extract the dictionary values for VARNAME (optionally with TAG) and # expand to a commented shell variable setting: # # # Some comment about what VAR is for. # visible_name=$lt_internal_name m4_define([_LT_LIBTOOL_DECLARE], [_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [description])))[]dnl m4_pushdef([_libtool_name], m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])), [0], [_libtool_name=[$]$1], [1], [_libtool_name=$lt_[]$1], [2], [_libtool_name=$lt_[]$1], [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl ]) # _LT_LIBTOOL_CONFIG_VARS # ----------------------- # Produce commented declarations of non-tagged libtool config variables # suitable for insertion in the LIBTOOL CONFIG section of the `libtool' # script. Tagged libtool config variables (even for the LIBTOOL CONFIG # section) are produced by _LT_LIBTOOL_TAG_VARS. m4_defun([_LT_LIBTOOL_CONFIG_VARS], [m4_foreach([_lt_var], m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)), [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])]) # _LT_LIBTOOL_TAG_VARS(TAG) # ------------------------- m4_define([_LT_LIBTOOL_TAG_VARS], [m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames), [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])]) # _LT_TAGVAR(VARNAME, [TAGNAME]) # ------------------------------ m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])]) # _LT_CONFIG_COMMANDS # ------------------- # Send accumulated output to $CONFIG_STATUS. Thanks to the lists of # variables for single and double quote escaping we saved from calls # to _LT_DECL, we can put quote escaped variables declarations # into `config.status', and then the shell code to quote escape them in # for loops in `config.status'. Finally, any additional code accumulated # from calls to _LT_CONFIG_LIBTOOL_INIT is expanded. m4_defun([_LT_CONFIG_COMMANDS], [AC_PROVIDE_IFELSE([LT_OUTPUT], dnl If the libtool generation code has been placed in $CONFIG_LT, dnl instead of duplicating it all over again into config.status, dnl then we will have config.status run $CONFIG_LT later, so it dnl needs to know what name is stored there: [AC_CONFIG_COMMANDS([libtool], [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])], dnl If the libtool generation code is destined for config.status, dnl expand the accumulated commands and init code now: [AC_CONFIG_COMMANDS([libtool], [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])]) ])#_LT_CONFIG_COMMANDS # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT], [ # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH sed_quote_subst='$sed_quote_subst' double_quote_subst='$double_quote_subst' delay_variable_subst='$delay_variable_subst' _LT_CONFIG_STATUS_DECLARATIONS LTCC='$LTCC' LTCFLAGS='$LTCFLAGS' compiler='$compiler_DEFAULT' # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$[]1 _LTECHO_EOF' } # Quote evaled strings. for var in lt_decl_all_varnames([[ \ ]], lt_decl_quote_varnames); do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[[\\\\\\\`\\"\\\$]]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done # Double-quote double-evaled strings. for var in lt_decl_all_varnames([[ \ ]], lt_decl_dquote_varnames); do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[[\\\\\\\`\\"\\\$]]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done _LT_OUTPUT_LIBTOOL_INIT ]) # _LT_GENERATED_FILE_INIT(FILE, [COMMENT]) # ------------------------------------ # Generate a child script FILE with all initialization necessary to # reuse the environment learned by the parent script, and make the # file executable. If COMMENT is supplied, it is inserted after the # `#!' sequence but before initialization text begins. After this # macro, additional text can be appended to FILE to form the body of # the child script. The macro ends with non-zero status if the # file could not be fully written (such as if the disk is full). m4_ifdef([AS_INIT_GENERATED], [m4_defun([_LT_GENERATED_FILE_INIT],[AS_INIT_GENERATED($@)])], [m4_defun([_LT_GENERATED_FILE_INIT], [m4_require([AS_PREPARE])]dnl [m4_pushdef([AS_MESSAGE_LOG_FD])]dnl [lt_write_fail=0 cat >$1 <<_ASEOF || lt_write_fail=1 #! $SHELL # Generated by $as_me. $2 SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$1 <<\_ASEOF || lt_write_fail=1 AS_SHELL_SANITIZE _AS_PREPARE exec AS_MESSAGE_FD>&1 _ASEOF test $lt_write_fail = 0 && chmod +x $1[]dnl m4_popdef([AS_MESSAGE_LOG_FD])])])# _LT_GENERATED_FILE_INIT # LT_OUTPUT # --------- # This macro allows early generation of the libtool script (before # AC_OUTPUT is called), incase it is used in configure for compilation # tests. AC_DEFUN([LT_OUTPUT], [: ${CONFIG_LT=./config.lt} AC_MSG_NOTICE([creating $CONFIG_LT]) _LT_GENERATED_FILE_INIT(["$CONFIG_LT"], [# Run this file to recreate a libtool stub with the current configuration.]) cat >>"$CONFIG_LT" <<\_LTEOF lt_cl_silent=false exec AS_MESSAGE_LOG_FD>>config.log { echo AS_BOX([Running $as_me.]) } >&AS_MESSAGE_LOG_FD lt_cl_help="\ \`$as_me' creates a local libtool stub from the current configuration, for use in further configure time tests before the real libtool is generated. Usage: $[0] [[OPTIONS]] -h, --help print this help, then exit -V, --version print version number, then exit -q, --quiet do not print progress messages -d, --debug don't remove temporary files Report bugs to ." lt_cl_version="\ m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION]) configured by $[0], generated by m4_PACKAGE_STRING. Copyright (C) 2011 Free Software Foundation, Inc. This config.lt script is free software; the Free Software Foundation gives unlimited permision to copy, distribute and modify it." while test $[#] != 0 do case $[1] in --version | --v* | -V ) echo "$lt_cl_version"; exit 0 ;; --help | --h* | -h ) echo "$lt_cl_help"; exit 0 ;; --debug | --d* | -d ) debug=: ;; --quiet | --q* | --silent | --s* | -q ) lt_cl_silent=: ;; -*) AC_MSG_ERROR([unrecognized option: $[1] Try \`$[0] --help' for more information.]) ;; *) AC_MSG_ERROR([unrecognized argument: $[1] Try \`$[0] --help' for more information.]) ;; esac shift done if $lt_cl_silent; then exec AS_MESSAGE_FD>/dev/null fi _LTEOF cat >>"$CONFIG_LT" <<_LTEOF _LT_OUTPUT_LIBTOOL_COMMANDS_INIT _LTEOF cat >>"$CONFIG_LT" <<\_LTEOF AC_MSG_NOTICE([creating $ofile]) _LT_OUTPUT_LIBTOOL_COMMANDS AS_EXIT(0) _LTEOF chmod +x "$CONFIG_LT" # configure is writing to config.log, but config.lt does its own redirection, # appending to config.log, which fails on DOS, as config.log is still kept # open by configure. Here we exec the FD to /dev/null, effectively closing # config.log, so it can be properly (re)opened and appended to by config.lt. lt_cl_success=: test "$silent" = yes && lt_config_lt_args="$lt_config_lt_args --quiet" exec AS_MESSAGE_LOG_FD>/dev/null $SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false exec AS_MESSAGE_LOG_FD>>config.log $lt_cl_success || AS_EXIT(1) ])# LT_OUTPUT # _LT_CONFIG(TAG) # --------------- # If TAG is the built-in tag, create an initial libtool script with a # default configuration from the untagged config vars. Otherwise add code # to config.status for appending the configuration named by TAG from the # matching tagged config vars. m4_defun([_LT_CONFIG], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl _LT_CONFIG_SAVE_COMMANDS([ m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl m4_if(_LT_TAG, [C], [ # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes. if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi cfgfile="${ofile}T" trap "$RM \"$cfgfile\"; exit 1" 1 2 15 $RM "$cfgfile" cat <<_LT_EOF >> "$cfgfile" #! $SHELL # `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services. # Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION # Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: # NOTE: Changes made to this file will be lost: look at ltmain.sh. # _LT_COPYING _LT_LIBTOOL_TAGS # ### BEGIN LIBTOOL CONFIG _LT_LIBTOOL_CONFIG_VARS _LT_LIBTOOL_TAG_VARS # ### END LIBTOOL CONFIG _LT_EOF case $host_os in aix3*) cat <<\_LT_EOF >> "$cfgfile" # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi _LT_EOF ;; esac _LT_PROG_LTMAIN # We use sed instead of cat because bash on DJGPP gets confused if # if finds mixed CR/LF and LF-only lines. Since sed operates in # text mode, it properly converts lines to CR/LF. This bash problem # is reportedly fixed, but why not run on old versions too? sed '$q' "$ltmain" >> "$cfgfile" \ || (rm -f "$cfgfile"; exit 1) _LT_PROG_REPLACE_SHELLFNS mv -f "$cfgfile" "$ofile" || (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") chmod +x "$ofile" ], [cat <<_LT_EOF >> "$ofile" dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded dnl in a comment (ie after a #). # ### BEGIN LIBTOOL TAG CONFIG: $1 _LT_LIBTOOL_TAG_VARS(_LT_TAG) # ### END LIBTOOL TAG CONFIG: $1 _LT_EOF ])dnl /m4_if ], [m4_if([$1], [], [ PACKAGE='$PACKAGE' VERSION='$VERSION' TIMESTAMP='$TIMESTAMP' RM='$RM' ofile='$ofile'], []) ])dnl /_LT_CONFIG_SAVE_COMMANDS ])# _LT_CONFIG # LT_SUPPORTED_TAG(TAG) # --------------------- # Trace this macro to discover what tags are supported by the libtool # --tag option, using: # autoconf --trace 'LT_SUPPORTED_TAG:$1' AC_DEFUN([LT_SUPPORTED_TAG], []) # C support is built-in for now m4_define([_LT_LANG_C_enabled], []) m4_define([_LT_TAGS], []) # LT_LANG(LANG) # ------------- # Enable libtool support for the given language if not already enabled. AC_DEFUN([LT_LANG], [AC_BEFORE([$0], [LT_OUTPUT])dnl m4_case([$1], [C], [_LT_LANG(C)], [C++], [_LT_LANG(CXX)], [Go], [_LT_LANG(GO)], [Java], [_LT_LANG(GCJ)], [Fortran 77], [_LT_LANG(F77)], [Fortran], [_LT_LANG(FC)], [Windows Resource], [_LT_LANG(RC)], [m4_ifdef([_LT_LANG_]$1[_CONFIG], [_LT_LANG($1)], [m4_fatal([$0: unsupported language: "$1"])])])dnl ])# LT_LANG # _LT_LANG(LANGNAME) # ------------------ m4_defun([_LT_LANG], [m4_ifdef([_LT_LANG_]$1[_enabled], [], [LT_SUPPORTED_TAG([$1])dnl m4_append([_LT_TAGS], [$1 ])dnl m4_define([_LT_LANG_]$1[_enabled], [])dnl _LT_LANG_$1_CONFIG($1)])dnl ])# _LT_LANG m4_ifndef([AC_PROG_GO], [ ############################################################ # NOTE: This macro has been submitted for inclusion into # # GNU Autoconf as AC_PROG_GO. When it is available in # # a released version of Autoconf we should remove this # # macro and use it instead. # ############################################################ m4_defun([AC_PROG_GO], [AC_LANG_PUSH(Go)dnl AC_ARG_VAR([GOC], [Go compiler command])dnl AC_ARG_VAR([GOFLAGS], [Go compiler flags])dnl _AC_ARG_VAR_LDFLAGS()dnl AC_CHECK_TOOL(GOC, gccgo) if test -z "$GOC"; then if test -n "$ac_tool_prefix"; then AC_CHECK_PROG(GOC, [${ac_tool_prefix}gccgo], [${ac_tool_prefix}gccgo]) fi fi if test -z "$GOC"; then AC_CHECK_PROG(GOC, gccgo, gccgo, false) fi ])#m4_defun ])#m4_ifndef # _LT_LANG_DEFAULT_CONFIG # ----------------------- m4_defun([_LT_LANG_DEFAULT_CONFIG], [AC_PROVIDE_IFELSE([AC_PROG_CXX], [LT_LANG(CXX)], [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])]) AC_PROVIDE_IFELSE([AC_PROG_F77], [LT_LANG(F77)], [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])]) AC_PROVIDE_IFELSE([AC_PROG_FC], [LT_LANG(FC)], [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])]) dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal dnl pulling things in needlessly. AC_PROVIDE_IFELSE([AC_PROG_GCJ], [LT_LANG(GCJ)], [AC_PROVIDE_IFELSE([A][M_PROG_GCJ], [LT_LANG(GCJ)], [AC_PROVIDE_IFELSE([LT_PROG_GCJ], [LT_LANG(GCJ)], [m4_ifdef([AC_PROG_GCJ], [m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])]) m4_ifdef([A][M_PROG_GCJ], [m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])]) m4_ifdef([LT_PROG_GCJ], [m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])]) AC_PROVIDE_IFELSE([AC_PROG_GO], [LT_LANG(GO)], [m4_define([AC_PROG_GO], defn([AC_PROG_GO])[LT_LANG(GO)])]) AC_PROVIDE_IFELSE([LT_PROG_RC], [LT_LANG(RC)], [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])]) ])# _LT_LANG_DEFAULT_CONFIG # Obsolete macros: AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)]) AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)]) AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)]) AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)]) AU_DEFUN([AC_LIBTOOL_RC], [LT_LANG(Windows Resource)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_CXX], []) dnl AC_DEFUN([AC_LIBTOOL_F77], []) dnl AC_DEFUN([AC_LIBTOOL_FC], []) dnl AC_DEFUN([AC_LIBTOOL_GCJ], []) dnl AC_DEFUN([AC_LIBTOOL_RC], []) # _LT_TAG_COMPILER # ---------------- m4_defun([_LT_TAG_COMPILER], [AC_REQUIRE([AC_PROG_CC])dnl _LT_DECL([LTCC], [CC], [1], [A C compiler])dnl _LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl _LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl _LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC ])# _LT_TAG_COMPILER # _LT_COMPILER_BOILERPLATE # ------------------------ # Check for compiler boilerplate output or warnings with # the simple compiler test code. m4_defun([_LT_COMPILER_BOILERPLATE], [m4_require([_LT_DECL_SED])dnl ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" >conftest.$ac_ext eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_compiler_boilerplate=`cat conftest.err` $RM conftest* ])# _LT_COMPILER_BOILERPLATE # _LT_LINKER_BOILERPLATE # ---------------------- # Check for linker boilerplate output or warnings with # the simple link test code. m4_defun([_LT_LINKER_BOILERPLATE], [m4_require([_LT_DECL_SED])dnl ac_outfile=conftest.$ac_objext echo "$lt_simple_link_test_code" >conftest.$ac_ext eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* ])# _LT_LINKER_BOILERPLATE # _LT_REQUIRED_DARWIN_CHECKS # ------------------------- m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[ case $host_os in rhapsody* | darwin*) AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:]) AC_CHECK_TOOL([NMEDIT], [nmedit], [:]) AC_CHECK_TOOL([LIPO], [lipo], [:]) AC_CHECK_TOOL([OTOOL], [otool], [:]) AC_CHECK_TOOL([OTOOL64], [otool64], [:]) _LT_DECL([], [DSYMUTIL], [1], [Tool to manipulate archived DWARF debug symbol files on Mac OS X]) _LT_DECL([], [NMEDIT], [1], [Tool to change global to local symbols on Mac OS X]) _LT_DECL([], [LIPO], [1], [Tool to manipulate fat objects and archives on Mac OS X]) _LT_DECL([], [OTOOL], [1], [ldd/readelf like tool for Mach-O binaries on Mac OS X]) _LT_DECL([], [OTOOL64], [1], [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4]) AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod], [lt_cv_apple_cc_single_mod=no if test -z "${LT_MULTI_MODULE}"; then # By default we will add the -single_module flag. You can override # by either setting the environment variable LT_MULTI_MODULE # non-empty at configure time, or by adding -multi_module to the # link flags. rm -rf libconftest.dylib* echo "int foo(void){return 1;}" > conftest.c echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c 2>conftest.err _lt_result=$? # If there is a non-empty error log, and "single_module" # appears in it, assume the flag caused a linker warning if test -s conftest.err && $GREP single_module conftest.err; then cat conftest.err >&AS_MESSAGE_LOG_FD # Otherwise, if the output was created with a 0 exit code from # the compiler, it worked. elif test -f libconftest.dylib && test $_lt_result -eq 0; then lt_cv_apple_cc_single_mod=yes else cat conftest.err >&AS_MESSAGE_LOG_FD fi rm -rf libconftest.dylib* rm -f conftest.* fi]) AC_CACHE_CHECK([for -exported_symbols_list linker flag], [lt_cv_ld_exported_symbols_list], [lt_cv_ld_exported_symbols_list=no save_LDFLAGS=$LDFLAGS echo "_main" > conftest.sym LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], [lt_cv_ld_exported_symbols_list=yes], [lt_cv_ld_exported_symbols_list=no]) LDFLAGS="$save_LDFLAGS" ]) AC_CACHE_CHECK([for -force_load linker flag],[lt_cv_ld_force_load], [lt_cv_ld_force_load=no cat > conftest.c << _LT_EOF int forced_loaded() { return 2;} _LT_EOF echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&AS_MESSAGE_LOG_FD echo "$AR cru libconftest.a conftest.o" >&AS_MESSAGE_LOG_FD $AR cru libconftest.a conftest.o 2>&AS_MESSAGE_LOG_FD echo "$RANLIB libconftest.a" >&AS_MESSAGE_LOG_FD $RANLIB libconftest.a 2>&AS_MESSAGE_LOG_FD cat > conftest.c << _LT_EOF int main() { return 0;} _LT_EOF echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err _lt_result=$? if test -s conftest.err && $GREP force_load conftest.err; then cat conftest.err >&AS_MESSAGE_LOG_FD elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then lt_cv_ld_force_load=yes else cat conftest.err >&AS_MESSAGE_LOG_FD fi rm -f conftest.err libconftest.a conftest conftest.c rm -rf conftest.dSYM ]) case $host_os in rhapsody* | darwin1.[[012]]) _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;; darwin1.*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; darwin*) # darwin 5.x on # if running on 10.5 or later, the deployment target defaults # to the OS version, if on x86, and 10.4, the deployment # target defaults to 10.4. Don't you love it? case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in 10.0,*86*-darwin8*|10.0,*-darwin[[91]]*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; 10.[[012]]*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; 10.*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; esac ;; esac if test "$lt_cv_apple_cc_single_mod" = "yes"; then _lt_dar_single_mod='$single_module' fi if test "$lt_cv_ld_exported_symbols_list" = "yes"; then _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym' else _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}' fi if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then _lt_dsymutil='~$DSYMUTIL $lib || :' else _lt_dsymutil= fi ;; esac ]) # _LT_DARWIN_LINKER_FEATURES([TAG]) # --------------------------------- # Checks for linker and compiler features on darwin m4_defun([_LT_DARWIN_LINKER_FEATURES], [ m4_require([_LT_REQUIRED_DARWIN_CHECKS]) _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported if test "$lt_cv_ld_force_load" = "yes"; then _LT_TAGVAR(whole_archive_flag_spec, $1)='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' m4_case([$1], [F77], [_LT_TAGVAR(compiler_needs_object, $1)=yes], [FC], [_LT_TAGVAR(compiler_needs_object, $1)=yes]) else _LT_TAGVAR(whole_archive_flag_spec, $1)='' fi _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined" case $cc_basename in ifort*) _lt_dar_can_shared=yes ;; *) _lt_dar_can_shared=$GCC ;; esac if test "$_lt_dar_can_shared" = "yes"; then output_verbose_link_cmd=func_echo_all _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" m4_if([$1], [CXX], [ if test "$lt_cv_apple_cc_single_mod" != "yes"; then _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}" _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}" fi ],[]) else _LT_TAGVAR(ld_shlibs, $1)=no fi ]) # _LT_SYS_MODULE_PATH_AIX([TAGNAME]) # ---------------------------------- # Links a minimal program and checks the executable # for the system default hardcoded library path. In most cases, # this is /usr/lib:/lib, but when the MPI compilers are used # the location of the communication and MPI libs are included too. # If we don't find anything, use the default library path according # to the aix ld manual. # Store the results from the different compilers for each TAGNAME. # Allow to override them for all tags through lt_cv_aix_libpath. m4_defun([_LT_SYS_MODULE_PATH_AIX], [m4_require([_LT_DECL_SED])dnl if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else AC_CACHE_VAL([_LT_TAGVAR([lt_cv_aix_libpath_], [$1])], [AC_LINK_IFELSE([AC_LANG_PROGRAM],[ lt_aix_libpath_sed='[ /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }]' _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi],[]) if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then _LT_TAGVAR([lt_cv_aix_libpath_], [$1])="/usr/lib:/lib" fi ]) aix_libpath=$_LT_TAGVAR([lt_cv_aix_libpath_], [$1]) fi ])# _LT_SYS_MODULE_PATH_AIX # _LT_SHELL_INIT(ARG) # ------------------- m4_define([_LT_SHELL_INIT], [m4_divert_text([M4SH-INIT], [$1 ])])# _LT_SHELL_INIT # _LT_PROG_ECHO_BACKSLASH # ----------------------- # Find how we can fake an echo command that does not interpret backslash. # In particular, with Autoconf 2.60 or later we add some code to the start # of the generated configure script which will find a shell with a builtin # printf (which we can use as an echo command). m4_defun([_LT_PROG_ECHO_BACKSLASH], [ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO AC_MSG_CHECKING([how to print strings]) # Test print first, because it will be a builtin if present. if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='print -r --' elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='printf %s\n' else # Use this function as a fallback that always works. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $[]1 _LTECHO_EOF' } ECHO='func_fallback_echo' fi # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "$*" } case "$ECHO" in printf*) AC_MSG_RESULT([printf]) ;; print*) AC_MSG_RESULT([print -r]) ;; *) AC_MSG_RESULT([cat]) ;; esac m4_ifdef([_AS_DETECT_SUGGESTED], [_AS_DETECT_SUGGESTED([ test -n "${ZSH_VERSION+set}${BASH_VERSION+set}" || ( ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO PATH=/empty FPATH=/empty; export PATH FPATH test "X`printf %s $ECHO`" = "X$ECHO" \ || test "X`print -r -- $ECHO`" = "X$ECHO" )])]) _LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts]) _LT_DECL([], [ECHO], [1], [An echo program that protects backslashes]) ])# _LT_PROG_ECHO_BACKSLASH # _LT_WITH_SYSROOT # ---------------- AC_DEFUN([_LT_WITH_SYSROOT], [AC_MSG_CHECKING([for sysroot]) AC_ARG_WITH([sysroot], [ --with-sysroot[=DIR] Search for dependent libraries within DIR (or the compiler's sysroot if not specified).], [], [with_sysroot=no]) dnl lt_sysroot will always be passed unquoted. We quote it here dnl in case the user passed a directory name. lt_sysroot= case ${with_sysroot} in #( yes) if test "$GCC" = yes; then lt_sysroot=`$CC --print-sysroot 2>/dev/null` fi ;; #( /*) lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"` ;; #( no|'') ;; #( *) AC_MSG_RESULT([${with_sysroot}]) AC_MSG_ERROR([The sysroot must be an absolute path.]) ;; esac AC_MSG_RESULT([${lt_sysroot:-no}]) _LT_DECL([], [lt_sysroot], [0], [The root where to search for ]dnl [dependent libraries, and in which our libraries should be installed.])]) # _LT_ENABLE_LOCK # --------------- m4_defun([_LT_ENABLE_LOCK], [AC_ARG_ENABLE([libtool-lock], [AS_HELP_STRING([--disable-libtool-lock], [avoid locking (might break parallel builds)])]) test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes # Some flags need to be propagated to the compiler or linker for good # libtool support. case $host in ia64-*-hpux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `/usr/bin/file conftest.$ac_objext` in *ELF-32*) HPUX_IA64_MODE="32" ;; *ELF-64*) HPUX_IA64_MODE="64" ;; esac fi rm -rf conftest* ;; *-*-irix6*) # Find out which ABI we are using. echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then if test "$lt_cv_prog_gnu_ld" = yes; then case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -melf32bsmip" ;; *N32*) LD="${LD-ld} -melf32bmipn32" ;; *64-bit*) LD="${LD-ld} -melf64bmip" ;; esac else case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -32" ;; *N32*) LD="${LD-ld} -n32" ;; *64-bit*) LD="${LD-ld} -64" ;; esac fi fi rm -rf conftest* ;; x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `/usr/bin/file conftest.o` in *32-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_i386_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_i386" ;; ppc64-*linux*|powerpc64-*linux*) LD="${LD-ld} -m elf32ppclinux" ;; s390x-*linux*) LD="${LD-ld} -m elf_s390" ;; sparc64-*linux*) LD="${LD-ld} -m elf32_sparc" ;; esac ;; *64-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_x86_64_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_x86_64" ;; ppc*-*linux*|powerpc*-*linux*) LD="${LD-ld} -m elf64ppc" ;; s390*-*linux*|s390*-*tpf*) LD="${LD-ld} -m elf64_s390" ;; sparc*-*linux*) LD="${LD-ld} -m elf64_sparc" ;; esac ;; esac fi rm -rf conftest* ;; *-*-sco3.2v5*) # On SCO OpenServer 5, we need -belf to get full-featured binaries. SAVE_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS -belf" AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf, [AC_LANG_PUSH(C) AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no]) AC_LANG_POP]) if test x"$lt_cv_cc_needs_belf" != x"yes"; then # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf CFLAGS="$SAVE_CFLAGS" fi ;; *-*solaris*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `/usr/bin/file conftest.o` in *64-bit*) case $lt_cv_prog_gnu_ld in yes*) case $host in i?86-*-solaris*) LD="${LD-ld} -m elf_x86_64" ;; sparc*-*-solaris*) LD="${LD-ld} -m elf64_sparc" ;; esac # GNU ld 2.21 introduced _sol2 emulations. Use them if available. if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then LD="${LD-ld}_sol2" fi ;; *) if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then LD="${LD-ld} -64" fi ;; esac ;; esac fi rm -rf conftest* ;; esac need_locks="$enable_libtool_lock" ])# _LT_ENABLE_LOCK # _LT_PROG_AR # ----------- m4_defun([_LT_PROG_AR], [AC_CHECK_TOOLS(AR, [ar], false) : ${AR=ar} : ${AR_FLAGS=cru} _LT_DECL([], [AR], [1], [The archiver]) _LT_DECL([], [AR_FLAGS], [1], [Flags to create an archive]) AC_CACHE_CHECK([for archiver @FILE support], [lt_cv_ar_at_file], [lt_cv_ar_at_file=no AC_COMPILE_IFELSE([AC_LANG_PROGRAM], [echo conftest.$ac_objext > conftest.lst lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&AS_MESSAGE_LOG_FD' AC_TRY_EVAL([lt_ar_try]) if test "$ac_status" -eq 0; then # Ensure the archiver fails upon bogus file names. rm -f conftest.$ac_objext libconftest.a AC_TRY_EVAL([lt_ar_try]) if test "$ac_status" -ne 0; then lt_cv_ar_at_file=@ fi fi rm -f conftest.* libconftest.a ]) ]) if test "x$lt_cv_ar_at_file" = xno; then archiver_list_spec= else archiver_list_spec=$lt_cv_ar_at_file fi _LT_DECL([], [archiver_list_spec], [1], [How to feed a file listing to the archiver]) ])# _LT_PROG_AR # _LT_CMD_OLD_ARCHIVE # ------------------- m4_defun([_LT_CMD_OLD_ARCHIVE], [_LT_PROG_AR AC_CHECK_TOOL(STRIP, strip, :) test -z "$STRIP" && STRIP=: _LT_DECL([], [STRIP], [1], [A symbol stripping program]) AC_CHECK_TOOL(RANLIB, ranlib, :) test -z "$RANLIB" && RANLIB=: _LT_DECL([], [RANLIB], [1], [Commands used to install an old-style archive]) # Determine commands to create old-style static archives. old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' old_postinstall_cmds='chmod 644 $oldlib' old_postuninstall_cmds= if test -n "$RANLIB"; then case $host_os in openbsd*) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" ;; *) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" ;; esac old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" fi case $host_os in darwin*) lock_old_archive_extraction=yes ;; *) lock_old_archive_extraction=no ;; esac _LT_DECL([], [old_postinstall_cmds], [2]) _LT_DECL([], [old_postuninstall_cmds], [2]) _LT_TAGDECL([], [old_archive_cmds], [2], [Commands used to build an old-style archive]) _LT_DECL([], [lock_old_archive_extraction], [0], [Whether to use a lock for old archive extraction]) ])# _LT_CMD_OLD_ARCHIVE # _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, # [OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE]) # ---------------------------------------------------------------- # Check whether the given compiler option works AC_DEFUN([_LT_COMPILER_OPTION], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_SED])dnl AC_CACHE_CHECK([$1], [$2], [$2=no m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4]) echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$3" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&AS_MESSAGE_LOG_FD echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then $2=yes fi fi $RM conftest* ]) if test x"[$]$2" = xyes; then m4_if([$5], , :, [$5]) else m4_if([$6], , :, [$6]) fi ])# _LT_COMPILER_OPTION # Old name: AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], []) # _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, # [ACTION-SUCCESS], [ACTION-FAILURE]) # ---------------------------------------------------- # Check whether the given linker option works AC_DEFUN([_LT_LINKER_OPTION], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_SED])dnl AC_CACHE_CHECK([$1], [$2], [$2=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS $3" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&AS_MESSAGE_LOG_FD $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then $2=yes fi else $2=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" ]) if test x"[$]$2" = xyes; then m4_if([$4], , :, [$4]) else m4_if([$5], , :, [$5]) fi ])# _LT_LINKER_OPTION # Old name: AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], []) # LT_CMD_MAX_LEN #--------------- AC_DEFUN([LT_CMD_MAX_LEN], [AC_REQUIRE([AC_CANONICAL_HOST])dnl # find the maximum length of command line arguments AC_MSG_CHECKING([the maximum length of command line arguments]) AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl i=0 teststring="ABCD" case $build_os in msdosdjgpp*) # On DJGPP, this test can blow up pretty badly due to problems in libc # (any single argument exceeding 2000 bytes causes a buffer overrun # during glob expansion). Even if it were fixed, the result of this # check would be larger than it should be. lt_cv_sys_max_cmd_len=12288; # 12K is about right ;; gnu*) # Under GNU Hurd, this test is not required because there is # no limit to the length of command line arguments. # Libtool will interpret -1 as no limit whatsoever lt_cv_sys_max_cmd_len=-1; ;; cygwin* | mingw* | cegcc*) # On Win9x/ME, this test blows up -- it succeeds, but takes # about 5 minutes as the teststring grows exponentially. # Worse, since 9x/ME are not pre-emptively multitasking, # you end up with a "frozen" computer, even though with patience # the test eventually succeeds (with a max line length of 256k). # Instead, let's just punt: use the minimum linelength reported by # all of the supported platforms: 8192 (on NT/2K/XP). lt_cv_sys_max_cmd_len=8192; ;; mint*) # On MiNT this can take a long time and run out of memory. lt_cv_sys_max_cmd_len=8192; ;; amigaos*) # On AmigaOS with pdksh, this test takes hours, literally. # So we just punt and use a minimum line length of 8192. lt_cv_sys_max_cmd_len=8192; ;; netbsd* | freebsd* | openbsd* | darwin* | dragonfly*) # This has been around since 386BSD, at least. Likely further. if test -x /sbin/sysctl; then lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` elif test -x /usr/sbin/sysctl; then lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` else lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs fi # And add a safety zone lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` ;; interix*) # We know the value 262144 and hardcode it with a safety zone (like BSD) lt_cv_sys_max_cmd_len=196608 ;; os2*) # The test takes a long time on OS/2. lt_cv_sys_max_cmd_len=8192 ;; osf*) # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not # nice to cause kernel panics so lets avoid the loop below. # First set a reasonable default. lt_cv_sys_max_cmd_len=16384 # if test -x /sbin/sysconfig; then case `/sbin/sysconfig -q proc exec_disable_arg_limit` in *1*) lt_cv_sys_max_cmd_len=-1 ;; esac fi ;; sco3.2v5*) lt_cv_sys_max_cmd_len=102400 ;; sysv5* | sco5v6* | sysv4.2uw2*) kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` if test -n "$kargmax"; then lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[ ]]//'` else lt_cv_sys_max_cmd_len=32768 fi ;; *) lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` if test -n "$lt_cv_sys_max_cmd_len"; then lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` else # Make teststring a little bigger before we do anything with it. # a 1K string should be a reasonable start. for i in 1 2 3 4 5 6 7 8 ; do teststring=$teststring$teststring done SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} # If test is not a shell built-in, we'll probably end up computing a # maximum length that is only half of the actual maximum length, but # we can't tell. while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \ = "X$teststring$teststring"; } >/dev/null 2>&1 && test $i != 17 # 1/2 MB should be enough do i=`expr $i + 1` teststring=$teststring$teststring done # Only check the string length outside the loop. lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` teststring= # Add a significant safety factor because C++ compilers can tack on # massive amounts of additional arguments before passing them to the # linker. It appears as though 1/2 is a usable value. lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` fi ;; esac ]) if test -n $lt_cv_sys_max_cmd_len ; then AC_MSG_RESULT($lt_cv_sys_max_cmd_len) else AC_MSG_RESULT(none) fi max_cmd_len=$lt_cv_sys_max_cmd_len _LT_DECL([], [max_cmd_len], [0], [What is the maximum length of a command?]) ])# LT_CMD_MAX_LEN # Old name: AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], []) # _LT_HEADER_DLFCN # ---------------- m4_defun([_LT_HEADER_DLFCN], [AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl ])# _LT_HEADER_DLFCN # _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE, # ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING) # ---------------------------------------------------------------- m4_defun([_LT_TRY_DLOPEN_SELF], [m4_require([_LT_HEADER_DLFCN])dnl if test "$cross_compiling" = yes; then : [$4] else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF [#line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisbility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; }] _LT_EOF if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) $1 ;; x$lt_dlneed_uscore) $2 ;; x$lt_dlunknown|x*) $3 ;; esac else : # compilation failed $3 fi fi rm -fr conftest* ])# _LT_TRY_DLOPEN_SELF # LT_SYS_DLOPEN_SELF # ------------------ AC_DEFUN([LT_SYS_DLOPEN_SELF], [m4_require([_LT_HEADER_DLFCN])dnl if test "x$enable_dlopen" != xyes; then enable_dlopen=unknown enable_dlopen_self=unknown enable_dlopen_self_static=unknown else lt_cv_dlopen=no lt_cv_dlopen_libs= case $host_os in beos*) lt_cv_dlopen="load_add_on" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ;; mingw* | pw32* | cegcc*) lt_cv_dlopen="LoadLibrary" lt_cv_dlopen_libs= ;; cygwin*) lt_cv_dlopen="dlopen" lt_cv_dlopen_libs= ;; darwin*) # if libdl is installed we need to link against it AC_CHECK_LIB([dl], [dlopen], [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[ lt_cv_dlopen="dyld" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ]) ;; *) AC_CHECK_FUNC([shl_load], [lt_cv_dlopen="shl_load"], [AC_CHECK_LIB([dld], [shl_load], [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"], [AC_CHECK_FUNC([dlopen], [lt_cv_dlopen="dlopen"], [AC_CHECK_LIB([dl], [dlopen], [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"], [AC_CHECK_LIB([svld], [dlopen], [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"], [AC_CHECK_LIB([dld], [dld_link], [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"]) ]) ]) ]) ]) ]) ;; esac if test "x$lt_cv_dlopen" != xno; then enable_dlopen=yes else enable_dlopen=no fi case $lt_cv_dlopen in dlopen) save_CPPFLAGS="$CPPFLAGS" test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" save_LDFLAGS="$LDFLAGS" wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" save_LIBS="$LIBS" LIBS="$lt_cv_dlopen_libs $LIBS" AC_CACHE_CHECK([whether a program can dlopen itself], lt_cv_dlopen_self, [dnl _LT_TRY_DLOPEN_SELF( lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes, lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross) ]) if test "x$lt_cv_dlopen_self" = xyes; then wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" AC_CACHE_CHECK([whether a statically linked program can dlopen itself], lt_cv_dlopen_self_static, [dnl _LT_TRY_DLOPEN_SELF( lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=no, lt_cv_dlopen_self_static=cross) ]) fi CPPFLAGS="$save_CPPFLAGS" LDFLAGS="$save_LDFLAGS" LIBS="$save_LIBS" ;; esac case $lt_cv_dlopen_self in yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; *) enable_dlopen_self=unknown ;; esac case $lt_cv_dlopen_self_static in yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; *) enable_dlopen_self_static=unknown ;; esac fi _LT_DECL([dlopen_support], [enable_dlopen], [0], [Whether dlopen is supported]) _LT_DECL([dlopen_self], [enable_dlopen_self], [0], [Whether dlopen of programs is supported]) _LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0], [Whether dlopen of statically linked programs is supported]) ])# LT_SYS_DLOPEN_SELF # Old name: AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], []) # _LT_COMPILER_C_O([TAGNAME]) # --------------------------- # Check to see if options -c and -o are simultaneously supported by compiler. # This macro does not hard code the compiler like AC_PROG_CC_C_O. m4_defun([_LT_COMPILER_C_O], [m4_require([_LT_DECL_SED])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_TAG_COMPILER])dnl AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext], [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)], [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&AS_MESSAGE_LOG_FD echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes fi fi chmod u+w . 2>&AS_MESSAGE_LOG_FD $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* ]) _LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1], [Does compiler simultaneously support -c and -o options?]) ])# _LT_COMPILER_C_O # _LT_COMPILER_FILE_LOCKS([TAGNAME]) # ---------------------------------- # Check to see if we can do hard links to lock some files if needed m4_defun([_LT_COMPILER_FILE_LOCKS], [m4_require([_LT_ENABLE_LOCK])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl _LT_COMPILER_C_O([$1]) hard_links="nottested" if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then # do not overwrite the value of need_locks provided by the user AC_MSG_CHECKING([if we can lock with hard links]) hard_links=yes $RM conftest* ln conftest.a conftest.b 2>/dev/null && hard_links=no touch conftest.a ln conftest.a conftest.b 2>&5 || hard_links=no ln conftest.a conftest.b 2>/dev/null && hard_links=no AC_MSG_RESULT([$hard_links]) if test "$hard_links" = no; then AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe]) need_locks=warn fi else need_locks=no fi _LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?]) ])# _LT_COMPILER_FILE_LOCKS # _LT_CHECK_OBJDIR # ---------------- m4_defun([_LT_CHECK_OBJDIR], [AC_CACHE_CHECK([for objdir], [lt_cv_objdir], [rm -f .libs 2>/dev/null mkdir .libs 2>/dev/null if test -d .libs; then lt_cv_objdir=.libs else # MS-DOS does not allow filenames that begin with a dot. lt_cv_objdir=_libs fi rmdir .libs 2>/dev/null]) objdir=$lt_cv_objdir _LT_DECL([], [objdir], [0], [The name of the directory that contains temporary libtool files])dnl m4_pattern_allow([LT_OBJDIR])dnl AC_DEFINE_UNQUOTED(LT_OBJDIR, "$lt_cv_objdir/", [Define to the sub-directory in which libtool stores uninstalled libraries.]) ])# _LT_CHECK_OBJDIR # _LT_LINKER_HARDCODE_LIBPATH([TAGNAME]) # -------------------------------------- # Check hardcoding attributes. m4_defun([_LT_LINKER_HARDCODE_LIBPATH], [AC_MSG_CHECKING([how to hardcode library paths into programs]) _LT_TAGVAR(hardcode_action, $1)= if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" || test -n "$_LT_TAGVAR(runpath_var, $1)" || test "X$_LT_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then # We can hardcode non-existent directories. if test "$_LT_TAGVAR(hardcode_direct, $1)" != no && # If the only mechanism to avoid hardcoding is shlibpath_var, we # have to relink, otherwise we might link with an installed library # when we should be linking with a yet-to-be-installed one ## test "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" != no && test "$_LT_TAGVAR(hardcode_minus_L, $1)" != no; then # Linking always hardcodes the temporary library directory. _LT_TAGVAR(hardcode_action, $1)=relink else # We can link without hardcoding, and we can hardcode nonexisting dirs. _LT_TAGVAR(hardcode_action, $1)=immediate fi else # We cannot hardcode anything, or else we can only hardcode existing # directories. _LT_TAGVAR(hardcode_action, $1)=unsupported fi AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)]) if test "$_LT_TAGVAR(hardcode_action, $1)" = relink || test "$_LT_TAGVAR(inherit_rpath, $1)" = yes; then # Fast installation is not supported enable_fast_install=no elif test "$shlibpath_overrides_runpath" = yes || test "$enable_shared" = no; then # Fast installation is not necessary enable_fast_install=needless fi _LT_TAGDECL([], [hardcode_action], [0], [How to hardcode a shared library path into an executable]) ])# _LT_LINKER_HARDCODE_LIBPATH # _LT_CMD_STRIPLIB # ---------------- m4_defun([_LT_CMD_STRIPLIB], [m4_require([_LT_DECL_EGREP]) striplib= old_striplib= AC_MSG_CHECKING([whether stripping libraries is possible]) if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" test -z "$striplib" && striplib="$STRIP --strip-unneeded" AC_MSG_RESULT([yes]) else # FIXME - insert some real tests, host_os isn't really good enough case $host_os in darwin*) if test -n "$STRIP" ; then striplib="$STRIP -x" old_striplib="$STRIP -S" AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) fi ;; *) AC_MSG_RESULT([no]) ;; esac fi _LT_DECL([], [old_striplib], [1], [Commands to strip libraries]) _LT_DECL([], [striplib], [1]) ])# _LT_CMD_STRIPLIB # _LT_SYS_DYNAMIC_LINKER([TAG]) # ----------------------------- # PORTME Fill in your ld.so characteristics m4_defun([_LT_SYS_DYNAMIC_LINKER], [AC_REQUIRE([AC_CANONICAL_HOST])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_OBJDUMP])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_CHECK_SHELL_FEATURES])dnl AC_MSG_CHECKING([dynamic linker characteristics]) m4_if([$1], [], [ if test "$GCC" = yes; then case $host_os in darwin*) lt_awk_arg="/^libraries:/,/LR/" ;; *) lt_awk_arg="/^libraries:/" ;; esac case $host_os in mingw* | cegcc*) lt_sed_strip_eq="s,=\([[A-Za-z]]:\),\1,g" ;; *) lt_sed_strip_eq="s,=/,/,g" ;; esac lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` case $lt_search_path_spec in *\;*) # if the path contains ";" then we assume it to be the separator # otherwise default to the standard path separator (i.e. ":") - it is # assumed that no part of a normal pathname contains ";" but that should # okay in the real world where ";" in dirpaths is itself problematic. lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'` ;; *) lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"` ;; esac # Ok, now we have the path, separated by spaces, we can step through it # and add multilib dir if necessary. lt_tmp_lt_search_path_spec= lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` for lt_sys_path in $lt_search_path_spec; do if test -d "$lt_sys_path/$lt_multi_os_dir"; then lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir" else test -d "$lt_sys_path" && \ lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" fi done lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk ' BEGIN {RS=" "; FS="/|\n";} { lt_foo=""; lt_count=0; for (lt_i = NF; lt_i > 0; lt_i--) { if ($lt_i != "" && $lt_i != ".") { if ($lt_i == "..") { lt_count++; } else { if (lt_count == 0) { lt_foo="/" $lt_i lt_foo; } else { lt_count--; } } } } if (lt_foo != "") { lt_freq[[lt_foo]]++; } if (lt_freq[[lt_foo]] == 1) { print lt_foo; } }'` # AWK program above erroneously prepends '/' to C:/dos/paths # for these hosts. case $host_os in mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ $SED 's,/\([[A-Za-z]]:\),\1,g'` ;; esac sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` else sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" fi]) library_names_spec= libname_spec='lib$name' soname_spec= shrext_cmds=".so" postinstall_cmds= postuninstall_cmds= finish_cmds= finish_eval= shlibpath_var= shlibpath_overrides_runpath=unknown version_type=none dynamic_linker="$host_os ld.so" sys_lib_dlsearch_path_spec="/lib /usr/lib" need_lib_prefix=unknown hardcode_into_libs=no # when you set need_version to no, make sure it does not cause -set_version # flags to be left without arguments need_version=unknown case $host_os in aix3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' shlibpath_var=LIBPATH # AIX 3 has no versioning support, so we append a major version to the name. soname_spec='${libname}${release}${shared_ext}$major' ;; aix[[4-9]]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no hardcode_into_libs=yes if test "$host_cpu" = ia64; then # AIX 5 supports IA64 library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH else # With GCC up to 2.95.x, collect2 would create an import file # for dependence libraries. The import file would start with # the line `#! .'. This would cause the generated library to # depend on `.', always an invalid library. This was fixed in # development snapshots of GCC prior to 3.0. case $host_os in aix4 | aix4.[[01]] | aix4.[[01]].*) if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' echo ' yes ' echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then : else can_build_shared=no fi ;; esac # AIX (on Power*) has no versioning support, so currently we can not hardcode correct # soname into executable. Probably we can add versioning support to # collect2, so additional links can be useful in future. if test "$aix_use_runtimelinking" = yes; then # If using run time linking (on AIX 4.2 or later) use lib.so # instead of lib.a to let people know that these are not # typical AIX shared libraries. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' else # We preserve .a as extension for shared libraries through AIX4.2 # and later when we are not doing run time linking. library_names_spec='${libname}${release}.a $libname.a' soname_spec='${libname}${release}${shared_ext}$major' fi shlibpath_var=LIBPATH fi ;; amigaos*) case $host_cpu in powerpc) # Since July 2007 AmigaOS4 officially supports .so libraries. # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' ;; m68k) library_names_spec='$libname.ixlibrary $libname.a' # Create ${libname}_ixlibrary.a entries in /sys/libs. finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' ;; esac ;; beos*) library_names_spec='${libname}${shared_ext}' dynamic_linker="$host_os ld.so" shlibpath_var=LIBRARY_PATH ;; bsdi[[45]]*) version_type=linux # correct to gnu/linux during the next big refactor need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" # the default ld.so.conf also contains /usr/contrib/lib and # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow # libtool to hard-code these into programs ;; cygwin* | mingw* | pw32* | cegcc*) version_type=windows shrext_cmds=".dll" need_version=no need_lib_prefix=no case $GCC,$cc_basename in yes,*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes case $host_os in cygwin*) # Cygwin DLLs use 'cyg' prefix rather than 'lib' soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' m4_if([$1], [],[ sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"]) ;; mingw* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' ;; pw32*) # pw32 DLLs use 'pw' prefix rather than 'lib' library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' ;; esac dynamic_linker='Win32 ld.exe' ;; *,cl*) # Native MSVC libname_spec='$name' soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' library_names_spec='${libname}.dll.lib' case $build_os in mingw*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' for lt_path in $LIB do IFS=$lt_save_ifs # Let DOS variable expansion print the short 8.3 style file name. lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" done IFS=$lt_save_ifs # Convert to MSYS style. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([[a-zA-Z]]\\):| /\\1|g' -e 's|^ ||'` ;; cygwin*) # Convert to unix form, then to dos form, then back to unix form # but this time dos style (no spaces!) so that the unix form looks # like /cygdrive/c/PROGRA~1:/cygdr... sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` ;; *) sys_lib_search_path_spec="$LIB" if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then # It is most probably a Windows format PATH. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` else sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` fi # FIXME: find the short name or the path components, as spaces are # common. (e.g. "Program Files" -> "PROGRA~1") ;; esac # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes dynamic_linker='Win32 link.exe' ;; *) # Assume MSVC wrapper library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib' dynamic_linker='Win32 ld.exe' ;; esac # FIXME: first we should search . and the directory the executable is in shlibpath_var=PATH ;; darwin* | rhapsody*) dynamic_linker="$host_os dyld" version_type=darwin need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' soname_spec='${libname}${release}${major}$shared_ext' shlibpath_overrides_runpath=yes shlibpath_var=DYLD_LIBRARY_PATH shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' m4_if([$1], [],[ sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"]) sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' ;; dgux*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; freebsd* | dragonfly*) # DragonFly does not have aout. When/if they implement a new # versioning mechanism, adjust this. if test -x /usr/bin/objformat; then objformat=`/usr/bin/objformat` else case $host_os in freebsd[[23]].*) objformat=aout ;; *) objformat=elf ;; esac fi version_type=freebsd-$objformat case $version_type in freebsd-elf*) library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' need_version=no need_lib_prefix=no ;; freebsd-*) library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' need_version=yes ;; esac shlibpath_var=LD_LIBRARY_PATH case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes ;; freebsd3.[[01]]* | freebsdelf3.[[01]]*) shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \ freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1) shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; *) # from 4.6 on, and DragonFly shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; esac ;; haiku*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no dynamic_linker="$host_os runtime_loader" library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=yes sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' hardcode_into_libs=yes ;; hpux9* | hpux10* | hpux11*) # Give a soname corresponding to the major version so that dld.sl refuses to # link against other versions. version_type=sunos need_lib_prefix=no need_version=no case $host_cpu in ia64*) shrext_cmds='.so' hardcode_into_libs=yes dynamic_linker="$host_os dld.so" shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' if test "X$HPUX_IA64_MODE" = X32; then sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" else sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" fi sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; hppa*64*) shrext_cmds='.sl' hardcode_into_libs=yes dynamic_linker="$host_os dld.sl" shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; *) shrext_cmds='.sl' dynamic_linker="$host_os dld.sl" shlibpath_var=SHLIB_PATH shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' ;; esac # HP-UX runs *really* slowly unless shared libraries are mode 555, ... postinstall_cmds='chmod 555 $lib' # or fails outright, so override atomically: install_override_mode=555 ;; interix[[3-9]]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; irix5* | irix6* | nonstopux*) case $host_os in nonstopux*) version_type=nonstopux ;; *) if test "$lt_cv_prog_gnu_ld" = yes; then version_type=linux # correct to gnu/linux during the next big refactor else version_type=irix fi ;; esac need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' case $host_os in irix5* | nonstopux*) libsuff= shlibsuff= ;; *) case $LD in # libtool.m4 will add one of these switches to LD *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= libmagic=32-bit;; *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 libmagic=N32;; *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 libmagic=64-bit;; *) libsuff= shlibsuff= libmagic=never-match;; esac ;; esac shlibpath_var=LD_LIBRARY${shlibsuff}_PATH shlibpath_overrides_runpath=no sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" hardcode_into_libs=yes ;; # No shared lib support for Linux oldld, aout, or coff. linux*oldld* | linux*aout* | linux*coff*) dynamic_linker=no ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no # Some binutils ld are patched to set DT_RUNPATH AC_CACHE_VAL([lt_cv_shlibpath_overrides_runpath], [lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \ LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\"" AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null], [lt_cv_shlibpath_overrides_runpath=yes])]) LDFLAGS=$save_LDFLAGS libdir=$save_libdir ]) shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on # powerpc, because MkLinux only supported shared libraries with the # GNU dynamic linker. Since this was broken with cross compilers, # most powerpc-linux boxes support dynamic linking these days and # people can always --disable-shared, the test was removed, and we # assume the GNU/Linux dynamic linker is in use. dynamic_linker='GNU/Linux ld.so' ;; netbsdelf*-gnu) version_type=linux need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='NetBSD ld.elf_so' ;; netbsd*) version_type=sunos need_lib_prefix=no need_version=no if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' dynamic_linker='NetBSD (a.out) ld.so' else library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='NetBSD ld.elf_so' fi shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; *nto* | *qnx*) version_type=qnx need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='ldqnx.so' ;; openbsd*) version_type=sunos sys_lib_dlsearch_path_spec="/usr/lib" need_lib_prefix=no # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. case $host_os in openbsd3.3 | openbsd3.3.*) need_version=yes ;; *) need_version=no ;; esac library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' shlibpath_var=LD_LIBRARY_PATH if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then case $host_os in openbsd2.[[89]] | openbsd2.[[89]].*) shlibpath_overrides_runpath=no ;; *) shlibpath_overrides_runpath=yes ;; esac else shlibpath_overrides_runpath=yes fi ;; os2*) libname_spec='$name' shrext_cmds=".dll" need_lib_prefix=no library_names_spec='$libname${shared_ext} $libname.a' dynamic_linker='OS/2 ld.exe' shlibpath_var=LIBPATH ;; osf3* | osf4* | osf5*) version_type=osf need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" ;; rdos*) dynamic_linker=no ;; solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes # ldd complains unless libraries are executable postinstall_cmds='chmod +x $lib' ;; sunos4*) version_type=sunos library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes if test "$with_gnu_ld" = yes; then need_lib_prefix=no fi need_version=yes ;; sysv4 | sysv4.3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH case $host_vendor in sni) shlibpath_overrides_runpath=no need_lib_prefix=no runpath_var=LD_RUN_PATH ;; siemens) need_lib_prefix=no ;; motorola) need_lib_prefix=no need_version=no shlibpath_overrides_runpath=no sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' ;; esac ;; sysv4*MP*) if test -d /usr/nec ;then version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' soname_spec='$libname${shared_ext}.$major' shlibpath_var=LD_LIBRARY_PATH fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) version_type=freebsd-elf need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes if test "$with_gnu_ld" = yes; then sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' else sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' case $host_os in sco3.2v5*) sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" ;; esac fi sys_lib_dlsearch_path_spec='/usr/lib' ;; tpf*) # TPF is a cross-target only. Preferred cross-host = GNU/Linux. version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; uts4*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; *) dynamic_linker=no ;; esac AC_MSG_RESULT([$dynamic_linker]) test "$dynamic_linker" = no && can_build_shared=no variables_saved_for_relink="PATH $shlibpath_var $runpath_var" if test "$GCC" = yes; then variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" fi if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" fi if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" fi _LT_DECL([], [variables_saved_for_relink], [1], [Variables whose values should be saved in libtool wrapper scripts and restored at link time]) _LT_DECL([], [need_lib_prefix], [0], [Do we need the "lib" prefix for modules?]) _LT_DECL([], [need_version], [0], [Do we need a version for libraries?]) _LT_DECL([], [version_type], [0], [Library versioning type]) _LT_DECL([], [runpath_var], [0], [Shared library runtime path variable]) _LT_DECL([], [shlibpath_var], [0],[Shared library path variable]) _LT_DECL([], [shlibpath_overrides_runpath], [0], [Is shlibpath searched before the hard-coded library search path?]) _LT_DECL([], [libname_spec], [1], [Format of library name prefix]) _LT_DECL([], [library_names_spec], [1], [[List of archive names. First name is the real one, the rest are links. The last name is the one that the linker finds with -lNAME]]) _LT_DECL([], [soname_spec], [1], [[The coded name of the library, if different from the real name]]) _LT_DECL([], [install_override_mode], [1], [Permission mode override for installation of shared libraries]) _LT_DECL([], [postinstall_cmds], [2], [Command to use after installation of a shared archive]) _LT_DECL([], [postuninstall_cmds], [2], [Command to use after uninstallation of a shared archive]) _LT_DECL([], [finish_cmds], [2], [Commands used to finish a libtool library installation in a directory]) _LT_DECL([], [finish_eval], [1], [[As "finish_cmds", except a single script fragment to be evaled but not shown]]) _LT_DECL([], [hardcode_into_libs], [0], [Whether we should hardcode library paths into libraries]) _LT_DECL([], [sys_lib_search_path_spec], [2], [Compile-time system search path for libraries]) _LT_DECL([], [sys_lib_dlsearch_path_spec], [2], [Run-time system search path for libraries]) ])# _LT_SYS_DYNAMIC_LINKER # _LT_PATH_TOOL_PREFIX(TOOL) # -------------------------- # find a file program which can recognize shared library AC_DEFUN([_LT_PATH_TOOL_PREFIX], [m4_require([_LT_DECL_EGREP])dnl AC_MSG_CHECKING([for $1]) AC_CACHE_VAL(lt_cv_path_MAGIC_CMD, [case $MAGIC_CMD in [[\\/*] | ?:[\\/]*]) lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD="$MAGIC_CMD" lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR dnl $ac_dummy forces splitting on constant user-supplied paths. dnl POSIX.2 word splitting is done only on the output of word expansions, dnl not every word. This closes a longstanding sh security hole. ac_dummy="m4_if([$2], , $PATH, [$2])" for ac_dir in $ac_dummy; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f $ac_dir/$1; then lt_cv_path_MAGIC_CMD="$ac_dir/$1" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS="$lt_save_ifs" MAGIC_CMD="$lt_save_MAGIC_CMD" ;; esac]) MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if test -n "$MAGIC_CMD"; then AC_MSG_RESULT($MAGIC_CMD) else AC_MSG_RESULT(no) fi _LT_DECL([], [MAGIC_CMD], [0], [Used to examine libraries when file_magic_cmd begins with "file"])dnl ])# _LT_PATH_TOOL_PREFIX # Old name: AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], []) # _LT_PATH_MAGIC # -------------- # find a file program which can recognize a shared library m4_defun([_LT_PATH_MAGIC], [_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH) if test -z "$lt_cv_path_MAGIC_CMD"; then if test -n "$ac_tool_prefix"; then _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH) else MAGIC_CMD=: fi fi ])# _LT_PATH_MAGIC # LT_PATH_LD # ---------- # find the pathname to the GNU or non-GNU linker AC_DEFUN([LT_PATH_LD], [AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_PROG_ECHO_BACKSLASH])dnl AC_ARG_WITH([gnu-ld], [AS_HELP_STRING([--with-gnu-ld], [assume the C compiler uses GNU ld @<:@default=no@:>@])], [test "$withval" = no || with_gnu_ld=yes], [with_gnu_ld=no])dnl ac_prog=ld if test "$GCC" = yes; then # Check if gcc -print-prog-name=ld gives a path. AC_MSG_CHECKING([for ld used by $CC]) case $host in *-*-mingw*) # gcc leaves a trailing carriage return which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [[\\/]]* | ?:[[\\/]]*) re_direlt='/[[^/]][[^/]]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD="$ac_prog" ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test "$with_gnu_ld" = yes; then AC_MSG_CHECKING([for GNU ld]) else AC_MSG_CHECKING([for non-GNU ld]) fi AC_CACHE_VAL(lt_cv_path_LD, [if test -z "$LD"; then lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD="$ac_dir/$ac_prog" # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &1 /dev/null 2>&1; then lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' else # Keep this pattern in sync with the one in func_win32_libid. lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' lt_cv_file_magic_cmd='$OBJDUMP -f' fi ;; cegcc*) # use the weaker test based on 'objdump'. See mingw*. lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' lt_cv_file_magic_cmd='$OBJDUMP -f' ;; darwin* | rhapsody*) lt_cv_deplibs_check_method=pass_all ;; freebsd* | dragonfly*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then case $host_cpu in i*86 ) # Not sure whether the presence of OpenBSD here was a mistake. # Let's accept both of them until this is cleared up. lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` ;; esac else lt_cv_deplibs_check_method=pass_all fi ;; haiku*) lt_cv_deplibs_check_method=pass_all ;; hpux10.20* | hpux11*) lt_cv_file_magic_cmd=/usr/bin/file case $host_cpu in ia64*) lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64' lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so ;; hppa*64*) [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]'] lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl ;; *) lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]]\.[[0-9]]) shared library' lt_cv_file_magic_test_file=/usr/lib/libc.sl ;; esac ;; interix[[3-9]]*) # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$' ;; irix5* | irix6* | nonstopux*) case $LD in *-32|*"-32 ") libmagic=32-bit;; *-n32|*"-n32 ") libmagic=N32;; *-64|*"-64 ") libmagic=64-bit;; *) libmagic=never-match;; esac lt_cv_deplibs_check_method=pass_all ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) lt_cv_deplibs_check_method=pass_all ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$' fi ;; newos6*) lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=/usr/lib/libnls.so ;; *nto* | *qnx*) lt_cv_deplibs_check_method=pass_all ;; openbsd*) if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' fi ;; osf3* | osf4* | osf5*) lt_cv_deplibs_check_method=pass_all ;; rdos*) lt_cv_deplibs_check_method=pass_all ;; solaris*) lt_cv_deplibs_check_method=pass_all ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) lt_cv_deplibs_check_method=pass_all ;; sysv4 | sysv4.3*) case $host_vendor in motorola) lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]' lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` ;; ncr) lt_cv_deplibs_check_method=pass_all ;; sequent) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )' ;; sni) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib" lt_cv_file_magic_test_file=/lib/libc.so ;; siemens) lt_cv_deplibs_check_method=pass_all ;; pc) lt_cv_deplibs_check_method=pass_all ;; esac ;; tpf*) lt_cv_deplibs_check_method=pass_all ;; esac ]) file_magic_glob= want_nocaseglob=no if test "$build" = "$host"; then case $host_os in mingw* | pw32*) if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then want_nocaseglob=yes else file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[[\1]]\/[[\1]]\/g;/g"` fi ;; esac fi file_magic_cmd=$lt_cv_file_magic_cmd deplibs_check_method=$lt_cv_deplibs_check_method test -z "$deplibs_check_method" && deplibs_check_method=unknown _LT_DECL([], [deplibs_check_method], [1], [Method to check whether dependent libraries are shared objects]) _LT_DECL([], [file_magic_cmd], [1], [Command to use when deplibs_check_method = "file_magic"]) _LT_DECL([], [file_magic_glob], [1], [How to find potential files when deplibs_check_method = "file_magic"]) _LT_DECL([], [want_nocaseglob], [1], [Find potential files using nocaseglob when deplibs_check_method = "file_magic"]) ])# _LT_CHECK_MAGIC_METHOD # LT_PATH_NM # ---------- # find the pathname to a BSD- or MS-compatible name lister AC_DEFUN([LT_PATH_NM], [AC_REQUIRE([AC_PROG_CC])dnl AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM, [if test -n "$NM"; then # Let the user override the test. lt_cv_path_NM="$NM" else lt_nm_to_check="${ac_tool_prefix}nm" if test -n "$ac_tool_prefix" && test "$build" = "$host"; then lt_nm_to_check="$lt_nm_to_check nm" fi for lt_tmp_nm in $lt_nm_to_check; do lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. tmp_nm="$ac_dir/$lt_tmp_nm" if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then # Check to see if the nm accepts a BSD-compat flag. # Adding the `sed 1q' prevents false positives on HP-UX, which says: # nm: unknown option "B" ignored # Tru64's nm complains that /dev/null is an invalid object file case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in */dev/null* | *'Invalid file or object type'*) lt_cv_path_NM="$tmp_nm -B" break ;; *) case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in */dev/null*) lt_cv_path_NM="$tmp_nm -p" break ;; *) lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but continue # so that we can try to find one that supports BSD flags ;; esac ;; esac fi done IFS="$lt_save_ifs" done : ${lt_cv_path_NM=no} fi]) if test "$lt_cv_path_NM" != "no"; then NM="$lt_cv_path_NM" else # Didn't find any BSD compatible name lister, look for dumpbin. if test -n "$DUMPBIN"; then : # Let the user override the test. else AC_CHECK_TOOLS(DUMPBIN, [dumpbin "link -dump"], :) case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in *COFF*) DUMPBIN="$DUMPBIN -symbols" ;; *) DUMPBIN=: ;; esac fi AC_SUBST([DUMPBIN]) if test "$DUMPBIN" != ":"; then NM="$DUMPBIN" fi fi test -z "$NM" && NM=nm AC_SUBST([NM]) _LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface], [lt_cv_nm_interface="BSD nm" echo "int some_variable = 0;" > conftest.$ac_ext (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$ac_compile" 2>conftest.err) cat conftest.err >&AS_MESSAGE_LOG_FD (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD) (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) cat conftest.err >&AS_MESSAGE_LOG_FD (eval echo "\"\$as_me:$LINENO: output\"" >&AS_MESSAGE_LOG_FD) cat conftest.out >&AS_MESSAGE_LOG_FD if $GREP 'External.*some_variable' conftest.out > /dev/null; then lt_cv_nm_interface="MS dumpbin" fi rm -f conftest*]) ])# LT_PATH_NM # Old names: AU_ALIAS([AM_PROG_NM], [LT_PATH_NM]) AU_ALIAS([AC_PROG_NM], [LT_PATH_NM]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_PROG_NM], []) dnl AC_DEFUN([AC_PROG_NM], []) # _LT_CHECK_SHAREDLIB_FROM_LINKLIB # -------------------------------- # how to determine the name of the shared library # associated with a specific link library. # -- PORTME fill in with the dynamic library characteristics m4_defun([_LT_CHECK_SHAREDLIB_FROM_LINKLIB], [m4_require([_LT_DECL_EGREP]) m4_require([_LT_DECL_OBJDUMP]) m4_require([_LT_DECL_DLLTOOL]) AC_CACHE_CHECK([how to associate runtime and link libraries], lt_cv_sharedlib_from_linklib_cmd, [lt_cv_sharedlib_from_linklib_cmd='unknown' case $host_os in cygwin* | mingw* | pw32* | cegcc*) # two different shell functions defined in ltmain.sh # decide which to use based on capabilities of $DLLTOOL case `$DLLTOOL --help 2>&1` in *--identify-strict*) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib ;; *) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback ;; esac ;; *) # fallback: assume linklib IS sharedlib lt_cv_sharedlib_from_linklib_cmd="$ECHO" ;; esac ]) sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO _LT_DECL([], [sharedlib_from_linklib_cmd], [1], [Command to associate shared and link libraries]) ])# _LT_CHECK_SHAREDLIB_FROM_LINKLIB # _LT_PATH_MANIFEST_TOOL # ---------------------- # locate the manifest tool m4_defun([_LT_PATH_MANIFEST_TOOL], [AC_CHECK_TOOL(MANIFEST_TOOL, mt, :) test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt AC_CACHE_CHECK([if $MANIFEST_TOOL is a manifest tool], [lt_cv_path_mainfest_tool], [lt_cv_path_mainfest_tool=no echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&AS_MESSAGE_LOG_FD $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out cat conftest.err >&AS_MESSAGE_LOG_FD if $GREP 'Manifest Tool' conftest.out > /dev/null; then lt_cv_path_mainfest_tool=yes fi rm -f conftest*]) if test "x$lt_cv_path_mainfest_tool" != xyes; then MANIFEST_TOOL=: fi _LT_DECL([], [MANIFEST_TOOL], [1], [Manifest tool])dnl ])# _LT_PATH_MANIFEST_TOOL # LT_LIB_M # -------- # check for math library AC_DEFUN([LT_LIB_M], [AC_REQUIRE([AC_CANONICAL_HOST])dnl LIBM= case $host in *-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-pw32* | *-*-darwin*) # These system don't have libm, or don't need it ;; *-ncr-sysv4.3*) AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw") AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm") ;; *) AC_CHECK_LIB(m, cos, LIBM="-lm") ;; esac AC_SUBST([LIBM]) ])# LT_LIB_M # Old name: AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_CHECK_LIBM], []) # _LT_COMPILER_NO_RTTI([TAGNAME]) # ------------------------------- m4_defun([_LT_COMPILER_NO_RTTI], [m4_require([_LT_TAG_COMPILER])dnl _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= if test "$GCC" = yes; then case $cc_basename in nvcc*) _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -Xcompiler -fno-builtin' ;; *) _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' ;; esac _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions], lt_cv_prog_compiler_rtti_exceptions, [-fno-rtti -fno-exceptions], [], [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"]) fi _LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1], [Compiler flag to turn off builtin functions]) ])# _LT_COMPILER_NO_RTTI # _LT_CMD_GLOBAL_SYMBOLS # ---------------------- m4_defun([_LT_CMD_GLOBAL_SYMBOLS], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([LT_PATH_NM])dnl AC_REQUIRE([LT_PATH_LD])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_TAG_COMPILER])dnl # Check for command to grab the raw symbol name followed by C symbol from nm. AC_MSG_CHECKING([command to parse $NM output from $compiler object]) AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe], [ # These are sane defaults that work on at least a few old systems. # [They come from Ultrix. What could be older than Ultrix?!! ;)] # Character class describing NM global symbol codes. symcode='[[BCDEGRST]]' # Regexp to match symbols that can be accessed directly from C. sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)' # Define system-specific variables. case $host_os in aix*) symcode='[[BCDT]]' ;; cygwin* | mingw* | pw32* | cegcc*) symcode='[[ABCDGISTW]]' ;; hpux*) if test "$host_cpu" = ia64; then symcode='[[ABCDEGRST]]' fi ;; irix* | nonstopux*) symcode='[[BCDEGRST]]' ;; osf*) symcode='[[BCDEGQRST]]' ;; solaris*) symcode='[[BDRT]]' ;; sco3.2v5*) symcode='[[DT]]' ;; sysv4.2uw2*) symcode='[[DT]]' ;; sysv5* | sco5v6* | unixware* | OpenUNIX*) symcode='[[ABDT]]' ;; sysv4) symcode='[[DFNSTU]]' ;; esac # If we're using GNU nm, then use its standard symbol codes. case `$NM -V 2>&1` in *GNU* | *'with BFD'*) symcode='[[ABCDGIRSTW]]' ;; esac # Transform an extracted symbol line into a proper C declaration. # Some systems (esp. on ia64) link data and code symbols differently, # so use this general approach. lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" # Transform an extracted symbol line into symbol name and symbol address lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (void *) \&\2},/p'" lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/ {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"lib\2\", (void *) \&\2},/p'" # Handle CRLF in mingw tool chain opt_cr= case $build_os in mingw*) opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp ;; esac # Try without a prefix underscore, then with it. for ac_symprfx in "" "_"; do # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. symxfrm="\\1 $ac_symprfx\\2 \\2" # Write the raw and C identifiers. if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Fake it for dumpbin and say T for any non-static function # and D for any global variable. # Also find C++ and __fastcall symbols from MSVC++, # which start with @ or ?. lt_cv_sys_global_symbol_pipe="$AWK ['"\ " {last_section=section; section=\$ 3};"\ " /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\ " /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ " \$ 0!~/External *\|/{next};"\ " / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ " {if(hide[section]) next};"\ " {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\ " {split(\$ 0, a, /\||\r/); split(a[2], s)};"\ " s[1]~/^[@?]/{print s[1], s[1]; next};"\ " s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\ " ' prfx=^$ac_symprfx]" else lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[ ]]\($symcode$symcode*\)[[ ]][[ ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" fi lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'" # Check to see that the pipe works correctly. pipe_works=no rm -f conftest* cat > conftest.$ac_ext <<_LT_EOF #ifdef __cplusplus extern "C" { #endif char nm_test_var; void nm_test_func(void); void nm_test_func(void){} #ifdef __cplusplus } #endif int main(){nm_test_var='a';nm_test_func();return(0);} _LT_EOF if AC_TRY_EVAL(ac_compile); then # Now try to grab the symbols. nlist=conftest.nm if AC_TRY_EVAL(NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) && test -s "$nlist"; then # Try sorting and uniquifying the output. if sort "$nlist" | uniq > "$nlist"T; then mv -f "$nlist"T "$nlist" else rm -f "$nlist"T fi # Make sure that we snagged all the symbols we need. if $GREP ' nm_test_var$' "$nlist" >/dev/null; then if $GREP ' nm_test_func$' "$nlist" >/dev/null; then cat <<_LT_EOF > conftest.$ac_ext /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) /* DATA imports from DLLs on WIN32 con't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT@&t@_DLSYM_CONST #elif defined(__osf__) /* This system does not cope well with relocations in const data. */ # define LT@&t@_DLSYM_CONST #else # define LT@&t@_DLSYM_CONST const #endif #ifdef __cplusplus extern "C" { #endif _LT_EOF # Now generate the symbol file. eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' cat <<_LT_EOF >> conftest.$ac_ext /* The mapping between symbol names and symbols. */ LT@&t@_DLSYM_CONST struct { const char *name; void *address; } lt__PROGRAM__LTX_preloaded_symbols[[]] = { { "@PROGRAM@", (void *) 0 }, _LT_EOF $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext cat <<\_LT_EOF >> conftest.$ac_ext {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt__PROGRAM__LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif _LT_EOF # Now try linking the two files. mv conftest.$ac_objext conftstm.$ac_objext lt_globsym_save_LIBS=$LIBS lt_globsym_save_CFLAGS=$CFLAGS LIBS="conftstm.$ac_objext" CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)" if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then pipe_works=yes fi LIBS=$lt_globsym_save_LIBS CFLAGS=$lt_globsym_save_CFLAGS else echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD fi else echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD fi else echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD fi else echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD cat conftest.$ac_ext >&5 fi rm -rf conftest* conftst* # Do not use the global_symbol_pipe unless it works. if test "$pipe_works" = yes; then break else lt_cv_sys_global_symbol_pipe= fi done ]) if test -z "$lt_cv_sys_global_symbol_pipe"; then lt_cv_sys_global_symbol_to_cdecl= fi if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then AC_MSG_RESULT(failed) else AC_MSG_RESULT(ok) fi # Response file support. if test "$lt_cv_nm_interface" = "MS dumpbin"; then nm_file_list_spec='@' elif $NM --help 2>/dev/null | grep '[[@]]FILE' >/dev/null; then nm_file_list_spec='@' fi _LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1], [Take the output of nm and produce a listing of raw symbols and C names]) _LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1], [Transform the output of nm in a proper C declaration]) _LT_DECL([global_symbol_to_c_name_address], [lt_cv_sys_global_symbol_to_c_name_address], [1], [Transform the output of nm in a C name address pair]) _LT_DECL([global_symbol_to_c_name_address_lib_prefix], [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1], [Transform the output of nm in a C name address pair when lib prefix is needed]) _LT_DECL([], [nm_file_list_spec], [1], [Specify filename containing input files for $NM]) ]) # _LT_CMD_GLOBAL_SYMBOLS # _LT_COMPILER_PIC([TAGNAME]) # --------------------------- m4_defun([_LT_COMPILER_PIC], [m4_require([_LT_TAG_COMPILER])dnl _LT_TAGVAR(lt_prog_compiler_wl, $1)= _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)= m4_if([$1], [CXX], [ # C++ specific cases for pic, static, wl, etc. if test "$GXX" = yes; then _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' case $host_os in aix*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the `-m68020' flag to GCC prevents building anything better, # like `-m68040'. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' ;; *djgpp*) # DJGPP does not support shared libraries at all _LT_TAGVAR(lt_prog_compiler_pic, $1)= ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. _LT_TAGVAR(lt_prog_compiler_static, $1)= ;; interix[[3-9]]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic fi ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac else case $host_os in aix[[4-9]]*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' else _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' fi ;; chorus*) case $cc_basename in cxch68*) # Green Hills C++ Compiler # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" ;; esac ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; dgux*) case $cc_basename in ec++*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' ;; ghcx*) # Green Hills C++ Compiler _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; *) ;; esac ;; freebsd* | dragonfly*) # FreeBSD uses GNU C++ ;; hpux9* | hpux10* | hpux11*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' if test "$host_cpu" != ia64; then _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' fi ;; aCC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' ;; esac ;; *) ;; esac ;; interix*) # This is c89, which is MS Visual C++ (no shared libs) # Anyone wants to do a port? ;; irix5* | irix6* | nonstopux*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' # CC pic flag -KPIC is the default. ;; *) ;; esac ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in KCC*) # KAI C++ Compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; ecpc* ) # old Intel C++ for x86_64 which still supported -KPIC. _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; icpc* ) # Intel C++, used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; pgCC* | pgcpp*) # Portland Group C++ compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; cxx*) # Compaq C++ # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; xlc* | xlC* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL 8.0, 9.0 on PPC and BlueGene _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; esac ;; esac ;; lynxos*) ;; m88k*) ;; mvs*) case $cc_basename in cxx*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall' ;; *) ;; esac ;; netbsd* | netbsdelf*-gnu) ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' ;; RCC*) # Rational C++ 2.4.1 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; cxx*) # Digital/Compaq C++ _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; *) ;; esac ;; psos*) ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; gcx*) # Green Hills C++ Compiler _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' ;; *) ;; esac ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; lcc*) # Lucid _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; *) ;; esac ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' ;; *) ;; esac ;; vxworks*) ;; *) _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; esac fi ], [ if test "$GCC" = yes; then _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' case $host_os in aix*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the `-m68020' flag to GCC prevents building anything better, # like `-m68040'. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. _LT_TAGVAR(lt_prog_compiler_static, $1)= ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac ;; interix[[3-9]]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; msdosdjgpp*) # Just because we use GCC doesn't mean we suddenly get shared libraries # on systems that don't support them. _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no enable_shared=no ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic fi ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac case $cc_basename in nvcc*) # Cuda Compiler Driver 2.2 _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Xlinker ' if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then _LT_TAGVAR(lt_prog_compiler_pic, $1)="-Xcompiler $_LT_TAGVAR(lt_prog_compiler_pic, $1)" fi ;; esac else # PORTME Check for flag to pass linker flags through the system compiler. case $host_os in aix*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' else _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' fi ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; hpux9* | hpux10* | hpux11*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but # not for PA HP-UX. case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' ;; esac # Is there a better lt_prog_compiler_static that works with the bundled CC? _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' ;; irix5* | irix6* | nonstopux*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # PIC (with -KPIC) is the default. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in # old Intel for x86_64 which still supported -KPIC. ecc*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; # icc used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. icc* | ifort*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; # Lahey Fortran 8.1. lf95*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared' _LT_TAGVAR(lt_prog_compiler_static, $1)='--static' ;; nagfor*) # NAG Fortran compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group compilers (*not* the Pentium gcc compiler, # which looks to be a dead project) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; ccc*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # All Alpha code is PIC. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; xl* | bgxl* | bgf* | mpixl*) # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [[1-7]].* | *Sun*Fortran*\ 8.[[0-3]]*) # Sun Fortran 8.3 passes all unrecognized flags to the linker _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='' ;; *Sun\ F* | *Sun*Fortran*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; *Sun\ C*) # Sun C 5.9 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' ;; *Intel*\ [[CF]]*Compiler*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; *Portland\ Group*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; esac ;; esac ;; newsos6) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; osf3* | osf4* | osf5*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # All OSF/1 code is PIC. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; rdos*) _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; solaris*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' case $cc_basename in f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';; *) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';; esac ;; sunos4*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; sysv4 | sysv4.2uw2* | sysv4.3*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; sysv4*MP*) if test -d /usr/nec ;then _LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; unicos*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; uts4*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; *) _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; esac fi ]) case $host_os in # For platforms which do not support PIC, -DPIC is meaningless: *djgpp*) _LT_TAGVAR(lt_prog_compiler_pic, $1)= ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])" ;; esac AC_CACHE_CHECK([for $compiler option to produce PIC], [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)], [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_prog_compiler_pic, $1)]) _LT_TAGVAR(lt_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_cv_prog_compiler_pic, $1) # # Check to make sure the PIC flag actually works. # if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works], [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)], [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [], [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in "" | " "*) ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;; esac], [_LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no]) fi _LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1], [Additional compiler flags for building library objects]) _LT_TAGDECL([wl], [lt_prog_compiler_wl], [1], [How to pass a linker flag through the compiler]) # # Check to make sure the static flag actually works. # wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\" _LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works], _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1), $lt_tmp_static_flag, [], [_LT_TAGVAR(lt_prog_compiler_static, $1)=]) _LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1], [Compiler flag to prevent dynamic linking]) ])# _LT_COMPILER_PIC # _LT_LINKER_SHLIBS([TAGNAME]) # ---------------------------- # See if the linker supports building shared libraries. m4_defun([_LT_LINKER_SHLIBS], [AC_REQUIRE([LT_PATH_LD])dnl AC_REQUIRE([LT_PATH_NM])dnl m4_require([_LT_PATH_MANIFEST_TOOL])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl m4_require([_LT_TAG_COMPILER])dnl AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) m4_if([$1], [CXX], [ _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] case $host_os in aix[[4-9]]*) # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to AIX nm, but means don't demangle with GNU nm # Also, AIX nm treats weak defined symbols like other global defined # symbols, whereas GNU nm marks them as "W". if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' else _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' fi ;; pw32*) _LT_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds" ;; cygwin* | mingw* | cegcc*) case $cc_basename in cl*) _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' ;; *) _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'] ;; esac ;; linux* | k*bsd*-gnu | gnu*) _LT_TAGVAR(link_all_deplibs, $1)=no ;; *) _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' ;; esac ], [ runpath_var= _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_cmds, $1)= _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(compiler_needs_object, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(old_archive_from_new_cmds, $1)= _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)= _LT_TAGVAR(thread_safe_flag_spec, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= # include_expsyms should be a list of space-separated symbols to be *always* # included in the symbol list _LT_TAGVAR(include_expsyms, $1)= # exclude_expsyms can be an extended regexp of symbols to exclude # it will be wrapped by ` (' and `)$', so one must not match beginning or # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', # as well as any symbol that contains `d'. _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out # platforms (ab)use it in PIC code, but their linkers get confused if # the symbol is explicitly referenced. Since portable code cannot # rely on this symbol name, it's probably fine to never include it in # preloaded symbol tables. # Exclude shared library initialization/finalization symbols. dnl Note also adjust exclude_expsyms for C++ above. extract_expsyms_cmds= case $host_os in cygwin* | mingw* | pw32* | cegcc*) # FIXME: the MSVC++ port hasn't been tested in a loooong time # When not using gcc, we currently assume that we are using # Microsoft Visual C++. if test "$GCC" != yes; then with_gnu_ld=no fi ;; interix*) # we just hope/assume this is gcc and not c89 (= MSVC++) with_gnu_ld=yes ;; openbsd*) with_gnu_ld=no ;; linux* | k*bsd*-gnu | gnu*) _LT_TAGVAR(link_all_deplibs, $1)=no ;; esac _LT_TAGVAR(ld_shlibs, $1)=yes # On some targets, GNU ld is compatible enough with the native linker # that we're better off using the native interface for both. lt_use_gnu_ld_interface=no if test "$with_gnu_ld" = yes; then case $host_os in aix*) # The AIX port of GNU ld has always aspired to compatibility # with the native linker. However, as the warning in the GNU ld # block says, versions before 2.19.5* couldn't really create working # shared libraries, regardless of the interface used. case `$LD -v 2>&1` in *\ \(GNU\ Binutils\)\ 2.19.5*) ;; *\ \(GNU\ Binutils\)\ 2.[[2-9]]*) ;; *\ \(GNU\ Binutils\)\ [[3-9]]*) ;; *) lt_use_gnu_ld_interface=yes ;; esac ;; *) lt_use_gnu_ld_interface=yes ;; esac fi if test "$lt_use_gnu_ld_interface" = yes; then # If archive_cmds runs LD, not CC, wlarc should be empty wlarc='${wl}' # Set some defaults for GNU ld with shared library support. These # are reset later if shared libraries are not supported. Putting them # here allows them to be overridden if necessary. runpath_var=LD_RUN_PATH _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' # ancient GNU ld didn't support --whole-archive et. al. if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' else _LT_TAGVAR(whole_archive_flag_spec, $1)= fi supports_anon_versioning=no case `$LD -v 2>&1` in *GNU\ gold*) supports_anon_versioning=yes ;; *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11 *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... *\ 2.11.*) ;; # other 2.11 versions *) supports_anon_versioning=yes ;; esac # See if GNU ld supports shared libraries. case $host_os in aix[[3-9]]*) # On AIX/PPC, the GNU linker is very broken if test "$host_cpu" != ia64; then _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: the GNU linker, at least up to release 2.19, is reported *** to be unable to reliably create shared libraries on AIX. *** Therefore, libtool is disabling shared libraries support. If you *** really care for shared libraries, you may want to install binutils *** 2.20 or above, or modify your PATH so that a non-GNU linker is found. *** You will then need to restart the configuration process. _LT_EOF fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='' ;; m68k) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; cygwin* | mingw* | pw32* | cegcc*) # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, # as there is no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'] if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file (1st line # is EXPORTS), use it as is; otherwise, prepend... _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; haiku*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(link_all_deplibs, $1)=yes ;; interix[[3-9]]*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu) tmp_diet=no if test "$host_os" = linux-dietlibc; then case $cc_basename in diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) esac fi if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ && test "$tmp_diet" = no then tmp_addflag=' $pic_flag' tmp_sharedflag='-shared' case $cc_basename,$host_cpu in pgcc*) # Portland Group C compiler _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag' ;; pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group f77 and f90 compilers _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag -Mnomain' ;; ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 tmp_addflag=' -i_dynamic' ;; efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 tmp_addflag=' -i_dynamic -nofor_main' ;; ifc* | ifort*) # Intel Fortran compiler tmp_addflag=' -nofor_main' ;; lf95*) # Lahey Fortran 8.1 _LT_TAGVAR(whole_archive_flag_spec, $1)= tmp_sharedflag='--shared' ;; xl[[cC]]* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL C 8.0 on PPC (deal with xlf below) tmp_sharedflag='-qmkshrobj' tmp_addflag= ;; nvcc*) # Cuda Compiler Driver 2.2 _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes ;; esac case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C 5.9 _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes tmp_sharedflag='-G' ;; *Sun\ F*) # Sun Fortran 8.3 tmp_sharedflag='-G' ;; esac _LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' if test "x$supports_anon_versioning" = xyes; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' fi case $cc_basename in xlf* | bgf* | bgxlf* | mpixlf*) # IBM XL Fortran 10.1 on PPC cannot create shared libs itself _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib' if test "x$supports_anon_versioning" = xyes; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' fi ;; esac else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' wlarc= else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' fi ;; solaris*) if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: The releases 2.8.* of the GNU linker cannot reliably *** create shared libraries on Solaris systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.9.1 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) case `$LD -v 2>&1` in *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*) _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not *** reliably create shared libraries on SCO systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.16.91.0.3 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF ;; *) # For security reasons, it is highly recommended that you always # use absolute paths for naming shared libraries, and exclude the # DT_RUNPATH tag from executables and libraries. But doing so # requires that you compile everything twice, which is a pain. if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; sunos4*) _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' wlarc= _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac if test "$_LT_TAGVAR(ld_shlibs, $1)" = no; then runpath_var= _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= fi else # PORTME fill in a description of your system's linker (not GNU ld) case $host_os in aix3*) _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' # Note: this linker hardcodes the directories in LIBPATH if there # are no directories specified by -L. _LT_TAGVAR(hardcode_minus_L, $1)=yes if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then # Neither direct hardcoding nor static linking is supported with a # broken collect2. _LT_TAGVAR(hardcode_direct, $1)=unsupported fi ;; aix[[4-9]]*) if test "$host_cpu" = ia64; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag="" else # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to AIX nm, but means don't demangle with GNU nm # Also, AIX nm treats weak defined symbols like other global # defined symbols, whereas GNU nm marks them as "W". if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' else _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' fi aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # need to do runtime linking. case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) for ld_flag in $LDFLAGS; do if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then aix_use_runtimelinking=yes break fi done ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. _LT_TAGVAR(archive_cmds, $1)='' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(file_list_spec, $1)='${wl}-f,' if test "$GCC" = yes; then case $host_os in aix4.[[012]]|aix4.[[012]].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`${CC} -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 _LT_TAGVAR(hardcode_direct, $1)=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)= fi ;; esac shared_flag='-shared' if test "$aix_use_runtimelinking" = yes; then shared_flag="$shared_flag "'${wl}-G' fi _LT_TAGVAR(link_all_deplibs, $1)=no else # not using gcc if test "$host_cpu" = ia64; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test "$aix_use_runtimelinking" = yes; then shared_flag='${wl}-G' else shared_flag='${wl}-bM:SRE' fi fi fi _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to export. _LT_TAGVAR(always_export_symbols, $1)=yes if test "$aix_use_runtimelinking" = yes; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. _LT_TAGVAR(allow_undefined_flag, $1)='-berok' # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" else if test "$host_cpu" = ia64; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib' _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok' _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok' if test "$with_gnu_ld" = yes; then # We only use this code for GNU lds that support --whole-archive. _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' fi _LT_TAGVAR(archive_cmds_need_lc, $1)=yes # This is similar to how AIX traditionally builds its shared libraries. _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' fi fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='' ;; m68k) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac ;; bsdi[[45]]*) _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic ;; cygwin* | mingw* | pw32* | cegcc*) # When not using gcc, we currently assume that we are using # Microsoft Visual C++. # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. case $cc_basename in cl*) # Native MSVC _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; else sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1,DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols' # Don't use ranlib _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib' _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile="$lt_outputfile.exe" lt_tool_outputfile="$lt_tool_outputfile.exe" ;; esac~ if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # Assume MSVC wrapper _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=' # The linker will automatically build a .lib file if we build a DLL. _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' # FIXME: Should let the user specify the lib program. _LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes ;; esac ;; darwin* | rhapsody*) _LT_DARWIN_LINKER_FEATURES($1) ;; dgux*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor # support. Future versions do this automatically, but an explicit c++rt0.o # does not break anything, and helps significantly (at the cost of a little # extra space). freebsd2.2*) _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # Unfortunately, older versions of FreeBSD 2 do not have this feature. freebsd2.*) _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # FreeBSD 3 and greater uses gcc -shared to do shared libraries. freebsd* | dragonfly*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; hpux9*) if test "$GCC" = yes; then _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' else _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_direct, $1)=yes # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' ;; hpux10*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi if test "$with_gnu_ld" = no; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes fi ;; hpux11*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' ;; esac else case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) m4_if($1, [], [ # Older versions of the 11.00 compiler do not understand -b yet # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does) _LT_LINKER_OPTION([if $CC understands -b], _LT_TAGVAR(lt_cv_prog_compiler__b, $1), [-b], [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'], [_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'])], [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags']) ;; esac fi if test "$with_gnu_ld" = no; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: case $host_cpu in hppa*64*|ia64*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac fi ;; irix5* | irix6* | nonstopux*) if test "$GCC" = yes; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' # Try to use the -exported_symbol ld option, if it does not # work, assume that -exports_file does not work either and # implicitly export all symbols. # This should be the same for all languages, so no per-tag cache variable. AC_CACHE_CHECK([whether the $host_os linker accepts -exported_symbol], [lt_cv_irix_exported_symbol], [save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null" AC_LINK_IFELSE( [AC_LANG_SOURCE( [AC_LANG_CASE([C], [[int foo (void) { return 0; }]], [C++], [[int foo (void) { return 0; }]], [Fortran 77], [[ subroutine foo end]], [Fortran], [[ subroutine foo end]])])], [lt_cv_irix_exported_symbol=yes], [lt_cv_irix_exported_symbol=no]) LDFLAGS="$save_LDFLAGS"]) if test "$lt_cv_irix_exported_symbol" = yes; then _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib' fi else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(inherit_rpath, $1)=yes _LT_TAGVAR(link_all_deplibs, $1)=yes ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out else _LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; newsos6) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *nto* | *qnx*) ;; openbsd*) if test -f /usr/libexec/ld.so; then _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=yes if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' else case $host_os in openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*) _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' ;; esac fi else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; os2*) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' ;; osf3*) if test "$GCC" = yes; then _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' else _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: ;; osf4* | osf5*) # as osf3* with the addition of -msym flag if test "$GCC" = yes; then _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' else _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ $CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp' # Both c and cxx compiler support -rpath directly _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_separator, $1)=: ;; solaris*) _LT_TAGVAR(no_undefined_flag, $1)=' -z defs' if test "$GCC" = yes; then wlarc='${wl}' _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' else case `$CC -V 2>&1` in *"Compilers 5.0"*) wlarc='' _LT_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' ;; *) wlarc='${wl}' _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' ;; esac fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands `-z linker_flag'. GCC discards it without `$wl', # but is careful enough not to reorder. # Supported since Solaris 2.6 (maybe 2.5.1?) if test "$GCC" = yes; then _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' else _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' fi ;; esac _LT_TAGVAR(link_all_deplibs, $1)=yes ;; sunos4*) if test "x$host_vendor" = xsequent; then # Use $CC to link under sequent, because it throws in some extra .o # files that make .init and .fini sections work. _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; sysv4) case $host_vendor in sni) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true??? ;; siemens) ## LD is ld it makes a PLAMLIB ## CC just makes a GrossModule. _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs' _LT_TAGVAR(hardcode_direct, $1)=no ;; motorola) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie ;; esac runpath_var='LD_RUN_PATH' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; sysv4.3*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport' ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var=LD_RUN_PATH hardcode_runpath_var=yes _LT_TAGVAR(ld_shlibs, $1)=yes fi ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We can NOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport' runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; uts4*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(ld_shlibs, $1)=no ;; esac if test x$host_vendor = xsni; then case $host in sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Blargedynsym' ;; esac fi fi ]) AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no _LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld _LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl _LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl _LT_DECL([], [extract_expsyms_cmds], [2], [The commands to extract the exported symbol list from a shared archive]) # # Do we need to explicitly link libc? # case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in x|xyes) # Assume -lc should be added _LT_TAGVAR(archive_cmds_need_lc, $1)=yes if test "$enable_shared" = yes && test "$GCC" = yes; then case $_LT_TAGVAR(archive_cmds, $1) in *'~'*) # FIXME: we may have to deal with multi-command sequences. ;; '$CC '*) # Test whether the compiler implicitly links with -lc since on some # systems, -lgcc has to come before -lc. If gcc already passes -lc # to ld, don't add -lc before -lgcc. AC_CACHE_CHECK([whether -lc should be explicitly linked in], [lt_cv_]_LT_TAGVAR(archive_cmds_need_lc, $1), [$RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if AC_TRY_EVAL(ac_compile) 2>conftest.err; then soname=conftest lib=conftest libobjs=conftest.$ac_objext deplibs= wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1) compiler_flags=-v linker_flags=-v verstring= output_objdir=. libname=conftest lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1) _LT_TAGVAR(allow_undefined_flag, $1)= if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) then lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=no else lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=yes fi _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag else cat conftest.err 1>&5 fi $RM conftest* ]) _LT_TAGVAR(archive_cmds_need_lc, $1)=$lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1) ;; esac fi ;; esac _LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0], [Whether or not to add -lc for building shared libraries]) _LT_TAGDECL([allow_libtool_libs_with_static_runtimes], [enable_shared_with_static_runtimes], [0], [Whether or not to disallow shared libs when runtime libs are static]) _LT_TAGDECL([], [export_dynamic_flag_spec], [1], [Compiler flag to allow reflexive dlopens]) _LT_TAGDECL([], [whole_archive_flag_spec], [1], [Compiler flag to generate shared objects directly from archives]) _LT_TAGDECL([], [compiler_needs_object], [1], [Whether the compiler copes with passing no objects directly]) _LT_TAGDECL([], [old_archive_from_new_cmds], [2], [Create an old-style archive from a shared archive]) _LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2], [Create a temporary old-style archive to link instead of a shared archive]) _LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive]) _LT_TAGDECL([], [archive_expsym_cmds], [2]) _LT_TAGDECL([], [module_cmds], [2], [Commands used to build a loadable module if different from building a shared archive.]) _LT_TAGDECL([], [module_expsym_cmds], [2]) _LT_TAGDECL([], [with_gnu_ld], [1], [Whether we are building with GNU ld or not]) _LT_TAGDECL([], [allow_undefined_flag], [1], [Flag that allows shared libraries with undefined symbols to be built]) _LT_TAGDECL([], [no_undefined_flag], [1], [Flag that enforces no undefined symbols]) _LT_TAGDECL([], [hardcode_libdir_flag_spec], [1], [Flag to hardcode $libdir into a binary during linking. This must work even if $libdir does not exist]) _LT_TAGDECL([], [hardcode_libdir_separator], [1], [Whether we need a single "-rpath" flag with a separated argument]) _LT_TAGDECL([], [hardcode_direct], [0], [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_direct_absolute], [0], [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the resulting binary and the resulting library dependency is "absolute", i.e impossible to change by setting ${shlibpath_var} if the library is relocated]) _LT_TAGDECL([], [hardcode_minus_L], [0], [Set to "yes" if using the -LDIR flag during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_shlibpath_var], [0], [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_automatic], [0], [Set to "yes" if building a shared library automatically hardcodes DIR into the library and all subsequent libraries and executables linked against it]) _LT_TAGDECL([], [inherit_rpath], [0], [Set to yes if linker adds runtime paths of dependent libraries to runtime path list]) _LT_TAGDECL([], [link_all_deplibs], [0], [Whether libtool must link a program against all its dependency libraries]) _LT_TAGDECL([], [always_export_symbols], [0], [Set to "yes" if exported symbols are required]) _LT_TAGDECL([], [export_symbols_cmds], [2], [The commands to list exported symbols]) _LT_TAGDECL([], [exclude_expsyms], [1], [Symbols that should not be listed in the preloaded symbols]) _LT_TAGDECL([], [include_expsyms], [1], [Symbols that must always be exported]) _LT_TAGDECL([], [prelink_cmds], [2], [Commands necessary for linking programs (against libraries) with templates]) _LT_TAGDECL([], [postlink_cmds], [2], [Commands necessary for finishing linking programs]) _LT_TAGDECL([], [file_list_spec], [1], [Specify filename containing input files]) dnl FIXME: Not yet implemented dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1], dnl [Compiler flag to generate thread safe objects]) ])# _LT_LINKER_SHLIBS # _LT_LANG_C_CONFIG([TAG]) # ------------------------ # Ensure that the configuration variables for a C compiler are suitably # defined. These variables are subsequently used by _LT_CONFIG to write # the compiler configuration to `libtool'. m4_defun([_LT_LANG_C_CONFIG], [m4_require([_LT_DECL_EGREP])dnl lt_save_CC="$CC" AC_LANG_PUSH(C) # Source file extension for C test sources. ac_ext=c # Object file extension for compiled C test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(){return(0);}' _LT_TAG_COMPILER # Save the default compiler, since it gets overwritten when the other # tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. compiler_DEFAULT=$CC # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) LT_SYS_DLOPEN_SELF _LT_CMD_STRIPLIB # Report which library types will actually be built AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_CONFIG($1) fi AC_LANG_POP CC="$lt_save_CC" ])# _LT_LANG_C_CONFIG # _LT_LANG_CXX_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for a C++ compiler are suitably # defined. These variables are subsequently used by _LT_CONFIG to write # the compiler configuration to `libtool'. m4_defun([_LT_LANG_CXX_CONFIG], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_PATH_MANIFEST_TOOL])dnl if test -n "$CXX" && ( test "X$CXX" != "Xno" && ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) || (test "X$CXX" != "Xg++"))) ; then AC_PROG_CXXCPP else _lt_caught_CXX_error=yes fi AC_LANG_PUSH(C++) _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(compiler_needs_object, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for C++ test sources. ac_ext=cpp # Object file extension for compiled C++ test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the CXX compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test "$_lt_caught_CXX_error" != yes; then # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_LD=$LD lt_save_GCC=$GCC GCC=$GXX lt_save_with_gnu_ld=$with_gnu_ld lt_save_path_LD=$lt_cv_path_LD if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx else $as_unset lt_cv_prog_gnu_ld fi if test -n "${lt_cv_path_LDCXX+set}"; then lt_cv_path_LD=$lt_cv_path_LDCXX else $as_unset lt_cv_path_LD fi test -z "${LDCXX+set}" || LD=$LDCXX CC=${CXX-"c++"} CFLAGS=$CXXFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) if test -n "$compiler"; then # We don't want -fno-exception when compiling C++ code, so set the # no_builtin_flag separately if test "$GXX" = yes; then _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' else _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= fi if test "$GXX" = yes; then # Set up default GNU C++ configuration LT_PATH_LD # Check if GNU C++ uses GNU ld as the underlying linker, since the # archiving commands below assume that GNU ld is being used. if test "$with_gnu_ld" = yes; then _LT_TAGVAR(archive_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' # If archive_cmds runs LD, not CC, wlarc should be empty # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to # investigate it a little bit more. (MM) wlarc='${wl}' # ancient GNU ld didn't support --whole-archive et. al. if eval "`$CC -print-prog-name=ld` --help 2>&1" | $GREP 'no-whole-archive' > /dev/null; then _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' else _LT_TAGVAR(whole_archive_flag_spec, $1)= fi else with_gnu_ld=no wlarc= # A generic and very simple default shared library creation # command for GNU C++ for the case where it uses the native # linker, instead of GNU ld. If possible, this setting should # overridden to take advantage of the native linker features on # the platform it is being used on. _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' fi # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else GXX=no with_gnu_ld=no wlarc= fi # PORTME: fill in a description of your system's C++ link characteristics AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) _LT_TAGVAR(ld_shlibs, $1)=yes case $host_os in aix3*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aix[[4-9]]*) if test "$host_cpu" = ia64; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag="" else aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # need to do runtime linking. case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) for ld_flag in $LDFLAGS; do case $ld_flag in *-brtl*) aix_use_runtimelinking=yes break ;; esac done ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. _LT_TAGVAR(archive_cmds, $1)='' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(file_list_spec, $1)='${wl}-f,' if test "$GXX" = yes; then case $host_os in aix4.[[012]]|aix4.[[012]].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`${CC} -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 _LT_TAGVAR(hardcode_direct, $1)=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)= fi esac shared_flag='-shared' if test "$aix_use_runtimelinking" = yes; then shared_flag="$shared_flag "'${wl}-G' fi else # not using gcc if test "$host_cpu" = ia64; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test "$aix_use_runtimelinking" = yes; then shared_flag='${wl}-G' else shared_flag='${wl}-bM:SRE' fi fi fi _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to # export. _LT_TAGVAR(always_export_symbols, $1)=yes if test "$aix_use_runtimelinking" = yes; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. _LT_TAGVAR(allow_undefined_flag, $1)='-berok' # Determine the default libpath from the value encoded in an empty # executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" else if test "$host_cpu" = ia64; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib' _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok' _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok' if test "$with_gnu_ld" = yes; then # We only use this code for GNU lds that support --whole-archive. _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' fi _LT_TAGVAR(archive_cmds_need_lc, $1)=yes # This is similar to how AIX traditionally builds its shared # libraries. _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' fi fi ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; chorus*) case $cc_basename in *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; cygwin* | mingw* | pw32* | cegcc*) case $GXX,$cc_basename in ,cl* | no,cl*) # Native MSVC # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then $SED -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; else $SED -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes # Don't use ranlib _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib' _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile="$lt_outputfile.exe" lt_tool_outputfile="$lt_tool_outputfile.exe" ;; esac~ func_to_tool_file "$lt_outputfile"~ if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # g++ # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, # as there is no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file (1st line # is EXPORTS), use it as is; otherwise, prepend... _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; darwin* | rhapsody*) _LT_DARWIN_LINKER_FEATURES($1) ;; dgux*) case $cc_basename in ec++*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; ghcx*) # Green Hills C++ Compiler # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; freebsd2.*) # C++ shared libraries reported to be fairly broken before # switch to ELF _LT_TAGVAR(ld_shlibs, $1)=no ;; freebsd-elf*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;; freebsd* | dragonfly*) # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF # conventions _LT_TAGVAR(ld_shlibs, $1)=yes ;; haiku*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(link_all_deplibs, $1)=yes ;; hpux9*) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, # but as the default # location of the library. case $cc_basename in CC*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aCC*) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes; then _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; hpux10*|hpux11*) if test $with_gnu_ld = no; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: case $host_cpu in hppa*64*|ia64*) ;; *) _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' ;; esac fi case $host_cpu in hppa*64*|ia64*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, # but as the default # location of the library. ;; esac case $cc_basename in CC*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aCC*) case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes; then if test $with_gnu_ld = no; then case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac fi else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; interix[[3-9]]*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; irix5* | irix6*) case $cc_basename in CC*) # SGI C++ _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' # Archives containing C++ object files must be created using # "CC -ar", where "CC" is the IRIX C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs' ;; *) if test "$GXX" = yes; then if test "$with_gnu_ld" = no; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` -o $lib' fi fi _LT_TAGVAR(link_all_deplibs, $1)=yes ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(inherit_rpath, $1)=yes ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' # Archives containing C++ object files must be created using # "CC -Bstatic", where "CC" is the KAI C++ compiler. _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;; icpc* | ecpc* ) # Intel C++ with_gnu_ld=yes # version 8.0 and above of icpc choke on multiply defined symbols # if we add $predep_objects and $postdep_objects, however 7.1 and # earlier do not add the objects themselves. case `$CC -V 2>&1` in *"Version 7."*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' ;; *) # Version 8.0 or newer tmp_idyn= case $host_cpu in ia64*) tmp_idyn=' -i_dynamic';; esac _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' ;; esac _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive' ;; pgCC* | pgcpp*) # Portland Group C++ compiler case `$CC -V` in *pgCC\ [[1-5]].* | *pgcpp\ [[1-5]].*) _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~ compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"' _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~ $AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~ $RANLIB $oldlib' _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' ;; *) # Version 6 and above use weak symbols _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' ;; cxx*) # Compaq C++ _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols' runpath_var=LD_RUN_PATH _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed' ;; xl* | mpixl* | bgxl*) # IBM XL 8.0 on PPC, with GNU ld _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' if test "x$supports_anon_versioning" = xyes; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' fi ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes # Not sure whether something based on # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 # would be better. output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' ;; esac ;; esac ;; lynxos*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; m88k*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; mvs*) case $cc_basename in cxx*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' wlarc= _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no fi # Workaround some broken pre-1.5 toolchains output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' ;; *nto* | *qnx*) _LT_TAGVAR(ld_shlibs, $1)=yes ;; openbsd2*) # C++ shared libraries are fairly broken _LT_TAGVAR(ld_shlibs, $1)=no ;; openbsd*) if test -f /usr/libexec/ld.so; then _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' fi output_verbose_link_cmd=func_echo_all else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Archives containing C++ object files must be created using # the KAI C++ compiler. case $host in osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;; *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;; esac ;; RCC*) # Rational C++ 2.4.1 # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; cxx*) case $host in osf3*) _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && func_echo_all "${wl}-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' ;; *) _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ echo "-hidden">> $lib.exp~ $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~ $RM $lib.exp' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' ;; esac _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes && test "$with_gnu_ld" = no; then _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' case $host in osf3*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; psos*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; lcc*) # Lucid # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ _LT_TAGVAR(archive_cmds_need_lc,$1)=yes _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands `-z linker_flag'. # Supported since Solaris 2.6 (maybe 2.5.1?) _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' ;; esac _LT_TAGVAR(link_all_deplibs, $1)=yes output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' ;; gcx*) # Green Hills C++ Compiler _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' # The C++ compiler must be used to create the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs' ;; *) # GNU C++ compiler with Solaris linker if test "$GXX" = yes && test "$with_gnu_ld" = no; then _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs' if $CC --version | $GREP -v '^2\.7' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # g++ 2.7 appears to require `-G' NOT `-shared' on this # platform. _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir' case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' ;; esac fi ;; esac ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var='LD_RUN_PATH' case $cc_basename in CC*) _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We can NOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport' runpath_var='LD_RUN_PATH' case $cc_basename in CC*) _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(old_archive_cmds, $1)='$CC -Tprelink_objects $oldobjs~ '"$_LT_TAGVAR(old_archive_cmds, $1)" _LT_TAGVAR(reload_cmds, $1)='$CC -Tprelink_objects $reload_objs~ '"$_LT_TAGVAR(reload_cmds, $1)" ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; vxworks*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no _LT_TAGVAR(GCC, $1)="$GXX" _LT_TAGVAR(LD, $1)="$LD" ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_SYS_HIDDEN_LIBDEPS($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS LDCXX=$LD LD=$lt_save_LD GCC=$lt_save_GCC with_gnu_ld=$lt_save_with_gnu_ld lt_cv_path_LDCXX=$lt_cv_path_LD lt_cv_path_LD=$lt_save_path_LD lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld fi # test "$_lt_caught_CXX_error" != yes AC_LANG_POP ])# _LT_LANG_CXX_CONFIG # _LT_FUNC_STRIPNAME_CNF # ---------------------- # func_stripname_cnf prefix suffix name # strip PREFIX and SUFFIX off of NAME. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). # # This function is identical to the (non-XSI) version of func_stripname, # except this one can be used by m4 code that may be executed by configure, # rather than the libtool script. m4_defun([_LT_FUNC_STRIPNAME_CNF],[dnl AC_REQUIRE([_LT_DECL_SED]) AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH]) func_stripname_cnf () { case ${2} in .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;; *) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;; esac } # func_stripname_cnf ])# _LT_FUNC_STRIPNAME_CNF # _LT_SYS_HIDDEN_LIBDEPS([TAGNAME]) # --------------------------------- # Figure out "hidden" library dependencies from verbose # compiler output when linking a shared library. # Parse the compiler output and extract the necessary # objects, libraries and library flags. m4_defun([_LT_SYS_HIDDEN_LIBDEPS], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl AC_REQUIRE([_LT_FUNC_STRIPNAME_CNF])dnl # Dependencies to place before and after the object being linked: _LT_TAGVAR(predep_objects, $1)= _LT_TAGVAR(postdep_objects, $1)= _LT_TAGVAR(predeps, $1)= _LT_TAGVAR(postdeps, $1)= _LT_TAGVAR(compiler_lib_search_path, $1)= dnl we can't use the lt_simple_compile_test_code here, dnl because it contains code intended for an executable, dnl not a library. It's possible we should let each dnl tag define a new lt_????_link_test_code variable, dnl but it's only used here... m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF int a; void foo (void) { a = 0; } _LT_EOF ], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF class Foo { public: Foo (void) { a = 0; } private: int a; }; _LT_EOF ], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF subroutine foo implicit none integer*4 a a=0 return end _LT_EOF ], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF subroutine foo implicit none integer a a=0 return end _LT_EOF ], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF public class foo { private int a; public void bar (void) { a = 0; } }; _LT_EOF ], [$1], [GO], [cat > conftest.$ac_ext <<_LT_EOF package foo func foo() { } _LT_EOF ]) _lt_libdeps_save_CFLAGS=$CFLAGS case "$CC $CFLAGS " in #( *\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;; *\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;; *\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;; esac dnl Parse the compiler output and extract the necessary dnl objects, libraries and library flags. if AC_TRY_EVAL(ac_compile); then # Parse the compiler output and extract the necessary # objects, libraries and library flags. # Sentinel used to keep track of whether or not we are before # the conftest object file. pre_test_object_deps_done=no for p in `eval "$output_verbose_link_cmd"`; do case ${prev}${p} in -L* | -R* | -l*) # Some compilers place space between "-{L,R}" and the path. # Remove the space. if test $p = "-L" || test $p = "-R"; then prev=$p continue fi # Expand the sysroot to ease extracting the directories later. if test -z "$prev"; then case $p in -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;; -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;; -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;; esac fi case $p in =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;; esac if test "$pre_test_object_deps_done" = no; then case ${prev} in -L | -R) # Internal compiler library paths should come after those # provided the user. The postdeps already come after the # user supplied libs so there is no need to process them. if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then _LT_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}" else _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}" fi ;; # The "-l" case would never come before the object being # linked, so don't bother handling this case. esac else if test -z "$_LT_TAGVAR(postdeps, $1)"; then _LT_TAGVAR(postdeps, $1)="${prev}${p}" else _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} ${prev}${p}" fi fi prev= ;; *.lto.$objext) ;; # Ignore GCC LTO objects *.$objext) # This assumes that the test object file only shows up # once in the compiler output. if test "$p" = "conftest.$objext"; then pre_test_object_deps_done=yes continue fi if test "$pre_test_object_deps_done" = no; then if test -z "$_LT_TAGVAR(predep_objects, $1)"; then _LT_TAGVAR(predep_objects, $1)="$p" else _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p" fi else if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then _LT_TAGVAR(postdep_objects, $1)="$p" else _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p" fi fi ;; *) ;; # Ignore the rest. esac done # Clean up. rm -f a.out a.exe else echo "libtool.m4: error: problem compiling $1 test program" fi $RM -f confest.$objext CFLAGS=$_lt_libdeps_save_CFLAGS # PORTME: override above test on systems where it is broken m4_if([$1], [CXX], [case $host_os in interix[[3-9]]*) # Interix 3.5 installs completely hosed .la files for C++, so rather than # hack all around it, let's just trust "g++" to DTRT. _LT_TAGVAR(predep_objects,$1)= _LT_TAGVAR(postdep_objects,$1)= _LT_TAGVAR(postdeps,$1)= ;; linux*) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 # The more standards-conforming stlport4 library is # incompatible with the Cstd library. Avoid specifying # it if it's in CXXFLAGS. Ignore libCrun as # -library=stlport4 depends on it. case " $CXX $CXXFLAGS " in *" -library=stlport4 "*) solaris_use_stlport4=yes ;; esac if test "$solaris_use_stlport4" != yes; then _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun' fi ;; esac ;; solaris*) case $cc_basename in CC* | sunCC*) # The more standards-conforming stlport4 library is # incompatible with the Cstd library. Avoid specifying # it if it's in CXXFLAGS. Ignore libCrun as # -library=stlport4 depends on it. case " $CXX $CXXFLAGS " in *" -library=stlport4 "*) solaris_use_stlport4=yes ;; esac # Adding this requires a known-good setup of shared libraries for # Sun compiler versions before 5.6, else PIC objects from an old # archive will be linked into the output, leading to subtle bugs. if test "$solaris_use_stlport4" != yes; then _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun' fi ;; esac ;; esac ]) case " $_LT_TAGVAR(postdeps, $1) " in *" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;; esac _LT_TAGVAR(compiler_lib_search_dirs, $1)= if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | ${SED} -e 's! -L! !g' -e 's!^ !!'` fi _LT_TAGDECL([], [compiler_lib_search_dirs], [1], [The directories searched by this compiler when creating a shared library]) _LT_TAGDECL([], [predep_objects], [1], [Dependencies to place before and after the objects being linked to create a shared library]) _LT_TAGDECL([], [postdep_objects], [1]) _LT_TAGDECL([], [predeps], [1]) _LT_TAGDECL([], [postdeps], [1]) _LT_TAGDECL([], [compiler_lib_search_path], [1], [The library search path used internally by the compiler when linking a shared library]) ])# _LT_SYS_HIDDEN_LIBDEPS # _LT_LANG_F77_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for a Fortran 77 compiler are # suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_F77_CONFIG], [AC_LANG_PUSH(Fortran 77) if test -z "$F77" || test "X$F77" = "Xno"; then _lt_disable_F77=yes fi _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for f77 test sources. ac_ext=f # Object file extension for compiled f77 test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the F77 compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test "$_lt_disable_F77" != yes; then # Code to be used in simple compile tests lt_simple_compile_test_code="\ subroutine t return end " # Code to be used in simple link tests lt_simple_link_test_code="\ program t end " # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC="$CC" lt_save_GCC=$GCC lt_save_CFLAGS=$CFLAGS CC=${F77-"f77"} CFLAGS=$FFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) GCC=$G77 if test -n "$compiler"; then AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_TAGVAR(GCC, $1)="$G77" _LT_TAGVAR(LD, $1)="$LD" ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" GCC=$lt_save_GCC CC="$lt_save_CC" CFLAGS="$lt_save_CFLAGS" fi # test "$_lt_disable_F77" != yes AC_LANG_POP ])# _LT_LANG_F77_CONFIG # _LT_LANG_FC_CONFIG([TAG]) # ------------------------- # Ensure that the configuration variables for a Fortran compiler are # suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_FC_CONFIG], [AC_LANG_PUSH(Fortran) if test -z "$FC" || test "X$FC" = "Xno"; then _lt_disable_FC=yes fi _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for fc test sources. ac_ext=${ac_fc_srcext-f} # Object file extension for compiled fc test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the FC compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test "$_lt_disable_FC" != yes; then # Code to be used in simple compile tests lt_simple_compile_test_code="\ subroutine t return end " # Code to be used in simple link tests lt_simple_link_test_code="\ program t end " # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC="$CC" lt_save_GCC=$GCC lt_save_CFLAGS=$CFLAGS CC=${FC-"f95"} CFLAGS=$FCFLAGS compiler=$CC GCC=$ac_cv_fc_compiler_gnu _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) if test -n "$compiler"; then AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_TAGVAR(GCC, $1)="$ac_cv_fc_compiler_gnu" _LT_TAGVAR(LD, $1)="$LD" ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_SYS_HIDDEN_LIBDEPS($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS fi # test "$_lt_disable_FC" != yes AC_LANG_POP ])# _LT_LANG_FC_CONFIG # _LT_LANG_GCJ_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for the GNU Java Compiler compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_GCJ_CONFIG], [AC_REQUIRE([LT_PROG_GCJ])dnl AC_LANG_SAVE # Source file extension for Java test sources. ac_ext=java # Object file extension for compiled Java test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="class foo {}" # Code to be used in simple link tests lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC=yes CC=${GCJ-"gcj"} CFLAGS=$GCJFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_TAGVAR(LD, $1)="$LD" _LT_CC_BASENAME([$compiler]) # GCJ did not exist at the time GCC didn't implicitly link libc in. _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi AC_LANG_RESTORE GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_GCJ_CONFIG # _LT_LANG_GO_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for the GNU Go compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_GO_CONFIG], [AC_REQUIRE([LT_PROG_GO])dnl AC_LANG_SAVE # Source file extension for Go test sources. ac_ext=go # Object file extension for compiled Go test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="package main; func main() { }" # Code to be used in simple link tests lt_simple_link_test_code='package main; func main() { }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC=yes CC=${GOC-"gccgo"} CFLAGS=$GOFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_TAGVAR(LD, $1)="$LD" _LT_CC_BASENAME([$compiler]) # Go did not exist at the time GCC didn't implicitly link libc in. _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi AC_LANG_RESTORE GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_GO_CONFIG # _LT_LANG_RC_CONFIG([TAG]) # ------------------------- # Ensure that the configuration variables for the Windows resource compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_RC_CONFIG], [AC_REQUIRE([LT_PROG_RC])dnl AC_LANG_SAVE # Source file extension for RC test sources. ac_ext=rc # Object file extension for compiled RC test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }' # Code to be used in simple link tests lt_simple_link_test_code="$lt_simple_compile_test_code" # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC="$CC" lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC= CC=${RC-"windres"} CFLAGS= compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes if test -n "$compiler"; then : _LT_CONFIG($1) fi GCC=$lt_save_GCC AC_LANG_RESTORE CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_RC_CONFIG # LT_PROG_GCJ # ----------- AC_DEFUN([LT_PROG_GCJ], [m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ], [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ], [AC_CHECK_TOOL(GCJ, gcj,) test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2" AC_SUBST(GCJFLAGS)])])[]dnl ]) # Old name: AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_GCJ], []) # LT_PROG_GO # ---------- AC_DEFUN([LT_PROG_GO], [AC_CHECK_TOOL(GOC, gccgo,) ]) # LT_PROG_RC # ---------- AC_DEFUN([LT_PROG_RC], [AC_CHECK_TOOL(RC, windres,) ]) # Old name: AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_RC], []) # _LT_DECL_EGREP # -------------- # If we don't have a new enough Autoconf to choose the best grep # available, choose the one first in the user's PATH. m4_defun([_LT_DECL_EGREP], [AC_REQUIRE([AC_PROG_EGREP])dnl AC_REQUIRE([AC_PROG_FGREP])dnl test -z "$GREP" && GREP=grep _LT_DECL([], [GREP], [1], [A grep program that handles long lines]) _LT_DECL([], [EGREP], [1], [An ERE matcher]) _LT_DECL([], [FGREP], [1], [A literal string matcher]) dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too AC_SUBST([GREP]) ]) # _LT_DECL_OBJDUMP # -------------- # If we don't have a new enough Autoconf to choose the best objdump # available, choose the one first in the user's PATH. m4_defun([_LT_DECL_OBJDUMP], [AC_CHECK_TOOL(OBJDUMP, objdump, false) test -z "$OBJDUMP" && OBJDUMP=objdump _LT_DECL([], [OBJDUMP], [1], [An object symbol dumper]) AC_SUBST([OBJDUMP]) ]) # _LT_DECL_DLLTOOL # ---------------- # Ensure DLLTOOL variable is set. m4_defun([_LT_DECL_DLLTOOL], [AC_CHECK_TOOL(DLLTOOL, dlltool, false) test -z "$DLLTOOL" && DLLTOOL=dlltool _LT_DECL([], [DLLTOOL], [1], [DLL creation program]) AC_SUBST([DLLTOOL]) ]) # _LT_DECL_SED # ------------ # Check for a fully-functional sed program, that truncates # as few characters as possible. Prefer GNU sed if found. m4_defun([_LT_DECL_SED], [AC_PROG_SED test -z "$SED" && SED=sed Xsed="$SED -e 1s/^X//" _LT_DECL([], [SED], [1], [A sed program that does not truncate output]) _LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"], [Sed that helps us avoid accidentally triggering echo(1) options like -n]) ])# _LT_DECL_SED m4_ifndef([AC_PROG_SED], [ ############################################################ # NOTE: This macro has been submitted for inclusion into # # GNU Autoconf as AC_PROG_SED. When it is available in # # a released version of Autoconf we should remove this # # macro and use it instead. # ############################################################ m4_defun([AC_PROG_SED], [AC_MSG_CHECKING([for a sed that does not truncate output]) AC_CACHE_VAL(lt_cv_path_SED, [# Loop through the user's path and test for sed and gsed. # Then use that list of sed's as ones to test for truncation. as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for lt_ac_prog in sed gsed; do for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext" fi done done done IFS=$as_save_IFS lt_ac_max=0 lt_ac_count=0 # Add /usr/xpg4/bin/sed as it is typically found on Solaris # along with /bin/sed that truncates output. for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do test ! -f $lt_ac_sed && continue cat /dev/null > conftest.in lt_ac_count=0 echo $ECHO_N "0123456789$ECHO_C" >conftest.in # Check for GNU sed and select it if it is found. if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then lt_cv_path_SED=$lt_ac_sed break fi while true; do cat conftest.in conftest.in >conftest.tmp mv conftest.tmp conftest.in cp conftest.in conftest.nl echo >>conftest.nl $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break cmp -s conftest.out conftest.nl || break # 10000 chars as input seems more than enough test $lt_ac_count -gt 10 && break lt_ac_count=`expr $lt_ac_count + 1` if test $lt_ac_count -gt $lt_ac_max; then lt_ac_max=$lt_ac_count lt_cv_path_SED=$lt_ac_sed fi done done ]) SED=$lt_cv_path_SED AC_SUBST([SED]) AC_MSG_RESULT([$SED]) ])#AC_PROG_SED ])#m4_ifndef # Old name: AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_SED], []) # _LT_CHECK_SHELL_FEATURES # ------------------------ # Find out whether the shell is Bourne or XSI compatible, # or has some other useful features. m4_defun([_LT_CHECK_SHELL_FEATURES], [AC_MSG_CHECKING([whether the shell understands some XSI constructs]) # Try some XSI features xsi_shell=no ( _lt_dummy="a/b/c" test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \ = c,a/b,b/c, \ && eval 'test $(( 1 + 1 )) -eq 2 \ && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \ && xsi_shell=yes AC_MSG_RESULT([$xsi_shell]) _LT_CONFIG_LIBTOOL_INIT([xsi_shell='$xsi_shell']) AC_MSG_CHECKING([whether the shell understands "+="]) lt_shell_append=no ( foo=bar; set foo baz; eval "$[1]+=\$[2]" && test "$foo" = barbaz ) \ >/dev/null 2>&1 \ && lt_shell_append=yes AC_MSG_RESULT([$lt_shell_append]) _LT_CONFIG_LIBTOOL_INIT([lt_shell_append='$lt_shell_append']) if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then lt_unset=unset else lt_unset=false fi _LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl # test EBCDIC or ASCII case `echo X|tr X '\101'` in A) # ASCII based system # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr lt_SP2NL='tr \040 \012' lt_NL2SP='tr \015\012 \040\040' ;; *) # EBCDIC based system lt_SP2NL='tr \100 \n' lt_NL2SP='tr \r\n \100\100' ;; esac _LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl _LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl ])# _LT_CHECK_SHELL_FEATURES # _LT_PROG_FUNCTION_REPLACE (FUNCNAME, REPLACEMENT-BODY) # ------------------------------------------------------ # In `$cfgfile', look for function FUNCNAME delimited by `^FUNCNAME ()$' and # '^} FUNCNAME ', and replace its body with REPLACEMENT-BODY. m4_defun([_LT_PROG_FUNCTION_REPLACE], [dnl { sed -e '/^$1 ()$/,/^} # $1 /c\ $1 ()\ {\ m4_bpatsubsts([$2], [$], [\\], [^\([ ]\)], [\\\1]) } # Extended-shell $1 implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: ]) # _LT_PROG_REPLACE_SHELLFNS # ------------------------- # Replace existing portable implementations of several shell functions with # equivalent extended shell implementations where those features are available.. m4_defun([_LT_PROG_REPLACE_SHELLFNS], [if test x"$xsi_shell" = xyes; then _LT_PROG_FUNCTION_REPLACE([func_dirname], [dnl case ${1} in */*) func_dirname_result="${1%/*}${2}" ;; * ) func_dirname_result="${3}" ;; esac]) _LT_PROG_FUNCTION_REPLACE([func_basename], [dnl func_basename_result="${1##*/}"]) _LT_PROG_FUNCTION_REPLACE([func_dirname_and_basename], [dnl case ${1} in */*) func_dirname_result="${1%/*}${2}" ;; * ) func_dirname_result="${3}" ;; esac func_basename_result="${1##*/}"]) _LT_PROG_FUNCTION_REPLACE([func_stripname], [dnl # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are # positional parameters, so assign one to ordinary parameter first. func_stripname_result=${3} func_stripname_result=${func_stripname_result#"${1}"} func_stripname_result=${func_stripname_result%"${2}"}]) _LT_PROG_FUNCTION_REPLACE([func_split_long_opt], [dnl func_split_long_opt_name=${1%%=*} func_split_long_opt_arg=${1#*=}]) _LT_PROG_FUNCTION_REPLACE([func_split_short_opt], [dnl func_split_short_opt_arg=${1#??} func_split_short_opt_name=${1%"$func_split_short_opt_arg"}]) _LT_PROG_FUNCTION_REPLACE([func_lo2o], [dnl case ${1} in *.lo) func_lo2o_result=${1%.lo}.${objext} ;; *) func_lo2o_result=${1} ;; esac]) _LT_PROG_FUNCTION_REPLACE([func_xform], [ func_xform_result=${1%.*}.lo]) _LT_PROG_FUNCTION_REPLACE([func_arith], [ func_arith_result=$(( $[*] ))]) _LT_PROG_FUNCTION_REPLACE([func_len], [ func_len_result=${#1}]) fi if test x"$lt_shell_append" = xyes; then _LT_PROG_FUNCTION_REPLACE([func_append], [ eval "${1}+=\\${2}"]) _LT_PROG_FUNCTION_REPLACE([func_append_quoted], [dnl func_quote_for_eval "${2}" dnl m4 expansion turns \\\\ into \\, and then the shell eval turns that into \ eval "${1}+=\\\\ \\$func_quote_for_eval_result"]) # Save a `func_append' function call where possible by direct use of '+=' sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: else # Save a `func_append' function call even when '+=' is not available sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: fi if test x"$_lt_function_replace_fail" = x":"; then AC_MSG_WARN([Unable to substitute extended shell functions in $ofile]) fi ]) # _LT_PATH_CONVERSION_FUNCTIONS # ----------------------------- # Determine which file name conversion functions should be used by # func_to_host_file (and, implicitly, by func_to_host_path). These are needed # for certain cross-compile configurations and native mingw. m4_defun([_LT_PATH_CONVERSION_FUNCTIONS], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl AC_MSG_CHECKING([how to convert $build file names to $host format]) AC_CACHE_VAL(lt_cv_to_host_file_cmd, [case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32 ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32 ;; esac ;; *-*-cygwin* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_noop ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin ;; esac ;; * ) # unhandled hosts (and "normal" native builds) lt_cv_to_host_file_cmd=func_convert_file_noop ;; esac ]) to_host_file_cmd=$lt_cv_to_host_file_cmd AC_MSG_RESULT([$lt_cv_to_host_file_cmd]) _LT_DECL([to_host_file_cmd], [lt_cv_to_host_file_cmd], [0], [convert $build file names to $host format])dnl AC_MSG_CHECKING([how to convert $build file names to toolchain format]) AC_CACHE_VAL(lt_cv_to_tool_file_cmd, [#assume ordinary cross tools, or native build. lt_cv_to_tool_file_cmd=func_convert_file_noop case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 ;; esac ;; esac ]) to_tool_file_cmd=$lt_cv_to_tool_file_cmd AC_MSG_RESULT([$lt_cv_to_tool_file_cmd]) _LT_DECL([to_tool_file_cmd], [lt_cv_to_tool_file_cmd], [0], [convert $build files to toolchain format])dnl ])# _LT_PATH_CONVERSION_FUNCTIONS sipxtapi-3.3.0~test17/m4/ltoptions.m40000644000175000017500000003007312321250471020213 0ustar00danieldaniel00000000000000# Helper functions for option handling. -*- Autoconf -*- # # Copyright (C) 2004, 2005, 2007, 2008, 2009 Free Software Foundation, # Inc. # Written by Gary V. Vaughan, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 7 ltoptions.m4 # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])]) # _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME) # ------------------------------------------ m4_define([_LT_MANGLE_OPTION], [[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])]) # _LT_SET_OPTION(MACRO-NAME, OPTION-NAME) # --------------------------------------- # Set option OPTION-NAME for macro MACRO-NAME, and if there is a # matching handler defined, dispatch to it. Other OPTION-NAMEs are # saved as a flag. m4_define([_LT_SET_OPTION], [m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]), _LT_MANGLE_DEFUN([$1], [$2]), [m4_warning([Unknown $1 option `$2'])])[]dnl ]) # _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET]) # ------------------------------------------------------------ # Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. m4_define([_LT_IF_OPTION], [m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])]) # _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET) # ------------------------------------------------------- # Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME # are set. m4_define([_LT_UNLESS_OPTIONS], [m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option), [m4_define([$0_found])])])[]dnl m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3 ])[]dnl ]) # _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST) # ---------------------------------------- # OPTION-LIST is a space-separated list of Libtool options associated # with MACRO-NAME. If any OPTION has a matching handler declared with # LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about # the unknown option and exit. m4_defun([_LT_SET_OPTIONS], [# Set options m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), [_LT_SET_OPTION([$1], _LT_Option)]) m4_if([$1],[LT_INIT],[ dnl dnl Simply set some default values (i.e off) if boolean options were not dnl specified: _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no ]) _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no ]) dnl dnl If no reference was made to various pairs of opposing options, then dnl we run the default mode handler for the pair. For example, if neither dnl `shared' nor `disable-shared' was passed, we enable building of shared dnl archives by default: _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED]) _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC]) _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC]) _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install], [_LT_ENABLE_FAST_INSTALL]) ]) ])# _LT_SET_OPTIONS ## --------------------------------- ## ## Macros to handle LT_INIT options. ## ## --------------------------------- ## # _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME) # ----------------------------------------- m4_define([_LT_MANGLE_DEFUN], [[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])]) # LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE) # ----------------------------------------------- m4_define([LT_OPTION_DEFINE], [m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl ])# LT_OPTION_DEFINE # dlopen # ------ LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes ]) AU_DEFUN([AC_LIBTOOL_DLOPEN], [_LT_SET_OPTION([LT_INIT], [dlopen]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `dlopen' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], []) # win32-dll # --------- # Declare package support for building win32 dll's. LT_OPTION_DEFINE([LT_INIT], [win32-dll], [enable_win32_dll=yes case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*) AC_CHECK_TOOL(AS, as, false) AC_CHECK_TOOL(DLLTOOL, dlltool, false) AC_CHECK_TOOL(OBJDUMP, objdump, false) ;; esac test -z "$AS" && AS=as _LT_DECL([], [AS], [1], [Assembler program])dnl test -z "$DLLTOOL" && DLLTOOL=dlltool _LT_DECL([], [DLLTOOL], [1], [DLL creation program])dnl test -z "$OBJDUMP" && OBJDUMP=objdump _LT_DECL([], [OBJDUMP], [1], [Object dumper program])dnl ])# win32-dll AU_DEFUN([AC_LIBTOOL_WIN32_DLL], [AC_REQUIRE([AC_CANONICAL_HOST])dnl _LT_SET_OPTION([LT_INIT], [win32-dll]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `win32-dll' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], []) # _LT_ENABLE_SHARED([DEFAULT]) # ---------------------------- # implement the --enable-shared flag, and supports the `shared' and # `disable-shared' LT_INIT options. # DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. m4_define([_LT_ENABLE_SHARED], [m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([shared], [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@], [build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_shared=yes ;; no) enable_shared=no ;; *) enable_shared=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_shared=yes fi done IFS="$lt_save_ifs" ;; esac], [enable_shared=]_LT_ENABLE_SHARED_DEFAULT) _LT_DECL([build_libtool_libs], [enable_shared], [0], [Whether or not to build shared libraries]) ])# _LT_ENABLE_SHARED LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])]) # Old names: AC_DEFUN([AC_ENABLE_SHARED], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared]) ]) AC_DEFUN([AC_DISABLE_SHARED], [_LT_SET_OPTION([LT_INIT], [disable-shared]) ]) AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)]) AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_ENABLE_SHARED], []) dnl AC_DEFUN([AM_DISABLE_SHARED], []) # _LT_ENABLE_STATIC([DEFAULT]) # ---------------------------- # implement the --enable-static flag, and support the `static' and # `disable-static' LT_INIT options. # DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. m4_define([_LT_ENABLE_STATIC], [m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([static], [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@], [build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_static=yes ;; no) enable_static=no ;; *) enable_static=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_static=yes fi done IFS="$lt_save_ifs" ;; esac], [enable_static=]_LT_ENABLE_STATIC_DEFAULT) _LT_DECL([build_old_libs], [enable_static], [0], [Whether or not to build static libraries]) ])# _LT_ENABLE_STATIC LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])]) # Old names: AC_DEFUN([AC_ENABLE_STATIC], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static]) ]) AC_DEFUN([AC_DISABLE_STATIC], [_LT_SET_OPTION([LT_INIT], [disable-static]) ]) AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)]) AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_ENABLE_STATIC], []) dnl AC_DEFUN([AM_DISABLE_STATIC], []) # _LT_ENABLE_FAST_INSTALL([DEFAULT]) # ---------------------------------- # implement the --enable-fast-install flag, and support the `fast-install' # and `disable-fast-install' LT_INIT options. # DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. m4_define([_LT_ENABLE_FAST_INSTALL], [m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([fast-install], [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@], [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_fast_install=yes ;; no) enable_fast_install=no ;; *) enable_fast_install=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_fast_install=yes fi done IFS="$lt_save_ifs" ;; esac], [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT) _LT_DECL([fast_install], [enable_fast_install], [0], [Whether or not to optimize for fast installation])dnl ])# _LT_ENABLE_FAST_INSTALL LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])]) # Old names: AU_DEFUN([AC_ENABLE_FAST_INSTALL], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `fast-install' option into LT_INIT's first parameter.]) ]) AU_DEFUN([AC_DISABLE_FAST_INSTALL], [_LT_SET_OPTION([LT_INIT], [disable-fast-install]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `disable-fast-install' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], []) dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], []) # _LT_WITH_PIC([MODE]) # -------------------- # implement the --with-pic flag, and support the `pic-only' and `no-pic' # LT_INIT options. # MODE is either `yes' or `no'. If omitted, it defaults to `both'. m4_define([_LT_WITH_PIC], [AC_ARG_WITH([pic], [AS_HELP_STRING([--with-pic@<:@=PKGS@:>@], [try to use only PIC/non-PIC objects @<:@default=use both@:>@])], [lt_p=${PACKAGE-default} case $withval in yes|no) pic_mode=$withval ;; *) pic_mode=default # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for lt_pkg in $withval; do IFS="$lt_save_ifs" if test "X$lt_pkg" = "X$lt_p"; then pic_mode=yes fi done IFS="$lt_save_ifs" ;; esac], [pic_mode=default]) test -z "$pic_mode" && pic_mode=m4_default([$1], [default]) _LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl ])# _LT_WITH_PIC LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])]) LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])]) # Old name: AU_DEFUN([AC_LIBTOOL_PICMODE], [_LT_SET_OPTION([LT_INIT], [pic-only]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `pic-only' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_PICMODE], []) ## ----------------- ## ## LTDL_INIT Options ## ## ----------------- ## m4_define([_LTDL_MODE], []) LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive], [m4_define([_LTDL_MODE], [nonrecursive])]) LT_OPTION_DEFINE([LTDL_INIT], [recursive], [m4_define([_LTDL_MODE], [recursive])]) LT_OPTION_DEFINE([LTDL_INIT], [subproject], [m4_define([_LTDL_MODE], [subproject])]) m4_define([_LTDL_TYPE], []) LT_OPTION_DEFINE([LTDL_INIT], [installable], [m4_define([_LTDL_TYPE], [installable])]) LT_OPTION_DEFINE([LTDL_INIT], [convenience], [m4_define([_LTDL_TYPE], [convenience])]) sipxtapi-3.3.0~test17/m4/ltsugar.m40000644000175000017500000001042412321250471017637 0ustar00danieldaniel00000000000000# ltsugar.m4 -- libtool m4 base layer. -*-Autoconf-*- # # Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc. # Written by Gary V. Vaughan, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 6 ltsugar.m4 # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])]) # lt_join(SEP, ARG1, [ARG2...]) # ----------------------------- # Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their # associated separator. # Needed until we can rely on m4_join from Autoconf 2.62, since all earlier # versions in m4sugar had bugs. m4_define([lt_join], [m4_if([$#], [1], [], [$#], [2], [[$2]], [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])]) m4_define([_lt_join], [m4_if([$#$2], [2], [], [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])]) # lt_car(LIST) # lt_cdr(LIST) # ------------ # Manipulate m4 lists. # These macros are necessary as long as will still need to support # Autoconf-2.59 which quotes differently. m4_define([lt_car], [[$1]]) m4_define([lt_cdr], [m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])], [$#], 1, [], [m4_dquote(m4_shift($@))])]) m4_define([lt_unquote], $1) # lt_append(MACRO-NAME, STRING, [SEPARATOR]) # ------------------------------------------ # Redefine MACRO-NAME to hold its former content plus `SEPARATOR'`STRING'. # Note that neither SEPARATOR nor STRING are expanded; they are appended # to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked). # No SEPARATOR is output if MACRO-NAME was previously undefined (different # than defined and empty). # # This macro is needed until we can rely on Autoconf 2.62, since earlier # versions of m4sugar mistakenly expanded SEPARATOR but not STRING. m4_define([lt_append], [m4_define([$1], m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])]) # lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...]) # ---------------------------------------------------------- # Produce a SEP delimited list of all paired combinations of elements of # PREFIX-LIST with SUFFIX1 through SUFFIXn. Each element of the list # has the form PREFIXmINFIXSUFFIXn. # Needed until we can rely on m4_combine added in Autoconf 2.62. m4_define([lt_combine], [m4_if(m4_eval([$# > 3]), [1], [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl [[m4_foreach([_Lt_prefix], [$2], [m4_foreach([_Lt_suffix], ]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[, [_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])]) # lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ]) # ----------------------------------------------------------------------- # Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited # by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ. m4_define([lt_if_append_uniq], [m4_ifdef([$1], [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1], [lt_append([$1], [$2], [$3])$4], [$5])], [lt_append([$1], [$2], [$3])$4])]) # lt_dict_add(DICT, KEY, VALUE) # ----------------------------- m4_define([lt_dict_add], [m4_define([$1($2)], [$3])]) # lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE) # -------------------------------------------- m4_define([lt_dict_add_subkey], [m4_define([$1($2:$3)], [$4])]) # lt_dict_fetch(DICT, KEY, [SUBKEY]) # ---------------------------------- m4_define([lt_dict_fetch], [m4_ifval([$3], m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]), m4_ifdef([$1($2)], [m4_defn([$1($2)])]))]) # lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE]) # ----------------------------------------------------------------- m4_define([lt_if_dict_fetch], [m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4], [$5], [$6])]) # lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...]) # -------------------------------------------------------------- m4_define([lt_dict_filter], [m4_if([$5], [], [], [lt_join(m4_quote(m4_default([$4], [[, ]])), lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]), [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl ]) sipxtapi-3.3.0~test17/m4/ltversion.m40000644000175000017500000000126212321250471020203 0ustar00danieldaniel00000000000000# ltversion.m4 -- version numbers -*- Autoconf -*- # # Copyright (C) 2004 Free Software Foundation, Inc. # Written by Scott James Remnant, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # @configure_input@ # serial 3337 ltversion.m4 # This file is part of GNU Libtool m4_define([LT_PACKAGE_VERSION], [2.4.2]) m4_define([LT_PACKAGE_REVISION], [1.3337]) AC_DEFUN([LTVERSION_VERSION], [macro_version='2.4.2' macro_revision='1.3337' _LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?]) _LT_DECL(, macro_revision, 0) ]) sipxtapi-3.3.0~test17/m4/lt~obsolete.m40000644000175000017500000001375612321250471020543 0ustar00danieldaniel00000000000000# lt~obsolete.m4 -- aclocal satisfying obsolete definitions. -*-Autoconf-*- # # Copyright (C) 2004, 2005, 2007, 2009 Free Software Foundation, Inc. # Written by Scott James Remnant, 2004. # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 5 lt~obsolete.m4 # These exist entirely to fool aclocal when bootstrapping libtool. # # In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN) # which have later been changed to m4_define as they aren't part of the # exported API, or moved to Autoconf or Automake where they belong. # # The trouble is, aclocal is a bit thick. It'll see the old AC_DEFUN # in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us # using a macro with the same name in our local m4/libtool.m4 it'll # pull the old libtool.m4 in (it doesn't see our shiny new m4_define # and doesn't know about Autoconf macros at all.) # # So we provide this file, which has a silly filename so it's always # included after everything else. This provides aclocal with the # AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything # because those macros already exist, or will be overwritten later. # We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. # # Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here. # Yes, that means every name once taken will need to remain here until # we give up compatibility with versions before 1.7, at which point # we need to keep only those names which we still refer to. # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])]) m4_ifndef([AC_LIBTOOL_LINKER_OPTION], [AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])]) m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP])]) m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])]) m4_ifndef([_LT_AC_SHELL_INIT], [AC_DEFUN([_LT_AC_SHELL_INIT])]) m4_ifndef([_LT_AC_SYS_LIBPATH_AIX], [AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])]) m4_ifndef([_LT_PROG_LTMAIN], [AC_DEFUN([_LT_PROG_LTMAIN])]) m4_ifndef([_LT_AC_TAGVAR], [AC_DEFUN([_LT_AC_TAGVAR])]) m4_ifndef([AC_LTDL_ENABLE_INSTALL], [AC_DEFUN([AC_LTDL_ENABLE_INSTALL])]) m4_ifndef([AC_LTDL_PREOPEN], [AC_DEFUN([AC_LTDL_PREOPEN])]) m4_ifndef([_LT_AC_SYS_COMPILER], [AC_DEFUN([_LT_AC_SYS_COMPILER])]) m4_ifndef([_LT_AC_LOCK], [AC_DEFUN([_LT_AC_LOCK])]) m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE], [AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])]) m4_ifndef([_LT_AC_TRY_DLOPEN_SELF], [AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])]) m4_ifndef([AC_LIBTOOL_PROG_CC_C_O], [AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])]) m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])]) m4_ifndef([AC_LIBTOOL_OBJDIR], [AC_DEFUN([AC_LIBTOOL_OBJDIR])]) m4_ifndef([AC_LTDL_OBJDIR], [AC_DEFUN([AC_LTDL_OBJDIR])]) m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])]) m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP], [AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])]) m4_ifndef([AC_PATH_MAGIC], [AC_DEFUN([AC_PATH_MAGIC])]) m4_ifndef([AC_PROG_LD_GNU], [AC_DEFUN([AC_PROG_LD_GNU])]) m4_ifndef([AC_PROG_LD_RELOAD_FLAG], [AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])]) m4_ifndef([AC_DEPLIBS_CHECK_METHOD], [AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])]) m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])]) m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])]) m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])]) m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS], [AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])]) m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP], [AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])]) m4_ifndef([LT_AC_PROG_EGREP], [AC_DEFUN([LT_AC_PROG_EGREP])]) m4_ifndef([LT_AC_PROG_SED], [AC_DEFUN([LT_AC_PROG_SED])]) m4_ifndef([_LT_CC_BASENAME], [AC_DEFUN([_LT_CC_BASENAME])]) m4_ifndef([_LT_COMPILER_BOILERPLATE], [AC_DEFUN([_LT_COMPILER_BOILERPLATE])]) m4_ifndef([_LT_LINKER_BOILERPLATE], [AC_DEFUN([_LT_LINKER_BOILERPLATE])]) m4_ifndef([_AC_PROG_LIBTOOL], [AC_DEFUN([_AC_PROG_LIBTOOL])]) m4_ifndef([AC_LIBTOOL_SETUP], [AC_DEFUN([AC_LIBTOOL_SETUP])]) m4_ifndef([_LT_AC_CHECK_DLFCN], [AC_DEFUN([_LT_AC_CHECK_DLFCN])]) m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER], [AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])]) m4_ifndef([_LT_AC_TAGCONFIG], [AC_DEFUN([_LT_AC_TAGCONFIG])]) m4_ifndef([AC_DISABLE_FAST_INSTALL], [AC_DEFUN([AC_DISABLE_FAST_INSTALL])]) m4_ifndef([_LT_AC_LANG_CXX], [AC_DEFUN([_LT_AC_LANG_CXX])]) m4_ifndef([_LT_AC_LANG_F77], [AC_DEFUN([_LT_AC_LANG_F77])]) m4_ifndef([_LT_AC_LANG_GCJ], [AC_DEFUN([_LT_AC_LANG_GCJ])]) m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])]) m4_ifndef([_LT_AC_LANG_C_CONFIG], [AC_DEFUN([_LT_AC_LANG_C_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])]) m4_ifndef([_LT_AC_LANG_CXX_CONFIG], [AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])]) m4_ifndef([_LT_AC_LANG_F77_CONFIG], [AC_DEFUN([_LT_AC_LANG_F77_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])]) m4_ifndef([_LT_AC_LANG_GCJ_CONFIG], [AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])]) m4_ifndef([_LT_AC_LANG_RC_CONFIG], [AC_DEFUN([_LT_AC_LANG_RC_CONFIG])]) m4_ifndef([AC_LIBTOOL_CONFIG], [AC_DEFUN([AC_LIBTOOL_CONFIG])]) m4_ifndef([_LT_AC_FILE_LTDLL_C], [AC_DEFUN([_LT_AC_FILE_LTDLL_C])]) m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS], [AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])]) m4_ifndef([_LT_AC_PROG_CXXCPP], [AC_DEFUN([_LT_AC_PROG_CXXCPP])]) m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS], [AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])]) m4_ifndef([_LT_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])]) m4_ifndef([_LT_PROG_F77], [AC_DEFUN([_LT_PROG_F77])]) m4_ifndef([_LT_PROG_FC], [AC_DEFUN([_LT_PROG_FC])]) m4_ifndef([_LT_PROG_CXX], [AC_DEFUN([_LT_PROG_CXX])]) sipxtapi-3.3.0~test17/m4/sipXlib.m40000644000175000017500000005441512205613305017600 0ustar00danieldaniel00000000000000## ## Libs from SipFoundry ## ## Common C and C++ flags for pingtel related source AC_DEFUN([SFAC_INIT_FLAGS], [ ## TODO Remove cpu specifics and use make variables setup for this ## ## NOTES: ## -D__pingtel_on_posix__ - really used for linux v.s. other ## -D_REENTRANT - rougewave ? ## -fmessage-length=0 - ? ## AC_SUBST(SIPX_INCDIR, [${includedir}]) AC_SUBST(SIPX_LIBDIR, [${libdir}]) # Autoconf already provides a built-in abs_srcdir substitution, however, # while it specifies a root-directory rooted path, it can have relative # parts in the middle of it. For Doxygen STRIP_FROM_PATH, I need a full, # path to the project directory, without any relative bits at all. # Thus, sipx_abs_srcdir was conceived. SFAC_SRCDIR_EXPAND AC_SUBST(sipx_abs_srcdir, [${abs_srcdir}]) SF_CXX_C_FLAGS="-D__pingtel_on_posix__ -D_linux_ -D_REENTRANT -D_FILE_OFFSET_BITS=64 -fmessage-length=0" SF_CXX_WARNINGS="-Wall -Wformat -Wwrite-strings -Wpointer-arith" CXXFLAGS="$CXXFLAGS $SF_CXX_C_FLAGS $SF_CXX_WARNINGS" CFLAGS="$CFLAGS $SF_CXX_C_FLAGS $SF_CXX_WARNINGS -Wnested-externs -Wmissing-declarations -Wmissing-prototypes" ## NOTE: These are not expanded (e.g. contain $(prefix)) and are only ## fit for Makefiles. You can however write a Makefile that transforms ## *.in to * with the concrete values. ## ## See sipXconfig/Makefile.am for an example. ## See autoconf manual 4.7.2 Installation Directory Variables for why it's restricted ## AC_SUBST(SIPX_BINDIR, [${bindir}]) AC_SUBST(SIPX_CONFDIR, [${sysconfdir}/sipxpbx]) AC_SUBST(SIPX_DATADIR, [${datadir}/sipxpbx]) AC_SUBST(SIPX_LOGDIR, [${localstatedir}/log/sipxpbx]) AC_SUBST(SIPX_RUNDIR, [${localstatedir}/run/sipxpbx]) AC_SUBST(SIPX_TMPDIR, [${localstatedir}/tmp]) AC_SUBST(SIPX_DBDIR, [${localstatedir}/sipxdata/sipdb]) AC_SUBST(SIPX_SCHEMADIR, [${datadir}/sipx/schema]) AC_SUBST(SIPX_DOCDIR, [${datadir}/doc/sipx]) # temporary - see http://track.sipfoundry.org/browse/XPB-33 AC_SUBST(SIPX_VXMLDATADIR,[${localstatedir}/sipxdata/mediaserver/data]) AC_SUBST(SIPX_PARKMUSICDIR,[${localstatedir}/sipxdata/parkserver/music]) # temporary - see http://track.sipfoundry.org/browse/XPB-93 AC_SUBST(SIPX_BACKUPDIR, [${localstatedir}/sipxdata/backup]) AC_SUBST(SIPX_CONFIGPHONEDIR, [${localstatedir}/sipxdata/configserver/phone]) ## Used in a number of different project and subjective where this should really go ## INSTALL instruction assume default, otherwise safe to change/override AC_ARG_VAR(wwwdir, [Web root for web content, default is ${datadir}/www. \ WARNING: Adjust accordingly when following INSTALL instructions]) test -z $wwwdir && wwwdir='${datadir}/www' AC_ARG_VAR(SIPXPBXUSER, [The user that sipXpbx runs under, default is 'sipxchange']) test -z $SIPXPBXUSER && SIPXPBXUSER=sipxchange AC_SUBST(SIPXPHONECONF, [${sysconfdir}/sipxphone]) AC_SUBST(SIPXPHONEDATA, [${datadir}/sipxphone]) AC_SUBST(SIPXPHONELIB, [${datadir}/sipxphone/lib]) AC_ARG_ENABLE(rpmbuild, [ --enable-rpmbuild Build an rpm], enable_rpmbuild=yes ) AC_ARG_ENABLE(buildnumber, [ --enable-buildnumber enable build number as part of RPM name], enable_buildnumber=yes) ]) ## Check to see that we are using the minimum required version of automake AC_DEFUN([SFAC_AUTOMAKE_VERSION],[ AC_MSG_CHECKING(for automake version >= $1) sf_am_version=`automake --version | head -n 1 | awk '/^automake/ {print $NF}'` AX_COMPARE_VERSION( [$1], [le], [$sf_am_version], AC_MSG_RESULT( $sf_am_version is ok), AC_MSG_ERROR( found $sf_am_version - you must upgrade automake )) ]) ## sipXportLib # SFAC_LIB_PORT attempts to find the sf portability library and include # files by looking in /usr/[lib|include], /usr/local/[lib|include], and # relative paths. # # If not found, the configure is aborted. Otherwise, variables are defined # for both the INC and LIB paths # AND the paths are added to the CFLAGS and CXXFLAGS AC_DEFUN([SFAC_LIB_PORT], [ AC_REQUIRE([SFAC_INIT_FLAGS]) AC_REQUIRE([CHECK_PCRE]) AC_REQUIRE([CHECK_SSL]) SFAC_ARG_WITH_INCLUDE([os/OsDefs.h], [sipxportinc], [ --with-sipxportinc= portability include path ], [sipXportLib]) if test x_$foundpath != x_; then AC_MSG_RESULT($foundpath) else AC_MSG_ERROR('os/OsDefs.h' not found) fi SIPXPORTINC=$foundpath AC_SUBST(SIPXPORTINC) CFLAGS="-I$SIPXPORTINC $PCRE_CFLAGS $CFLAGS" CXXFLAGS="-I$SIPXPORTINC $PCRE_CXXFLAGS $CXXFLAGS" foundpath="" SFAC_ARG_WITH_INCLUDE([sipxunit/TestUtilities.h], [sipxportinc], [ --with-sipxportinc= portability include path ], [sipXportLib]) if test x_$foundpath != x_; then AC_MSG_RESULT($foundpath) else AC_MSG_ERROR('sipxunit/TestUtilities.h' not found) fi SIPXUNITINC=$foundpath AC_SUBST(SIPXUNITINC) CFLAGS="-I$SIPXUNITINC $CFLAGS" CXXFLAGS="-I$SIPXUNITINC $CXXFLAGS" foundpath="" SFAC_ARG_WITH_LIB([libsipXport.la], [sipxportlib], [ --with-sipxportlib= portability library path ], [sipXportLib]) if test x_$foundpath != x_; then AC_MSG_RESULT($foundpath) AC_SUBST(SIPXPORT_LIBS, "$foundpath/libsipXport.la") AC_SUBST(SIPXPORT_STATIC_LIBS, "$foundpath/libsipXport.a") AC_SUBST(SIPXPORT_LDFLAGS, "-L$foundpath") else AC_MSG_ERROR('libsipXport.la' not found) fi foundpath="" SFAC_ARG_WITH_LIB([libsipXunit.la], [sipxportlib], [ --with-sipxportlib= portability library path ], [sipXportLib]) if test x_$foundpath != x_; then AC_MSG_RESULT($foundpath) # sipXunit unitesting support AC_SUBST(SIPXUNIT_LDFLAGS, "-L$foundpath") AC_SUBST(SIPXUNIT_LIBS, "$foundpath/libsipXunit.la") else AC_MSG_ERROR('libsipXunit.la' not found) fi ]) # SFAC_LIB_PORT ## sipXtackLib # SFAC_LIB_STACK attempts to find the sf networking library and include # files by looking in /usr/[lib|include], /usr/local/[lib|include], and # relative paths. # # If not found, the configure is aborted. Otherwise, variables are defined # for both the INC and LIB paths AND the paths are added to the CFLAGS, # CXXFLAGS, LDFLAGS, and LIBS. AC_DEFUN([SFAC_LIB_STACK], [ AC_REQUIRE([SFAC_LIB_PORT]) AC_REQUIRE([SFAC_LIB_SDP]) SFAC_ARG_WITH_INCLUDE([net/SipUserAgent.h], [sipxtackinc], [ --with-sipxtackinc= sip stack include path ], [sipXtackLib]) if test x_$foundpath != x_; then AC_MSG_RESULT($foundpath) else AC_MSG_ERROR('net/SipUserAgent.h' not found) fi SIPXTACKINC=$foundpath AC_SUBST(SIPXTACKINC) if test "$SIPXTACKINC" != "$SIPXPORTINC" then CFLAGS="-I$SIPXTACKINC $CFLAGS" CXXFLAGS="-I$SIPXTACKINC $CXXFLAGS" fi if test x${disable_stream_player} != xtrue; then SFAC_ARG_WITH_LIB([libsipXtack.la], [sipxtacklib], [ --with-sipxtacklib= sip stack library path ], [sipXtackLib]) if test x_$foundpath != x_; then AC_MSG_RESULT($foundpath) else AC_MSG_ERROR('libsipXtack.la' not found) fi SIPXTACKLIB=$foundpath AC_SUBST(SIPXTACK_LIBS,["$SIPXTACKLIB/libsipXtack.la"]) AC_SUBST(SIPXTACK_STATIC_LIBS,["$SIPXTACKLIB/libsipXtack.a"]) AC_SUBST(SIPXTACK_LDFLAGS,["-L$SIPXTACKLIB"]) else AC_MSG_RESULT(Stream player is disabled - linking with sipXtackLib not required) fi ]) # SFAC_LIB_STACK ## sipXsdpLib # # If not found, the configure is aborted. Otherwise, variables are defined # for both the INC and LIB paths AND the paths are added to the CFLAGS, # CXXFLAGS, LDFLAGS, and LIBS. AC_DEFUN([SFAC_LIB_SDP], [ AC_REQUIRE([SFAC_LIB_PORT]) SFAC_ARG_WITH_INCLUDE([sdp/Sdp.h], [sipxsdpinc], [ --with-sipxsdpinc= sdp include path ], [sipXsdpLib]) if test x_$foundpath != x_; then AC_MSG_RESULT($foundpath) else AC_MSG_ERROR('sdp/Sdp.h' not found) fi SIPXSDPINC=$foundpath AC_SUBST(SIPXSDPINC) if test "$SIPXSDPINC" != "$SIPXPORTINC" then CFLAGS="-I$SIPXSDPINC $CFLAGS" CXXFLAGS="-I$SIPXSDPINC $CXXFLAGS" fi SFAC_ARG_WITH_LIB([libsipXsdp.la], [sipxsdplib], [ --with-sipxsdplib= sdp library path ], [sipXsdpLib]) if test x_$foundpath != x_; then AC_MSG_RESULT($foundpath) else AC_MSG_ERROR('libsipXsdp.la' not found) fi SIPXSDPLIB=$foundpath AC_SUBST(SIPXSDP_LIBS,["$SIPXSDPLIB/libsipXsdp.la"]) AC_SUBST(SIPXSDP_STATIC_LIBS,["$SIPXSDPLIB/libsipXsdp.a"]) AC_SUBST(SIPXSDP_LDFLAGS,["-L$SIPXSDPLIB"]) ]) # SFAC_LIB_SDP ## sipXmediaLib # SFAC_LIB_MEDIA attempts to find the sf media library and include # files by looking in /usr/[lib|include], /usr/local/[lib|include], and # relative paths. # # If not found, the configure is aborted. Otherwise, variables are defined # for both the INC and LIB paths AND the paths are added to the CFLAGS, # CXXFLAGS, LDFLAGS, and LIBS. AC_DEFUN([SFAC_LIB_MEDIA], [ AC_REQUIRE([SFAC_LIB_STACK]) SFAC_ARG_WITH_INCLUDE([mp/MpMediaTask.h], [sipxmediainc], [ --with-sipxmediainc= media library include path ], [sipXmediaLib]) if test x_$foundpath != x_; then AC_MSG_RESULT($foundpath) else AC_MSG_ERROR('mp/MpMediaTask.h' not found) fi SIPXMEDIAINC=$foundpath AC_SUBST(SIPXMEDIAINC) if test "$SIPXMEDIAINC" != "$SIPXTACKINC" then CFLAGS="-I$SIPXMEDIAINC $CFLAGS" CXXFLAGS="-I$SIPXMEDIAINC $CXXFLAGS" fi SFAC_ARG_WITH_LIB([libsipXmedia.la], [sipxmedialib], [ --with-sipxmedialib= media library path ], [sipXmediaLib]) if test x_$foundpath != x_; then AC_MSG_RESULT($foundpath) else AC_MSG_ERROR('libsipXmedia.la' not found) fi SIPXMEDIALIB=$foundpath AC_SUBST(SIPXMEDIA_LIBS, ["$SIPXMEDIALIB/libsipXmedia.la"]) AC_SUBST(SIPXMEDIA_STATIC_LIBS, ["$SIPXMEDIALIB/libsipXmedia.a"]) AC_SUBST(SIPXMEDIA_LDFLAGS, ["-L$SIPXMEDIALIB"]) ]) # SFAC_LIB_MEDIA ## sipXmediaProcessingLib # SFAC_LIB_MEDIA_PROCESSING attempts to find the sf media processing library and include # files by looking in /usr/[lib|include], /usr/local/[lib|include], and # relative paths. # # If not found, the configure is aborted. Otherwise, variables are defined # for both the INC and LIB paths AND the paths are added to the CFLAGS, # CXXFLAGS, LDFLAGS, and LIBS. AC_DEFUN([SFAC_LIB_MEDIA_PROCESSING], [ AC_REQUIRE([SFAC_LIB_MEDIA]) SFAC_ARG_WITH_INCLUDE([mi/CpMediaInterface.h], [sipxmediainterfaceinc], [ --with-sipxmediainterfaceinc= media interface library include path ], [sipXmediaAdapterLib]) if test x_$foundpath != x_; then AC_MSG_RESULT($foundpath) else AC_MSG_ERROR('mi/CpMediaInterface.h' not found) fi SIPXMEDIAINTERFACEINC=$foundpath AC_SUBST(SIPXMEDIAINTERFACEINC) if test "$SIPXMEDIAINTERFACEINC" != "$SIPXMEDIAINC" then CFLAGS="-I$SIPXMEDIAINTERFACEINC $CFLAGS" CXXFLAGS="-I$SIPXMEDIAINTERFACEINC $CXXFLAGS" fi SFAC_ARG_WITH_LIB([libsipXmediaProcessing.la], [sipxmediaprocessinglib], [ --with-sipxmediaprocessinglib= media library path ], [sipXmediaAdapterLib]) if test x_$foundpath != x_; then AC_MSG_RESULT($foundpath) else AC_MSG_ERROR('libsipXmediaProcessing.la' not found) fi SIPXMEDIAMPLIB=$foundpath AC_SUBST(SIPXMEDIA_MP_LIBS, ["$SIPXMEDIAMPLIB/libsipXmediaProcessing.la"]) AC_SUBST(SIPXMEDIA_MP_STATIC_LIBS, ["$SIPXMEDIAMPLIB/libsipXmediaProcessing.a"]) AC_SUBST(SIPXMEDIA_MP_LDFLAGS, ["-L$SIPXMEDIAMPLIB"]) ]) # SFAC_LIB_MEDIA_PROCESSING ## Optionally compile in the GIPS library in the media subsystem # (sipXmediaLib project) and executables that link it in # Conditionally use the GIPS audio libraries AC_DEFUN([CHECK_GIPSNEQ], [ AC_ARG_WITH(gipsneq, [ --with-gipsneq Compile the media subsystem with the GIPS audio libraries ], compile_with_gips=yes) AC_MSG_CHECKING(if link in with gips NetEQ) if test x$compile_with_gips = xyes then AC_MSG_RESULT(yes) SFAC_SRCDIR_EXPAND AC_MSG_CHECKING(for gips includes) # Define HAVE_GIPS for c pre-processor GIPS_CPPFLAGS=-DHAVE_GIPS if test -e $withval/include/GIPS/Vendor_gips_typedefs.h then gips_dir=$withval elif test -e $abs_srcdir/../sipXbuild/vendors/gips/include/GIPS/Vendor_gips_typedefs.h then gips_dir=$abs_srcdir/../sipXbuild/vendors/gips else AC_MSG_ERROR(GIPS/Vendor_gips_typedefs.h not found) fi AC_MSG_RESULT($gips_dir) # Add GIPS include path GIPSINC=$gips_dir/include # Add GIPS objects to be linked in GIPS_NEQ_OBJS=$gips_dir/GIPS_SuSE_i386.a CPPFLAGS="$CPPFLAGS $GIPS_CPPFLAGS -I$GIPSINC" # GIPS needs to be at the end of the list #LIBS="$LIBS $GIPS_OBJS" else AC_MSG_RESULT(no) fi AC_SUBST(GIPSINC) AC_SUBST(GIPS_NEQ_OBJS) AC_SUBST(GIPS_CPPFLAGS) ]) # CHECK_GIPSNEQ AC_DEFUN([CHECK_GIPSVE], [ AC_ARG_WITH(gipsve, [ --with-gipsve Link to GIPS voice engine if --with-gipsve is set], link_with_gipsve=yes) AC_MSG_CHECKING(if linking to gips voice engine) if test x$link_with_gipsve = xyes then AC_MSG_RESULT(yes) SFAC_SRCDIR_EXPAND AC_MSG_CHECKING(for gips includes) if test -e $abs_srcdir/../sipXbuild/vendors/gips/VoiceEngine/interface/GipsVoiceEngineLib.h then gips_dir=$abs_srcdir/../sipXbuild/vendors/gips else AC_MSG_ERROR(sipXbuild/vendors/gips/VoiceEngine/interface/GipsVoiceEngineLib.h not found) fi AC_MSG_RESULT($gips_dir) # Add GIPS include path GIPSINC=$gips_dir/VoiceEngine/interface CPPFLAGS="$CPPFLAGS -I$gips_dir/include -I$GIPSINC -DVOICE_ENGINE" # Add GIPS objects to be linked in if test "`uname`" == "Darwin"; then GIPS_VE_OBJS="$gips_dir/VoiceEngine/libraries/VoiceEngine_mac_ppc_gcc.a" else GIPS_VE_OBJS="$gips_dir/VoiceEngine/libraries/VoiceEngine_Linux_Alsa_gcc.a" fi else AC_MSG_RESULT(no) fi AC_SUBST(GIPSINC) AC_SUBST(GIPS_VE_OBJS) AC_SUBST(SIPXMEDIA_VE_LIBS, ["$SIPXMEDIALIB/libsipXvoiceEngine.la"]) AC_SUBST(SIPXMEDIA_VE_STATIC_LIBS, ["$SIPXMEDIALIB/libsipXvoiceEngine.a"]) AM_CONDITIONAL(BUILDVE, test x$link_with_gipsve = xyes) ]) # CHECK_GIPSVE AC_DEFUN([CHECK_GIPSCE], [ AC_ARG_WITH(gipsce, [ --with-gipsce Link to GIPS conference engine if --with-gipsce is set], link_with_gipsce=yes) AC_MSG_CHECKING(if linking to gips conference engine) if test x$link_with_gipsce = xyes then AC_MSG_RESULT(yes) SFAC_SRCDIR_EXPAND AC_MSG_CHECKING(for gips includes) if test -e $abs_srcdir/../sipXbuild/vendors/gips/ConferenceEngine/interface/ConferenceEngine.h then gips_dir=$abs_srcdir/../sipXbuild/vendors/gips else AC_MSG_ERROR(sipXbuild/vendors/gips/ConferenceEngine/interface/ConferenceEngine.h not found) fi AC_MSG_RESULT($gips_dir) # Add GIPS include path GIPSINC=$gips_dir/ConferenceEngine/interface CPPFLAGS="$CPPFLAGS -I$gips_dir/include -I$GIPSINC -DVOICE_ENGINE" # Add GIPS objects to be linked in GIPS_CE_OBJS="$gips_dir/ConferenceEngine/libraries/ConferenceEngine_Linux_gcc.a" else AC_MSG_RESULT(no) fi AC_SUBST(GIPSINC) AC_SUBST(GIPS_CE_OBJS) AC_SUBST(SIPXMEDIA_CE_LIBS, ["$SIPXMEDIALIB/libsipXconferenceEngine.la"]) AM_CONDITIONAL(BUILDCE, test x$link_with_gipsce = xyes) ]) # CHECK_GIPSCE AC_DEFUN([CHECK_VIDEO], [ AC_ARG_ENABLE(video, [ --enable-video Include video support (no)], [], [enable_video=no]) AC_MSG_CHECKING(for video (--enable-video)) if test x$enable_video != xno then AC_MSG_RESULT(yes) VIDEO_DEFINE=-DVIDEO AC_SUBST(VIDEO_DEFINE) else AC_MSG_RESULT(no) fi ]) # CHECK_VIDEO ## sipXcallLib # SFAC_LIB_CALL attempts to find the sf call processing library and include # files by looking in /usr/[lib|include], /usr/local/[lib|include], and # relative paths. # # If not found, the configure is aborted. Otherwise, variables are defined # for both the INC and LIB paths AND the paths are added to the CFLAGS, # CXXFLAGS, LDFLAGS, and LIBS. AC_DEFUN([SFAC_LIB_CALL], [ AC_REQUIRE([SFAC_LIB_MEDIA_PROCESSING]) SFAC_ARG_WITH_INCLUDE([cp/CallManager.h], [sipxcallinc], [ --with-sipxcallinc= call processing library include path ], [sipXcallLib]) if test x_$foundpath != x_; then AC_MSG_RESULT($foundpath) else AC_MSG_ERROR('cp/CallManager.h' not found) fi SIPXCALLINC=$foundpath AC_SUBST(SIPXCALLINC) if test "$SIPXCALLINC" != "$SIPXPORTINC" then CFLAGS="-I$SIPXCALLINC $CFLAGS" CXXFLAGS="-I$SIPXCALLINC $CXXFLAGS" fi SFAC_ARG_WITH_LIB([libsipXcall.la], [sipxcalllib], [ --with-sipxcalllib= call processing library path ], [sipXcallLib]) if test x_$foundpath != x_; then AC_MSG_RESULT($foundpath) else AC_MSG_ERROR('libsipXcall.la' not found) fi SIPXCALLLIB=$foundpath AC_SUBST(SIPXCALL_LIBS, ["$SIPXCALLLIB/libsipXcall.la"]) AC_SUBST(SIPXCALL_STATIC_LIBS, ["$SIPXCALLLIB/libsipXcall.a"]) AC_SUBST(SIPXCALL_LDFLAGS,["-L$SIPXCALLLIB"]) ]) # SFAC_LIB_CALL ## sipXcommserverLib # SFAC_LIB_CALL attempts to find the sf communication server library and # include files by looking in /usr/[lib|include], /usr/local/[lib|include], # and relative paths. # # If not found, the configure is aborted. Otherwise, variables are defined # for both the INC and LIB paths AND the paths are added to the CFLAGS, # CXXFLAGS, LDFLAGS, and LIBS. AC_DEFUN([SFAC_LIB_COMMSERVER], [ AC_REQUIRE([SFAC_LIB_STACK]) SFAC_ARG_WITH_INCLUDE([sipdb/SIPDBManager.h], [sipxcommserverinc], [ --with-sipxcommserverinc= call processing library include path ], [sipXcommserverLib]) if test x_$foundpath != x_; then AC_MSG_RESULT($foundpath) else AC_MSG_ERROR('sipdb/SIPDBManager.h' not found) fi SIPXCOMMSERVERINC=$foundpath if test "$SIPXCOMMSERVERINC" != "$SIPXPORTINC" then CFLAGS="-I$SIPXCOMMSERVERINC $CFLAGS" CXXFLAGS="-I$SIPXCOMMSERVERINC $CXXFLAGS" fi AC_SUBST(SIPXCOMMSERVERINC) SFAC_ARG_WITH_LIB([libsipXcommserver.la], [sipxcommserverlib], [ --with-sipxcommserverlib= call processing library path ], [sipXcommserverLib]) if test x_$foundpath != x_; then AC_MSG_RESULT($foundpath) else AC_MSG_ERROR('libsipXcommserver.la' not found) fi SIPXCOMMSERVERLIB=$foundpath AC_SUBST(SIPXCOMMSERVER_LIBS, ["$SIPXCOMMSERVERLIB/libsipXcommserver.la"]) AC_SUBST(SIPXCOMMSERVER_LDFLAGS,["-L$SIPXCOMMSERVERLIB"]) ]) # SFAC_LIB_COMMSERVER ## Generic find of an include # Fed from AC_DEFUN([SFAC_INCLUDE_{module name here}], # # $1 - sample include file # $2 - variable name (for overridding with --with-$2 # $3 - help text # $4 - directory name (assumed parallel with this script) AC_DEFUN([SFAC_ARG_WITH_INCLUDE], [ SFAC_SRCDIR_EXPAND() AC_MSG_CHECKING(for [$4] includes) AC_ARG_WITH( [$2], [ [$3] ], [ include_path=$withval ], [ include_path="$includedir $prefix/include /usr/include /usr/local/include [$abs_srcdir]/../[$4]/interface [$abs_srcdir]/../[$4]/include [$abs_srcdir]/../[$4]/src/test" ] ) for dir in $include_path ; do if test -f "$dir/[$1]"; then foundpath=$dir; break; fi; done if test x_$foundpath = x_; then AC_MSG_ERROR("'$1' not found; searched $include_path") fi ]) # SFAC_ARG_WITH_INCLUDE ## Generic find of a library # Fed from AC_DEFUN([SFAC_LIB_{module name here}], # # $1 - sample lib file # $2 - variable name (for overridding with --with-$2 # $3 - help text # $4 - directory name (assumed parallel with this script) AC_DEFUN([SFAC_ARG_WITH_LIB], [ SFAC_SRCDIR_EXPAND() AC_MSG_CHECKING(for [$4] libraries) AC_ARG_WITH( [$2], [ [$3] ], [ lib_path=$withval ], [ lib_path="$libdir $prefix/lib /usr/lib /usr/local/lib `pwd`/../[$4]/src `pwd`/../[$4]/sipXmediaMediaProcessing/src `pwd`/../[$4]/src/test/sipxunit `pwd`/../[$4]/src/test/sipxportunit"] ) foundpath="" for dir in $lib_path ; do if test -f "$dir/[$1]"; then foundpath=$dir; break; fi; done if test x_$foundpath = x_; then AC_MSG_ERROR("'$1' not found; searched $lib_path") fi ]) # SFAC_ARG_WITH_LIB AC_DEFUN([SFAC_SRCDIR_EXPAND], [ abs_srcdir=`cd $srcdir && pwd` ]) AC_DEFUN([SFAC_FEATURE_SIP_TLS], [ AC_ARG_ENABLE(sip-tls, [ --enable-sip-tls enable support for sips: and transport=tls (no)], [], [enable_sip_tls=no]) AC_MSG_CHECKING([Support for SIP over TLS]) AC_MSG_RESULT(${enable_sip_tls}) if test "${enable_sip_tls}" = "yes" then CFLAGS="-DSIP_TLS $CFLAGS" CXXFLAGS="-DSIP_TLS $CXXFLAGS" fi AM_CONDITIONAL(BUILDTLS, test x$enable_sip_tls = xyes) ]) AC_DEFUN([SFAC_FEATURE_SIPX_EZPHONE], [ AC_REQUIRE([CHECK_WXWIDGETS]) AC_ARG_ENABLE(sipx-ezphone, [ --enable-sipx-ezphone build the sipXezPhone example application (no)], [], [enable_sipx_ezphone=no]) AC_MSG_CHECKING([Building sipXezPhone]) # If sipx-ezphone is requested, check for its prerequisites. if test x$enable_sipx_ezphone = xyes then if test x$enable_wxwidgets != xyes then AC_MSG_ERROR([wxWidgets is required for sipXezPhone]) enable_sipx_ezphone=no fi fi AM_CONDITIONAL(BUILDEZPHONE, test x$enable_sipx_ezphone = xyes) AC_MSG_RESULT(${enable_sipx_ezphone}) ]) sipxtapi-3.3.0~test17/README0000644000175000017500000000000012205613305016241 0ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/configure.ac0000644000175000017500000001660312321443717017676 0ustar00danieldaniel00000000000000# -*- Autoconf -*- # Process this file with autoconf to produce a configure script. AC_PREREQ(2.69) # test0 tarballs are not for any distribution AC_INIT(sipXtapi, 3.3.0~test17, sipxtapi-dev@list.sipfoundry.org) AC_CONFIG_SRCDIR([sipXportLib/src/os/OsConfigDb.cpp]) AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_MACRO_DIR([m4]) AM_INIT_AUTOMAKE([-Wno-extra-portability tar-ustar]) #AC_PREFIX_DEFAULT([/usr/local/sipx]) m4_ifdef([AM_PROG_AR], [AM_PROG_AR]) LT_INIT SFAC_AUTOMAKE_VERSION([1.11]) #CHECK_AUTOCONF # Configure pkg-config PKG_PROG_PKG_CONFIG AM_CONFIG_HEADER([config.h]) # Codec plugin loading uses dlopen, so we need to check for it here. AC_LIBTOOL_DLOPEN # Checks for programs. AC_PROG_CXX AC_PROG_CC # Check for cross compilation AM_CONDITIONAL(CROSS_COMPILING, test x$cross_compiling = xyes) # Dynamic extenition CHECH_DYNEXT # Checks for libraries. CHECK_COREAUDIO CHECK_CARBON #CHECK_LIBRT # Check for SpanDSP library CHECK_SPANDSP # Enable use of code that uses speex dsp library ENABLE_SPEEX_DSP # Look for GSM and Speex codecs CHECK_GSM ENABLE_CODEC_SPEEX CHECK_ILBC CHECK_PCMA_PCMU CHECK_TONES CHECK_L16 CHECK_G726 CHECK_G722 CHECK_AMR_AMRWB CHECK_OPUS # PCRE is mandatory PKG_CHECK_MODULES([DEPS_PCRE], [libpcre >= 4.5]) # OpenSSL is mandatory, find it or configure fails: CHECK_SSL # Checks for header files. AC_HEADER_DIRENT AC_HEADER_STDC AC_HEADER_SYS_WAIT AC_CHECK_HEADERS([arpa/inet.h fcntl.h limits.h malloc.h netdb.h netinet/in.h stdlib.h string.h sys/ioctl.h sys/socket.h sys/time.h unistd.h]) # Check CPPUnit - begin # can't be encapsulated as a function due to search path ordering issues AM_PATH_CPPUNIT(1.9, [ SIPX_UNIT_TARGET="sipxunit" ], [ SIPX_UNIT_TARGET="sipxportunit" CPPUNIT_CFLAGS=' -DNO_CPPUNIT -I$(top_srcdir)/sipXportLib/src/test/sipxportunit ' AC_MSG_WARN("cppunit not found") ] ) AC_SUBST(SIPX_UNIT_TARGET) AM_CONDITIONAL([BUILD_SIPXUNIT], [test "x$SIPX_UNIT_TARGET" == "xsipxunit" ]) AM_CONDITIONAL([BUILD_SIPXPORTUNIT], [test "x$SIPX_UNIT_TARGET" == "xsipxportunit" ]) # Check CPPUnit - end # Checks for typedefs, structures, and compiler characteristics. AC_HEADER_STDBOOL AC_C_CONST AC_TYPE_SIZE_T AC_HEADER_TIME AC_STRUCT_TM AC_TYPE_UID_T AC_C_VOLATILE # Checks for library functions. AC_FUNC_CLOSEDIR_VOID AC_FUNC_FORK AC_PROG_GCC_TRADITIONAL AC_FUNC_MALLOC AC_FUNC_MEMCMP AC_FUNC_MKTIME AC_FUNC_SELECT_ARGTYPES AC_TYPE_SIGNAL AC_FUNC_STAT AC_FUNC_STRFTIME AC_CHECK_FUNCS([clock_gettime getcwd gethostbyname gethostname gettimeofday inet_ntoa localtime_r memchr memset mkdir putenv rmdir select setenv socket strchr strdup strerror strrchr strstr strtol strtoul tzset]) # Check for toplogy flowgraph interface CHECK_GRAPH_INTERFACE # SPEEX detection and configuration code inside general.m4 cannot do # sub-configure with AC_CONFIG_SUBDIRS, since it would be called more # than once, so do it here, where we know it only happens once. #if test "x$contrib_speex_enabled" == "xyes"; then # # speex codec has it's own configure, so be sure to call it. # AC_CONFIG_SUBDIRS([contrib/libspeex]) #fi # Specify a SPEEX_CONTRIB make variable conditional upon using contrib speex. dnl Do not stick AM_CONDITIONAL inside a shell conditional. dnl If you do, automake will be confused, thus, it is in configure.ac. AM_CONDITIONAL(SPEEX_CONTRIB, [test "x$contrib_speex_enabled" == "xyes"]) # declaring other codecs staff DECLARE_CODECS_STAFF # Check stream player setting CHECK_STREAM_PLAYER if test ${disable_stream_player} = true; then AC_MSG_RESULT(Stream player is disabled) CXXFLAGS+=" -DDISABLE_STREAM_PLAYER " fi SFAC_INIT_FLAGS SFAC_FEATURE_SIP_TLS # Enable local audio support (microphone / speaker) AC_ARG_ENABLE(local-audio, [ --enable-local-audio Enable local audio (speaker and microphone), makes sense for CallFlowGraph only], [ case "${enableval}" in yes) enable_local_audio=true ;; no) enable_local_audio=false ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-local-audio) ;; esac],[enable_local_audio=false]) AM_CONDITIONAL(ENABLE_LOCAL_AUDIO, test x$enable_local_audio = xtrue) ENABLE_DOXYGEN AM_CONDITIONAL(DOC, test x$enable_doc = xyes) AM_CONDITIONAL(USE_BLDNO, test x$enable_buildnumber = xyes) ## Sipviewer is written in java and compiled w/ant so allow someone ## w/o java or ant to effectively ignore anything about this AC_ARG_ENABLE(sipviewer, [ --enable-sipviewer Compile java based sipviewer program (needs JVM)], , enable_sipviewer=no) AM_CONDITIONAL(SIPVIEWER, test x$enable_sipviewer = xyes) if test x$enable_sipviewer = xyes then ## SIPViewer is only part of project that uses java, so restrict ## test only if installing sipviewer CHECK_JDK CHECK_ANT fi AM_CONDITIONAL(USE_BLDNO, test x$enable_buildnumber = xyes) EXTERNAL_EXTENITIONS EXTERNAL_EXTENITIONS_MEDIA SPEACKER_SELECTION_CHECK # Conditionally use the GIPS audio libraries CHECK_GIPSNEQ CHECK_GIPSVE CHECK_GIPSCE CHECK_VIDEO SFAC_FEATURE_SIPX_EZPHONE # named is used in some sipXtackLib tests CHECK_NAMED AC_SEARCH_LIBS([clock_nanosleep],[rt posix4]) AC_CONFIG_FILES([ Makefile sipxtapi.spec bin/Makefile sipXcallLib/Makefile sipXcallLib/doc/Makefile sipXcallLib/examples/Makefile sipXcallLib/examples/sipXezPhone/Makefile sipXcallLib/include/Makefile sipXcallLib/src/Makefile sipXcallLib/src/test/Makefile sipXcallLib/src/test/tapi/Makefile sipXmediaAdapterLib/Makefile sipXmediaAdapterLib/interface/Makefile sipXmediaAdapterLib/sipXmediaMediaProcessing/Makefile sipXmediaAdapterLib/sipXmediaMediaProcessing/src/Makefile sipXmediaAdapterLib/sipXmediaMediaProcessing/src/test/Makefile sipXmediaAdapterLib/sipXmediaMediaProcessing/include/Makefile sipXmediaAdapterLib/examples/Makefile sipXmediaAdapterLib/doc/Makefile sipXmediaLib/Makefile sipXmediaLib/include/Makefile sipXmediaLib/src/Makefile sipXmediaLib/src/mp/codecs/Makefile sipXmediaLib/src/mp/codecs/plggsm/Makefile sipXmediaLib/src/mp/codecs/plgpcmapcmu/Makefile sipXmediaLib/src/mp/codecs/plgtones/Makefile sipXmediaLib/src/mp/codecs/plgl16/Makefile sipXmediaLib/src/mp/codecs/plgspeex/Makefile sipXmediaLib/src/mp/codecs/plgilbc/Makefile sipXmediaLib/src/mp/codecs/plgg726/Makefile sipXmediaLib/src/mp/codecs/plgg722/Makefile sipXmediaLib/src/mp/codecs/plgamr/Makefile sipXmediaLib/src/mp/codecs/plgamrwb/Makefile sipXmediaLib/src/mp/codecs/plgopus/Makefile sipXmediaLib/src/test/Makefile sipXmediaLib/doc/Makefile sipXportLib/Makefile sipXportLib/include/Makefile sipXportLib/src/Makefile sipXportLib/src/test/Makefile sipXportLib/src/test/sipxunit/Makefile sipXportLib/src/test/sipxportunit/Makefile sipXportLib/src/test/testplugin/Makefile sipXportLib/syslogviewer/Makefile sipXportLib/doc/Makefile sipXsdpLib/Makefile sipXsdpLib/include/Makefile sipXsdpLib/src/Makefile sipXsdpLib/src/test/Makefile sipXsdpLib/doc/Makefile sipXtackLib/Makefile sipXtackLib/include/Makefile sipXtackLib/src/Makefile sipXtackLib/meta/Makefile sipXtackLib/src/test/Makefile sipXtackLib/examples/Makefile sipXtackLib/examples/im/Makefile sipXtackLib/examples/xmlrpc/Makefile sipXtackLib/syslog2siptrace/Makefile sipXtackLib/siplog2siptrace/Makefile sipXtackLib/sipviewer/Makefile sipXtackLib/siptest/Makefile sipXtackLib/siptest/src/Makefile sipXtackLib/siptest/include/Makefile sipXtackLib/siptest/src/siptest/Makefile sipXtackLib/doc/Makefile ]) AC_OUTPUT sipxtapi-3.3.0~test17/aclocal.m40000644000175000017500000013365212321444774017260 0ustar00danieldaniel00000000000000# generated automatically by aclocal 1.11.6 -*- Autoconf -*- # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, # 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, # Inc. # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.69],, [m4_warning([this file was generated for autoconf 2.69. You have another version of autoconf. It may work, but is not guaranteed to. If you have problems, you may need to regenerate the build system entirely. To do so, use the procedure documented by the package, typically `autoreconf'.])]) dnl dnl AM_PATH_CPPUNIT(MINIMUM-VERSION, [ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]) dnl AC_DEFUN([AM_PATH_CPPUNIT], [ AC_ARG_WITH(cppunit-prefix,[ --with-cppunit-prefix=PFX Prefix where CppUnit is installed (optional)], cppunit_config_prefix="$withval", cppunit_config_prefix="") AC_ARG_WITH(cppunit-exec-prefix,[ --with-cppunit-exec-prefix=PFX Exec prefix where CppUnit is installed (optional)], cppunit_config_exec_prefix="$withval", cppunit_config_exec_prefix="") if test x$cppunit_config_exec_prefix != x ; then cppunit_config_args="$cppunit_config_args --exec-prefix=$cppunit_config_exec_prefix" if test x${CPPUNIT_CONFIG+set} != xset ; then CPPUNIT_CONFIG=$cppunit_config_exec_prefix/bin/cppunit-config fi fi if test x$cppunit_config_prefix != x ; then cppunit_config_args="$cppunit_config_args --prefix=$cppunit_config_prefix" if test x${CPPUNIT_CONFIG+set} != xset ; then CPPUNIT_CONFIG=$cppunit_config_prefix/bin/cppunit-config fi fi AC_PATH_PROG(CPPUNIT_CONFIG, cppunit-config, no) cppunit_version_min=$1 AC_MSG_CHECKING(for Cppunit - version >= $cppunit_version_min) no_cppunit="" if test "$CPPUNIT_CONFIG" = "no" ; then AC_MSG_RESULT(no) no_cppunit=yes else CPPUNIT_CFLAGS=`$CPPUNIT_CONFIG --cflags` CPPUNIT_LIBS=`$CPPUNIT_CONFIG --libs` cppunit_version=`$CPPUNIT_CONFIG --version` cppunit_major_version=`echo $cppunit_version | \ sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'` cppunit_minor_version=`echo $cppunit_version | \ sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'` cppunit_micro_version=`echo $cppunit_version | \ sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'` cppunit_major_min=`echo $cppunit_version_min | \ sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'` if test "x${cppunit_major_min}" = "x" ; then cppunit_major_min=0 fi cppunit_minor_min=`echo $cppunit_version_min | \ sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'` if test "x${cppunit_minor_min}" = "x" ; then cppunit_minor_min=0 fi cppunit_micro_min=`echo $cppunit_version_min | \ sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'` if test "x${cppunit_micro_min}" = "x" ; then cppunit_micro_min=0 fi cppunit_version_proper=`expr \ $cppunit_major_version \> $cppunit_major_min \| \ $cppunit_major_version \= $cppunit_major_min \& \ $cppunit_minor_version \> $cppunit_minor_min \| \ $cppunit_major_version \= $cppunit_major_min \& \ $cppunit_minor_version \= $cppunit_minor_min \& \ $cppunit_micro_version \>= $cppunit_micro_min ` if test "$cppunit_version_proper" = "1" ; then AC_MSG_RESULT([$cppunit_major_version.$cppunit_minor_version.$cppunit_micro_version]) else AC_MSG_RESULT(no) no_cppunit=yes fi fi if test "x$no_cppunit" = x ; then ifelse([$2], , :, [$2]) else CPPUNIT_CFLAGS="" CPPUNIT_LIBS="" ifelse([$3], , :, [$3]) fi AC_SUBST(CPPUNIT_CFLAGS) AC_SUBST(CPPUNIT_LIBS) ]) # pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*- # serial 1 (pkg-config-0.24) # # Copyright © 2004 Scott James Remnant . # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # PKG_PROG_PKG_CONFIG([MIN-VERSION]) # ---------------------------------- AC_DEFUN([PKG_PROG_PKG_CONFIG], [m4_pattern_forbid([^_?PKG_[A-Z_]+$]) m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$]) m4_pattern_allow([^PKG_CONFIG_(DISABLE_UNINSTALLED|TOP_BUILD_DIR|DEBUG_SPEW)$]) AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility]) AC_ARG_VAR([PKG_CONFIG_PATH], [directories to add to pkg-config's search path]) AC_ARG_VAR([PKG_CONFIG_LIBDIR], [path overriding pkg-config's built-in search path]) if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then AC_PATH_TOOL([PKG_CONFIG], [pkg-config]) fi if test -n "$PKG_CONFIG"; then _pkg_min_version=m4_default([$1], [0.9.0]) AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version]) if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) PKG_CONFIG="" fi fi[]dnl ])# PKG_PROG_PKG_CONFIG # PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) # # Check to see whether a particular set of modules exists. Similar # to PKG_CHECK_MODULES(), but does not set variables or print errors. # # Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG]) # only at the first occurence in configure.ac, so if the first place # it's called might be skipped (such as if it is within an "if", you # have to call PKG_CHECK_EXISTS manually # -------------------------------------------------------------- AC_DEFUN([PKG_CHECK_EXISTS], [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl if test -n "$PKG_CONFIG" && \ AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then m4_default([$2], [:]) m4_ifvaln([$3], [else $3])dnl fi]) # _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES]) # --------------------------------------------- m4_define([_PKG_CONFIG], [if test -n "$$1"; then pkg_cv_[]$1="$$1" elif test -n "$PKG_CONFIG"; then PKG_CHECK_EXISTS([$3], [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes ], [pkg_failed=yes]) else pkg_failed=untried fi[]dnl ])# _PKG_CONFIG # _PKG_SHORT_ERRORS_SUPPORTED # ----------------------------- AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED], [AC_REQUIRE([PKG_PROG_PKG_CONFIG]) if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi[]dnl ])# _PKG_SHORT_ERRORS_SUPPORTED # PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND], # [ACTION-IF-NOT-FOUND]) # # # Note that if there is a possibility the first call to # PKG_CHECK_MODULES might not happen, you should be sure to include an # explicit call to PKG_PROG_PKG_CONFIG in your configure.ac # # # -------------------------------------------------------------- AC_DEFUN([PKG_CHECK_MODULES], [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl pkg_failed=no AC_MSG_CHECKING([for $1]) _PKG_CONFIG([$1][_CFLAGS], [cflags], [$2]) _PKG_CONFIG([$1][_LIBS], [libs], [$2]) m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS and $1[]_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details.]) if test $pkg_failed = yes; then AC_MSG_RESULT([no]) _PKG_SHORT_ERRORS_SUPPORTED if test $_pkg_short_errors_supported = yes; then $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "$2" 2>&1` else $1[]_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "$2" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD m4_default([$4], [AC_MSG_ERROR( [Package requirements ($2) were not met: $$1_PKG_ERRORS Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. _PKG_TEXT])[]dnl ]) elif test $pkg_failed = untried; then AC_MSG_RESULT([no]) m4_default([$4], [AC_MSG_FAILURE( [The pkg-config script could not be found or is too old. Make sure it is in your PATH or set the PKG_CONFIG environment variable to the full path to pkg-config. _PKG_TEXT To get pkg-config, see .])[]dnl ]) else $1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS $1[]_LIBS=$pkg_cv_[]$1[]_LIBS AC_MSG_RESULT([yes]) $3 fi[]dnl ])# PKG_CHECK_MODULES # Copyright (C) 2002, 2003, 2005, 2006, 2007, 2008, 2011 Free Software # Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 1 # AM_AUTOMAKE_VERSION(VERSION) # ---------------------------- # Automake X.Y traces this macro to ensure aclocal.m4 has been # generated from the m4 files accompanying Automake X.Y. # (This private macro should not be called outside this file.) AC_DEFUN([AM_AUTOMAKE_VERSION], [am__api_version='1.11' dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to dnl require some minimum version. Point them to the right macro. m4_if([$1], [1.11.6], [], [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl ]) # _AM_AUTOCONF_VERSION(VERSION) # ----------------------------- # aclocal traces this macro to find the Autoconf version. # This is a private macro too. Using m4_define simplifies # the logic in aclocal, which can simply ignore this definition. m4_define([_AM_AUTOCONF_VERSION], []) # AM_SET_CURRENT_AUTOMAKE_VERSION # ------------------------------- # Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced. # This function is AC_REQUIREd by AM_INIT_AUTOMAKE. AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], [AM_AUTOMAKE_VERSION([1.11.6])dnl m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl _AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))]) # Copyright (C) 2011 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 1 # AM_PROG_AR([ACT-IF-FAIL]) # ------------------------- # Try to determine the archiver interface, and trigger the ar-lib wrapper # if it is needed. If the detection of archiver interface fails, run # ACT-IF-FAIL (default is to abort configure with a proper error message). AC_DEFUN([AM_PROG_AR], [AC_BEFORE([$0], [LT_INIT])dnl AC_BEFORE([$0], [AC_PROG_LIBTOOL])dnl AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl AC_REQUIRE_AUX_FILE([ar-lib])dnl AC_CHECK_TOOLS([AR], [ar lib "link -lib"], [false]) : ${AR=ar} AC_CACHE_CHECK([the archiver ($AR) interface], [am_cv_ar_interface], [am_cv_ar_interface=ar AC_COMPILE_IFELSE([AC_LANG_SOURCE([[int some_variable = 0;]])], [am_ar_try='$AR cru libconftest.a conftest.$ac_objext >&AS_MESSAGE_LOG_FD' AC_TRY_EVAL([am_ar_try]) if test "$ac_status" -eq 0; then am_cv_ar_interface=ar else am_ar_try='$AR -NOLOGO -OUT:conftest.lib conftest.$ac_objext >&AS_MESSAGE_LOG_FD' AC_TRY_EVAL([am_ar_try]) if test "$ac_status" -eq 0; then am_cv_ar_interface=lib else am_cv_ar_interface=unknown fi fi rm -f conftest.lib libconftest.a ]) ]) case $am_cv_ar_interface in ar) ;; lib) # Microsoft lib, so override with the ar-lib wrapper script. # FIXME: It is wrong to rewrite AR. # But if we don't then we get into trouble of one sort or another. # A longer-term fix would be to have automake use am__AR in this case, # and then we could set am__AR="$am_aux_dir/ar-lib \$(AR)" or something # similar. AR="$am_aux_dir/ar-lib $AR" ;; unknown) m4_default([$1], [AC_MSG_ERROR([could not determine $AR interface])]) ;; esac AC_SUBST([AR])dnl ]) # AM_AUX_DIR_EXPAND -*- Autoconf -*- # Copyright (C) 2001, 2003, 2005, 2011 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 1 # For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets # $ac_aux_dir to `$srcdir/foo'. In other projects, it is set to # `$srcdir', `$srcdir/..', or `$srcdir/../..'. # # Of course, Automake must honor this variable whenever it calls a # tool from the auxiliary directory. The problem is that $srcdir (and # therefore $ac_aux_dir as well) can be either absolute or relative, # depending on how configure is run. This is pretty annoying, since # it makes $ac_aux_dir quite unusable in subdirectories: in the top # source directory, any form will work fine, but in subdirectories a # relative path needs to be adjusted first. # # $ac_aux_dir/missing # fails when called from a subdirectory if $ac_aux_dir is relative # $top_srcdir/$ac_aux_dir/missing # fails if $ac_aux_dir is absolute, # fails when called from a subdirectory in a VPATH build with # a relative $ac_aux_dir # # The reason of the latter failure is that $top_srcdir and $ac_aux_dir # are both prefixed by $srcdir. In an in-source build this is usually # harmless because $srcdir is `.', but things will broke when you # start a VPATH build or use an absolute $srcdir. # # So we could use something similar to $top_srcdir/$ac_aux_dir/missing, # iff we strip the leading $srcdir from $ac_aux_dir. That would be: # am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"` # and then we would define $MISSING as # MISSING="\${SHELL} $am_aux_dir/missing" # This will work as long as MISSING is not called from configure, because # unfortunately $(top_srcdir) has no meaning in configure. # However there are other variables, like CC, which are often used in # configure, and could therefore not use this "fixed" $ac_aux_dir. # # Another solution, used here, is to always expand $ac_aux_dir to an # absolute PATH. The drawback is that using absolute paths prevent a # configured tree to be moved without reconfiguration. AC_DEFUN([AM_AUX_DIR_EXPAND], [dnl Rely on autoconf to set up CDPATH properly. AC_PREREQ([2.50])dnl # expand $ac_aux_dir to an absolute path am_aux_dir=`cd $ac_aux_dir && pwd` ]) # AM_CONDITIONAL -*- Autoconf -*- # Copyright (C) 1997, 2000, 2001, 2003, 2004, 2005, 2006, 2008 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 9 # AM_CONDITIONAL(NAME, SHELL-CONDITION) # ------------------------------------- # Define a conditional. AC_DEFUN([AM_CONDITIONAL], [AC_PREREQ(2.52)dnl ifelse([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl AC_SUBST([$1_TRUE])dnl AC_SUBST([$1_FALSE])dnl _AM_SUBST_NOTMAKE([$1_TRUE])dnl _AM_SUBST_NOTMAKE([$1_FALSE])dnl m4_define([_AM_COND_VALUE_$1], [$2])dnl if $2; then $1_TRUE= $1_FALSE='#' else $1_TRUE='#' $1_FALSE= fi AC_CONFIG_COMMANDS_PRE( [if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then AC_MSG_ERROR([[conditional "$1" was never defined. Usually this means the macro was only invoked conditionally.]]) fi])]) # Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2009, # 2010, 2011 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 12 # There are a few dirty hacks below to avoid letting `AC_PROG_CC' be # written in clear, in which case automake, when reading aclocal.m4, # will think it sees a *use*, and therefore will trigger all it's # C support machinery. Also note that it means that autoscan, seeing # CC etc. in the Makefile, will ask for an AC_PROG_CC use... # _AM_DEPENDENCIES(NAME) # ---------------------- # See how the compiler implements dependency checking. # NAME is "CC", "CXX", "GCJ", or "OBJC". # We try a few techniques and use that to set a single cache variable. # # We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was # modified to invoke _AM_DEPENDENCIES(CC); we would have a circular # dependency, and given that the user is not expected to run this macro, # just rely on AC_PROG_CC. AC_DEFUN([_AM_DEPENDENCIES], [AC_REQUIRE([AM_SET_DEPDIR])dnl AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl AC_REQUIRE([AM_MAKE_INCLUDE])dnl AC_REQUIRE([AM_DEP_TRACK])dnl ifelse([$1], CC, [depcc="$CC" am_compiler_list=], [$1], CXX, [depcc="$CXX" am_compiler_list=], [$1], OBJC, [depcc="$OBJC" am_compiler_list='gcc3 gcc'], [$1], UPC, [depcc="$UPC" am_compiler_list=], [$1], GCJ, [depcc="$GCJ" am_compiler_list='gcc3 gcc'], [depcc="$$1" am_compiler_list=]) AC_CACHE_CHECK([dependency style of $depcc], [am_cv_$1_dependencies_compiler_type], [if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named `D' -- because `-MD' means `put the output # in D'. rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_$1_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp` fi am__universal=false m4_case([$1], [CC], [case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac], [CXX], [case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac]) for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with # Solaris 8's {/usr,}/bin/sh. touch sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with `-c' and `-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle `-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # after this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok `-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_$1_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_$1_dependencies_compiler_type=none fi ]) AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type]) AM_CONDITIONAL([am__fastdep$1], [ test "x$enable_dependency_tracking" != xno \ && test "$am_cv_$1_dependencies_compiler_type" = gcc3]) ]) # AM_SET_DEPDIR # ------------- # Choose a directory name for dependency files. # This macro is AC_REQUIREd in _AM_DEPENDENCIES AC_DEFUN([AM_SET_DEPDIR], [AC_REQUIRE([AM_SET_LEADING_DOT])dnl AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl ]) # AM_DEP_TRACK # ------------ AC_DEFUN([AM_DEP_TRACK], [AC_ARG_ENABLE(dependency-tracking, [ --disable-dependency-tracking speeds up one-time build --enable-dependency-tracking do not reject slow dependency extractors]) if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' am__nodep='_no' fi AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) AC_SUBST([AMDEPBACKSLASH])dnl _AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl AC_SUBST([am__nodep])dnl _AM_SUBST_NOTMAKE([am__nodep])dnl ]) # Generate code to set up dependency tracking. -*- Autoconf -*- # Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2008 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. #serial 5 # _AM_OUTPUT_DEPENDENCY_COMMANDS # ------------------------------ AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS], [{ # Autoconf 2.62 quotes --file arguments for eval, but not when files # are listed without --file. Let's play safe and only enable the eval # if we detect the quoting. case $CONFIG_FILES in *\'*) eval set x "$CONFIG_FILES" ;; *) set x $CONFIG_FILES ;; esac shift for mf do # Strip MF so we end up with the name of the file. mf=`echo "$mf" | sed -e 's/:.*$//'` # Check whether this is an Automake generated Makefile or not. # We used to match only the files named `Makefile.in', but # some people rename them; so instead we look at the file content. # Grep'ing the first line is not enough: some people post-process # each Makefile.in and add a new line on top of each file to say so. # Grep'ing the whole file is not good either: AIX grep has a line # limit of 2048, but all sed's we know have understand at least 4000. if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then dirpart=`AS_DIRNAME("$mf")` else continue fi # Extract the definition of DEPDIR, am__include, and am__quote # from the Makefile without running `make'. DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` test -z "$DEPDIR" && continue am__include=`sed -n 's/^am__include = //p' < "$mf"` test -z "am__include" && continue am__quote=`sed -n 's/^am__quote = //p' < "$mf"` # When using ansi2knr, U may be empty or an underscore; expand it U=`sed -n 's/^U = //p' < "$mf"` # Find all dependency output files, they are included files with # $(DEPDIR) in their names. We invoke sed twice because it is the # simplest approach to changing $(DEPDIR) to its actual value in the # expansion. for file in `sed -n " s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do # Make sure the directory exists. test -f "$dirpart/$file" && continue fdir=`AS_DIRNAME(["$file"])` AS_MKDIR_P([$dirpart/$fdir]) # echo "creating $dirpart/$file" echo '# dummy' > "$dirpart/$file" done done } ])# _AM_OUTPUT_DEPENDENCY_COMMANDS # AM_OUTPUT_DEPENDENCY_COMMANDS # ----------------------------- # This macro should only be invoked once -- use via AC_REQUIRE. # # This code is only required when automatic dependency tracking # is enabled. FIXME. This creates each `.P' file that we will # need in order to bootstrap the dependency handling code. AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS], [AC_CONFIG_COMMANDS([depfiles], [test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS], [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"]) ]) # Copyright (C) 1996, 1997, 2000, 2001, 2003, 2005 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 8 # AM_CONFIG_HEADER is obsolete. It has been replaced by AC_CONFIG_HEADERS. AU_DEFUN([AM_CONFIG_HEADER], [AC_CONFIG_HEADERS($@)]) # Do all the work for Automake. -*- Autoconf -*- # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, # 2005, 2006, 2008, 2009 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 16 # This macro actually does too much. Some checks are only needed if # your package does certain things. But this isn't really a big deal. # AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE]) # AM_INIT_AUTOMAKE([OPTIONS]) # ----------------------------------------------- # The call with PACKAGE and VERSION arguments is the old style # call (pre autoconf-2.50), which is being phased out. PACKAGE # and VERSION should now be passed to AC_INIT and removed from # the call to AM_INIT_AUTOMAKE. # We support both call styles for the transition. After # the next Automake release, Autoconf can make the AC_INIT # arguments mandatory, and then we can depend on a new Autoconf # release and drop the old call support. AC_DEFUN([AM_INIT_AUTOMAKE], [AC_PREREQ([2.62])dnl dnl Autoconf wants to disallow AM_ names. We explicitly allow dnl the ones we care about. m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl AC_REQUIRE([AC_PROG_INSTALL])dnl if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl # test to see if srcdir already configured if test -f $srcdir/config.status; then AC_MSG_ERROR([source directory already configured; run "make distclean" there first]) fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi AC_SUBST([CYGPATH_W]) # Define the identity of the package. dnl Distinguish between old-style and new-style calls. m4_ifval([$2], [m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl AC_SUBST([PACKAGE], [$1])dnl AC_SUBST([VERSION], [$2])], [_AM_SET_OPTIONS([$1])dnl dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT. m4_if(m4_ifdef([AC_PACKAGE_NAME], 1)m4_ifdef([AC_PACKAGE_VERSION], 1), 11,, [m4_fatal([AC_INIT should be called with package and version arguments])])dnl AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl _AM_IF_OPTION([no-define],, [AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of package]) AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version number of package])])dnl # Some tools Automake needs. AC_REQUIRE([AM_SANITY_CHECK])dnl AC_REQUIRE([AC_ARG_PROGRAM])dnl AM_MISSING_PROG(ACLOCAL, aclocal-${am__api_version}) AM_MISSING_PROG(AUTOCONF, autoconf) AM_MISSING_PROG(AUTOMAKE, automake-${am__api_version}) AM_MISSING_PROG(AUTOHEADER, autoheader) AM_MISSING_PROG(MAKEINFO, makeinfo) AC_REQUIRE([AM_PROG_INSTALL_SH])dnl AC_REQUIRE([AM_PROG_INSTALL_STRIP])dnl AC_REQUIRE([AM_PROG_MKDIR_P])dnl # We need awk for the "check" target. The system "awk" is bad on # some platforms. AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([AC_PROG_MAKE_SET])dnl AC_REQUIRE([AM_SET_LEADING_DOT])dnl _AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])], [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], [_AM_PROG_TAR([v7])])]) _AM_IF_OPTION([no-dependencies],, [AC_PROVIDE_IFELSE([AC_PROG_CC], [_AM_DEPENDENCIES(CC)], [define([AC_PROG_CC], defn([AC_PROG_CC])[_AM_DEPENDENCIES(CC)])])dnl AC_PROVIDE_IFELSE([AC_PROG_CXX], [_AM_DEPENDENCIES(CXX)], [define([AC_PROG_CXX], defn([AC_PROG_CXX])[_AM_DEPENDENCIES(CXX)])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJC], [_AM_DEPENDENCIES(OBJC)], [define([AC_PROG_OBJC], defn([AC_PROG_OBJC])[_AM_DEPENDENCIES(OBJC)])])dnl ]) _AM_IF_OPTION([silent-rules], [AC_REQUIRE([AM_SILENT_RULES])])dnl dnl The `parallel-tests' driver may need to know about EXEEXT, so add the dnl `am__EXEEXT' conditional if _AM_COMPILER_EXEEXT was seen. This macro dnl is hooked onto _AC_COMPILER_EXEEXT early, see below. AC_CONFIG_COMMANDS_PRE(dnl [m4_provide_if([_AM_COMPILER_EXEEXT], [AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"])])])dnl ]) dnl Hook into `_AC_COMPILER_EXEEXT' early to learn its expansion. Do not dnl add the conditional right here, as _AC_COMPILER_EXEEXT may be further dnl mangled by Autoconf and run in a shell conditional statement. m4_define([_AC_COMPILER_EXEEXT], m4_defn([_AC_COMPILER_EXEEXT])[m4_provide([_AM_COMPILER_EXEEXT])]) # When config.status generates a header, we must update the stamp-h file. # This file resides in the same directory as the config header # that is generated. The stamp files are numbered to have different names. # Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the # loop where config.status creates the headers, so we can generate # our stamp files there. AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK], [# Compute $1's index in $config_headers. _am_arg=$1 _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count]) # Copyright (C) 2001, 2003, 2005, 2008, 2011 Free Software Foundation, # Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 1 # AM_PROG_INSTALL_SH # ------------------ # Define $install_sh. AC_DEFUN([AM_PROG_INSTALL_SH], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl if test x"${install_sh}" != xset; then case $am_aux_dir in *\ * | *\ *) install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; *) install_sh="\${SHELL} $am_aux_dir/install-sh" esac fi AC_SUBST(install_sh)]) # Copyright (C) 2003, 2005 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 2 # Check whether the underlying file-system supports filenames # with a leading dot. For instance MS-DOS doesn't. AC_DEFUN([AM_SET_LEADING_DOT], [rm -rf .tst 2>/dev/null mkdir .tst 2>/dev/null if test -d .tst; then am__leading_dot=. else am__leading_dot=_ fi rmdir .tst 2>/dev/null AC_SUBST([am__leading_dot])]) # Check to see how 'make' treats includes. -*- Autoconf -*- # Copyright (C) 2001, 2002, 2003, 2005, 2009 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 4 # AM_MAKE_INCLUDE() # ----------------- # Check to see how make treats includes. AC_DEFUN([AM_MAKE_INCLUDE], [am_make=${MAKE-make} cat > confinc << 'END' am__doit: @echo this is the am__doit target .PHONY: am__doit END # If we don't find an include directive, just comment out the code. AC_MSG_CHECKING([for style of include used by $am_make]) am__include="#" am__quote= _am_result=none # First try GNU make style include. echo "include confinc" > confmf # Ignore all kinds of additional output from `make'. case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=include am__quote= _am_result=GNU ;; esac # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=.include am__quote="\"" _am_result=BSD ;; esac fi AC_SUBST([am__include]) AC_SUBST([am__quote]) AC_MSG_RESULT([$_am_result]) rm -f confinc confmf ]) # Fake the existence of programs that GNU maintainers use. -*- Autoconf -*- # Copyright (C) 1997, 1999, 2000, 2001, 2003, 2004, 2005, 2008 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 6 # AM_MISSING_PROG(NAME, PROGRAM) # ------------------------------ AC_DEFUN([AM_MISSING_PROG], [AC_REQUIRE([AM_MISSING_HAS_RUN]) $1=${$1-"${am_missing_run}$2"} AC_SUBST($1)]) # AM_MISSING_HAS_RUN # ------------------ # Define MISSING if not defined so far and test if it supports --run. # If it does, set am_missing_run to use it, otherwise, to nothing. AC_DEFUN([AM_MISSING_HAS_RUN], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl AC_REQUIRE_AUX_FILE([missing])dnl if test x"${MISSING+set}" != xset; then case $am_aux_dir in *\ * | *\ *) MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; *) MISSING="\${SHELL} $am_aux_dir/missing" ;; esac fi # Use eval to expand $SHELL if eval "$MISSING --run true"; then am_missing_run="$MISSING --run " else am_missing_run= AC_MSG_WARN([`missing' script is too old or missing]) fi ]) # Copyright (C) 2003, 2004, 2005, 2006, 2011 Free Software Foundation, # Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 1 # AM_PROG_MKDIR_P # --------------- # Check for `mkdir -p'. AC_DEFUN([AM_PROG_MKDIR_P], [AC_PREREQ([2.60])dnl AC_REQUIRE([AC_PROG_MKDIR_P])dnl dnl Automake 1.8 to 1.9.6 used to define mkdir_p. We now use MKDIR_P, dnl while keeping a definition of mkdir_p for backward compatibility. dnl @MKDIR_P@ is magic: AC_OUTPUT adjusts its value for each Makefile. dnl However we cannot define mkdir_p as $(MKDIR_P) for the sake of dnl Makefile.ins that do not define MKDIR_P, so we do our own dnl adjustment using top_builddir (which is defined more often than dnl MKDIR_P). AC_SUBST([mkdir_p], ["$MKDIR_P"])dnl case $mkdir_p in [[\\/$]]* | ?:[[\\/]]*) ;; */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;; esac ]) # Helper functions for option handling. -*- Autoconf -*- # Copyright (C) 2001, 2002, 2003, 2005, 2008, 2010 Free Software # Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 5 # _AM_MANGLE_OPTION(NAME) # ----------------------- AC_DEFUN([_AM_MANGLE_OPTION], [[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])]) # _AM_SET_OPTION(NAME) # -------------------- # Set option NAME. Presently that only means defining a flag for this option. AC_DEFUN([_AM_SET_OPTION], [m4_define(_AM_MANGLE_OPTION([$1]), 1)]) # _AM_SET_OPTIONS(OPTIONS) # ------------------------ # OPTIONS is a space-separated list of Automake options. AC_DEFUN([_AM_SET_OPTIONS], [m4_foreach_w([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])]) # _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET]) # ------------------------------------------- # Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. AC_DEFUN([_AM_IF_OPTION], [m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])]) # Copyright (C) 2001, 2003, 2005, 2011 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 1 # AM_RUN_LOG(COMMAND) # ------------------- # Run COMMAND, save the exit status in ac_status, and log it. # (This has been adapted from Autoconf's _AC_RUN_LOG macro.) AC_DEFUN([AM_RUN_LOG], [{ echo "$as_me:$LINENO: $1" >&AS_MESSAGE_LOG_FD ($1) >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD (exit $ac_status); }]) # Check to make sure that the build environment is sane. -*- Autoconf -*- # Copyright (C) 1996, 1997, 2000, 2001, 2003, 2005, 2008 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 5 # AM_SANITY_CHECK # --------------- AC_DEFUN([AM_SANITY_CHECK], [AC_MSG_CHECKING([whether build environment is sane]) # Just in case sleep 1 echo timestamp > conftest.file # Reject unsafe characters in $srcdir or the absolute working directory # name. Accept space and tab only in the latter. am_lf=' ' case `pwd` in *[[\\\"\#\$\&\'\`$am_lf]]*) AC_MSG_ERROR([unsafe absolute working directory name]);; esac case $srcdir in *[[\\\"\#\$\&\'\`$am_lf\ \ ]]*) AC_MSG_ERROR([unsafe srcdir value: `$srcdir']);; esac # Do `set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` if test "$[*]" = "X"; then # -L didn't work. set X `ls -t "$srcdir/configure" conftest.file` fi rm -f conftest.file if test "$[*]" != "X $srcdir/configure conftest.file" \ && test "$[*]" != "X conftest.file $srcdir/configure"; then # If neither matched, then we have a broken ls. This can happen # if, for instance, CONFIG_SHELL is bash and it inherits a # broken ls alias from the environment. This has actually # happened. Such a system could not be considered "sane". AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken alias in your environment]) fi test "$[2]" = conftest.file ) then # Ok. : else AC_MSG_ERROR([newly created file is older than distributed files! Check your system clock]) fi AC_MSG_RESULT(yes)]) # Copyright (C) 2001, 2003, 2005, 2011 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 1 # AM_PROG_INSTALL_STRIP # --------------------- # One issue with vendor `install' (even GNU) is that you can't # specify the program used to strip binaries. This is especially # annoying in cross-compiling environments, where the build's strip # is unlikely to handle the host's binaries. # Fortunately install-sh will honor a STRIPPROG variable, so we # always use install-sh in `make install-strip', and initialize # STRIPPROG with the value of the STRIP variable (set by the user). AC_DEFUN([AM_PROG_INSTALL_STRIP], [AC_REQUIRE([AM_PROG_INSTALL_SH])dnl # Installed binaries are usually stripped using `strip' when the user # run `make install-strip'. However `strip' might not be the right # tool to use in cross-compilation environments, therefore Automake # will honor the `STRIP' environment variable to overrule this program. dnl Don't test for $cross_compiling = yes, because it might be `maybe'. if test "$cross_compiling" != no; then AC_CHECK_TOOL([STRIP], [strip], :) fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" AC_SUBST([INSTALL_STRIP_PROGRAM])]) # Copyright (C) 2006, 2008, 2010 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 3 # _AM_SUBST_NOTMAKE(VARIABLE) # --------------------------- # Prevent Automake from outputting VARIABLE = @VARIABLE@ in Makefile.in. # This macro is traced by Automake. AC_DEFUN([_AM_SUBST_NOTMAKE]) # AM_SUBST_NOTMAKE(VARIABLE) # -------------------------- # Public sister of _AM_SUBST_NOTMAKE. AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)]) # Check how to create a tarball. -*- Autoconf -*- # Copyright (C) 2004, 2005, 2012 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 2 # _AM_PROG_TAR(FORMAT) # -------------------- # Check how to create a tarball in format FORMAT. # FORMAT should be one of `v7', `ustar', or `pax'. # # Substitute a variable $(am__tar) that is a command # writing to stdout a FORMAT-tarball containing the directory # $tardir. # tardir=directory && $(am__tar) > result.tar # # Substitute a variable $(am__untar) that extract such # a tarball read from stdin. # $(am__untar) < result.tar AC_DEFUN([_AM_PROG_TAR], [# Always define AMTAR for backward compatibility. Yes, it's still used # in the wild :-( We should find a proper way to deprecate it ... AC_SUBST([AMTAR], ['$${TAR-tar}']) m4_if([$1], [v7], [am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'], [m4_case([$1], [ustar],, [pax],, [m4_fatal([Unknown tar format])]) AC_MSG_CHECKING([how to create a $1 tar archive]) # Loop over all known methods to create a tar archive until one works. _am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none' _am_tools=${am_cv_prog_tar_$1-$_am_tools} # Do not fold the above two line into one, because Tru64 sh and # Solaris sh will not grok spaces in the rhs of `-'. for _am_tool in $_am_tools do case $_am_tool in gnutar) for _am_tar in tar gnutar gtar; do AM_RUN_LOG([$_am_tar --version]) && break done am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"' am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"' am__untar="$_am_tar -xf -" ;; plaintar) # Must skip GNU tar: if it does not support --format= it doesn't create # ustar tarball either. (tar --version) >/dev/null 2>&1 && continue am__tar='tar chf - "$$tardir"' am__tar_='tar chf - "$tardir"' am__untar='tar xf -' ;; pax) am__tar='pax -L -x $1 -w "$$tardir"' am__tar_='pax -L -x $1 -w "$tardir"' am__untar='pax -r' ;; cpio) am__tar='find "$$tardir" -print | cpio -o -H $1 -L' am__tar_='find "$tardir" -print | cpio -o -H $1 -L' am__untar='cpio -i -H $1 -d' ;; none) am__tar=false am__tar_=false am__untar=false ;; esac # If the value was cached, stop now. We just wanted to have am__tar # and am__untar set. test -n "${am_cv_prog_tar_$1}" && break # tar/untar a dummy directory, and stop if the command works rm -rf conftest.dir mkdir conftest.dir echo GrepMe > conftest.dir/file AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar]) rm -rf conftest.dir if test -s conftest.tar; then AM_RUN_LOG([$am__untar /dev/null 2>&1 && break fi done rm -rf conftest.dir AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool]) AC_MSG_RESULT([$am_cv_prog_tar_$1])]) AC_SUBST([am__tar]) AC_SUBST([am__untar]) ]) # _AM_PROG_TAR m4_include([m4/general.m4]) m4_include([m4/libtool.m4]) m4_include([m4/ltoptions.m4]) m4_include([m4/ltsugar.m4]) m4_include([m4/ltversion.m4]) m4_include([m4/lt~obsolete.m4]) m4_include([m4/sipXlib.m4]) sipxtapi-3.3.0~test17/Makefile.am0000644000175000017500000000105412205613305017427 0ustar00danieldaniel00000000000000 ACLOCAL_AMFLAGS = -I m4 include $(top_srcdir)/config/sipXcommon.am.inc EXTRA_DIST = \ sipxtapi.spec \ config/sipXpkgtop.mak \ config/sipX-config.in \ config/sipX-buildstamp.cpp.in \ config/sipX-buildstamp.h.in \ config/sipXprojtop.mak \ config/sipXcommon.am.inc unconditional_SUBDIRS = \ bin \ sipXportLib \ sipXsdpLib \ sipXtackLib \ sipXmediaLib \ sipXmediaAdapterLib \ sipXcallLib include $(top_srcdir)/config/sipXpkgtop.mak SUBDIRS = $(unconditional_SUBDIRS) $(doc_SUBDIRS) DISTCLEANFILES = BUILDSTAMP sipxtapi-3.3.0~test17/Makefile.in0000644000175000017500000007610512321445004017447 0ustar00danieldaniel00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # -*-makefile-*- VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ DIST_COMMON = README $(am__configure_deps) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in $(srcdir)/config.h.in \ $(srcdir)/sipxtapi.spec.in \ $(top_srcdir)/config/sipXcommon.am.inc \ $(top_srcdir)/config/sipXpkgtop.mak $(top_srcdir)/configure \ AUTHORS COPYING ChangeLog INSTALL NEWS build-aux/ar-lib \ build-aux/config.guess build-aux/config.sub build-aux/depcomp \ build-aux/install-sh build-aux/ltmain.sh build-aux/missing subdir = . ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/general.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/sipXlib.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ configure.lineno config.status.lineno mkinstalldirs = $(install_sh) -d CONFIG_HEADER = config.h CONFIG_CLEAN_FILES = sipxtapi.spec CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ html-recursive info-recursive install-data-recursive \ install-dvi-recursive install-exec-recursive \ install-html-recursive install-info-recursive \ install-pdf-recursive install-ps-recursive install-recursive \ installcheck-recursive installdirs-recursive pdf-recursive \ ps-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ distdir dist dist-all distcheck ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) distdir = $(PACKAGE)-$(VERSION) top_distdir = $(distdir) am__remove_distdir = \ if test -d "$(distdir)"; then \ find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \ && rm -rf "$(distdir)" \ || { sleep 5 && rm -rf "$(distdir)"; }; \ else :; fi am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" DIST_ARCHIVES = $(distdir).tar.gz GZIP_ENV = --best distuninstallcheck_listfiles = find . -type f -print am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \ | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$' distcleancheck_listfiles = find . -type f -print ACLOCAL = @ACLOCAL@ AMRNB_INCLUDE = @AMRNB_INCLUDE@ AMRNB_LIB_ROOT = @AMRNB_LIB_ROOT@ AMRWB_INCLUDE = @AMRWB_INCLUDE@ AMRWB_LIB_ROOT = @AMRWB_LIB_ROOT@ AMRWB_TARGET = @AMRWB_TARGET@ AMR_TARGET = @AMR_TARGET@ AMTAR = @AMTAR@ ANT = @ANT@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CARBON_LIBS = @CARBON_LIBS@ CA_LIBS = @CA_LIBS@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPUNIT_CFLAGS = @CPPUNIT_CFLAGS@ CPPUNIT_CONFIG = @CPPUNIT_CONFIG@ CPPUNIT_LIBS = @CPPUNIT_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPS_PCRE_CFLAGS = @DEPS_PCRE_CFLAGS@ DEPS_PCRE_LIBS = @DEPS_PCRE_LIBS@ DLLTOOL = @DLLTOOL@ DOT = @DOT@ DOXYGEN = @DOXYGEN@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DYNEXT = @DYNEXT@ EAGC_LDFLAGS = @EAGC_LDFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EJBE_LDFLAGS = @EJBE_LDFLAGS@ EPLC_LDFLAGS = @EPLC_LDFLAGS@ EVAD_LDFLAGS = @EVAD_LDFLAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ G722_TARGET = @G722_TARGET@ G726_TARGET = @G726_TARGET@ GIPSINC = @GIPSINC@ GIPS_CE_OBJS = @GIPS_CE_OBJS@ GIPS_CPPFLAGS = @GIPS_CPPFLAGS@ GIPS_NEQ_OBJS = @GIPS_NEQ_OBJS@ GIPS_VE_OBJS = @GIPS_VE_OBJS@ GREP = @GREP@ GSM_CFLAGS = @GSM_CFLAGS@ GSM_CXXFLAGS = @GSM_CXXFLAGS@ GSM_LDFLAGS = @GSM_LDFLAGS@ GSM_LIBS = @GSM_LIBS@ GSM_TARGET = @GSM_TARGET@ ILBC_INCLUDE = @ILBC_INCLUDE@ ILBC_LIB_ROOT = @ILBC_LIB_ROOT@ ILBC_LIB_TARGET = @ILBC_LIB_TARGET@ ILBC_TARGET = @ILBC_TARGET@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTERFACE_FLAGS = @INTERFACE_FLAGS@ JAVA = @JAVA@ JAVAC_DEBUG = @JAVAC_DEBUG@ JAVAC_OPTIMIZED = @JAVAC_OPTIMIZED@ JAVA_HOME = @JAVA_HOME@ L16_TARGET = @L16_TARGET@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NAMED_PROGRAM = @NAMED_PROGRAM@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPUS_CFLAGS = @OPUS_CFLAGS@ OPUS_LIBS = @OPUS_LIBS@ OPUS_TARGET = @OPUS_TARGET@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PCMAPCMU_TARGET = @PCMAPCMU_TARGET@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ RTL_CXXFLAGS = @RTL_CXXFLAGS@ RTL_LDFLAGS = @RTL_LDFLAGS@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SIPXMEDIA_CE_LIBS = @SIPXMEDIA_CE_LIBS@ SIPXMEDIA_VE_LIBS = @SIPXMEDIA_VE_LIBS@ SIPXMEDIA_VE_STATIC_LIBS = @SIPXMEDIA_VE_STATIC_LIBS@ SIPXPBXUSER = @SIPXPBXUSER@ SIPXPHONECONF = @SIPXPHONECONF@ SIPXPHONEDATA = @SIPXPHONEDATA@ SIPXPHONELIB = @SIPXPHONELIB@ SIPX_BACKUPDIR = @SIPX_BACKUPDIR@ SIPX_BINDIR = @SIPX_BINDIR@ SIPX_CONFDIR = @SIPX_CONFDIR@ SIPX_CONFIGPHONEDIR = @SIPX_CONFIGPHONEDIR@ SIPX_DATADIR = @SIPX_DATADIR@ SIPX_DBDIR = @SIPX_DBDIR@ SIPX_DOCDIR = @SIPX_DOCDIR@ SIPX_INCDIR = @SIPX_INCDIR@ SIPX_LIBDIR = @SIPX_LIBDIR@ SIPX_LOGDIR = @SIPX_LOGDIR@ SIPX_PARKMUSICDIR = @SIPX_PARKMUSICDIR@ SIPX_RUNDIR = @SIPX_RUNDIR@ SIPX_SCHEMADIR = @SIPX_SCHEMADIR@ SIPX_TMPDIR = @SIPX_TMPDIR@ SIPX_UNIT_TARGET = @SIPX_UNIT_TARGET@ SIPX_VXMLDATADIR = @SIPX_VXMLDATADIR@ SPANDSP_CFLAGS = @SPANDSP_CFLAGS@ SPANDSP_CXXFLAGS = @SPANDSP_CXXFLAGS@ SPANDSP_LDFLAGS = @SPANDSP_LDFLAGS@ SPANDSP_LIBS = @SPANDSP_LIBS@ SPEEXDSP_CFLAGS = @SPEEXDSP_CFLAGS@ SPEEXDSP_LIBS = @SPEEXDSP_LIBS@ SPEEXDSP_STATIC_LIB = @SPEEXDSP_STATIC_LIB@ SPEEX_CFLAGS = @SPEEX_CFLAGS@ SPEEX_LIBS = @SPEEX_LIBS@ SPEEX_ROOT = @SPEEX_ROOT@ SPEEX_STATIC_LIB = @SPEEX_STATIC_LIB@ SPEEX_TARGET = @SPEEX_TARGET@ SS_LDFLAGS = @SS_LDFLAGS@ STATIC_CODEC_LIBS = @STATIC_CODEC_LIBS@ STRIP = @STRIP@ TONES_TARGET = @TONES_TARGET@ VERSION = @VERSION@ VIDEO_DEFINE = @VIDEO_DEFINE@ WXWIDGETS_CFLAGS = @WXWIDGETS_CFLAGS@ WXWIDGETS_CONFIG = @WXWIDGETS_CONFIG@ WXWIDGETS_CXXFLAGS = @WXWIDGETS_CXXFLAGS@ WXWIDGETS_LIBS = @WXWIDGETS_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ codeclibdir = @codeclibdir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ enable_dot = @enable_dot@ enable_html_docs = @enable_html_docs@ enable_latex_docs = @enable_latex_docs@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ jar = @jar@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ sipx_abs_srcdir = @sipx_abs_srcdir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ wwwdir = @wwwdir@ ACLOCAL_AMFLAGS = -I m4 ConfigureArgs = $(shell sed \ -e '/^ *\$$ .*\/configure/!d' \ -e 's/^ *\$$ .*\/configure *//' \ $(top_builddir)/config.log \ ) LocalizeSipXconfig = sed \ -e 's,@PACKAGE\@,@PACKAGE@,g' \ -e 's,@VERSION\@,@VERSION@,g' \ -e 's,@abs_builddir\@,@abs_builddir@,g' \ -e 's,@abs_srcdir\@,@abs_srcdir@,g' \ -e 's,@abs_top_srcdir\@,@abs_top_srcdir@,g' \ -e 's,@sipx_abs_srcdir\@,@sipx_abs_srcdir@,g' \ -e 's!@CONFIGURE_OPTIONS@!$(ConfigureArgs)!g' \ -e 's,@bindir\@,$(bindir),g' \ -e 's,@datadir\@,$(datadir),g' \ -e 's,@htmldir\@,@htmldir@,g' \ -e 's,@INSTALL\@,@INSTALL@,g' \ -e 's,@install_sh\@,@install_sh@,g' \ -e 's,@libdir\@,$(libdir),g' \ -e 's,@localstatedir\@,$(localstatedir),g' \ -e 's,@pkgdatadir\@,@pkgdatadir@,g' \ -e 's,@prefix\@,$(prefix),g' \ -e 's,@profiledir\@,@profiledir@,g' \ -e 's,@wwwdir\@,@wwwdir@,g' \ -e 's,@host\@,@host@,g' \ -e 's,@PERL\@,@PERL@,g' \ -e 's,@APACHE2_HTTPD\@,@APACHE2_HTTPD@,g' \ -e 's,@APACHE2_MOD\@,@APACHE2_MOD@,g' \ -e 's,@CLOVER_HOME\@,@CLOVER_HOME@,g' \ -e 's,@JAVAC_DEBUG\@,@JAVAC_DEBUG@,g' \ -e 's,@JAVAC_OPTIMIZED\@,@JAVAC_OPTIMIZED@,g' \ -e 's,@JAVA\@,@JAVA@,g' \ -e 's,@JAVA_HOME\@,@JAVA_HOME@,g' \ -e 's,@JBOSS_HOME\@,@JBOSS_HOME@,g' \ -e 's,@JBOSS_SERVER_CONF\@,@JBOSS_SERVER_CONF@,g' \ -e 's,@SIPFOUNDRY_ORG\@,@SIPFOUNDRY_ORG@,g' \ -e 's,@SIPXCONFIG_LIBDIR\@,@SIPXCONFIG_LIBDIR@,g' \ -e 's,@SIPXPBXUSER\@,@SIPXPBXUSER@,g' \ -e 's,@SIPX_BINDIR\@,@SIPX_BINDIR@,g' \ -e 's,@SIPX_CONFDIR\@,@SIPX_CONFDIR@,g' \ -e 's,@SIPX_CONFIGPHONEDIR\@,@SIPX_CONFIGPHONEDIR@,g' \ -e 's,@SIPX_BACKUPDIR\@,@SIPX_BACKUPDIR@,g' \ -e 's,@SIPX_DATADIR\@,@SIPX_DATADIR@,g' \ -e 's,@SIPX_DBDIR\@,@SIPX_DBDIR@,g' \ -e 's,@SIPX_DOCDIR\@,@SIPX_DOCDIR@,g' \ -e 's,@SIPX_LOGDIR\@,@SIPX_LOGDIR@,g' \ -e 's,@SIPX_RUNDIR\@,@SIPX_RUNDIR@,g' \ -e 's,@SIPX_TMPDIR\@,@SIPX_TMPDIR@,g' \ -e 's,@SIPX_INCDIR\@,@SIPX_INCDIR@,g' \ -e 's,@SIPX_LIBDIR\@,@SIPX_LIBDIR@,g' \ -e 's,@SIPX_SCHEMADIR\@,@SIPX_SCHEMADIR@,g' \ -e 's,@SIPX_VXMLDATADIR\@,@SIPX_VXMLDATADIR@,g' \ -e 's,@SIPX_PARKMUSICDIR\@,@SIPX_PARKMUSICDIR@,g' \ -e 's,@SPRING_HOME\@,@SPRING_HOME@,g' \ -e 's,@XPRESSA_BUILD_NUMBER\@,@XPRESSA_BUILD_NUMBER@,g' \ -e 's,@XPRESSA_BUILD_COMMENT\@,@XPRESSA_BUILD_COMMENT@,g' \ -e 's,@SIPXPHONELIB\@,@SIPXPHONELIB@,g' \ -e 's,@SIPXPHONEDATA\@,@SIPXPHONEDATA@,g' \ -e 's,@SIPXPHONECONF\@,@SIPXPHONECONF@,g' \ -e 's,@NAMED_PROGRAM\@,@NAMED_PROGRAM@,g' EXTRA_DIST = \ sipxtapi.spec \ config/sipXpkgtop.mak \ config/sipX-config.in \ config/sipX-buildstamp.cpp.in \ config/sipX-buildstamp.h.in \ config/sipXprojtop.mak \ config/sipXcommon.am.inc unconditional_SUBDIRS = \ bin \ sipXportLib \ sipXsdpLib \ sipXtackLib \ sipXmediaLib \ sipXmediaAdapterLib \ sipXcallLib SUBDIRS = $(unconditional_SUBDIRS) $(doc_SUBDIRS) DISTCLEANFILES = BUILDSTAMP all: config.h $(MAKE) $(AM_MAKEFLAGS) all-recursive .SUFFIXES: am--refresh: Makefile @: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(top_srcdir)/config/sipXcommon.am.inc $(top_srcdir)/config/sipXpkgtop.mak $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ echo ' cd $(srcdir) && $(AUTOMAKE) --gnu'; \ $(am__cd) $(srcdir) && $(AUTOMAKE) --gnu \ && exit 0; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ echo ' $(SHELL) ./config.status'; \ $(SHELL) ./config.status;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/config/sipXcommon.am.inc $(top_srcdir)/config/sipXpkgtop.mak: $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) $(SHELL) ./config.status --recheck $(top_srcdir)/configure: $(am__configure_deps) $(am__cd) $(srcdir) && $(AUTOCONF) $(ACLOCAL_M4): $(am__aclocal_m4_deps) $(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) $(am__aclocal_m4_deps): config.h: stamp-h1 @if test ! -f $@; then rm -f stamp-h1; else :; fi @if test ! -f $@; then $(MAKE) $(AM_MAKEFLAGS) stamp-h1; else :; fi stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status @rm -f stamp-h1 cd $(top_builddir) && $(SHELL) ./config.status config.h $(srcdir)/config.h.in: $(am__configure_deps) ($(am__cd) $(top_srcdir) && $(AUTOHEADER)) rm -f stamp-h1 touch $@ distclean-hdr: -rm -f config.h stamp-h1 sipxtapi.spec: $(top_builddir)/config.status $(srcdir)/sipxtapi.spec.in cd $(top_builddir) && $(SHELL) ./config.status $@ mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs distclean-libtool: -rm -f libtool config.lt # This directory's subdirectories are mostly independent; you can cd # into them and run `make' without going through this Makefile. # To change the values of `make' variables: instead of editing Makefiles, # (1) if the variable is set in `config.status', edit `config.status' # (which will cause the Makefiles to be regenerated when you run `make'); # (2) otherwise, pass the desired values on the `make' command line. $(RECURSIVE_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ list='$(SUBDIRS)'; for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" $(RECURSIVE_CLEAN_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ rev=''; for subdir in $$list; do \ if test "$$subdir" = "."; then :; else \ rev="$$subdir $$rev"; \ fi; \ done; \ rev="$$rev ."; \ target=`echo $@ | sed s/-recursive//`; \ for subdir in $$rev; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done && test -z "$$fail" tags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ done ctags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ done ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: tags-recursive $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: ctags-recursive $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) $(am__remove_distdir) test -d "$(distdir)" || mkdir "$(distdir)" @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done -test -n "$(am__skip_mode_fix)" \ || find "$(distdir)" -type d ! -perm -755 \ -exec chmod u+rwx,go+rx {} \; -o \ ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \ || chmod -R a+r "$(distdir)" dist-gzip: distdir tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz $(am__remove_distdir) dist-bzip2: distdir tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 $(am__remove_distdir) dist-lzip: distdir tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz $(am__remove_distdir) dist-lzma: distdir tardir=$(distdir) && $(am__tar) | lzma -9 -c >$(distdir).tar.lzma $(am__remove_distdir) dist-xz: distdir tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz $(am__remove_distdir) dist-tarZ: distdir tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z $(am__remove_distdir) dist-shar: distdir shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz $(am__remove_distdir) dist-zip: distdir -rm -f $(distdir).zip zip -rq $(distdir).zip $(distdir) $(am__remove_distdir) dist dist-all: distdir tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz $(am__remove_distdir) # This target untars the dist file and tries a VPATH configuration. Then # it guarantees that the distribution is self-contained by making another # tarfile. distcheck: dist case '$(DIST_ARCHIVES)' in \ *.tar.gz*) \ GZIP=$(GZIP_ENV) gzip -dc $(distdir).tar.gz | $(am__untar) ;;\ *.tar.bz2*) \ bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\ *.tar.lzma*) \ lzma -dc $(distdir).tar.lzma | $(am__untar) ;;\ *.tar.lz*) \ lzip -dc $(distdir).tar.lz | $(am__untar) ;;\ *.tar.xz*) \ xz -dc $(distdir).tar.xz | $(am__untar) ;;\ *.tar.Z*) \ uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ *.shar.gz*) \ GZIP=$(GZIP_ENV) gzip -dc $(distdir).shar.gz | unshar ;;\ *.zip*) \ unzip $(distdir).zip ;;\ esac chmod -R a-w $(distdir); chmod u+w $(distdir) mkdir $(distdir)/_build mkdir $(distdir)/_inst chmod a-w $(distdir) test -d $(distdir)/_build || exit 0; \ dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ && am__cwd=`pwd` \ && $(am__cd) $(distdir)/_build \ && ../configure --srcdir=.. --prefix="$$dc_install_base" \ $(AM_DISTCHECK_CONFIGURE_FLAGS) \ $(DISTCHECK_CONFIGURE_FLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) dvi \ && $(MAKE) $(AM_MAKEFLAGS) check \ && $(MAKE) $(AM_MAKEFLAGS) install \ && $(MAKE) $(AM_MAKEFLAGS) installcheck \ && $(MAKE) $(AM_MAKEFLAGS) uninstall \ && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ distuninstallcheck \ && chmod -R a-w "$$dc_install_base" \ && ({ \ (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ } || { rm -rf "$$dc_destdir"; exit 1; }) \ && rm -rf "$$dc_destdir" \ && $(MAKE) $(AM_MAKEFLAGS) dist \ && rm -rf $(DIST_ARCHIVES) \ && $(MAKE) $(AM_MAKEFLAGS) distcleancheck \ && cd "$$am__cwd" \ || exit 1 $(am__remove_distdir) @(echo "$(distdir) archives ready for distribution: "; \ list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x' distuninstallcheck: @test -n '$(distuninstallcheck_dir)' || { \ echo 'ERROR: trying to run $@ with an empty' \ '$$(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ $(am__cd) '$(distuninstallcheck_dir)' || { \ echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left after uninstall:" ; \ if test -n "$(DESTDIR)"; then \ echo " (check DESTDIR support)"; \ fi ; \ $(distuninstallcheck_listfiles) ; \ exit 1; } >&2 distcleancheck: distclean @if test '$(srcdir)' = . ; then \ echo "ERROR: distcleancheck can only run from a VPATH build" ; \ exit 1 ; \ fi @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left in build directory after distclean:" ; \ $(distcleancheck_listfiles) ; \ exit 1; } >&2 check-am: all-am check: check-recursive all-am: Makefile config.h installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) -test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -f Makefile distclean-am: clean-am distclean-generic distclean-hdr \ distclean-libtool distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -rf $(top_srcdir)/autom4te.cache -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) all \ ctags-recursive install-am install-strip tags-recursive .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ all all-am am--refresh check check-am clean clean-generic \ clean-libtool ctags ctags-recursive dist dist-all dist-bzip2 \ dist-gzip dist-lzip dist-lzma dist-shar dist-tarZ dist-xz \ dist-zip distcheck distclean distclean-generic distclean-hdr \ distclean-libtool distclean-tags distcleancheck distdir \ distuninstallcheck dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \ ps ps-am tags tags-recursive uninstall uninstall-am all: BUILDSTAMP SVN-VERSION: svnversion @top_srcdir@ > SVN-VERSION .PHONY: BUILDSTAMP BUILDSTAMP: if test -d @top_srcdir@/.svn \ ;then \ sipxSvnVersion=`svnversion @top_srcdir@` \ ;elif test -f @top_srcdir@/SVN-VERSION \ ;then \ sipxSvnVersion=`cat @top_srcdir@/SVN-VERSION` \ ;fi \ ;if test -z "$${sipxSvnVersion}" -o "export" = "$${sipxSvnVersion}" \ ;then \ sipxSvnVersion="SVN-UNKNOWN" \ ;fi \ ;sipxBuildTime=`date -u --iso-8601=seconds | sed 's/+0000//'` \ ;sipxBuildHost=`hostname --short` \ ;SIPX_BUILDSTAMP="r$${sipxSvnVersion} $${sipxBuildTime} $${sipxBuildHost}" \ ;echo "$${SIPX_BUILDSTAMP}" > BUILDSTAMP \ ;${LocalizeSipXconfig} \ -e "s/@SIPX_BUILDSTAMP\@/$${SIPX_BUILDSTAMP}/" \ -e "s/sipx/SipX/" \ $(srcdir)/config/sipX-buildstamp.cpp.in \ > config/@PACKAGE@-buildstamp.cpp \ ;${LocalizeSipXconfig} \ -e "s/@SIPX_BUILDSTAMP\@/$${SIPX_BUILDSTAMP}/" \ -e "s/sipx/SipX/" \ $(srcdir)/config/sipX-buildstamp.h.in \ > config/@PACKAGE@-buildstamp.h # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: sipxtapi-3.3.0~test17/config.h.in0000644000175000017500000001777212321445023017433 0ustar00danieldaniel00000000000000/* config.h.in. Generated from configure.ac by autoheader. */ /* Define to 1 if the `closedir' function returns void instead of `int'. */ #undef CLOSEDIR_VOID /* Select G722 for static link */ #undef CODEC_G722_STATIC /* Select G726 for static link */ #undef CODEC_G726_STATIC /* Select l16 for static link */ #undef CODEC_L16_STATIC /* Select Opus for static link */ #undef CODEC_OPUS_STATIC /* Select PCMA and PCMU codecs for static link */ #undef CODEC_PCMA_PCMU_STATIC /* Select SPEEX codecs for static link */ #undef CODEC_SPEEX_STATIC /* Select tones for static link */ #undef CODEC_TONES_STATIC /* Use external library for AGC */ #undef EXTERNAL_AGC /* Use external library for jitter buffer estimation */ #undef EXTERNAL_JB_ESTIMATION /* Use external library for PLC */ #undef EXTERNAL_PLC /* Use external library for speaker selection */ #undef EXTERNAL_SS /* Use external library for VAD */ #undef EXTERNAL_VAD /* Define to 1 if you have the `alarm' function. */ #undef HAVE_ALARM /* Define to 1 if you have the header file. */ #undef HAVE_ARPA_INET_H /* Define to 1 if you have the `clock_gettime' function. */ #undef HAVE_CLOCK_GETTIME /* Define to 1 if you have the header file, and it defines `DIR'. */ #undef HAVE_DIRENT_H /* Define to 1 if you have the header file. */ #undef HAVE_DLFCN_H /* Define to 1 if you have the header file. */ #undef HAVE_FCNTL_H /* Define to 1 if you have the `fork' function. */ #undef HAVE_FORK /* Define to 1 if you have the `getcwd' function. */ #undef HAVE_GETCWD /* Define to 1 if you have the `gethostbyname' function. */ #undef HAVE_GETHOSTBYNAME /* Define to 1 if you have the `gethostname' function. */ #undef HAVE_GETHOSTNAME /* Define to 1 if you have the `gettimeofday' function. */ #undef HAVE_GETTIMEOFDAY /* Define to 1 if you have the `inet_ntoa' function. */ #undef HAVE_INET_NTOA /* Define to 1 if you have the header file. */ #undef HAVE_INTTYPES_H /* Define to 1 if you have the header file. */ #undef HAVE_LIMITS_H /* Define to 1 if you have the `localtime_r' function. */ #undef HAVE_LOCALTIME_R /* Define to 1 if your system has a GNU libc compatible `malloc' function, and to 0 otherwise. */ #undef HAVE_MALLOC /* Define to 1 if you have the header file. */ #undef HAVE_MALLOC_H /* Define to 1 if you have the `memchr' function. */ #undef HAVE_MEMCHR /* Define to 1 if you have the header file. */ #undef HAVE_MEMORY_H /* Define to 1 if you have the `memset' function. */ #undef HAVE_MEMSET /* Define to 1 if you have the `mkdir' function. */ #undef HAVE_MKDIR /* Define to 1 if you have the header file, and it defines `DIR'. */ #undef HAVE_NDIR_H /* Define to 1 if you have the header file. */ #undef HAVE_NETDB_H /* Define to 1 if you have the header file. */ #undef HAVE_NETINET_IN_H /* Have old version of libspandsp */ #undef HAVE_OLD_LIBSPANDSP /* Define to 1 if you have the `putenv' function. */ #undef HAVE_PUTENV /* Define to 1 if you have the `rmdir' function. */ #undef HAVE_RMDIR /* Define to 1 if you have the `select' function. */ #undef HAVE_SELECT /* Define to 1 if you have the `setenv' function. */ #undef HAVE_SETENV /* Define to 1 if you have the `socket' function. */ #undef HAVE_SOCKET /* Define to 1 if `stat' has the bug that it succeeds when given the zero-length file name argument. */ #undef HAVE_STAT_EMPTY_STRING_BUG /* Define to 1 if stdbool.h conforms to C99. */ #undef HAVE_STDBOOL_H /* Define to 1 if you have the header file. */ #undef HAVE_STDINT_H /* Define to 1 if you have the header file. */ #undef HAVE_STDLIB_H /* Define to 1 if you have the `strchr' function. */ #undef HAVE_STRCHR /* Define to 1 if you have the `strdup' function. */ #undef HAVE_STRDUP /* Define to 1 if you have the `strerror' function. */ #undef HAVE_STRERROR /* Define to 1 if you have the `strftime' function. */ #undef HAVE_STRFTIME /* Define to 1 if you have the header file. */ #undef HAVE_STRINGS_H /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H /* Define to 1 if you have the `strrchr' function. */ #undef HAVE_STRRCHR /* Define to 1 if you have the `strstr' function. */ #undef HAVE_STRSTR /* Define to 1 if you have the `strtol' function. */ #undef HAVE_STRTOL /* Define to 1 if you have the `strtoul' function. */ #undef HAVE_STRTOUL /* Define to 1 if you have the header file, and it defines `DIR'. */ #undef HAVE_SYS_DIR_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_IOCTL_H /* Define to 1 if you have the header file, and it defines `DIR'. */ #undef HAVE_SYS_NDIR_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_SELECT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_SOCKET_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_STAT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TIME_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TYPES_H /* Define to 1 if you have that is POSIX.1 compatible. */ #undef HAVE_SYS_WAIT_H /* Define to 1 if you have the `tzset' function. */ #undef HAVE_TZSET /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* Define to 1 if you have the `vfork' function. */ #undef HAVE_VFORK /* Define to 1 if you have the header file. */ #undef HAVE_VFORK_H /* Define to 1 if `fork' works. */ #undef HAVE_WORKING_FORK /* Define to 1 if `vfork' works. */ #undef HAVE_WORKING_VFORK /* Define to 1 if the system has the type `_Bool'. */ #undef HAVE__BOOL /* Initialize external RTL collector with sipXmediaLib s internal one */ #undef INIT_EXTERNAL_RTL_COLLECTOR /* Enable Sepaker Selection resource in flowgraph */ #undef INSERT_SPEAKER_SELECTOR /* Define to 1 if `lstat' dereferences a symlink specified with a trailing slash. */ #undef LSTAT_FOLLOWS_SLASHED_SYMLINK /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #undef LT_OBJDIR /* Name of package */ #undef PACKAGE /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the home page for this package. */ #undef PACKAGE_URL /* Define to the version of this package. */ #undef PACKAGE_VERSION /* Define as the return type of signal handlers (`int' or `void'). */ #undef RETSIGTYPE /* Enable RTL_AUDIO for the whole library */ #undef RTL_AUDIO_ENABLED /* Enable RTL for the whole library */ #undef RTL_ENABLED /* Define to the type of arg 1 for `select'. */ #undef SELECT_TYPE_ARG1 /* Define to the type of args 2, 3 and 4 for `select'. */ #undef SELECT_TYPE_ARG234 /* Define to the type of arg 5 for `select'. */ #undef SELECT_TYPE_ARG5 /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS /* Define to 1 if you can safely include both and . */ #undef TIME_WITH_SYS_TIME /* Define to 1 if your declares `struct tm'. */ #undef TM_IN_SYS_TIME /* Version number of package */ #undef VERSION /* Define to empty if `const' does not conform to ANSI C. */ #undef const /* Define to `int' if doesn't define. */ #undef gid_t /* Define to rpl_malloc if the replacement function should be used. */ #undef malloc /* Define to `int' if does not define. */ #undef pid_t /* Define to `unsigned int' if does not define. */ #undef size_t /* Define to `int' if doesn't define. */ #undef uid_t /* Define as `fork' if `vfork' does not work. */ #undef vfork /* Define to empty if the keyword `volatile' does not work. Warning: valid code using `volatile' can become incorrect without. Disable with care. */ #undef volatile sipxtapi-3.3.0~test17/sipxtapi.spec.in0000644000175000017500000000464712205617434020537 0ustar00danieldaniel00000000000000Name: @PACKAGE@ Version: @VERSION@ Release: 4 Summary: SIP stack, RTP media framework and codecs License: LGPLv2 Url: http://www.sipxtapi.org Source: http://www.sipxtapi.org/files/pub/sipX/%{name}-%{version}.tar.gz BuildRequires: libtool automake autoconf BuildRequires: cppunit-devel BuildRequires: doxygen BuildRequires: gsm-devel BuildRequires: openssl-devel >= 0.9.8 BuildRequires: pcre-devel BuildRequires: spandsp-devel BuildRequires: xerces-c-devel %description sipXtapi is a framework that makes it easy to construct SIP user agents, including soft-phones and telephony servers. %package devel Requires: %{name}%{?_isa} = %{version}-%{release} Summary: Development files for %{name} %description devel The %{name}-devel package contains libraries and header files for developing applications that use %{name}. %package doc Summary: API documentation for %{name} %description doc sipXtapi is a framework that makes it easy to construct SIP user agents, including softphones and telephony servers. This package provides developer documentation about the API. %prep %setup -q %build %configure --enable-topology-graph --disable-codec-ilbc --disable-codec-g726 --enable-codec-g722 --enable-codec-gsm --disable-static sed -i 's|^hardcode_libdir_flag_spec=.*|hardcode_libdir_flag_spec=""|g' libtool sed -i 's|^runpath_var=LD_RUN_PATH|runpath_var=DIE_RPATH_DIE|g' libtool make %{?_smp_mflags} # sipXtapi provides unit tests but they are not currently invoked # automatically as they demand network access and other local resources # that have to be manually configured #%check %install make DESTDIR=%{buildroot} install rm -f %{buildroot}%{_libdir}/lib*.a rm -f %{buildroot}%{_libdir}/lib*.la rm -rf %{buildroot}%{_bindir} %post -p /sbin/ldconfig %postun -p /sbin/ldconfig %files %defattr(-, root, root, -) %doc COPYING %{_libdir}/lib*.so.* %{_libdir}/sipxtapi/ %files devel %defattr(-, root, root, -) %doc COPYING %{_includedir}/sipxtapi/ %{_libdir}/lib*.so %{_datarootdir}/sipxtapi/ %files doc %defattr(-, root, root, -) %doc %{_docdir}/%{name}/* %changelog * Wed Aug 7 2013 Daniel Pocock - @VERSION@-4 - Tweak documentation packaging * Wed Aug 7 2013 Daniel Pocock - @VERSION@-3 - Various spec file improvements * Wed Aug 7 2013 Daniel Pocock - @VERSION@-2 - Various spec file improvements * Mon May 6 2013 Daniel Pocock - @VERSION@-1 - Initial build sipxtapi-3.3.0~test17/configure0000755000175000017500000270657712321445004017330 0ustar00danieldaniel00000000000000#! /bin/sh # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.69 for sipXtapi 3.3.0~test17. # # Report bugs to . # # # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc. # # # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # Use a proper internal environment variable to ensure we don't fall # into an infinite loop, continuously re-executing ourselves. if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then _as_can_reexec=no; export _as_can_reexec; # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 as_fn_exit 255 fi # We don't want this to propagate to other subprocesses. { _as_can_reexec=; unset _as_can_reexec;} if test "x$CONFIG_SHELL" = x; then as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi " as_required="as_fn_return () { (exit \$1); } as_fn_success () { as_fn_return 0; } as_fn_failure () { as_fn_return 1; } as_fn_ret_success () { return 0; } as_fn_ret_failure () { return 1; } exitcode=0 as_fn_success || { exitcode=1; echo as_fn_success failed.; } as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : else exitcode=1; echo positional parameters were not saved. fi test x\$exitcode = x0 || exit 1 test -x / || exit 1" as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 test -n \"\${ZSH_VERSION+set}\${BASH_VERSION+set}\" || ( ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO PATH=/empty FPATH=/empty; export PATH FPATH test \"X\`printf %s \$ECHO\`\" = \"X\$ECHO\" \\ || test \"X\`print -r -- \$ECHO\`\" = \"X\$ECHO\" ) || exit 1 test \$(( 1 + 1 )) = 2 || exit 1" if (eval "$as_required") 2>/dev/null; then : as_have_required=yes else as_have_required=no fi if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR as_found=false for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. as_found=: case $as_dir in #( /*) for as_base in sh bash ksh sh5; do # Try only shells that exist, to save several forks. as_shell=$as_dir/$as_base if { test -f "$as_shell" || test -f "$as_shell.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : CONFIG_SHELL=$as_shell as_have_required=yes if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : break 2 fi fi done;; esac as_found=false done $as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : CONFIG_SHELL=$SHELL as_have_required=yes fi; } IFS=$as_save_IFS if test "x$CONFIG_SHELL" != x; then : export CONFIG_SHELL # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 exit 255 fi if test x$as_have_required = xno; then : $as_echo "$0: This script requires a shell more modern than all" $as_echo "$0: the shells that I found on your system." if test x${ZSH_VERSION+set} = xset ; then $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" $as_echo "$0: be upgraded to zsh 4.3.4 or later." else $as_echo "$0: Please tell bug-autoconf@gnu.org and $0: sipxtapi-dev@list.sipfoundry.org about your system, $0: including any error possibly output before this $0: message. Then install a modern shell, or manually run $0: the script under such a shell if you do have one." fi exit 1 fi fi fi SHELL=${CONFIG_SHELL-/bin/sh} export SHELL # Unset more variables known to interfere with behavior of common tools. CLICOLOR_FORCE= GREP_OPTIONS= unset CLICOLOR_FORCE GREP_OPTIONS ## --------------------- ## ## M4sh Shell Functions. ## ## --------------------- ## # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits as_lineno_1=$LINENO as_lineno_1a=$LINENO as_lineno_2=$LINENO as_lineno_2a=$LINENO eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= ' <$as_myself | sed ' s/[$]LINENO.*/&-/ t lineno b :lineno N :loop s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } # If we had to re-execute with $CONFIG_SHELL, we're ensured to have # already done that, so ensure we don't try to do so again and fall # in an infinite loop. This has already happened in practice. _as_can_reexec=no; export _as_can_reexec # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensitive to this). . "./$as_me.lineno" # Exit status is that of the last command. exit } ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" SHELL=${CONFIG_SHELL-/bin/sh} test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. # hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` # # Initializations. # ac_default_prefix=/usr/local ac_clean_files= ac_config_libobj_dir=. LIBOBJS= cross_compiling=no subdirs= MFLAGS= MAKEFLAGS= # Identity of this package. PACKAGE_NAME='sipXtapi' PACKAGE_TARNAME='sipxtapi' PACKAGE_VERSION='3.3.0~test17' PACKAGE_STRING='sipXtapi 3.3.0~test17' PACKAGE_BUGREPORT='sipxtapi-dev@list.sipfoundry.org' PACKAGE_URL='' ac_unique_file="sipXportLib/src/os/OsConfigDb.cpp" # Factoring default headers for most tests. ac_includes_default="\ #include #ifdef HAVE_SYS_TYPES_H # include #endif #ifdef HAVE_SYS_STAT_H # include #endif #ifdef STDC_HEADERS # include # include #else # ifdef HAVE_STDLIB_H # include # endif #endif #ifdef HAVE_STRING_H # if !defined STDC_HEADERS && defined HAVE_MEMORY_H # include # endif # include #endif #ifdef HAVE_STRINGS_H # include #endif #ifdef HAVE_INTTYPES_H # include #endif #ifdef HAVE_STDINT_H # include #endif #ifdef HAVE_UNISTD_H # include #endif" enable_option_checking=no ac_header_list= ac_func_list= ac_subst_vars='am__EXEEXT_FALSE am__EXEEXT_TRUE LTLIBOBJS NAMED_PROGRAM BUILDEZPHONE_FALSE BUILDEZPHONE_TRUE WXWIDGETS_LIBS WXWIDGETS_CXXFLAGS WXWIDGETS_CFLAGS WXWIDGETS_CONFIG VIDEO_DEFINE BUILDCE_FALSE BUILDCE_TRUE SIPXMEDIA_CE_LIBS GIPS_CE_OBJS BUILDVE_FALSE BUILDVE_TRUE SIPXMEDIA_VE_STATIC_LIBS SIPXMEDIA_VE_LIBS GIPS_VE_OBJS GIPS_CPPFLAGS GIPS_NEQ_OBJS GIPSINC RTL_LDFLAGS RTL_CXXFLAGS SS_LDFLAGS EAGC_LDFLAGS EJBE_LDFLAGS EPLC_LDFLAGS EVAD_LDFLAGS ANT JAVAC_DEBUG JAVAC_OPTIMIZED JAVA jar JAVA_HOME SIPVIEWER_FALSE SIPVIEWER_TRUE USE_BLDNO_FALSE USE_BLDNO_TRUE DOC_FALSE DOC_TRUE enable_latex_docs enable_html_docs enable_dot DOT DOXYGEN ENABLE_LOCAL_AUDIO_FALSE ENABLE_LOCAL_AUDIO_TRUE BUILDTLS_FALSE BUILDTLS_TRUE SIPXPHONELIB SIPXPHONEDATA SIPXPHONECONF SIPXPBXUSER wwwdir SIPX_CONFIGPHONEDIR SIPX_BACKUPDIR SIPX_PARKMUSICDIR SIPX_VXMLDATADIR SIPX_DOCDIR SIPX_SCHEMADIR SIPX_DBDIR SIPX_TMPDIR SIPX_RUNDIR SIPX_LOGDIR SIPX_DATADIR SIPX_CONFDIR SIPX_BINDIR sipx_abs_srcdir SIPX_LIBDIR SIPX_INCDIR DISABLE_STREAM_PLAYER_FALSE DISABLE_STREAM_PLAYER_TRUE codeclibdir SPEEX_CONTRIB_FALSE SPEEX_CONTRIB_TRUE INTERFACE_FLAGS LIBOBJS BUILD_SIPXPORTUNIT_FALSE BUILD_SIPXPORTUNIT_TRUE BUILD_SIPXUNIT_FALSE BUILD_SIPXUNIT_TRUE SIPX_UNIT_TARGET CPPUNIT_LIBS CPPUNIT_CFLAGS CPPUNIT_CONFIG DEPS_PCRE_LIBS DEPS_PCRE_CFLAGS OPUS_STATIC_FALSE OPUS_STATIC_TRUE BUILD_CODEC_OPUS_FALSE BUILD_CODEC_OPUS_TRUE OPUS_LIBS OPUS_CFLAGS OPUS_TARGET AMRWB_FALSE AMRWB_TRUE AMRWB_LIB_ROOT AMRWB_INCLUDE AMRWB_TARGET AMRNB_FALSE AMRNB_TRUE subdirs AMRNB_LIB_ROOT AMRNB_INCLUDE AMR_TARGET G722_STATIC_FALSE G722_STATIC_TRUE BUILD_CODEC_G722_FALSE BUILD_CODEC_G722_TRUE G722_TARGET G726_STATIC_FALSE G726_STATIC_TRUE BUILD_CODEC_G726_FALSE BUILD_CODEC_G726_TRUE G726_TARGET L16_STATIC_FALSE L16_STATIC_TRUE BUILD_CODEC_L16_FALSE BUILD_CODEC_L16_TRUE L16_TARGET TONES_STATIC_FALSE TONES_STATIC_TRUE BUILD_CODEC_TONES_FALSE BUILD_CODEC_TONES_TRUE TONES_TARGET PCMAPCMU_STATIC_FALSE PCMAPCMU_STATIC_TRUE BUILD_CODEC_PCMAPCMU_FALSE BUILD_CODEC_PCMAPCMU_TRUE PCMAPCMU_TARGET BUILD_CODEC_ILBC_FALSE BUILD_CODEC_ILBC_TRUE ILBC_TARGET ILBC_LIB_TARGET ILBC_LIB_ROOT ILBC_INCLUDE SPEEX_STATIC_FALSE SPEEX_STATIC_TRUE BUILD_CODEC_SPEEX_FALSE BUILD_CODEC_SPEEX_TRUE STATIC_CODEC_LIBS SPEEX_TARGET BUILD_CODEC_GSM_FALSE BUILD_CODEC_GSM_TRUE GSM_LDFLAGS GSM_LIBS GSM_CXXFLAGS GSM_CFLAGS GSM_TARGET SPEEXDSP_STATIC_LIB SPEEX_STATIC_LIB SPEEX_ROOT SPEEX_LIBS SPEEX_CFLAGS SPEEXDSP_LIBS SPEEXDSP_CFLAGS SPANDSP_LDFLAGS SPANDSP_LIBS SPANDSP_CXXFLAGS SPANDSP_CFLAGS CARBON_LIBS COREAUDIO_DRIVERS_FALSE COREAUDIO_DRIVERS_TRUE CA_LIBS DYNEXT CROSS_COMPILING_FALSE CROSS_COMPILING_TRUE CXXCPP am__fastdepCXX_FALSE am__fastdepCXX_TRUE CXXDEPMODE ac_ct_CXX CXXFLAGS CXX PKG_CONFIG_LIBDIR PKG_CONFIG_PATH PKG_CONFIG CPP OTOOL64 OTOOL LIPO NMEDIT DSYMUTIL MANIFEST_TOOL RANLIB DLLTOOL OBJDUMP LN_S NM ac_ct_DUMPBIN DUMPBIN LD FGREP EGREP GREP SED host_os host_vendor host_cpu host build_os build_vendor build_cpu build LIBTOOL am__fastdepCC_FALSE am__fastdepCC_TRUE CCDEPMODE am__nodep AMDEPBACKSLASH AMDEP_FALSE AMDEP_TRUE am__quote am__include DEPDIR OBJEXT EXEEXT ac_ct_CC CPPFLAGS LDFLAGS CFLAGS CC ac_ct_AR AR am__untar am__tar AMTAR am__leading_dot SET_MAKE AWK mkdir_p MKDIR_P INSTALL_STRIP_PROGRAM STRIP install_sh MAKEINFO AUTOHEADER AUTOMAKE AUTOCONF ACLOCAL VERSION PACKAGE CYGPATH_W am__isrc INSTALL_DATA INSTALL_SCRIPT INSTALL_PROGRAM target_alias host_alias build_alias LIBS ECHO_T ECHO_N ECHO_C DEFS mandir localedir libdir psdir pdfdir dvidir htmldir infodir docdir oldincludedir includedir localstatedir sharedstatedir sysconfdir datadir datarootdir libexecdir sbindir bindir program_transform_name prefix exec_prefix PACKAGE_URL PACKAGE_BUGREPORT PACKAGE_STRING PACKAGE_VERSION PACKAGE_TARNAME PACKAGE_NAME PATH_SEPARATOR SHELL' ac_subst_files='' ac_user_opts=' enable_option_checking enable_dependency_tracking enable_shared enable_static with_pic enable_fast_install with_gnu_ld with_sysroot enable_libtool_lock with_spandsp_includedir with_spandsp_libdir with_spandsp_validg726 enable_speex_dsp enable_contrib_speex enable_codec_gsm with_gsm with_gsm_includedir with_gsm_libdir enable_codec_speex enable_codec_ilbc enable_codec_pcmapcmu enable_codec_tones enable_codec_l16 enable_codec_g726 enable_codec_g722 enable_codec_amr enable_codec_amrwb enable_codec_opus with_cppunit_prefix with_cppunit_exec_prefix enable_topology_graph enable_stream_player enable_rpmbuild enable_buildnumber enable_sip_tls enable_local_audio enable_doxygen enable_dot enable_html_docs enable_latex_docs enable_sipviewer with_rtllibaudio with_rtllibaudio_path with_rtllibaudio_inc_path with_rtllib with_rtllib_path with_rtllib_inc_path enable_external_rtl_init enable_rtl enable_rtlaudio with_external_vad with_external_vad_path with_external_plc with_external_plc_path with_external_jbe with_external_jbe_path with_external_agc with_external_agc_path with_external_ss with_external_ss_path enable_speaker_selection with_gipsneq with_gipsve with_gipsce enable_video enable_sipx_ezphone with_named ' ac_precious_vars='build_alias host_alias target_alias CC CFLAGS LDFLAGS LIBS CPPFLAGS CPP PKG_CONFIG PKG_CONFIG_PATH PKG_CONFIG_LIBDIR CXX CXXFLAGS CCC CXXCPP SPEEXDSP_CFLAGS SPEEXDSP_LIBS SPEEX_CFLAGS SPEEX_LIBS DEPS_PCRE_CFLAGS DEPS_PCRE_LIBS wwwdir SIPXPBXUSER JAVA_HOME JAVAC_OPTIMIZED JAVAC_DEBUG ANT' ac_subdirs_all='sipXmediaLib/contrib/libamrnb/ sipXmediaLib/contrib/libamrwb/' # Initialize some variables set by options. ac_init_help= ac_init_version=false ac_unrecognized_opts= ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null exec_prefix=NONE no_create= no_recursion= prefix=NONE program_prefix=NONE program_suffix=NONE program_transform_name=s,x,x, silent= site= srcdir= verbose= x_includes=NONE x_libraries=NONE # Installation directory options. # These are left unexpanded so users can "make install exec_prefix=/foo" # and all the variables that are supposed to be based on exec_prefix # by default will actually change. # Use braces instead of parens because sh, perl, etc. also accept them. # (The list follows the same order as the GNU Coding Standards.) bindir='${exec_prefix}/bin' sbindir='${exec_prefix}/sbin' libexecdir='${exec_prefix}/libexec' datarootdir='${prefix}/share' datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' infodir='${datarootdir}/info' htmldir='${docdir}' dvidir='${docdir}' pdfdir='${docdir}' psdir='${docdir}' libdir='${exec_prefix}/lib' localedir='${datarootdir}/locale' mandir='${datarootdir}/man' ac_prev= ac_dashdash= for ac_option do # If the previous option needs an argument, assign it. if test -n "$ac_prev"; then eval $ac_prev=\$ac_option ac_prev= continue fi case $ac_option in *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; *=) ac_optarg= ;; *) ac_optarg=yes ;; esac # Accept the important Cygnus configure options, so we can diagnose typos. case $ac_dashdash$ac_option in --) ac_dashdash=yes ;; -bindir | --bindir | --bindi | --bind | --bin | --bi) ac_prev=bindir ;; -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) bindir=$ac_optarg ;; -build | --build | --buil | --bui | --bu) ac_prev=build_alias ;; -build=* | --build=* | --buil=* | --bui=* | --bu=*) build_alias=$ac_optarg ;; -cache-file | --cache-file | --cache-fil | --cache-fi \ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) ac_prev=cache_file ;; -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) cache_file=$ac_optarg ;; --config-cache | -C) cache_file=config.cache ;; -datadir | --datadir | --datadi | --datad) ac_prev=datadir ;; -datadir=* | --datadir=* | --datadi=* | --datad=*) datadir=$ac_optarg ;; -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ | --dataroo | --dataro | --datar) ac_prev=datarootdir ;; -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) datarootdir=$ac_optarg ;; -disable-* | --disable-*) ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) docdir=$ac_optarg ;; -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) ac_prev=dvidir ;; -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) dvidir=$ac_optarg ;; -enable-* | --enable-*) ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ | --exec | --exe | --ex) ac_prev=exec_prefix ;; -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ | --exec=* | --exe=* | --ex=*) exec_prefix=$ac_optarg ;; -gas | --gas | --ga | --g) # Obsolete; use --with-gas. with_gas=yes ;; -help | --help | --hel | --he | -h) ac_init_help=long ;; -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) ac_init_help=recursive ;; -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) ac_init_help=short ;; -host | --host | --hos | --ho) ac_prev=host_alias ;; -host=* | --host=* | --hos=* | --ho=*) host_alias=$ac_optarg ;; -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) ac_prev=htmldir ;; -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ | --ht=*) htmldir=$ac_optarg ;; -includedir | --includedir | --includedi | --included | --include \ | --includ | --inclu | --incl | --inc) ac_prev=includedir ;; -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ | --includ=* | --inclu=* | --incl=* | --inc=*) includedir=$ac_optarg ;; -infodir | --infodir | --infodi | --infod | --info | --inf) ac_prev=infodir ;; -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) infodir=$ac_optarg ;; -libdir | --libdir | --libdi | --libd) ac_prev=libdir ;; -libdir=* | --libdir=* | --libdi=* | --libd=*) libdir=$ac_optarg ;; -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ | --libexe | --libex | --libe) ac_prev=libexecdir ;; -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ | --libexe=* | --libex=* | --libe=*) libexecdir=$ac_optarg ;; -localedir | --localedir | --localedi | --localed | --locale) ac_prev=localedir ;; -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) localedir=$ac_optarg ;; -localstatedir | --localstatedir | --localstatedi | --localstated \ | --localstate | --localstat | --localsta | --localst | --locals) ac_prev=localstatedir ;; -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) localstatedir=$ac_optarg ;; -mandir | --mandir | --mandi | --mand | --man | --ma | --m) ac_prev=mandir ;; -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) mandir=$ac_optarg ;; -nfp | --nfp | --nf) # Obsolete; use --without-fp. with_fp=no ;; -no-create | --no-create | --no-creat | --no-crea | --no-cre \ | --no-cr | --no-c | -n) no_create=yes ;; -no-recursion | --no-recursion | --no-recursio | --no-recursi \ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) no_recursion=yes ;; -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ | --oldin | --oldi | --old | --ol | --o) ac_prev=oldincludedir ;; -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) oldincludedir=$ac_optarg ;; -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) ac_prev=prefix ;; -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) prefix=$ac_optarg ;; -program-prefix | --program-prefix | --program-prefi | --program-pref \ | --program-pre | --program-pr | --program-p) ac_prev=program_prefix ;; -program-prefix=* | --program-prefix=* | --program-prefi=* \ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) program_prefix=$ac_optarg ;; -program-suffix | --program-suffix | --program-suffi | --program-suff \ | --program-suf | --program-su | --program-s) ac_prev=program_suffix ;; -program-suffix=* | --program-suffix=* | --program-suffi=* \ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) program_suffix=$ac_optarg ;; -program-transform-name | --program-transform-name \ | --program-transform-nam | --program-transform-na \ | --program-transform-n | --program-transform- \ | --program-transform | --program-transfor \ | --program-transfo | --program-transf \ | --program-trans | --program-tran \ | --progr-tra | --program-tr | --program-t) ac_prev=program_transform_name ;; -program-transform-name=* | --program-transform-name=* \ | --program-transform-nam=* | --program-transform-na=* \ | --program-transform-n=* | --program-transform-=* \ | --program-transform=* | --program-transfor=* \ | --program-transfo=* | --program-transf=* \ | --program-trans=* | --program-tran=* \ | --progr-tra=* | --program-tr=* | --program-t=*) program_transform_name=$ac_optarg ;; -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) ac_prev=pdfdir ;; -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) pdfdir=$ac_optarg ;; -psdir | --psdir | --psdi | --psd | --ps) ac_prev=psdir ;; -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) psdir=$ac_optarg ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ | --sbi=* | --sb=*) sbindir=$ac_optarg ;; -sharedstatedir | --sharedstatedir | --sharedstatedi \ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ | --sharedst | --shareds | --shared | --share | --shar \ | --sha | --sh) ac_prev=sharedstatedir ;; -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ | --sha=* | --sh=*) sharedstatedir=$ac_optarg ;; -site | --site | --sit) ac_prev=site ;; -site=* | --site=* | --sit=*) site=$ac_optarg ;; -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) ac_prev=srcdir ;; -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) srcdir=$ac_optarg ;; -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ | --syscon | --sysco | --sysc | --sys | --sy) ac_prev=sysconfdir ;; -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) sysconfdir=$ac_optarg ;; -target | --target | --targe | --targ | --tar | --ta | --t) ac_prev=target_alias ;; -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) target_alias=$ac_optarg ;; -v | -verbose | --verbose | --verbos | --verbo | --verb) verbose=yes ;; -version | --version | --versio | --versi | --vers | -V) ac_init_version=: ;; -with-* | --with-*) ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. with_x=yes ;; -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ | --x-incl | --x-inc | --x-in | --x-i) ac_prev=x_includes ;; -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) x_includes=$ac_optarg ;; -x-libraries | --x-libraries | --x-librarie | --x-librari \ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) ac_prev=x_libraries ;; -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; -*) as_fn_error $? "unrecognized option: \`$ac_option' Try \`$0 --help' for more information" ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. case $ac_envvar in #( '' | [0-9]* | *[!_$as_cr_alnum]* ) as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" ;; esac done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` as_fn_error $? "missing argument to $ac_option" fi if test -n "$ac_unrecognized_opts"; then case $enable_option_checking in no) ;; fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; esac fi # Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir do eval ac_val=\$$ac_var # Remove trailing slashes. case $ac_val in */ ) ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` eval $ac_var=\$ac_val;; esac # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: `$host' # used to hold the argument of --host etc. # FIXME: To remove some day. build=$build_alias host=$host_alias target=$target_alias # FIXME: To remove some day. if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi fi ac_tool_prefix= test -n "$host_alias" && ac_tool_prefix=$host_alias- test "$silent" = yes && exec 6>/dev/null ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || as_fn_error $? "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || as_fn_error $? "pwd does not report name of working directory" # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. ac_confdir=`$as_dirname -- "$as_myself" || $as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_myself" : 'X\(//\)[^/]' \| \ X"$as_myself" : 'X\(//\)$' \| \ X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` srcdir=$ac_confdir if test ! -r "$srcdir/$ac_unique_file"; then srcdir=.. fi else ac_srcdir_defaulted=no fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then srcdir=. fi # Remove unnecessary trailing slashes from srcdir. # Double slashes in file names in object file debugging info # mess up M-x gdb in Emacs. case $srcdir in */) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; esac for ac_var in $ac_precious_vars; do eval ac_env_${ac_var}_set=\${${ac_var}+set} eval ac_env_${ac_var}_value=\$${ac_var} eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} eval ac_cv_env_${ac_var}_value=\$${ac_var} done # # Report the --help message. # if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF \`configure' configures sipXtapi 3.3.0~test17 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit -q, --quiet, --silent do not print \`checking ...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for \`--cache-file=config.cache' -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or \`..'] Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify an installation prefix other than \`$ac_default_prefix' using \`--prefix', for instance \`--prefix=\$HOME'. For better control, use the options below. Fine tuning of the installation directories: --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] --datadir=DIR read-only architecture-independent data [DATAROOTDIR] --infodir=DIR info documentation [DATAROOTDIR/info] --localedir=DIR locale-dependent data [DATAROOTDIR/locale] --mandir=DIR man documentation [DATAROOTDIR/man] --docdir=DIR documentation root [DATAROOTDIR/doc/sipxtapi] --htmldir=DIR html documentation [DOCDIR] --dvidir=DIR dvi documentation [DOCDIR] --pdfdir=DIR pdf documentation [DOCDIR] --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF Program names: --program-prefix=PREFIX prepend PREFIX to installed program names --program-suffix=SUFFIX append SUFFIX to installed program names --program-transform-name=PROGRAM run sed PROGRAM on installed program names System types: --build=BUILD configure for building on BUILD [guessed] --host=HOST cross-compile to build programs to run on HOST [BUILD] _ACEOF fi if test -n "$ac_init_help"; then case $ac_init_help in short | recursive ) echo "Configuration of sipXtapi 3.3.0~test17:";; esac cat <<\_ACEOF Optional Features: --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --disable-dependency-tracking speeds up one-time build --enable-dependency-tracking do not reject slow dependency extractors --enable-shared[=PKGS] build shared libraries [default=yes] --enable-static[=PKGS] build static libraries [default=yes] --enable-fast-install[=PKGS] optimize for fast installation [default=yes] --disable-libtool-lock avoid locking (might break parallel builds) --enable-speex-dsp Enable SPEEX dsp library usage [default=no] --enable-contrib-speex Ignore any installed SPEEX libraries. Instead, build and use the ones in the contrib directory. [default=no] --enable-codec-gsm Enable support for GSM codec [default=auto] --enable-codec-speex Enable support for SPEEX codec [default=no] --enable-codec-ilbc Enable support for ilbc codec [default=yes] --enable-codec-pcmapcmu Enable support for PCMA and PCMU codecs [default=yes] --enable-codec-tones Enable support for Tones codec [default=yes] --enable-codec-l16 Enable support for L16 codec [default=no] --enable-codec-g726 Enable support for g726 codec [default=yes] --enable-codec-g722 Enable support for g722 codec [default=yes] --enable-codec-amr Enable support for amr codec [default=no] --enable-codec-amrwb Enable support for amrwb codec [default=no] --enable-codec-opus Enable support for Opus codec [default=yes] --enable-topology-graph Enable toplogy graph as default processing [default=no] --disable-stream-player Disable stream player (removes sipXtack dependency on media layer) [default=no] --enable-rpmbuild Build an rpm --enable-buildnumber enable build number as part of RPM name --enable-sip-tls enable support for sips: and transport=tls (no) --enable-local-audio Enable local audio (speaker and microphone), makes sense for CallFlowGraph only --enable-doxygen enable documentation generation with doxygen (yes) --enable-dot use 'dot' to generate graphs in doxygen (auto) --enable-html-docs enable HTML generation with doxygen (yes) --enable-latex-docs enable LaTeX documentation generation with doxygen (no) --enable-sipviewer Compile java based sipviewer program (needs JVM) --enable-external-rtl-init Initialize external RTL collector to log to sipXmediaLib internal one [default=no] --enable-rtl Enable RTL for the whole library [default=no] --enable-rtlaudio Enable RTL_AUDIO for the whole library [default=no] --enable-speaker-selection Enable Speaker Selection resource in flowgraph [default=no] --enable-video Include video support (no) --enable-sipx-ezphone build the sipXezPhone example application (no) Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) --with-pic[=PKGS] try to use only PIC/non-PIC objects [default=use both] --with-gnu-ld assume the C compiler uses GNU ld [default=no] --with-sysroot=DIR Search for dependent libraries within DIR (or the compiler's sysroot if not specified). --with-spandsp-includedir=PATH path to libspandsp include directory (containing spandsp.h) --with-spandsp-libdir=PATH path to libspandsp lib directory (containing libspandsp.{so,la}) --with-spandsp-validg726=VAL Set VAL to 'yes' or 'ok' to use G726 with old libspandsp (where packing mode parameter compiled in library) --with-gsm=PATH path to libgsm install directory --with-gsm-includedir=PATH path to libgsm include directory (containing gsm.h) --with-gsm-libdir=PATH path to libgsm lib directory (containing libgsm.{so,a}) --with-cppunit-prefix=PFX Prefix where CppUnit is installed (optional) --with-cppunit-exec-prefix=PFX Exec prefix where CppUnit is installed (optional) --with-rtllibaudio=library Use specified library for RtlAudio --with-rtllibaudio-path=PATH Add path for RtlAudio --with-rtllibaudio-inc-path=PATH Add path for headers for RtlAudio --with-rtllib=library Use specified library for Rtl --with-rtllib-path=PATH Add path for Rtl --with-rtllib-inc-path=PATH Add path for headers for Rtl --with-external-vad=library Use external library for VAD --with-external-vad-path=PATH Add path for searching external library for VAD --with-external-plc=library Use external library for PLC --with-external-plc-path=PATH Add path for searching external library for PLC --with-external-jbe=library Use external library for Jitter buffer estimation --with-external-jbe-path=PATH Add path for searching external library for JBE --with-external-agc=library Use external library for AGC --with-external-agc-path=PATH Add path for searching external library for AGC --with-external-ss=library Use external library for speaker selection --with-external-ss-path=PATH Add path for searching external library for SS --with-gipsneq Compile the media subsystem with the GIPS audio libraries --with-gipsve Link to GIPS voice engine if --with-gipsve is set --with-gipsce Link to GIPS conference engine if --with-gipsce is set --with-named=PATH the named/bind executable Some influential environment variables: CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory CPP C preprocessor PKG_CONFIG path to pkg-config utility PKG_CONFIG_PATH directories to add to pkg-config's search path PKG_CONFIG_LIBDIR path overriding pkg-config's built-in search path CXX C++ compiler command CXXFLAGS C++ compiler flags CXXCPP C++ preprocessor SPEEX_CFLAGS C compiler flags for SPEEX, overriding pkg-config SPEEX_LIBS linker flags for SPEEX, overriding pkg-config DEPS_PCRE_CFLAGS C compiler flags for DEPS_PCRE, overriding pkg-config DEPS_PCRE_LIBS linker flags for DEPS_PCRE, overriding pkg-config wwwdir Web root for web content, default is ${datadir}/www. WARNING: Adjust accordingly when following INSTALL instructions SIPXPBXUSER The user that sipXpbx runs under, default is 'sipxchange' JAVA_HOME Java Development Kit JAVAC_OPTIMIZED Java compiler option for faster performance. Default is on JAVAC_DEBUG Java compiler option to reduce code size. Default is off ANT Ant program Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to . _ACEOF ac_status=$? fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue test -d "$ac_dir" || { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix cd "$ac_dir" || { ac_status=$?; continue; } # Check for guested configure. if test -f "$ac_srcdir/configure.gnu"; then echo && $SHELL "$ac_srcdir/configure.gnu" --help=recursive elif test -f "$ac_srcdir/configure"; then echo && $SHELL "$ac_srcdir/configure" --help=recursive else $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF sipXtapi configure 3.3.0~test17 generated by GNU Autoconf 2.69 Copyright (C) 2012 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi ## ------------------------ ## ## Autoconf initialization. ## ## ------------------------ ## # ac_fn_c_try_compile LINENO # -------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_compile # ac_fn_c_try_link LINENO # ----------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_link () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext conftest$ac_exeext if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || test -x conftest$ac_exeext }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would # interfere with the next link command; also delete a directory that is # left behind by Apple's compiler. We do this before executing the actions. rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_link # ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists and can be compiled using the include files in # INCLUDES, setting the cache variable VAR accordingly. ac_fn_c_check_header_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_compile # ac_fn_c_try_cpp LINENO # ---------------------- # Try to preprocess conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_cpp () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } > conftest.i && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_cpp # ac_fn_c_try_run LINENO # ---------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. Assumes # that executables *can* be run. ac_fn_c_try_run () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then : ac_retval=0 else $as_echo "$as_me: program exited with status $ac_status" >&5 $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=$ac_status fi rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_run # ac_fn_c_check_func LINENO FUNC VAR # ---------------------------------- # Tests whether FUNC exists, setting the cache variable VAR accordingly ac_fn_c_check_func () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Define $2 to an innocuous variant, in case declares $2. For example, HP-UX 11i declares gettimeofday. */ #define $2 innocuous_$2 /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $2 (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $2 /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char $2 (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined __stub_$2 || defined __stub___$2 choke me #endif int main () { return $2 (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_func # ac_fn_cxx_try_compile LINENO # ---------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_cxx_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_cxx_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_compile # ac_fn_cxx_try_cpp LINENO # ------------------------ # Try to preprocess conftest.$ac_ext, and return whether this succeeded. ac_fn_cxx_try_cpp () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } > conftest.i && { test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" || test ! -s conftest.err }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_cpp # ac_fn_cxx_try_link LINENO # ------------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. ac_fn_cxx_try_link () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext conftest$ac_exeext if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_cxx_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || test -x conftest$ac_exeext }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would # interfere with the next link command; also delete a directory that is # left behind by Apple's compiler. We do this before executing the actions. rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_link # ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists, giving a warning if it cannot be compiled using # the include files in INCLUDES and setting the cache variable VAR # accordingly. ac_fn_c_check_header_mongrel () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if eval \${$3+:} false; then : { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } else # Is the header compilable? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 $as_echo_n "checking $2 usability... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_header_compiler=yes else ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 $as_echo "$ac_header_compiler" >&6; } # Is the header present? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 $as_echo_n "checking $2 presence... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include <$2> _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : ac_header_preproc=yes else ac_header_preproc=no fi rm -f conftest.err conftest.i conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 $as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( yes:no: ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 $as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ;; no:yes:* ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 $as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 $as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 $as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 $as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ( $as_echo "## ----------------------------------------------- ## ## Report this to sipxtapi-dev@list.sipfoundry.org ## ## ----------------------------------------------- ##" ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=\$ac_header_compiler" fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_mongrel # ac_fn_c_check_type LINENO TYPE VAR INCLUDES # ------------------------------------------- # Tests whether TYPE exists after having included INCLUDES, setting cache # variable VAR accordingly. ac_fn_c_check_type () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=no" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { if (sizeof ($2)) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { if (sizeof (($2))) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else eval "$3=yes" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_type cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by sipXtapi $as_me 3.3.0~test17, which was generated by GNU Autoconf 2.69. Invocation command line was $ $0 $@ _ACEOF exec 5>>config.log { cat <<_ASUNAME ## --------- ## ## Platform. ## ## --------- ## hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` /bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` /bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` /usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` /bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` /bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` _ASUNAME as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. $as_echo "PATH: $as_dir" done IFS=$as_save_IFS } >&5 cat >&5 <<_ACEOF ## ----------- ## ## Core tests. ## ## ----------- ## _ACEOF # Keep a trace of the command line. # Strip out --no-create and --no-recursion so they do not pile up. # Strip out --silent because we don't want to record it for future runs. # Also quote any args containing shell meta-characters. # Make two passes to allow for proper duplicate-argument suppression. ac_configure_args= ac_configure_args0= ac_configure_args1= ac_must_keep_next=false for ac_pass in 1 2 do for ac_arg do case $ac_arg in -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; 2) as_fn_append ac_configure_args1 " '$ac_arg'" if test $ac_must_keep_next = true; then ac_must_keep_next=false # Got value, back to normal. else case $ac_arg in *=* | --config-cache | -C | -disable-* | --disable-* \ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ | -with-* | --with-* | -without-* | --without-* | --x) case "$ac_configure_args0 " in "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; esac ;; -* ) ac_must_keep_next=true ;; esac fi as_fn_append ac_configure_args " '$ac_arg'" ;; esac done done { ac_configure_args0=; unset ac_configure_args0;} { ac_configure_args1=; unset ac_configure_args1;} # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there # would cause problems or look ugly. # WARNING: Use '\'' to represent an apostrophe within the trap. # WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. trap 'exit_status=$? # Save into config.log some information that might help in debugging. { echo $as_echo "## ---------------- ## ## Cache variables. ## ## ---------------- ##" echo # The following way of writing the cache mishandles newlines in values, ( for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( *${as_nl}ac_space=\ *) sed -n \ "s/'\''/'\''\\\\'\'''\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" ;; #( *) sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) echo $as_echo "## ----------------- ## ## Output variables. ## ## ----------------- ##" echo for ac_var in $ac_subst_vars do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo if test -n "$ac_subst_files"; then $as_echo "## ------------------- ## ## File substitutions. ## ## ------------------- ##" echo for ac_var in $ac_subst_files do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo fi if test -s confdefs.h; then $as_echo "## ----------- ## ## confdefs.h. ## ## ----------- ##" echo cat confdefs.h echo fi test "$ac_signal" != 0 && $as_echo "$as_me: caught signal $ac_signal" $as_echo "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status ' 0 for ac_signal in 1 2 13 15; do trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. rm -f -r conftest* confdefs.h $as_echo "/* confdefs.h */" > confdefs.h # Predefined preprocessor variables. cat >>confdefs.h <<_ACEOF #define PACKAGE_NAME "$PACKAGE_NAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_TARNAME "$PACKAGE_TARNAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_VERSION "$PACKAGE_VERSION" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_STRING "$PACKAGE_STRING" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_URL "$PACKAGE_URL" _ACEOF # Let the site file select an alternate cache file if it wants to. # Prefer an explicitly selected file to automatically selected ones. ac_site_file1=NONE ac_site_file2=NONE if test -n "$CONFIG_SITE"; then # We do not want a PATH search for config.site. case $CONFIG_SITE in #(( -*) ac_site_file1=./$CONFIG_SITE;; */*) ac_site_file1=$CONFIG_SITE;; *) ac_site_file1=./$CONFIG_SITE;; esac elif test "x$prefix" != xNONE; then ac_site_file1=$prefix/share/config.site ac_site_file2=$prefix/etc/config.site else ac_site_file1=$ac_default_prefix/share/config.site ac_site_file2=$ac_default_prefix/etc/config.site fi for ac_site_file in "$ac_site_file1" "$ac_site_file2" do test "x$ac_site_file" = xNONE && continue if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 $as_echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" \ || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "failed to load site script $ac_site_file See \`config.log' for more details" "$LINENO" 5; } fi done if test -r "$cache_file"; then # Some versions of bash will fail to source /dev/null (special files # actually), so we avoid doing that. DJGPP emulates it as a regular file. if test /dev/null != "$cache_file" && test -f "$cache_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 $as_echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . "$cache_file";; *) . "./$cache_file";; esac fi else { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 $as_echo "$as_me: creating cache $cache_file" >&6;} >$cache_file fi as_fn_append ac_header_list " sys/time.h" as_fn_append ac_header_list " unistd.h" as_fn_append ac_func_list " alarm" # Check that the precious variables saved in the cache have kept the same # value. ac_cache_corrupted=false for ac_var in $ac_precious_vars; do eval ac_old_set=\$ac_cv_env_${ac_var}_set eval ac_new_set=\$ac_env_${ac_var}_set eval ac_old_val=\$ac_cv_env_${ac_var}_value eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then # differences in whitespace do not lead to failure. ac_old_val_w=`echo x $ac_old_val` ac_new_val_w=`echo x $ac_new_val` if test "$ac_old_val_w" != "$ac_new_val_w"; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 $as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} ac_cache_corrupted=: else { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 $as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} eval $ac_var=\$ac_old_val fi { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 $as_echo "$as_me: former value: \`$ac_old_val'" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 $as_echo "$as_me: current value: \`$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. *) as_fn_append ac_configure_args " '$ac_arg'" ;; esac fi done if $ac_cache_corrupted; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 $as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 fi ## -------------------- ## ## Main body of script. ## ## -------------------- ## ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_aux_dir= for ac_dir in build-aux "$srcdir"/build-aux; do if test -f "$ac_dir/install-sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install-sh -c" break elif test -f "$ac_dir/install.sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install.sh -c" break elif test -f "$ac_dir/shtool"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/shtool install -c" break fi done if test -z "$ac_aux_dir"; then as_fn_error $? "cannot find install-sh, install.sh, or shtool in build-aux \"$srcdir\"/build-aux" "$LINENO" 5 fi # These three variables are undocumented and unsupported, # and are intended to be withdrawn in a future Autoconf release. # They can cause serious problems if a builder's source tree is in a directory # whose full name contains unusual characters. ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. am__api_version='1.11' # Find a good install program. We prefer a C program (faster), # so one script is as good as another. But avoid the broken or # incompatible versions: # SysV /etc/install, /usr/sbin/install # SunOS /usr/etc/install # IRIX /sbin/install # AIX /bin/install # AmigaOS /C/install, which installs bootblocks on floppy discs # AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag # AFS /usr/afsws/bin/install, which mishandles nonexistent args # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" # OS/2's system install, which has a completely different semantic # ./install, which can be erroneously created by make from ./install.sh. # Reject install programs that cannot install multiple files. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 $as_echo_n "checking for a BSD-compatible install... " >&6; } if test -z "$INSTALL"; then if ${ac_cv_path_install+:} false; then : $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. # Account for people who put trailing slashes in PATH elements. case $as_dir/ in #(( ./ | .// | /[cC]/* | \ /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ /usr/ucb/* ) ;; *) # OSF1 and SCO ODT 3.0 have their own names for install. # Don't use installbsd from OSF since it installs stuff as root # by default. for ac_prog in ginstall scoinst install; do for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then if test $ac_prog = install && grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # AIX install. It has an incompatible calling convention. : elif test $ac_prog = install && grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # program-specific install script used by HP pwplus--don't use. : else rm -rf conftest.one conftest.two conftest.dir echo one > conftest.one echo two > conftest.two mkdir conftest.dir if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && test -s conftest.one && test -s conftest.two && test -s conftest.dir/conftest.one && test -s conftest.dir/conftest.two then ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" break 3 fi fi fi done done ;; esac done IFS=$as_save_IFS rm -rf conftest.one conftest.two conftest.dir fi if test "${ac_cv_path_install+set}" = set; then INSTALL=$ac_cv_path_install else # As a last resort, use the slow shell script. Don't cache a # value for INSTALL within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. INSTALL=$ac_install_sh fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 $as_echo "$INSTALL" >&6; } # Use test -z because SunOS4 sh mishandles braces in ${var-val}. # It thinks the first close brace ends the variable substitution. test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build environment is sane" >&5 $as_echo_n "checking whether build environment is sane... " >&6; } # Just in case sleep 1 echo timestamp > conftest.file # Reject unsafe characters in $srcdir or the absolute working directory # name. Accept space and tab only in the latter. am_lf=' ' case `pwd` in *[\\\"\#\$\&\'\`$am_lf]*) as_fn_error $? "unsafe absolute working directory name" "$LINENO" 5;; esac case $srcdir in *[\\\"\#\$\&\'\`$am_lf\ \ ]*) as_fn_error $? "unsafe srcdir value: \`$srcdir'" "$LINENO" 5;; esac # Do `set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` if test "$*" = "X"; then # -L didn't work. set X `ls -t "$srcdir/configure" conftest.file` fi rm -f conftest.file if test "$*" != "X $srcdir/configure conftest.file" \ && test "$*" != "X conftest.file $srcdir/configure"; then # If neither matched, then we have a broken ls. This can happen # if, for instance, CONFIG_SHELL is bash and it inherits a # broken ls alias from the environment. This has actually # happened. Such a system could not be considered "sane". as_fn_error $? "ls -t appears to fail. Make sure there is not a broken alias in your environment" "$LINENO" 5 fi test "$2" = conftest.file ) then # Ok. : else as_fn_error $? "newly created file is older than distributed files! Check your system clock" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } test "$program_prefix" != NONE && program_transform_name="s&^&$program_prefix&;$program_transform_name" # Use a double $ so make ignores it. test "$program_suffix" != NONE && program_transform_name="s&\$&$program_suffix&;$program_transform_name" # Double any \ or $. # By default was `s,x,x', remove it if useless. ac_script='s/[\\$]/&&/g;s/;s,x,x,$//' program_transform_name=`$as_echo "$program_transform_name" | sed "$ac_script"` # expand $ac_aux_dir to an absolute path am_aux_dir=`cd $ac_aux_dir && pwd` if test x"${MISSING+set}" != xset; then case $am_aux_dir in *\ * | *\ *) MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; *) MISSING="\${SHELL} $am_aux_dir/missing" ;; esac fi # Use eval to expand $SHELL if eval "$MISSING --run true"; then am_missing_run="$MISSING --run " else am_missing_run= { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`missing' script is too old or missing" >&5 $as_echo "$as_me: WARNING: \`missing' script is too old or missing" >&2;} fi if test x"${install_sh}" != xset; then case $am_aux_dir in *\ * | *\ *) install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; *) install_sh="\${SHELL} $am_aux_dir/install-sh" esac fi # Installed binaries are usually stripped using `strip' when the user # run `make install-strip'. However `strip' might not be the right # tool to use in cross-compilation environments, therefore Automake # will honor the `STRIP' environment variable to overrule this program. if test "$cross_compiling" != no; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. set dummy ${ac_tool_prefix}strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_STRIP="${ac_tool_prefix}strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 $as_echo "$STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_STRIP"; then ac_ct_STRIP=$STRIP # Extract the first word of "strip", so it can be a program name with args. set dummy strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_STRIP="strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 $as_echo "$ac_ct_STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_STRIP" = x; then STRIP=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac STRIP=$ac_ct_STRIP fi else STRIP="$ac_cv_prog_STRIP" fi fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a thread-safe mkdir -p" >&5 $as_echo_n "checking for a thread-safe mkdir -p... " >&6; } if test -z "$MKDIR_P"; then if ${ac_cv_path_mkdir+:} false; then : $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in mkdir gmkdir; do for ac_exec_ext in '' $ac_executable_extensions; do as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext" || continue case `"$as_dir/$ac_prog$ac_exec_ext" --version 2>&1` in #( 'mkdir (GNU coreutils) '* | \ 'mkdir (coreutils) '* | \ 'mkdir (fileutils) '4.1*) ac_cv_path_mkdir=$as_dir/$ac_prog$ac_exec_ext break 3;; esac done done done IFS=$as_save_IFS fi test -d ./--version && rmdir ./--version if test "${ac_cv_path_mkdir+set}" = set; then MKDIR_P="$ac_cv_path_mkdir -p" else # As a last resort, use the slow shell script. Don't cache a # value for MKDIR_P within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. MKDIR_P="$ac_install_sh -d" fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MKDIR_P" >&5 $as_echo "$MKDIR_P" >&6; } mkdir_p="$MKDIR_P" case $mkdir_p in [\\/$]* | ?:[\\/]*) ;; */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;; esac for ac_prog in gawk mawk nawk awk do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AWK+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AWK"; then ac_cv_prog_AWK="$AWK" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AWK="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AWK=$ac_cv_prog_AWK if test -n "$AWK"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5 $as_echo "$AWK" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$AWK" && break done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 $as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } set x ${MAKE-make} ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then : $as_echo_n "(cached) " >&6 else cat >conftest.make <<\_ACEOF SHELL = /bin/sh all: @echo '@@@%%%=$(MAKE)=@@@%%%' _ACEOF # GNU make sometimes prints "make[1]: Entering ...", which would confuse us. case `${MAKE-make} -f conftest.make 2>/dev/null` in *@@@%%%=?*=@@@%%%*) eval ac_cv_prog_make_${ac_make}_set=yes;; *) eval ac_cv_prog_make_${ac_make}_set=no;; esac rm -f conftest.make fi if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } SET_MAKE= else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } SET_MAKE="MAKE=${MAKE-make}" fi rm -rf .tst 2>/dev/null mkdir .tst 2>/dev/null if test -d .tst; then am__leading_dot=. else am__leading_dot=_ fi rmdir .tst 2>/dev/null if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." am__isrc=' -I$(srcdir)' # test to see if srcdir already configured if test -f $srcdir/config.status; then as_fn_error $? "source directory already configured; run \"make distclean\" there first" "$LINENO" 5 fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi # Define the identity of the package. PACKAGE='sipxtapi' VERSION='3.3.0~test17' cat >>confdefs.h <<_ACEOF #define PACKAGE "$PACKAGE" _ACEOF cat >>confdefs.h <<_ACEOF #define VERSION "$VERSION" _ACEOF # Some tools Automake needs. ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"} AUTOCONF=${AUTOCONF-"${am_missing_run}autoconf"} AUTOMAKE=${AUTOMAKE-"${am_missing_run}automake-${am__api_version}"} AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"} MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"} # We need awk for the "check" target. The system "awk" is bad on # some platforms. # Always define AMTAR for backward compatibility. Yes, it's still used # in the wild :-( We should find a proper way to deprecate it ... AMTAR='$${TAR-tar}' { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to create a ustar tar archive" >&5 $as_echo_n "checking how to create a ustar tar archive... " >&6; } # Loop over all known methods to create a tar archive until one works. _am_tools='gnutar plaintar pax cpio none' _am_tools=${am_cv_prog_tar_ustar-$_am_tools} # Do not fold the above two line into one, because Tru64 sh and # Solaris sh will not grok spaces in the rhs of `-'. for _am_tool in $_am_tools do case $_am_tool in gnutar) for _am_tar in tar gnutar gtar; do { echo "$as_me:$LINENO: $_am_tar --version" >&5 ($_am_tar --version) >&5 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && break done am__tar="$_am_tar --format=ustar -chf - "'"$$tardir"' am__tar_="$_am_tar --format=ustar -chf - "'"$tardir"' am__untar="$_am_tar -xf -" ;; plaintar) # Must skip GNU tar: if it does not support --format= it doesn't create # ustar tarball either. (tar --version) >/dev/null 2>&1 && continue am__tar='tar chf - "$$tardir"' am__tar_='tar chf - "$tardir"' am__untar='tar xf -' ;; pax) am__tar='pax -L -x ustar -w "$$tardir"' am__tar_='pax -L -x ustar -w "$tardir"' am__untar='pax -r' ;; cpio) am__tar='find "$$tardir" -print | cpio -o -H ustar -L' am__tar_='find "$tardir" -print | cpio -o -H ustar -L' am__untar='cpio -i -H ustar -d' ;; none) am__tar=false am__tar_=false am__untar=false ;; esac # If the value was cached, stop now. We just wanted to have am__tar # and am__untar set. test -n "${am_cv_prog_tar_ustar}" && break # tar/untar a dummy directory, and stop if the command works rm -rf conftest.dir mkdir conftest.dir echo GrepMe > conftest.dir/file { echo "$as_me:$LINENO: tardir=conftest.dir && eval $am__tar_ >conftest.tar" >&5 (tardir=conftest.dir && eval $am__tar_ >conftest.tar) >&5 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } rm -rf conftest.dir if test -s conftest.tar; then { echo "$as_me:$LINENO: $am__untar &5 ($am__untar &5 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } grep GrepMe conftest.dir/file >/dev/null 2>&1 && break fi done rm -rf conftest.dir if ${am_cv_prog_tar_ustar+:} false; then : $as_echo_n "(cached) " >&6 else am_cv_prog_tar_ustar=$_am_tool fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_prog_tar_ustar" >&5 $as_echo "$am_cv_prog_tar_ustar" >&6; } #AC_PREFIX_DEFAULT([/usr/local/sipx]) DEPDIR="${am__leading_dot}deps" ac_config_commands="$ac_config_commands depfiles" am_make=${MAKE-make} cat > confinc << 'END' am__doit: @echo this is the am__doit target .PHONY: am__doit END # If we don't find an include directive, just comment out the code. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for style of include used by $am_make" >&5 $as_echo_n "checking for style of include used by $am_make... " >&6; } am__include="#" am__quote= _am_result=none # First try GNU make style include. echo "include confinc" > confmf # Ignore all kinds of additional output from `make'. case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=include am__quote= _am_result=GNU ;; esac # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=.include am__quote="\"" _am_result=BSD ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $_am_result" >&5 $as_echo "$_am_result" >&6; } rm -f confinc confmf # Check whether --enable-dependency-tracking was given. if test "${enable_dependency_tracking+set}" = set; then : enableval=$enable_dependency_tracking; fi if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' am__nodep='_no' fi if test "x$enable_dependency_tracking" != xno; then AMDEP_TRUE= AMDEP_FALSE='#' else AMDEP_TRUE='#' AMDEP_FALSE= fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" fi fi fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CC" && break done if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi fi fi test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH See \`config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 $as_echo_n "checking whether the C compiler works... " >&6; } ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` # The possible output files: ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" ac_rmfiles= for ac_file in $ac_files do case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; * ) ac_rmfiles="$ac_rmfiles $ac_file";; esac done rm -f $ac_rmfiles if { { ac_try="$ac_link_default" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link_default") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. # So ignore a value of `no', otherwise this would lead to `EXEEXT = no' # in a Makefile. We should not override ac_cv_exeext if it was cached, # so that the user can short-circuit this test for compilers unknown to # Autoconf. for ac_file in $ac_files '' do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most # certainly right. break;; *.* ) if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; then :; else ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` fi # We set ac_cv_exeext here because the later test for it is not # safe: cross compilers may not add the suffix if given an `-o' # argument, so we may need to know it at that point already. # Even if this section looks crufty: it has the advantage of # actually working. break;; * ) break;; esac done test "$ac_cv_exeext" = no && ac_cv_exeext= else ac_file='' fi if test -z "$ac_file"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "C compiler cannot create executables See \`config.log' for more details" "$LINENO" 5; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 $as_echo_n "checking for C compiler default output file name... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 $as_echo "$ac_file" >&6; } ac_exeext=$ac_cv_exeext rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 $as_echo_n "checking for suffix of executables... " >&6; } if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # If both `conftest.exe' and `conftest' are `present' (well, observable) # catch `conftest.exe'. For instance with Cygwin, `ls conftest' will # work properly (i.e., refer to `conftest.exe'), while it won't with # `rm'. for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` break;; * ) break;; esac done else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of executables: cannot compile and link See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest conftest$ac_cv_exeext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 $as_echo "$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { FILE *f = fopen ("conftest.out", "w"); return ferror (f) || fclose (f) != 0; ; return 0; } _ACEOF ac_clean_files="$ac_clean_files conftest.out" # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 $as_echo_n "checking whether we are cross compiling... " >&6; } if test "$cross_compiling" != yes; then { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if { ac_try='./conftest$ac_cv_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then cross_compiling=no else if test "$cross_compiling" = maybe; then cross_compiling=yes else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details" "$LINENO" 5; } fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 $as_echo "$cross_compiling" >&6; } rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 $as_echo_n "checking for suffix of object files... " >&6; } if ${ac_cv_objext+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.o conftest.obj if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : for ac_file in conftest.o conftest.obj conftest.*; do test -f "$ac_file" || continue; case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of object files: cannot compile See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 $as_echo "$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; } if ${ac_cv_c_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 $as_echo "$ac_cv_c_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GCC=yes else GCC= fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 $as_echo_n "checking whether $CC accepts -g... " >&6; } if ${ac_cv_prog_cc_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes else CFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 $as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; } if ${ac_cv_prog_cc_c89+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include struct stat; /* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ struct buf { int x; }; FILE * (*rcsopen) (struct buf *, struct stat *, int); static char *e (p, i) char **p; int i; { return p[i]; } static char *f (char * (*g) (char **, int), char **p, ...) { char *s; va_list v; va_start (v,p); s = g (p, va_arg (v,int)); va_end (v); return s; } /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not '\xHH' hex character constants. These don't provoke an error unfortunately, instead are silently treated as 'x'. The following induces an error, until -std is added to get proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an array size at least. It's necessary to write '\x00'==0 to get something that's true only with -std. */ int osf4_cc_array ['\x00' == 0 ? 1 : -1]; /* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters inside strings and character constants. */ #define FOO(x) 'x' int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); int argc; char **argv; int main () { return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; ; return 0; } _ACEOF for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_c89=$ac_arg fi rm -f core conftest.err conftest.$ac_objext test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC fi # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 $as_echo "none needed" >&6; } ;; xno) { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 $as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 $as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac if test "x$ac_cv_prog_cc_c89" != xno; then : fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu depcc="$CC" am_compiler_list= { $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 $as_echo_n "checking dependency style of $depcc... " >&6; } if ${am_cv_CC_dependencies_compiler_type+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named `D' -- because `-MD' means `put the output # in D'. rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_CC_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` fi am__universal=false case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with # Solaris 8's {/usr,}/bin/sh. touch sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with `-c' and `-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle `-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # after this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok `-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_CC_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_CC_dependencies_compiler_type=none fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_CC_dependencies_compiler_type" >&5 $as_echo "$am_cv_CC_dependencies_compiler_type" >&6; } CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type if test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then am__fastdepCC_TRUE= am__fastdepCC_FALSE='#' else am__fastdepCC_TRUE='#' am__fastdepCC_FALSE= fi if test -n "$ac_tool_prefix"; then for ac_prog in ar lib "link -lib" do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AR"; then ac_cv_prog_AR="$AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AR="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AR=$ac_cv_prog_AR if test -n "$AR"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 $as_echo "$AR" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$AR" && break done fi if test -z "$AR"; then ac_ct_AR=$AR for ac_prog in ar lib "link -lib" do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_AR"; then ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_AR="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_AR=$ac_cv_prog_ac_ct_AR if test -n "$ac_ct_AR"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5 $as_echo "$ac_ct_AR" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_AR" && break done if test "x$ac_ct_AR" = x; then AR="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac AR=$ac_ct_AR fi fi : ${AR=ar} { $as_echo "$as_me:${as_lineno-$LINENO}: checking the archiver ($AR) interface" >&5 $as_echo_n "checking the archiver ($AR) interface... " >&6; } if ${am_cv_ar_interface+:} false; then : $as_echo_n "(cached) " >&6 else am_cv_ar_interface=ar cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int some_variable = 0; _ACEOF if ac_fn_c_try_compile "$LINENO"; then : am_ar_try='$AR cru libconftest.a conftest.$ac_objext >&5' { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$am_ar_try\""; } >&5 (eval $am_ar_try) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test "$ac_status" -eq 0; then am_cv_ar_interface=ar else am_ar_try='$AR -NOLOGO -OUT:conftest.lib conftest.$ac_objext >&5' { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$am_ar_try\""; } >&5 (eval $am_ar_try) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test "$ac_status" -eq 0; then am_cv_ar_interface=lib else am_cv_ar_interface=unknown fi fi rm -f conftest.lib libconftest.a fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_ar_interface" >&5 $as_echo "$am_cv_ar_interface" >&6; } case $am_cv_ar_interface in ar) ;; lib) # Microsoft lib, so override with the ar-lib wrapper script. # FIXME: It is wrong to rewrite AR. # But if we don't then we get into trouble of one sort or another. # A longer-term fix would be to have automake use am__AR in this case, # and then we could set am__AR="$am_aux_dir/ar-lib \$(AR)" or something # similar. AR="$am_aux_dir/ar-lib $AR" ;; unknown) as_fn_error $? "could not determine $AR interface" "$LINENO" 5 ;; esac case `pwd` in *\ * | *\ *) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&5 $as_echo "$as_me: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&2;} ;; esac macro_version='2.4.2' macro_revision='1.3337' ltmain="$ac_aux_dir/ltmain.sh" # Make sure we can run config.sub. $SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 $as_echo_n "checking build system type... " >&6; } if ${ac_cv_build+:} false; then : $as_echo_n "(cached) " >&6 else ac_build_alias=$build_alias test "x$ac_build_alias" = x && ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` test "x$ac_build_alias" = x && as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 $as_echo "$ac_cv_build" >&6; } case $ac_cv_build in *-*-*) ;; *) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;; esac build=$ac_cv_build ac_save_IFS=$IFS; IFS='-' set x $ac_cv_build shift build_cpu=$1 build_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: build_os=$* IFS=$ac_save_IFS case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 $as_echo_n "checking host system type... " >&6; } if ${ac_cv_host+:} false; then : $as_echo_n "(cached) " >&6 else if test "x$host_alias" = x; then ac_cv_host=$ac_cv_build else ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5 fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 $as_echo "$ac_cv_host" >&6; } case $ac_cv_host in *-*-*) ;; *) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;; esac host=$ac_cv_host ac_save_IFS=$IFS; IFS='-' set x $ac_cv_host shift host_cpu=$1 host_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: host_os=$* IFS=$ac_save_IFS case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac # Backslashify metacharacters that are still active within # double-quoted strings. sed_quote_subst='s/\(["`$\\]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution to delay expansion of an escaped shell variable in a # double_quote_subst'ed string. delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' # Sed substitution to delay expansion of an escaped single quote. delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' # Sed substitution to avoid accidental globbing in evaled expressions no_glob_subst='s/\*/\\\*/g' ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to print strings" >&5 $as_echo_n "checking how to print strings... " >&6; } # Test print first, because it will be a builtin if present. if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='print -r --' elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='printf %s\n' else # Use this function as a fallback that always works. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } ECHO='func_fallback_echo' fi # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "" } case "$ECHO" in printf*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: printf" >&5 $as_echo "printf" >&6; } ;; print*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: print -r" >&5 $as_echo "print -r" >&6; } ;; *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: cat" >&5 $as_echo "cat" >&6; } ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5 $as_echo_n "checking for a sed that does not truncate output... " >&6; } if ${ac_cv_path_SED+:} false; then : $as_echo_n "(cached) " >&6 else ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ for ac_i in 1 2 3 4 5 6 7; do ac_script="$ac_script$as_nl$ac_script" done echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed { ac_script=; unset ac_script;} if test -z "$SED"; then ac_path_SED_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in sed gsed; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_SED="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_SED" || continue # Check for GNU ac_path_SED and select it if it is found. # Check for GNU $ac_path_SED case `"$ac_path_SED" --version 2>&1` in *GNU*) ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo '' >> "conftest.nl" "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_SED_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_SED="$ac_path_SED" ac_path_SED_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_SED_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_SED"; then as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5 fi else ac_cv_path_SED=$SED fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5 $as_echo "$ac_cv_path_SED" >&6; } SED="$ac_cv_path_SED" rm -f conftest.sed test -z "$SED" && SED=sed Xsed="$SED -e 1s/^X//" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 $as_echo_n "checking for grep that handles long lines and -e... " >&6; } if ${ac_cv_path_GREP+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$GREP"; then ac_path_GREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in grep ggrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_GREP" || continue # Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP case `"$ac_path_GREP" --version 2>&1` in *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'GREP' >> "conftest.nl" "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_GREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_GREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_GREP"; then as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_GREP=$GREP fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 $as_echo "$ac_cv_path_GREP" >&6; } GREP="$ac_cv_path_GREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 $as_echo_n "checking for egrep... " >&6; } if ${ac_cv_path_EGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 then ac_cv_path_EGREP="$GREP -E" else if test -z "$EGREP"; then ac_path_EGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in egrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_EGREP" || continue # Check for GNU ac_path_EGREP and select it if it is found. # Check for GNU $ac_path_EGREP case `"$ac_path_EGREP" --version 2>&1` in *GNU*) ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'EGREP' >> "conftest.nl" "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_EGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_EGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_EGREP"; then as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_EGREP=$EGREP fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 $as_echo "$ac_cv_path_EGREP" >&6; } EGREP="$ac_cv_path_EGREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5 $as_echo_n "checking for fgrep... " >&6; } if ${ac_cv_path_FGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1 then ac_cv_path_FGREP="$GREP -F" else if test -z "$FGREP"; then ac_path_FGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in fgrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_FGREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_FGREP" || continue # Check for GNU ac_path_FGREP and select it if it is found. # Check for GNU $ac_path_FGREP case `"$ac_path_FGREP" --version 2>&1` in *GNU*) ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'FGREP' >> "conftest.nl" "$ac_path_FGREP" FGREP < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_FGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_FGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_FGREP"; then as_fn_error $? "no acceptable fgrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_FGREP=$FGREP fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_FGREP" >&5 $as_echo "$ac_cv_path_FGREP" >&6; } FGREP="$ac_cv_path_FGREP" test -z "$GREP" && GREP=grep # Check whether --with-gnu-ld was given. if test "${with_gnu_ld+set}" = set; then : withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes else with_gnu_ld=no fi ac_prog=ld if test "$GCC" = yes; then # Check if gcc -print-prog-name=ld gives a path. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 $as_echo_n "checking for ld used by $CC... " >&6; } case $host in *-*-mingw*) # gcc leaves a trailing carriage return which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [\\/]* | ?:[\\/]*) re_direlt='/[^/][^/]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD="$ac_prog" ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test "$with_gnu_ld" = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 $as_echo_n "checking for GNU ld... " >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5 $as_echo_n "checking for non-GNU ld... " >&6; } fi if ${lt_cv_path_LD+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$LD"; then lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD="$ac_dir/$ac_prog" # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &5 $as_echo "$LD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5 $as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; } if ${lt_cv_prog_gnu_ld+:} false; then : $as_echo_n "(cached) " >&6 else # I'd rather use --version here, but apparently some GNU lds only accept -v. case `$LD -v 2>&1 &5 $as_echo "$lt_cv_prog_gnu_ld" >&6; } with_gnu_ld=$lt_cv_prog_gnu_ld { $as_echo "$as_me:${as_lineno-$LINENO}: checking for BSD- or MS-compatible name lister (nm)" >&5 $as_echo_n "checking for BSD- or MS-compatible name lister (nm)... " >&6; } if ${lt_cv_path_NM+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$NM"; then # Let the user override the test. lt_cv_path_NM="$NM" else lt_nm_to_check="${ac_tool_prefix}nm" if test -n "$ac_tool_prefix" && test "$build" = "$host"; then lt_nm_to_check="$lt_nm_to_check nm" fi for lt_tmp_nm in $lt_nm_to_check; do lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. tmp_nm="$ac_dir/$lt_tmp_nm" if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then # Check to see if the nm accepts a BSD-compat flag. # Adding the `sed 1q' prevents false positives on HP-UX, which says: # nm: unknown option "B" ignored # Tru64's nm complains that /dev/null is an invalid object file case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in */dev/null* | *'Invalid file or object type'*) lt_cv_path_NM="$tmp_nm -B" break ;; *) case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in */dev/null*) lt_cv_path_NM="$tmp_nm -p" break ;; *) lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but continue # so that we can try to find one that supports BSD flags ;; esac ;; esac fi done IFS="$lt_save_ifs" done : ${lt_cv_path_NM=no} fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5 $as_echo "$lt_cv_path_NM" >&6; } if test "$lt_cv_path_NM" != "no"; then NM="$lt_cv_path_NM" else # Didn't find any BSD compatible name lister, look for dumpbin. if test -n "$DUMPBIN"; then : # Let the user override the test. else if test -n "$ac_tool_prefix"; then for ac_prog in dumpbin "link -dump" do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DUMPBIN+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DUMPBIN"; then ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DUMPBIN="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DUMPBIN=$ac_cv_prog_DUMPBIN if test -n "$DUMPBIN"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DUMPBIN" >&5 $as_echo "$DUMPBIN" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$DUMPBIN" && break done fi if test -z "$DUMPBIN"; then ac_ct_DUMPBIN=$DUMPBIN for ac_prog in dumpbin "link -dump" do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DUMPBIN+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DUMPBIN"; then ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DUMPBIN="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DUMPBIN=$ac_cv_prog_ac_ct_DUMPBIN if test -n "$ac_ct_DUMPBIN"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DUMPBIN" >&5 $as_echo "$ac_ct_DUMPBIN" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_DUMPBIN" && break done if test "x$ac_ct_DUMPBIN" = x; then DUMPBIN=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DUMPBIN=$ac_ct_DUMPBIN fi fi case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in *COFF*) DUMPBIN="$DUMPBIN -symbols" ;; *) DUMPBIN=: ;; esac fi if test "$DUMPBIN" != ":"; then NM="$DUMPBIN" fi fi test -z "$NM" && NM=nm { $as_echo "$as_me:${as_lineno-$LINENO}: checking the name lister ($NM) interface" >&5 $as_echo_n "checking the name lister ($NM) interface... " >&6; } if ${lt_cv_nm_interface+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_nm_interface="BSD nm" echo "int some_variable = 0;" > conftest.$ac_ext (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&5) (eval "$ac_compile" 2>conftest.err) cat conftest.err >&5 (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&5) (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) cat conftest.err >&5 (eval echo "\"\$as_me:$LINENO: output\"" >&5) cat conftest.out >&5 if $GREP 'External.*some_variable' conftest.out > /dev/null; then lt_cv_nm_interface="MS dumpbin" fi rm -f conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5 $as_echo "$lt_cv_nm_interface" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5 $as_echo_n "checking whether ln -s works... " >&6; } LN_S=$as_ln_s if test "$LN_S" = "ln -s"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5 $as_echo "no, using $LN_S" >&6; } fi # find the maximum length of command line arguments { $as_echo "$as_me:${as_lineno-$LINENO}: checking the maximum length of command line arguments" >&5 $as_echo_n "checking the maximum length of command line arguments... " >&6; } if ${lt_cv_sys_max_cmd_len+:} false; then : $as_echo_n "(cached) " >&6 else i=0 teststring="ABCD" case $build_os in msdosdjgpp*) # On DJGPP, this test can blow up pretty badly due to problems in libc # (any single argument exceeding 2000 bytes causes a buffer overrun # during glob expansion). Even if it were fixed, the result of this # check would be larger than it should be. lt_cv_sys_max_cmd_len=12288; # 12K is about right ;; gnu*) # Under GNU Hurd, this test is not required because there is # no limit to the length of command line arguments. # Libtool will interpret -1 as no limit whatsoever lt_cv_sys_max_cmd_len=-1; ;; cygwin* | mingw* | cegcc*) # On Win9x/ME, this test blows up -- it succeeds, but takes # about 5 minutes as the teststring grows exponentially. # Worse, since 9x/ME are not pre-emptively multitasking, # you end up with a "frozen" computer, even though with patience # the test eventually succeeds (with a max line length of 256k). # Instead, let's just punt: use the minimum linelength reported by # all of the supported platforms: 8192 (on NT/2K/XP). lt_cv_sys_max_cmd_len=8192; ;; mint*) # On MiNT this can take a long time and run out of memory. lt_cv_sys_max_cmd_len=8192; ;; amigaos*) # On AmigaOS with pdksh, this test takes hours, literally. # So we just punt and use a minimum line length of 8192. lt_cv_sys_max_cmd_len=8192; ;; netbsd* | freebsd* | openbsd* | darwin* | dragonfly*) # This has been around since 386BSD, at least. Likely further. if test -x /sbin/sysctl; then lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` elif test -x /usr/sbin/sysctl; then lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` else lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs fi # And add a safety zone lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` ;; interix*) # We know the value 262144 and hardcode it with a safety zone (like BSD) lt_cv_sys_max_cmd_len=196608 ;; os2*) # The test takes a long time on OS/2. lt_cv_sys_max_cmd_len=8192 ;; osf*) # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not # nice to cause kernel panics so lets avoid the loop below. # First set a reasonable default. lt_cv_sys_max_cmd_len=16384 # if test -x /sbin/sysconfig; then case `/sbin/sysconfig -q proc exec_disable_arg_limit` in *1*) lt_cv_sys_max_cmd_len=-1 ;; esac fi ;; sco3.2v5*) lt_cv_sys_max_cmd_len=102400 ;; sysv5* | sco5v6* | sysv4.2uw2*) kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` if test -n "$kargmax"; then lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[ ]//'` else lt_cv_sys_max_cmd_len=32768 fi ;; *) lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` if test -n "$lt_cv_sys_max_cmd_len"; then lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` else # Make teststring a little bigger before we do anything with it. # a 1K string should be a reasonable start. for i in 1 2 3 4 5 6 7 8 ; do teststring=$teststring$teststring done SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} # If test is not a shell built-in, we'll probably end up computing a # maximum length that is only half of the actual maximum length, but # we can't tell. while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \ = "X$teststring$teststring"; } >/dev/null 2>&1 && test $i != 17 # 1/2 MB should be enough do i=`expr $i + 1` teststring=$teststring$teststring done # Only check the string length outside the loop. lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` teststring= # Add a significant safety factor because C++ compilers can tack on # massive amounts of additional arguments before passing them to the # linker. It appears as though 1/2 is a usable value. lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` fi ;; esac fi if test -n $lt_cv_sys_max_cmd_len ; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_max_cmd_len" >&5 $as_echo "$lt_cv_sys_max_cmd_len" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5 $as_echo "none" >&6; } fi max_cmd_len=$lt_cv_sys_max_cmd_len : ${CP="cp -f"} : ${MV="mv -f"} : ${RM="rm -f"} { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands some XSI constructs" >&5 $as_echo_n "checking whether the shell understands some XSI constructs... " >&6; } # Try some XSI features xsi_shell=no ( _lt_dummy="a/b/c" test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \ = c,a/b,b/c, \ && eval 'test $(( 1 + 1 )) -eq 2 \ && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \ && xsi_shell=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: $xsi_shell" >&5 $as_echo "$xsi_shell" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands \"+=\"" >&5 $as_echo_n "checking whether the shell understands \"+=\"... " >&6; } lt_shell_append=no ( foo=bar; set foo baz; eval "$1+=\$2" && test "$foo" = barbaz ) \ >/dev/null 2>&1 \ && lt_shell_append=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_shell_append" >&5 $as_echo "$lt_shell_append" >&6; } if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then lt_unset=unset else lt_unset=false fi # test EBCDIC or ASCII case `echo X|tr X '\101'` in A) # ASCII based system # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr lt_SP2NL='tr \040 \012' lt_NL2SP='tr \015\012 \040\040' ;; *) # EBCDIC based system lt_SP2NL='tr \100 \n' lt_NL2SP='tr \r\n \100\100' ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to $host format" >&5 $as_echo_n "checking how to convert $build file names to $host format... " >&6; } if ${lt_cv_to_host_file_cmd+:} false; then : $as_echo_n "(cached) " >&6 else case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32 ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32 ;; esac ;; *-*-cygwin* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_noop ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin ;; esac ;; * ) # unhandled hosts (and "normal" native builds) lt_cv_to_host_file_cmd=func_convert_file_noop ;; esac fi to_host_file_cmd=$lt_cv_to_host_file_cmd { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_host_file_cmd" >&5 $as_echo "$lt_cv_to_host_file_cmd" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to toolchain format" >&5 $as_echo_n "checking how to convert $build file names to toolchain format... " >&6; } if ${lt_cv_to_tool_file_cmd+:} false; then : $as_echo_n "(cached) " >&6 else #assume ordinary cross tools, or native build. lt_cv_to_tool_file_cmd=func_convert_file_noop case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 ;; esac ;; esac fi to_tool_file_cmd=$lt_cv_to_tool_file_cmd { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_tool_file_cmd" >&5 $as_echo "$lt_cv_to_tool_file_cmd" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $LD option to reload object files" >&5 $as_echo_n "checking for $LD option to reload object files... " >&6; } if ${lt_cv_ld_reload_flag+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_reload_flag='-r' fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5 $as_echo "$lt_cv_ld_reload_flag" >&6; } reload_flag=$lt_cv_ld_reload_flag case $reload_flag in "" | " "*) ;; *) reload_flag=" $reload_flag" ;; esac reload_cmds='$LD$reload_flag -o $output$reload_objs' case $host_os in cygwin* | mingw* | pw32* | cegcc*) if test "$GCC" != yes; then reload_cmds=false fi ;; darwin*) if test "$GCC" = yes; then reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs' else reload_cmds='$LD$reload_flag -o $output$reload_objs' fi ;; esac if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args. set dummy ${ac_tool_prefix}objdump; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OBJDUMP"; then ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OBJDUMP=$ac_cv_prog_OBJDUMP if test -n "$OBJDUMP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5 $as_echo "$OBJDUMP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OBJDUMP"; then ac_ct_OBJDUMP=$OBJDUMP # Extract the first word of "objdump", so it can be a program name with args. set dummy objdump; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OBJDUMP"; then ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OBJDUMP="objdump" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP if test -n "$ac_ct_OBJDUMP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5 $as_echo "$ac_ct_OBJDUMP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OBJDUMP" = x; then OBJDUMP="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OBJDUMP=$ac_ct_OBJDUMP fi else OBJDUMP="$ac_cv_prog_OBJDUMP" fi test -z "$OBJDUMP" && OBJDUMP=objdump { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to recognize dependent libraries" >&5 $as_echo_n "checking how to recognize dependent libraries... " >&6; } if ${lt_cv_deplibs_check_method+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_file_magic_cmd='$MAGIC_CMD' lt_cv_file_magic_test_file= lt_cv_deplibs_check_method='unknown' # Need to set the preceding variable on all platforms that support # interlibrary dependencies. # 'none' -- dependencies not supported. # `unknown' -- same as none, but documents that we really don't know. # 'pass_all' -- all dependencies passed with no checks. # 'test_compile' -- check by making test program. # 'file_magic [[regex]]' -- check by looking for files in library path # which responds to the $file_magic_cmd with a given extended regex. # If you have `file' or equivalent on your system and you're not sure # whether `pass_all' will *always* work, you probably want this one. case $host_os in aix[4-9]*) lt_cv_deplibs_check_method=pass_all ;; beos*) lt_cv_deplibs_check_method=pass_all ;; bsdi[45]*) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)' lt_cv_file_magic_cmd='/usr/bin/file -L' lt_cv_file_magic_test_file=/shlib/libc.so ;; cygwin*) # func_win32_libid is a shell function defined in ltmain.sh lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' ;; mingw* | pw32*) # Base MSYS/MinGW do not provide the 'file' command needed by # func_win32_libid shell function, so use a weaker test based on 'objdump', # unless we find 'file', for example because we are cross-compiling. # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin. if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' else # Keep this pattern in sync with the one in func_win32_libid. lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' lt_cv_file_magic_cmd='$OBJDUMP -f' fi ;; cegcc*) # use the weaker test based on 'objdump'. See mingw*. lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' lt_cv_file_magic_cmd='$OBJDUMP -f' ;; darwin* | rhapsody*) lt_cv_deplibs_check_method=pass_all ;; freebsd* | dragonfly*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then case $host_cpu in i*86 ) # Not sure whether the presence of OpenBSD here was a mistake. # Let's accept both of them until this is cleared up. lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` ;; esac else lt_cv_deplibs_check_method=pass_all fi ;; haiku*) lt_cv_deplibs_check_method=pass_all ;; hpux10.20* | hpux11*) lt_cv_file_magic_cmd=/usr/bin/file case $host_cpu in ia64*) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64' lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so ;; hppa*64*) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]' lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl ;; *) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9]\.[0-9]) shared library' lt_cv_file_magic_test_file=/usr/lib/libc.sl ;; esac ;; interix[3-9]*) # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$' ;; irix5* | irix6* | nonstopux*) case $LD in *-32|*"-32 ") libmagic=32-bit;; *-n32|*"-n32 ") libmagic=N32;; *-64|*"-64 ") libmagic=64-bit;; *) libmagic=never-match;; esac lt_cv_deplibs_check_method=pass_all ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) lt_cv_deplibs_check_method=pass_all ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$' fi ;; newos6*) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=/usr/lib/libnls.so ;; *nto* | *qnx*) lt_cv_deplibs_check_method=pass_all ;; openbsd*) if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' fi ;; osf3* | osf4* | osf5*) lt_cv_deplibs_check_method=pass_all ;; rdos*) lt_cv_deplibs_check_method=pass_all ;; solaris*) lt_cv_deplibs_check_method=pass_all ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) lt_cv_deplibs_check_method=pass_all ;; sysv4 | sysv4.3*) case $host_vendor in motorola) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]' lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` ;; ncr) lt_cv_deplibs_check_method=pass_all ;; sequent) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )' ;; sni) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib" lt_cv_file_magic_test_file=/lib/libc.so ;; siemens) lt_cv_deplibs_check_method=pass_all ;; pc) lt_cv_deplibs_check_method=pass_all ;; esac ;; tpf*) lt_cv_deplibs_check_method=pass_all ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_deplibs_check_method" >&5 $as_echo "$lt_cv_deplibs_check_method" >&6; } file_magic_glob= want_nocaseglob=no if test "$build" = "$host"; then case $host_os in mingw* | pw32*) if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then want_nocaseglob=yes else file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[\1]\/[\1]\/g;/g"` fi ;; esac fi file_magic_cmd=$lt_cv_file_magic_cmd deplibs_check_method=$lt_cv_deplibs_check_method test -z "$deplibs_check_method" && deplibs_check_method=unknown if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args. set dummy ${ac_tool_prefix}dlltool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DLLTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DLLTOOL"; then ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DLLTOOL=$ac_cv_prog_DLLTOOL if test -n "$DLLTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5 $as_echo "$DLLTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_DLLTOOL"; then ac_ct_DLLTOOL=$DLLTOOL # Extract the first word of "dlltool", so it can be a program name with args. set dummy dlltool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DLLTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DLLTOOL"; then ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DLLTOOL="dlltool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL if test -n "$ac_ct_DLLTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5 $as_echo "$ac_ct_DLLTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_DLLTOOL" = x; then DLLTOOL="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DLLTOOL=$ac_ct_DLLTOOL fi else DLLTOOL="$ac_cv_prog_DLLTOOL" fi test -z "$DLLTOOL" && DLLTOOL=dlltool { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to associate runtime and link libraries" >&5 $as_echo_n "checking how to associate runtime and link libraries... " >&6; } if ${lt_cv_sharedlib_from_linklib_cmd+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_sharedlib_from_linklib_cmd='unknown' case $host_os in cygwin* | mingw* | pw32* | cegcc*) # two different shell functions defined in ltmain.sh # decide which to use based on capabilities of $DLLTOOL case `$DLLTOOL --help 2>&1` in *--identify-strict*) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib ;; *) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback ;; esac ;; *) # fallback: assume linklib IS sharedlib lt_cv_sharedlib_from_linklib_cmd="$ECHO" ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sharedlib_from_linklib_cmd" >&5 $as_echo "$lt_cv_sharedlib_from_linklib_cmd" >&6; } sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO if test -n "$ac_tool_prefix"; then for ac_prog in ar do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AR"; then ac_cv_prog_AR="$AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AR="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AR=$ac_cv_prog_AR if test -n "$AR"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 $as_echo "$AR" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$AR" && break done fi if test -z "$AR"; then ac_ct_AR=$AR for ac_prog in ar do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_AR"; then ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_AR="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_AR=$ac_cv_prog_ac_ct_AR if test -n "$ac_ct_AR"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5 $as_echo "$ac_ct_AR" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_AR" && break done if test "x$ac_ct_AR" = x; then AR="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac AR=$ac_ct_AR fi fi : ${AR=ar} : ${AR_FLAGS=cru} { $as_echo "$as_me:${as_lineno-$LINENO}: checking for archiver @FILE support" >&5 $as_echo_n "checking for archiver @FILE support... " >&6; } if ${lt_cv_ar_at_file+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ar_at_file=no cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : echo conftest.$ac_objext > conftest.lst lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&5' { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 (eval $lt_ar_try) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test "$ac_status" -eq 0; then # Ensure the archiver fails upon bogus file names. rm -f conftest.$ac_objext libconftest.a { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 (eval $lt_ar_try) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test "$ac_status" -ne 0; then lt_cv_ar_at_file=@ fi fi rm -f conftest.* libconftest.a fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ar_at_file" >&5 $as_echo "$lt_cv_ar_at_file" >&6; } if test "x$lt_cv_ar_at_file" = xno; then archiver_list_spec= else archiver_list_spec=$lt_cv_ar_at_file fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. set dummy ${ac_tool_prefix}strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_STRIP="${ac_tool_prefix}strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 $as_echo "$STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_STRIP"; then ac_ct_STRIP=$STRIP # Extract the first word of "strip", so it can be a program name with args. set dummy strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_STRIP="strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 $as_echo "$ac_ct_STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_STRIP" = x; then STRIP=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac STRIP=$ac_ct_STRIP fi else STRIP="$ac_cv_prog_STRIP" fi test -z "$STRIP" && STRIP=: if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. set dummy ${ac_tool_prefix}ranlib; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_RANLIB+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$RANLIB"; then ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi RANLIB=$ac_cv_prog_RANLIB if test -n "$RANLIB"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 $as_echo "$RANLIB" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_RANLIB"; then ac_ct_RANLIB=$RANLIB # Extract the first word of "ranlib", so it can be a program name with args. set dummy ranlib; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_RANLIB+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_RANLIB"; then ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_RANLIB="ranlib" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB if test -n "$ac_ct_RANLIB"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 $as_echo "$ac_ct_RANLIB" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_RANLIB" = x; then RANLIB=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac RANLIB=$ac_ct_RANLIB fi else RANLIB="$ac_cv_prog_RANLIB" fi test -z "$RANLIB" && RANLIB=: # Determine commands to create old-style static archives. old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' old_postinstall_cmds='chmod 644 $oldlib' old_postuninstall_cmds= if test -n "$RANLIB"; then case $host_os in openbsd*) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" ;; *) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" ;; esac old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" fi case $host_os in darwin*) lock_old_archive_extraction=yes ;; *) lock_old_archive_extraction=no ;; esac # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # Check for command to grab the raw symbol name followed by C symbol from nm. { $as_echo "$as_me:${as_lineno-$LINENO}: checking command to parse $NM output from $compiler object" >&5 $as_echo_n "checking command to parse $NM output from $compiler object... " >&6; } if ${lt_cv_sys_global_symbol_pipe+:} false; then : $as_echo_n "(cached) " >&6 else # These are sane defaults that work on at least a few old systems. # [They come from Ultrix. What could be older than Ultrix?!! ;)] # Character class describing NM global symbol codes. symcode='[BCDEGRST]' # Regexp to match symbols that can be accessed directly from C. sympat='\([_A-Za-z][_A-Za-z0-9]*\)' # Define system-specific variables. case $host_os in aix*) symcode='[BCDT]' ;; cygwin* | mingw* | pw32* | cegcc*) symcode='[ABCDGISTW]' ;; hpux*) if test "$host_cpu" = ia64; then symcode='[ABCDEGRST]' fi ;; irix* | nonstopux*) symcode='[BCDEGRST]' ;; osf*) symcode='[BCDEGQRST]' ;; solaris*) symcode='[BDRT]' ;; sco3.2v5*) symcode='[DT]' ;; sysv4.2uw2*) symcode='[DT]' ;; sysv5* | sco5v6* | unixware* | OpenUNIX*) symcode='[ABDT]' ;; sysv4) symcode='[DFNSTU]' ;; esac # If we're using GNU nm, then use its standard symbol codes. case `$NM -V 2>&1` in *GNU* | *'with BFD'*) symcode='[ABCDGIRSTW]' ;; esac # Transform an extracted symbol line into a proper C declaration. # Some systems (esp. on ia64) link data and code symbols differently, # so use this general approach. lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" # Transform an extracted symbol line into symbol name and symbol address lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\)[ ]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"\2\", (void *) \&\2},/p'" lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([^ ]*\)[ ]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \(lib[^ ]*\)$/ {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"lib\2\", (void *) \&\2},/p'" # Handle CRLF in mingw tool chain opt_cr= case $build_os in mingw*) opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp ;; esac # Try without a prefix underscore, then with it. for ac_symprfx in "" "_"; do # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. symxfrm="\\1 $ac_symprfx\\2 \\2" # Write the raw and C identifiers. if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Fake it for dumpbin and say T for any non-static function # and D for any global variable. # Also find C++ and __fastcall symbols from MSVC++, # which start with @ or ?. lt_cv_sys_global_symbol_pipe="$AWK '"\ " {last_section=section; section=\$ 3};"\ " /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\ " /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ " \$ 0!~/External *\|/{next};"\ " / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ " {if(hide[section]) next};"\ " {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\ " {split(\$ 0, a, /\||\r/); split(a[2], s)};"\ " s[1]~/^[@?]/{print s[1], s[1]; next};"\ " s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\ " ' prfx=^$ac_symprfx" else lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[ ]\($symcode$symcode*\)[ ][ ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" fi lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'" # Check to see that the pipe works correctly. pipe_works=no rm -f conftest* cat > conftest.$ac_ext <<_LT_EOF #ifdef __cplusplus extern "C" { #endif char nm_test_var; void nm_test_func(void); void nm_test_func(void){} #ifdef __cplusplus } #endif int main(){nm_test_var='a';nm_test_func();return(0);} _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then # Now try to grab the symbols. nlist=conftest.nm if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist\""; } >&5 (eval $NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s "$nlist"; then # Try sorting and uniquifying the output. if sort "$nlist" | uniq > "$nlist"T; then mv -f "$nlist"T "$nlist" else rm -f "$nlist"T fi # Make sure that we snagged all the symbols we need. if $GREP ' nm_test_var$' "$nlist" >/dev/null; then if $GREP ' nm_test_func$' "$nlist" >/dev/null; then cat <<_LT_EOF > conftest.$ac_ext /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) /* DATA imports from DLLs on WIN32 con't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined(__osf__) /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif #ifdef __cplusplus extern "C" { #endif _LT_EOF # Now generate the symbol file. eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' cat <<_LT_EOF >> conftest.$ac_ext /* The mapping between symbol names and symbols. */ LT_DLSYM_CONST struct { const char *name; void *address; } lt__PROGRAM__LTX_preloaded_symbols[] = { { "@PROGRAM@", (void *) 0 }, _LT_EOF $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext cat <<\_LT_EOF >> conftest.$ac_ext {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt__PROGRAM__LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif _LT_EOF # Now try linking the two files. mv conftest.$ac_objext conftstm.$ac_objext lt_globsym_save_LIBS=$LIBS lt_globsym_save_CFLAGS=$CFLAGS LIBS="conftstm.$ac_objext" CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag" if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest${ac_exeext}; then pipe_works=yes fi LIBS=$lt_globsym_save_LIBS CFLAGS=$lt_globsym_save_CFLAGS else echo "cannot find nm_test_func in $nlist" >&5 fi else echo "cannot find nm_test_var in $nlist" >&5 fi else echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5 fi else echo "$progname: failed program was:" >&5 cat conftest.$ac_ext >&5 fi rm -rf conftest* conftst* # Do not use the global_symbol_pipe unless it works. if test "$pipe_works" = yes; then break else lt_cv_sys_global_symbol_pipe= fi done fi if test -z "$lt_cv_sys_global_symbol_pipe"; then lt_cv_sys_global_symbol_to_cdecl= fi if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: failed" >&5 $as_echo "failed" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } fi # Response file support. if test "$lt_cv_nm_interface" = "MS dumpbin"; then nm_file_list_spec='@' elif $NM --help 2>/dev/null | grep '[@]FILE' >/dev/null; then nm_file_list_spec='@' fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for sysroot" >&5 $as_echo_n "checking for sysroot... " >&6; } # Check whether --with-sysroot was given. if test "${with_sysroot+set}" = set; then : withval=$with_sysroot; else with_sysroot=no fi lt_sysroot= case ${with_sysroot} in #( yes) if test "$GCC" = yes; then lt_sysroot=`$CC --print-sysroot 2>/dev/null` fi ;; #( /*) lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"` ;; #( no|'') ;; #( *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${with_sysroot}" >&5 $as_echo "${with_sysroot}" >&6; } as_fn_error $? "The sysroot must be an absolute path." "$LINENO" 5 ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${lt_sysroot:-no}" >&5 $as_echo "${lt_sysroot:-no}" >&6; } # Check whether --enable-libtool-lock was given. if test "${enable_libtool_lock+set}" = set; then : enableval=$enable_libtool_lock; fi test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes # Some flags need to be propagated to the compiler or linker for good # libtool support. case $host in ia64-*-hpux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.$ac_objext` in *ELF-32*) HPUX_IA64_MODE="32" ;; *ELF-64*) HPUX_IA64_MODE="64" ;; esac fi rm -rf conftest* ;; *-*-irix6*) # Find out which ABI we are using. echo '#line '$LINENO' "configure"' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then if test "$lt_cv_prog_gnu_ld" = yes; then case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -melf32bsmip" ;; *N32*) LD="${LD-ld} -melf32bmipn32" ;; *64-bit*) LD="${LD-ld} -melf64bmip" ;; esac else case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -32" ;; *N32*) LD="${LD-ld} -n32" ;; *64-bit*) LD="${LD-ld} -64" ;; esac fi fi rm -rf conftest* ;; x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.o` in *32-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_i386_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_i386" ;; ppc64-*linux*|powerpc64-*linux*) LD="${LD-ld} -m elf32ppclinux" ;; s390x-*linux*) LD="${LD-ld} -m elf_s390" ;; sparc64-*linux*) LD="${LD-ld} -m elf32_sparc" ;; esac ;; *64-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_x86_64_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_x86_64" ;; ppc*-*linux*|powerpc*-*linux*) LD="${LD-ld} -m elf64ppc" ;; s390*-*linux*|s390*-*tpf*) LD="${LD-ld} -m elf64_s390" ;; sparc*-*linux*) LD="${LD-ld} -m elf64_sparc" ;; esac ;; esac fi rm -rf conftest* ;; *-*-sco3.2v5*) # On SCO OpenServer 5, we need -belf to get full-featured binaries. SAVE_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS -belf" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler needs -belf" >&5 $as_echo_n "checking whether the C compiler needs -belf... " >&6; } if ${lt_cv_cc_needs_belf+:} false; then : $as_echo_n "(cached) " >&6 else ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_cc_needs_belf=yes else lt_cv_cc_needs_belf=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_cc_needs_belf" >&5 $as_echo "$lt_cv_cc_needs_belf" >&6; } if test x"$lt_cv_cc_needs_belf" != x"yes"; then # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf CFLAGS="$SAVE_CFLAGS" fi ;; *-*solaris*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.o` in *64-bit*) case $lt_cv_prog_gnu_ld in yes*) case $host in i?86-*-solaris*) LD="${LD-ld} -m elf_x86_64" ;; sparc*-*-solaris*) LD="${LD-ld} -m elf64_sparc" ;; esac # GNU ld 2.21 introduced _sol2 emulations. Use them if available. if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then LD="${LD-ld}_sol2" fi ;; *) if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then LD="${LD-ld} -64" fi ;; esac ;; esac fi rm -rf conftest* ;; esac need_locks="$enable_libtool_lock" if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}mt", so it can be a program name with args. set dummy ${ac_tool_prefix}mt; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_MANIFEST_TOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$MANIFEST_TOOL"; then ac_cv_prog_MANIFEST_TOOL="$MANIFEST_TOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_MANIFEST_TOOL="${ac_tool_prefix}mt" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi MANIFEST_TOOL=$ac_cv_prog_MANIFEST_TOOL if test -n "$MANIFEST_TOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MANIFEST_TOOL" >&5 $as_echo "$MANIFEST_TOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_MANIFEST_TOOL"; then ac_ct_MANIFEST_TOOL=$MANIFEST_TOOL # Extract the first word of "mt", so it can be a program name with args. set dummy mt; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_MANIFEST_TOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_MANIFEST_TOOL"; then ac_cv_prog_ac_ct_MANIFEST_TOOL="$ac_ct_MANIFEST_TOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_MANIFEST_TOOL="mt" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_MANIFEST_TOOL=$ac_cv_prog_ac_ct_MANIFEST_TOOL if test -n "$ac_ct_MANIFEST_TOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_MANIFEST_TOOL" >&5 $as_echo "$ac_ct_MANIFEST_TOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_MANIFEST_TOOL" = x; then MANIFEST_TOOL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac MANIFEST_TOOL=$ac_ct_MANIFEST_TOOL fi else MANIFEST_TOOL="$ac_cv_prog_MANIFEST_TOOL" fi test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $MANIFEST_TOOL is a manifest tool" >&5 $as_echo_n "checking if $MANIFEST_TOOL is a manifest tool... " >&6; } if ${lt_cv_path_mainfest_tool+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_path_mainfest_tool=no echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&5 $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out cat conftest.err >&5 if $GREP 'Manifest Tool' conftest.out > /dev/null; then lt_cv_path_mainfest_tool=yes fi rm -f conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_mainfest_tool" >&5 $as_echo "$lt_cv_path_mainfest_tool" >&6; } if test "x$lt_cv_path_mainfest_tool" != xyes; then MANIFEST_TOOL=: fi case $host_os in rhapsody* | darwin*) if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dsymutil", so it can be a program name with args. set dummy ${ac_tool_prefix}dsymutil; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DSYMUTIL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DSYMUTIL"; then ac_cv_prog_DSYMUTIL="$DSYMUTIL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DSYMUTIL="${ac_tool_prefix}dsymutil" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DSYMUTIL=$ac_cv_prog_DSYMUTIL if test -n "$DSYMUTIL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DSYMUTIL" >&5 $as_echo "$DSYMUTIL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_DSYMUTIL"; then ac_ct_DSYMUTIL=$DSYMUTIL # Extract the first word of "dsymutil", so it can be a program name with args. set dummy dsymutil; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DSYMUTIL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DSYMUTIL"; then ac_cv_prog_ac_ct_DSYMUTIL="$ac_ct_DSYMUTIL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DSYMUTIL="dsymutil" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DSYMUTIL=$ac_cv_prog_ac_ct_DSYMUTIL if test -n "$ac_ct_DSYMUTIL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DSYMUTIL" >&5 $as_echo "$ac_ct_DSYMUTIL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_DSYMUTIL" = x; then DSYMUTIL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DSYMUTIL=$ac_ct_DSYMUTIL fi else DSYMUTIL="$ac_cv_prog_DSYMUTIL" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}nmedit", so it can be a program name with args. set dummy ${ac_tool_prefix}nmedit; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_NMEDIT+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$NMEDIT"; then ac_cv_prog_NMEDIT="$NMEDIT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_NMEDIT="${ac_tool_prefix}nmedit" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi NMEDIT=$ac_cv_prog_NMEDIT if test -n "$NMEDIT"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NMEDIT" >&5 $as_echo "$NMEDIT" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_NMEDIT"; then ac_ct_NMEDIT=$NMEDIT # Extract the first word of "nmedit", so it can be a program name with args. set dummy nmedit; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_NMEDIT+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_NMEDIT"; then ac_cv_prog_ac_ct_NMEDIT="$ac_ct_NMEDIT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_NMEDIT="nmedit" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_NMEDIT=$ac_cv_prog_ac_ct_NMEDIT if test -n "$ac_ct_NMEDIT"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_NMEDIT" >&5 $as_echo "$ac_ct_NMEDIT" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_NMEDIT" = x; then NMEDIT=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac NMEDIT=$ac_ct_NMEDIT fi else NMEDIT="$ac_cv_prog_NMEDIT" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}lipo", so it can be a program name with args. set dummy ${ac_tool_prefix}lipo; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_LIPO+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$LIPO"; then ac_cv_prog_LIPO="$LIPO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_LIPO="${ac_tool_prefix}lipo" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi LIPO=$ac_cv_prog_LIPO if test -n "$LIPO"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIPO" >&5 $as_echo "$LIPO" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_LIPO"; then ac_ct_LIPO=$LIPO # Extract the first word of "lipo", so it can be a program name with args. set dummy lipo; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_LIPO+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_LIPO"; then ac_cv_prog_ac_ct_LIPO="$ac_ct_LIPO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_LIPO="lipo" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_LIPO=$ac_cv_prog_ac_ct_LIPO if test -n "$ac_ct_LIPO"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_LIPO" >&5 $as_echo "$ac_ct_LIPO" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_LIPO" = x; then LIPO=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac LIPO=$ac_ct_LIPO fi else LIPO="$ac_cv_prog_LIPO" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}otool", so it can be a program name with args. set dummy ${ac_tool_prefix}otool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OTOOL"; then ac_cv_prog_OTOOL="$OTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OTOOL="${ac_tool_prefix}otool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OTOOL=$ac_cv_prog_OTOOL if test -n "$OTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL" >&5 $as_echo "$OTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OTOOL"; then ac_ct_OTOOL=$OTOOL # Extract the first word of "otool", so it can be a program name with args. set dummy otool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OTOOL"; then ac_cv_prog_ac_ct_OTOOL="$ac_ct_OTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OTOOL="otool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OTOOL=$ac_cv_prog_ac_ct_OTOOL if test -n "$ac_ct_OTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL" >&5 $as_echo "$ac_ct_OTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OTOOL" = x; then OTOOL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OTOOL=$ac_ct_OTOOL fi else OTOOL="$ac_cv_prog_OTOOL" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}otool64", so it can be a program name with args. set dummy ${ac_tool_prefix}otool64; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OTOOL64+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OTOOL64"; then ac_cv_prog_OTOOL64="$OTOOL64" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OTOOL64="${ac_tool_prefix}otool64" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OTOOL64=$ac_cv_prog_OTOOL64 if test -n "$OTOOL64"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL64" >&5 $as_echo "$OTOOL64" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OTOOL64"; then ac_ct_OTOOL64=$OTOOL64 # Extract the first word of "otool64", so it can be a program name with args. set dummy otool64; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OTOOL64+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OTOOL64"; then ac_cv_prog_ac_ct_OTOOL64="$ac_ct_OTOOL64" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OTOOL64="otool64" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OTOOL64=$ac_cv_prog_ac_ct_OTOOL64 if test -n "$ac_ct_OTOOL64"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL64" >&5 $as_echo "$ac_ct_OTOOL64" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OTOOL64" = x; then OTOOL64=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OTOOL64=$ac_ct_OTOOL64 fi else OTOOL64="$ac_cv_prog_OTOOL64" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -single_module linker flag" >&5 $as_echo_n "checking for -single_module linker flag... " >&6; } if ${lt_cv_apple_cc_single_mod+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_apple_cc_single_mod=no if test -z "${LT_MULTI_MODULE}"; then # By default we will add the -single_module flag. You can override # by either setting the environment variable LT_MULTI_MODULE # non-empty at configure time, or by adding -multi_module to the # link flags. rm -rf libconftest.dylib* echo "int foo(void){return 1;}" > conftest.c echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c" >&5 $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c 2>conftest.err _lt_result=$? # If there is a non-empty error log, and "single_module" # appears in it, assume the flag caused a linker warning if test -s conftest.err && $GREP single_module conftest.err; then cat conftest.err >&5 # Otherwise, if the output was created with a 0 exit code from # the compiler, it worked. elif test -f libconftest.dylib && test $_lt_result -eq 0; then lt_cv_apple_cc_single_mod=yes else cat conftest.err >&5 fi rm -rf libconftest.dylib* rm -f conftest.* fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_apple_cc_single_mod" >&5 $as_echo "$lt_cv_apple_cc_single_mod" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -exported_symbols_list linker flag" >&5 $as_echo_n "checking for -exported_symbols_list linker flag... " >&6; } if ${lt_cv_ld_exported_symbols_list+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_exported_symbols_list=no save_LDFLAGS=$LDFLAGS echo "_main" > conftest.sym LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_ld_exported_symbols_list=yes else lt_cv_ld_exported_symbols_list=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_exported_symbols_list" >&5 $as_echo "$lt_cv_ld_exported_symbols_list" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -force_load linker flag" >&5 $as_echo_n "checking for -force_load linker flag... " >&6; } if ${lt_cv_ld_force_load+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_force_load=no cat > conftest.c << _LT_EOF int forced_loaded() { return 2;} _LT_EOF echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&5 $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&5 echo "$AR cru libconftest.a conftest.o" >&5 $AR cru libconftest.a conftest.o 2>&5 echo "$RANLIB libconftest.a" >&5 $RANLIB libconftest.a 2>&5 cat > conftest.c << _LT_EOF int main() { return 0;} _LT_EOF echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&5 $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err _lt_result=$? if test -s conftest.err && $GREP force_load conftest.err; then cat conftest.err >&5 elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then lt_cv_ld_force_load=yes else cat conftest.err >&5 fi rm -f conftest.err libconftest.a conftest conftest.c rm -rf conftest.dSYM fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_force_load" >&5 $as_echo "$lt_cv_ld_force_load" >&6; } case $host_os in rhapsody* | darwin1.[012]) _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;; darwin1.*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; darwin*) # darwin 5.x on # if running on 10.5 or later, the deployment target defaults # to the OS version, if on x86, and 10.4, the deployment # target defaults to 10.4. Don't you love it? case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in 10.0,*86*-darwin8*|10.0,*-darwin[91]*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; 10.[012]*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; 10.*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; esac ;; esac if test "$lt_cv_apple_cc_single_mod" = "yes"; then _lt_dar_single_mod='$single_module' fi if test "$lt_cv_ld_exported_symbols_list" = "yes"; then _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym' else _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}' fi if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then _lt_dsymutil='~$DSYMUTIL $lib || :' else _lt_dsymutil= fi ;; esac ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 $as_echo_n "checking how to run the C preprocessor... " >&6; } # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then if ${ac_cv_prog_CPP+:} false; then : $as_echo_n "(cached) " >&6 else # Double quotes because CPP needs to be expanded for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" do ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : break fi done ac_cv_prog_CPP=$CPP fi CPP=$ac_cv_prog_CPP else ac_cv_prog_CPP=$CPP fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 $as_echo "$CPP" >&6; } ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details" "$LINENO" 5; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 $as_echo_n "checking for ANSI C header files... " >&6; } if ${ac_cv_header_stdc+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_stdc=yes else ac_cv_header_stdc=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "memchr" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "free" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. if test "$cross_compiling" = yes; then : : else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #if ((' ' & 0x0FF) == 0x020) # define ISLOWER(c) ('a' <= (c) && (c) <= 'z') # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else # define ISLOWER(c) \ (('a' <= (c) && (c) <= 'i') \ || ('j' <= (c) && (c) <= 'r') \ || ('s' <= (c) && (c) <= 'z')) # define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif #define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { int i; for (i = 0; i < 256; i++) if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) return 2; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : else ac_cv_header_stdc=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 $as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then $as_echo "#define STDC_HEADERS 1" >>confdefs.h fi # On IRIX 5.3, sys/types and inttypes.h are conflicting. for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ inttypes.h stdint.h unistd.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default " if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done for ac_header in dlfcn.h do : ac_fn_c_check_header_compile "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default " if test "x$ac_cv_header_dlfcn_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_DLFCN_H 1 _ACEOF fi done # Set options enable_dlopen=no enable_win32_dll=no # Check whether --enable-shared was given. if test "${enable_shared+set}" = set; then : enableval=$enable_shared; p=${PACKAGE-default} case $enableval in yes) enable_shared=yes ;; no) enable_shared=no ;; *) enable_shared=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_shared=yes fi done IFS="$lt_save_ifs" ;; esac else enable_shared=yes fi # Check whether --enable-static was given. if test "${enable_static+set}" = set; then : enableval=$enable_static; p=${PACKAGE-default} case $enableval in yes) enable_static=yes ;; no) enable_static=no ;; *) enable_static=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_static=yes fi done IFS="$lt_save_ifs" ;; esac else enable_static=yes fi # Check whether --with-pic was given. if test "${with_pic+set}" = set; then : withval=$with_pic; lt_p=${PACKAGE-default} case $withval in yes|no) pic_mode=$withval ;; *) pic_mode=default # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for lt_pkg in $withval; do IFS="$lt_save_ifs" if test "X$lt_pkg" = "X$lt_p"; then pic_mode=yes fi done IFS="$lt_save_ifs" ;; esac else pic_mode=default fi test -z "$pic_mode" && pic_mode=default # Check whether --enable-fast-install was given. if test "${enable_fast_install+set}" = set; then : enableval=$enable_fast_install; p=${PACKAGE-default} case $enableval in yes) enable_fast_install=yes ;; no) enable_fast_install=no ;; *) enable_fast_install=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_fast_install=yes fi done IFS="$lt_save_ifs" ;; esac else enable_fast_install=yes fi # This can be used to rebuild libtool when needed LIBTOOL_DEPS="$ltmain" # Always use our own libtool. LIBTOOL='$(SHELL) $(top_builddir)/libtool' test -z "$LN_S" && LN_S="ln -s" if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for objdir" >&5 $as_echo_n "checking for objdir... " >&6; } if ${lt_cv_objdir+:} false; then : $as_echo_n "(cached) " >&6 else rm -f .libs 2>/dev/null mkdir .libs 2>/dev/null if test -d .libs; then lt_cv_objdir=.libs else # MS-DOS does not allow filenames that begin with a dot. lt_cv_objdir=_libs fi rmdir .libs 2>/dev/null fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_objdir" >&5 $as_echo "$lt_cv_objdir" >&6; } objdir=$lt_cv_objdir cat >>confdefs.h <<_ACEOF #define LT_OBJDIR "$lt_cv_objdir/" _ACEOF case $host_os in aix3*) # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi ;; esac # Global variables: ofile=libtool can_build_shared=yes # All known linkers require a `.a' archive for static linking (except MSVC, # which needs '.lib'). libext=a with_gnu_ld="$lt_cv_prog_gnu_ld" old_CC="$CC" old_CFLAGS="$CFLAGS" # Set sane defaults for various variables test -z "$CC" && CC=cc test -z "$LTCC" && LTCC=$CC test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS test -z "$LD" && LD=ld test -z "$ac_objext" && ac_objext=o for cc_temp in $compiler""; do case $cc_temp in compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; \-*) ;; *) break;; esac done cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` # Only perform the check for file, if the check method requires it test -z "$MAGIC_CMD" && MAGIC_CMD=file case $deplibs_check_method in file_magic*) if test "$file_magic_cmd" = '$MAGIC_CMD'; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${ac_tool_prefix}file" >&5 $as_echo_n "checking for ${ac_tool_prefix}file... " >&6; } if ${lt_cv_path_MAGIC_CMD+:} false; then : $as_echo_n "(cached) " >&6 else case $MAGIC_CMD in [\\/*] | ?:[\\/]*) lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD="$MAGIC_CMD" lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" for ac_dir in $ac_dummy; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f $ac_dir/${ac_tool_prefix}file; then lt_cv_path_MAGIC_CMD="$ac_dir/${ac_tool_prefix}file" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS="$lt_save_ifs" MAGIC_CMD="$lt_save_MAGIC_CMD" ;; esac fi MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if test -n "$MAGIC_CMD"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 $as_echo "$MAGIC_CMD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test -z "$lt_cv_path_MAGIC_CMD"; then if test -n "$ac_tool_prefix"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for file" >&5 $as_echo_n "checking for file... " >&6; } if ${lt_cv_path_MAGIC_CMD+:} false; then : $as_echo_n "(cached) " >&6 else case $MAGIC_CMD in [\\/*] | ?:[\\/]*) lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD="$MAGIC_CMD" lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" for ac_dir in $ac_dummy; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f $ac_dir/file; then lt_cv_path_MAGIC_CMD="$ac_dir/file" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS="$lt_save_ifs" MAGIC_CMD="$lt_save_MAGIC_CMD" ;; esac fi MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if test -n "$MAGIC_CMD"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 $as_echo "$MAGIC_CMD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi else MAGIC_CMD=: fi fi fi ;; esac # Use C for the default configuration in the libtool script lt_save_CC="$CC" ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu # Source file extension for C test sources. ac_ext=c # Object file extension for compiled C test sources. objext=o objext=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(){return(0);}' # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # Save the default compiler, since it gets overwritten when the other # tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. compiler_DEFAULT=$CC # save warnings/boilerplate of simple test code ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" >conftest.$ac_ext eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_compiler_boilerplate=`cat conftest.err` $RM conftest* ac_outfile=conftest.$ac_objext echo "$lt_simple_link_test_code" >conftest.$ac_ext eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then lt_prog_compiler_no_builtin_flag= if test "$GCC" = yes; then case $cc_basename in nvcc*) lt_prog_compiler_no_builtin_flag=' -Xcompiler -fno-builtin' ;; *) lt_prog_compiler_no_builtin_flag=' -fno-builtin' ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -fno-rtti -fno-exceptions" >&5 $as_echo_n "checking if $compiler supports -fno-rtti -fno-exceptions... " >&6; } if ${lt_cv_prog_compiler_rtti_exceptions+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_rtti_exceptions=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-fno-rtti -fno-exceptions" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_rtti_exceptions=yes fi fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_rtti_exceptions" >&5 $as_echo "$lt_cv_prog_compiler_rtti_exceptions" >&6; } if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions" else : fi fi lt_prog_compiler_wl= lt_prog_compiler_pic= lt_prog_compiler_static= if test "$GCC" = yes; then lt_prog_compiler_wl='-Wl,' lt_prog_compiler_static='-static' case $host_os in aix*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor lt_prog_compiler_static='-Bstatic' fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support lt_prog_compiler_pic='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the `-m68020' flag to GCC prevents building anything better, # like `-m68040'. lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries lt_prog_compiler_pic='-DDLL_EXPORT' ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files lt_prog_compiler_pic='-fno-common' ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. lt_prog_compiler_static= ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) # +Z the default ;; *) lt_prog_compiler_pic='-fPIC' ;; esac ;; interix[3-9]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; msdosdjgpp*) # Just because we use GCC doesn't mean we suddenly get shared libraries # on systems that don't support them. lt_prog_compiler_can_build_shared=no enable_shared=no ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic='-fPIC -shared' ;; sysv4*MP*) if test -d /usr/nec; then lt_prog_compiler_pic=-Kconform_pic fi ;; *) lt_prog_compiler_pic='-fPIC' ;; esac case $cc_basename in nvcc*) # Cuda Compiler Driver 2.2 lt_prog_compiler_wl='-Xlinker ' if test -n "$lt_prog_compiler_pic"; then lt_prog_compiler_pic="-Xcompiler $lt_prog_compiler_pic" fi ;; esac else # PORTME Check for flag to pass linker flags through the system compiler. case $host_os in aix*) lt_prog_compiler_wl='-Wl,' if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor lt_prog_compiler_static='-Bstatic' else lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp' fi ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). lt_prog_compiler_pic='-DDLL_EXPORT' ;; hpux9* | hpux10* | hpux11*) lt_prog_compiler_wl='-Wl,' # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but # not for PA HP-UX. case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) lt_prog_compiler_pic='+Z' ;; esac # Is there a better lt_prog_compiler_static that works with the bundled CC? lt_prog_compiler_static='${wl}-a ${wl}archive' ;; irix5* | irix6* | nonstopux*) lt_prog_compiler_wl='-Wl,' # PIC (with -KPIC) is the default. lt_prog_compiler_static='-non_shared' ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in # old Intel for x86_64 which still supported -KPIC. ecc*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-static' ;; # icc used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. icc* | ifort*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fPIC' lt_prog_compiler_static='-static' ;; # Lahey Fortran 8.1. lf95*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='--shared' lt_prog_compiler_static='--static' ;; nagfor*) # NAG Fortran compiler lt_prog_compiler_wl='-Wl,-Wl,,' lt_prog_compiler_pic='-PIC' lt_prog_compiler_static='-Bstatic' ;; pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group compilers (*not* the Pentium gcc compiler, # which looks to be a dead project) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fpic' lt_prog_compiler_static='-Bstatic' ;; ccc*) lt_prog_compiler_wl='-Wl,' # All Alpha code is PIC. lt_prog_compiler_static='-non_shared' ;; xl* | bgxl* | bgf* | mpixl*) # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-qpic' lt_prog_compiler_static='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [1-7].* | *Sun*Fortran*\ 8.[0-3]*) # Sun Fortran 8.3 passes all unrecognized flags to the linker lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='' ;; *Sun\ F* | *Sun*Fortran*) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='-Qoption ld ' ;; *Sun\ C*) # Sun C 5.9 lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='-Wl,' ;; *Intel*\ [CF]*Compiler*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fPIC' lt_prog_compiler_static='-static' ;; *Portland\ Group*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fpic' lt_prog_compiler_static='-Bstatic' ;; esac ;; esac ;; newsos6) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic='-fPIC -shared' ;; osf3* | osf4* | osf5*) lt_prog_compiler_wl='-Wl,' # All OSF/1 code is PIC. lt_prog_compiler_static='-non_shared' ;; rdos*) lt_prog_compiler_static='-non_shared' ;; solaris*) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' case $cc_basename in f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) lt_prog_compiler_wl='-Qoption ld ';; *) lt_prog_compiler_wl='-Wl,';; esac ;; sunos4*) lt_prog_compiler_wl='-Qoption ld ' lt_prog_compiler_pic='-PIC' lt_prog_compiler_static='-Bstatic' ;; sysv4 | sysv4.2uw2* | sysv4.3*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; sysv4*MP*) if test -d /usr/nec ;then lt_prog_compiler_pic='-Kconform_pic' lt_prog_compiler_static='-Bstatic' fi ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; unicos*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_can_build_shared=no ;; uts4*) lt_prog_compiler_pic='-pic' lt_prog_compiler_static='-Bstatic' ;; *) lt_prog_compiler_can_build_shared=no ;; esac fi case $host_os in # For platforms which do not support PIC, -DPIC is meaningless: *djgpp*) lt_prog_compiler_pic= ;; *) lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC" ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5 $as_echo_n "checking for $compiler option to produce PIC... " >&6; } if ${lt_cv_prog_compiler_pic+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic=$lt_prog_compiler_pic fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic" >&5 $as_echo "$lt_cv_prog_compiler_pic" >&6; } lt_prog_compiler_pic=$lt_cv_prog_compiler_pic # # Check to make sure the PIC flag actually works. # if test -n "$lt_prog_compiler_pic"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5 $as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic works... " >&6; } if ${lt_cv_prog_compiler_pic_works+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic_works=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$lt_prog_compiler_pic -DPIC" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_pic_works=yes fi fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works" >&5 $as_echo "$lt_cv_prog_compiler_pic_works" >&6; } if test x"$lt_cv_prog_compiler_pic_works" = xyes; then case $lt_prog_compiler_pic in "" | " "*) ;; *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;; esac else lt_prog_compiler_pic= lt_prog_compiler_can_build_shared=no fi fi # # Check to make sure the static flag actually works. # wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\" { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5 $as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } if ${lt_cv_prog_compiler_static_works+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_static_works=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS $lt_tmp_static_flag" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_static_works=yes fi else lt_cv_prog_compiler_static_works=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works" >&5 $as_echo "$lt_cv_prog_compiler_static_works" >&6; } if test x"$lt_cv_prog_compiler_static_works" = xyes; then : else lt_prog_compiler_static= fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 $as_echo "$lt_cv_prog_compiler_c_o" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 $as_echo "$lt_cv_prog_compiler_c_o" >&6; } hard_links="nottested" if test "$lt_cv_prog_compiler_c_o" = no && test "$need_locks" != no; then # do not overwrite the value of need_locks provided by the user { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5 $as_echo_n "checking if we can lock with hard links... " >&6; } hard_links=yes $RM conftest* ln conftest.a conftest.b 2>/dev/null && hard_links=no touch conftest.a ln conftest.a conftest.b 2>&5 || hard_links=no ln conftest.a conftest.b 2>/dev/null && hard_links=no { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5 $as_echo "$hard_links" >&6; } if test "$hard_links" = no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 $as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} need_locks=warn fi else need_locks=no fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 $as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } runpath_var= allow_undefined_flag= always_export_symbols=no archive_cmds= archive_expsym_cmds= compiler_needs_object=no enable_shared_with_static_runtimes=no export_dynamic_flag_spec= export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' hardcode_automatic=no hardcode_direct=no hardcode_direct_absolute=no hardcode_libdir_flag_spec= hardcode_libdir_separator= hardcode_minus_L=no hardcode_shlibpath_var=unsupported inherit_rpath=no link_all_deplibs=unknown module_cmds= module_expsym_cmds= old_archive_from_new_cmds= old_archive_from_expsyms_cmds= thread_safe_flag_spec= whole_archive_flag_spec= # include_expsyms should be a list of space-separated symbols to be *always* # included in the symbol list include_expsyms= # exclude_expsyms can be an extended regexp of symbols to exclude # it will be wrapped by ` (' and `)$', so one must not match beginning or # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', # as well as any symbol that contains `d'. exclude_expsyms='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*' # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out # platforms (ab)use it in PIC code, but their linkers get confused if # the symbol is explicitly referenced. Since portable code cannot # rely on this symbol name, it's probably fine to never include it in # preloaded symbol tables. # Exclude shared library initialization/finalization symbols. extract_expsyms_cmds= case $host_os in cygwin* | mingw* | pw32* | cegcc*) # FIXME: the MSVC++ port hasn't been tested in a loooong time # When not using gcc, we currently assume that we are using # Microsoft Visual C++. if test "$GCC" != yes; then with_gnu_ld=no fi ;; interix*) # we just hope/assume this is gcc and not c89 (= MSVC++) with_gnu_ld=yes ;; openbsd*) with_gnu_ld=no ;; linux* | k*bsd*-gnu | gnu*) link_all_deplibs=no ;; esac ld_shlibs=yes # On some targets, GNU ld is compatible enough with the native linker # that we're better off using the native interface for both. lt_use_gnu_ld_interface=no if test "$with_gnu_ld" = yes; then case $host_os in aix*) # The AIX port of GNU ld has always aspired to compatibility # with the native linker. However, as the warning in the GNU ld # block says, versions before 2.19.5* couldn't really create working # shared libraries, regardless of the interface used. case `$LD -v 2>&1` in *\ \(GNU\ Binutils\)\ 2.19.5*) ;; *\ \(GNU\ Binutils\)\ 2.[2-9]*) ;; *\ \(GNU\ Binutils\)\ [3-9]*) ;; *) lt_use_gnu_ld_interface=yes ;; esac ;; *) lt_use_gnu_ld_interface=yes ;; esac fi if test "$lt_use_gnu_ld_interface" = yes; then # If archive_cmds runs LD, not CC, wlarc should be empty wlarc='${wl}' # Set some defaults for GNU ld with shared library support. These # are reset later if shared libraries are not supported. Putting them # here allows them to be overridden if necessary. runpath_var=LD_RUN_PATH hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' export_dynamic_flag_spec='${wl}--export-dynamic' # ancient GNU ld didn't support --whole-archive et. al. if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then whole_archive_flag_spec="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' else whole_archive_flag_spec= fi supports_anon_versioning=no case `$LD -v 2>&1` in *GNU\ gold*) supports_anon_versioning=yes ;; *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... *\ 2.11.*) ;; # other 2.11 versions *) supports_anon_versioning=yes ;; esac # See if GNU ld supports shared libraries. case $host_os in aix[3-9]*) # On AIX/PPC, the GNU linker is very broken if test "$host_cpu" != ia64; then ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: the GNU linker, at least up to release 2.19, is reported *** to be unable to reliably create shared libraries on AIX. *** Therefore, libtool is disabling shared libraries support. If you *** really care for shared libraries, you may want to install binutils *** 2.20 or above, or modify your PATH so that a non-GNU linker is found. *** You will then need to restart the configuration process. _LT_EOF fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='' ;; m68k) archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes ;; esac ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then allow_undefined_flag=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' else ld_shlibs=no fi ;; cygwin* | mingw* | pw32* | cegcc*) # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless, # as there is no search path for DLLs. hardcode_libdir_flag_spec='-L$libdir' export_dynamic_flag_spec='${wl}--export-all-symbols' allow_undefined_flag=unsupported always_export_symbols=no enable_shared_with_static_runtimes=yes export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols' exclude_expsyms='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname' if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file (1st line # is EXPORTS), use it as is; otherwise, prepend... archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else ld_shlibs=no fi ;; haiku*) archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' link_all_deplibs=yes ;; interix[3-9]*) hardcode_direct=no hardcode_shlibpath_var=no hardcode_libdir_flag_spec='${wl}-rpath,$libdir' export_dynamic_flag_spec='${wl}-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' archive_expsym_cmds='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu) tmp_diet=no if test "$host_os" = linux-dietlibc; then case $cc_basename in diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) esac fi if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ && test "$tmp_diet" = no then tmp_addflag=' $pic_flag' tmp_sharedflag='-shared' case $cc_basename,$host_cpu in pgcc*) # Portland Group C compiler whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag' ;; pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group f77 and f90 compilers whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag -Mnomain' ;; ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 tmp_addflag=' -i_dynamic' ;; efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 tmp_addflag=' -i_dynamic -nofor_main' ;; ifc* | ifort*) # Intel Fortran compiler tmp_addflag=' -nofor_main' ;; lf95*) # Lahey Fortran 8.1 whole_archive_flag_spec= tmp_sharedflag='--shared' ;; xl[cC]* | bgxl[cC]* | mpixl[cC]*) # IBM XL C 8.0 on PPC (deal with xlf below) tmp_sharedflag='-qmkshrobj' tmp_addflag= ;; nvcc*) # Cuda Compiler Driver 2.2 whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' compiler_needs_object=yes ;; esac case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C 5.9 whole_archive_flag_spec='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' compiler_needs_object=yes tmp_sharedflag='-G' ;; *Sun\ F*) # Sun Fortran 8.3 tmp_sharedflag='-G' ;; esac archive_cmds='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' if test "x$supports_anon_versioning" = xyes; then archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' fi case $cc_basename in xlf* | bgf* | bgxlf* | mpixlf*) # IBM XL Fortran 10.1 on PPC cannot create shared libs itself whole_archive_flag_spec='--whole-archive$convenience --no-whole-archive' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' archive_cmds='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib' if test "x$supports_anon_versioning" = xyes; then archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' fi ;; esac else ld_shlibs=no fi ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' wlarc= else archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' fi ;; solaris*) if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: The releases 2.8.* of the GNU linker cannot reliably *** create shared libraries on Solaris systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.9.1 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) case `$LD -v 2>&1` in *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*) ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not *** reliably create shared libraries on SCO systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.16.91.0.3 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF ;; *) # For security reasons, it is highly recommended that you always # use absolute paths for naming shared libraries, and exclude the # DT_RUNPATH tag from executables and libraries. But doing so # requires that you compile everything twice, which is a pain. if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; esac ;; sunos4*) archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' wlarc= hardcode_direct=yes hardcode_shlibpath_var=no ;; *) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; esac if test "$ld_shlibs" = no; then runpath_var= hardcode_libdir_flag_spec= export_dynamic_flag_spec= whole_archive_flag_spec= fi else # PORTME fill in a description of your system's linker (not GNU ld) case $host_os in aix3*) allow_undefined_flag=unsupported always_export_symbols=yes archive_expsym_cmds='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' # Note: this linker hardcodes the directories in LIBPATH if there # are no directories specified by -L. hardcode_minus_L=yes if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then # Neither direct hardcoding nor static linking is supported with a # broken collect2. hardcode_direct=unsupported fi ;; aix[4-9]*) if test "$host_cpu" = ia64; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag="" else # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to AIX nm, but means don't demangle with GNU nm # Also, AIX nm treats weak defined symbols like other global # defined symbols, whereas GNU nm marks them as "W". if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' else export_symbols_cmds='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' fi aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # need to do runtime linking. case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*) for ld_flag in $LDFLAGS; do if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then aix_use_runtimelinking=yes break fi done ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. archive_cmds='' hardcode_direct=yes hardcode_direct_absolute=yes hardcode_libdir_separator=':' link_all_deplibs=yes file_list_spec='${wl}-f,' if test "$GCC" = yes; then case $host_os in aix4.[012]|aix4.[012].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`${CC} -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 hardcode_direct=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking hardcode_minus_L=yes hardcode_libdir_flag_spec='-L$libdir' hardcode_libdir_separator= fi ;; esac shared_flag='-shared' if test "$aix_use_runtimelinking" = yes; then shared_flag="$shared_flag "'${wl}-G' fi link_all_deplibs=no else # not using gcc if test "$host_cpu" = ia64; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test "$aix_use_runtimelinking" = yes; then shared_flag='${wl}-G' else shared_flag='${wl}-bM:SRE' fi fi fi export_dynamic_flag_spec='${wl}-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to export. always_export_symbols=yes if test "$aix_use_runtimelinking" = yes; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. allow_undefined_flag='-berok' # Determine the default libpath from the value encoded in an # empty executable. if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath_+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_="/usr/lib:/lib" fi fi aix_libpath=$lt_cv_aix_libpath_ fi hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" archive_expsym_cmds='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" else if test "$host_cpu" = ia64; then hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib' allow_undefined_flag="-z nodefs" archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath_+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_="/usr/lib:/lib" fi fi aix_libpath=$lt_cv_aix_libpath_ fi hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. no_undefined_flag=' ${wl}-bernotok' allow_undefined_flag=' ${wl}-berok' if test "$with_gnu_ld" = yes; then # We only use this code for GNU lds that support --whole-archive. whole_archive_flag_spec='${wl}--whole-archive$convenience ${wl}--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives whole_archive_flag_spec='$convenience' fi archive_cmds_need_lc=yes # This is similar to how AIX traditionally builds its shared libraries. archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' fi fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='' ;; m68k) archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes ;; esac ;; bsdi[45]*) export_dynamic_flag_spec=-rdynamic ;; cygwin* | mingw* | pw32* | cegcc*) # When not using gcc, we currently assume that we are using # Microsoft Visual C++. # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. case $cc_basename in cl*) # Native MSVC hardcode_libdir_flag_spec=' ' allow_undefined_flag=unsupported always_export_symbols=yes file_list_spec='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. archive_cmds='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; else sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, )='true' enable_shared_with_static_runtimes=yes exclude_expsyms='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1,DATA/'\'' | $SED -e '\''/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols' # Don't use ranlib old_postinstall_cmds='chmod 644 $oldlib' postlink_cmds='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile="$lt_outputfile.exe" lt_tool_outputfile="$lt_tool_outputfile.exe" ;; esac~ if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # Assume MSVC wrapper hardcode_libdir_flag_spec=' ' allow_undefined_flag=unsupported # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. archive_cmds='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=' # The linker will automatically build a .lib file if we build a DLL. old_archive_from_new_cmds='true' # FIXME: Should let the user specify the lib program. old_archive_cmds='lib -OUT:$oldlib$oldobjs$old_deplibs' enable_shared_with_static_runtimes=yes ;; esac ;; darwin* | rhapsody*) archive_cmds_need_lc=no hardcode_direct=no hardcode_automatic=yes hardcode_shlibpath_var=unsupported if test "$lt_cv_ld_force_load" = "yes"; then whole_archive_flag_spec='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' else whole_archive_flag_spec='' fi link_all_deplibs=yes allow_undefined_flag="$_lt_dar_allow_undefined" case $cc_basename in ifort*) _lt_dar_can_shared=yes ;; *) _lt_dar_can_shared=$GCC ;; esac if test "$_lt_dar_can_shared" = "yes"; then output_verbose_link_cmd=func_echo_all archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" archive_expsym_cmds="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" module_expsym_cmds="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" else ld_shlibs=no fi ;; dgux*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-L$libdir' hardcode_shlibpath_var=no ;; # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor # support. Future versions do this automatically, but an explicit c++rt0.o # does not break anything, and helps significantly (at the cost of a little # extra space). freebsd2.2*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; # Unfortunately, older versions of FreeBSD 2 do not have this feature. freebsd2.*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes hardcode_minus_L=yes hardcode_shlibpath_var=no ;; # FreeBSD 3 and greater uses gcc -shared to do shared libraries. freebsd* | dragonfly*) archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; hpux9*) if test "$GCC" = yes; then archive_cmds='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' else archive_cmds='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' fi hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' hardcode_libdir_separator=: hardcode_direct=yes # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes export_dynamic_flag_spec='${wl}-E' ;; hpux10*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi if test "$with_gnu_ld" = no; then hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' hardcode_libdir_separator=: hardcode_direct=yes hardcode_direct_absolute=yes export_dynamic_flag_spec='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes fi ;; hpux11*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then case $host_cpu in hppa*64*) archive_cmds='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' ;; esac else case $host_cpu in hppa*64*) archive_cmds='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) # Older versions of the 11.00 compiler do not understand -b yet # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does) { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $CC understands -b" >&5 $as_echo_n "checking if $CC understands -b... " >&6; } if ${lt_cv_prog_compiler__b+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler__b=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -b" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler__b=yes fi else lt_cv_prog_compiler__b=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler__b" >&5 $as_echo "$lt_cv_prog_compiler__b" >&6; } if test x"$lt_cv_prog_compiler__b" = xyes; then archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi ;; esac fi if test "$with_gnu_ld" = no; then hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' hardcode_libdir_separator=: case $host_cpu in hppa*64*|ia64*) hardcode_direct=no hardcode_shlibpath_var=no ;; *) hardcode_direct=yes hardcode_direct_absolute=yes export_dynamic_flag_spec='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes ;; esac fi ;; irix5* | irix6* | nonstopux*) if test "$GCC" = yes; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' # Try to use the -exported_symbol ld option, if it does not # work, assume that -exports_file does not work either and # implicitly export all symbols. # This should be the same for all languages, so no per-tag cache variable. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $host_os linker accepts -exported_symbol" >&5 $as_echo_n "checking whether the $host_os linker accepts -exported_symbol... " >&6; } if ${lt_cv_irix_exported_symbol+:} false; then : $as_echo_n "(cached) " >&6 else save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int foo (void) { return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_irix_exported_symbol=yes else lt_cv_irix_exported_symbol=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_irix_exported_symbol" >&5 $as_echo "$lt_cv_irix_exported_symbol" >&6; } if test "$lt_cv_irix_exported_symbol" = yes; then archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib' fi else archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib' fi archive_cmds_need_lc='no' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator=: inherit_rpath=yes link_all_deplibs=yes ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out else archive_cmds='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF fi hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; newsos6) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator=: hardcode_shlibpath_var=no ;; *nto* | *qnx*) ;; openbsd*) if test -f /usr/libexec/ld.so; then hardcode_direct=yes hardcode_shlibpath_var=no hardcode_direct_absolute=yes if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' hardcode_libdir_flag_spec='${wl}-rpath,$libdir' export_dynamic_flag_spec='${wl}-E' else case $host_os in openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-R$libdir' ;; *) archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' hardcode_libdir_flag_spec='${wl}-rpath,$libdir' ;; esac fi else ld_shlibs=no fi ;; os2*) hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes allow_undefined_flag=unsupported archive_cmds='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' old_archive_from_new_cmds='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' ;; osf3*) if test "$GCC" = yes; then allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' else allow_undefined_flag=' -expect_unresolved \*' archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' fi archive_cmds_need_lc='no' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator=: ;; osf4* | osf5*) # as osf3* with the addition of -msym flag if test "$GCC" = yes; then allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' archive_cmds='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' else allow_undefined_flag=' -expect_unresolved \*' archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ $CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp' # Both c and cxx compiler support -rpath directly hardcode_libdir_flag_spec='-rpath $libdir' fi archive_cmds_need_lc='no' hardcode_libdir_separator=: ;; solaris*) no_undefined_flag=' -z defs' if test "$GCC" = yes; then wlarc='${wl}' archive_cmds='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' else case `$CC -V 2>&1` in *"Compilers 5.0"*) wlarc='' archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' ;; *) wlarc='${wl}' archive_cmds='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' ;; esac fi hardcode_libdir_flag_spec='-R$libdir' hardcode_shlibpath_var=no case $host_os in solaris2.[0-5] | solaris2.[0-5].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands `-z linker_flag'. GCC discards it without `$wl', # but is careful enough not to reorder. # Supported since Solaris 2.6 (maybe 2.5.1?) if test "$GCC" = yes; then whole_archive_flag_spec='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' else whole_archive_flag_spec='-z allextract$convenience -z defaultextract' fi ;; esac link_all_deplibs=yes ;; sunos4*) if test "x$host_vendor" = xsequent; then # Use $CC to link under sequent, because it throws in some extra .o # files that make .init and .fini sections work. archive_cmds='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' fi hardcode_libdir_flag_spec='-L$libdir' hardcode_direct=yes hardcode_minus_L=yes hardcode_shlibpath_var=no ;; sysv4) case $host_vendor in sni) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes # is this really true??? ;; siemens) ## LD is ld it makes a PLAMLIB ## CC just makes a GrossModule. archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags' reload_cmds='$CC -r -o $output$reload_objs' hardcode_direct=no ;; motorola) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=no #Motorola manual says yes, but my tests say they lie ;; esac runpath_var='LD_RUN_PATH' hardcode_shlibpath_var=no ;; sysv4.3*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_shlibpath_var=no export_dynamic_flag_spec='-Bexport' ;; sysv4*MP*) if test -d /usr/nec; then archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_shlibpath_var=no runpath_var=LD_RUN_PATH hardcode_runpath_var=yes ld_shlibs=yes fi ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) no_undefined_flag='${wl}-z,text' archive_cmds_need_lc=no hardcode_shlibpath_var=no runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We can NOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. no_undefined_flag='${wl}-z,text' allow_undefined_flag='${wl}-z,nodefs' archive_cmds_need_lc=no hardcode_shlibpath_var=no hardcode_libdir_flag_spec='${wl}-R,$libdir' hardcode_libdir_separator=':' link_all_deplibs=yes export_dynamic_flag_spec='${wl}-Bexport' runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; uts4*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-L$libdir' hardcode_shlibpath_var=no ;; *) ld_shlibs=no ;; esac if test x$host_vendor = xsni; then case $host in sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) export_dynamic_flag_spec='${wl}-Blargedynsym' ;; esac fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs" >&5 $as_echo "$ld_shlibs" >&6; } test "$ld_shlibs" = no && can_build_shared=no with_gnu_ld=$with_gnu_ld # # Do we need to explicitly link libc? # case "x$archive_cmds_need_lc" in x|xyes) # Assume -lc should be added archive_cmds_need_lc=yes if test "$enable_shared" = yes && test "$GCC" = yes; then case $archive_cmds in *'~'*) # FIXME: we may have to deal with multi-command sequences. ;; '$CC '*) # Test whether the compiler implicitly links with -lc since on some # systems, -lgcc has to come before -lc. If gcc already passes -lc # to ld, don't add -lc before -lgcc. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5 $as_echo_n "checking whether -lc should be explicitly linked in... " >&6; } if ${lt_cv_archive_cmds_need_lc+:} false; then : $as_echo_n "(cached) " >&6 else $RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } 2>conftest.err; then soname=conftest lib=conftest libobjs=conftest.$ac_objext deplibs= wl=$lt_prog_compiler_wl pic_flag=$lt_prog_compiler_pic compiler_flags=-v linker_flags=-v verstring= output_objdir=. libname=conftest lt_save_allow_undefined_flag=$allow_undefined_flag allow_undefined_flag= if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5 (eval $archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } then lt_cv_archive_cmds_need_lc=no else lt_cv_archive_cmds_need_lc=yes fi allow_undefined_flag=$lt_save_allow_undefined_flag else cat conftest.err 1>&5 fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc" >&5 $as_echo "$lt_cv_archive_cmds_need_lc" >&6; } archive_cmds_need_lc=$lt_cv_archive_cmds_need_lc ;; esac fi ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5 $as_echo_n "checking dynamic linker characteristics... " >&6; } if test "$GCC" = yes; then case $host_os in darwin*) lt_awk_arg="/^libraries:/,/LR/" ;; *) lt_awk_arg="/^libraries:/" ;; esac case $host_os in mingw* | cegcc*) lt_sed_strip_eq="s,=\([A-Za-z]:\),\1,g" ;; *) lt_sed_strip_eq="s,=/,/,g" ;; esac lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` case $lt_search_path_spec in *\;*) # if the path contains ";" then we assume it to be the separator # otherwise default to the standard path separator (i.e. ":") - it is # assumed that no part of a normal pathname contains ";" but that should # okay in the real world where ";" in dirpaths is itself problematic. lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'` ;; *) lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"` ;; esac # Ok, now we have the path, separated by spaces, we can step through it # and add multilib dir if necessary. lt_tmp_lt_search_path_spec= lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` for lt_sys_path in $lt_search_path_spec; do if test -d "$lt_sys_path/$lt_multi_os_dir"; then lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir" else test -d "$lt_sys_path" && \ lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" fi done lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk ' BEGIN {RS=" "; FS="/|\n";} { lt_foo=""; lt_count=0; for (lt_i = NF; lt_i > 0; lt_i--) { if ($lt_i != "" && $lt_i != ".") { if ($lt_i == "..") { lt_count++; } else { if (lt_count == 0) { lt_foo="/" $lt_i lt_foo; } else { lt_count--; } } } } if (lt_foo != "") { lt_freq[lt_foo]++; } if (lt_freq[lt_foo] == 1) { print lt_foo; } }'` # AWK program above erroneously prepends '/' to C:/dos/paths # for these hosts. case $host_os in mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ $SED 's,/\([A-Za-z]:\),\1,g'` ;; esac sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` else sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" fi library_names_spec= libname_spec='lib$name' soname_spec= shrext_cmds=".so" postinstall_cmds= postuninstall_cmds= finish_cmds= finish_eval= shlibpath_var= shlibpath_overrides_runpath=unknown version_type=none dynamic_linker="$host_os ld.so" sys_lib_dlsearch_path_spec="/lib /usr/lib" need_lib_prefix=unknown hardcode_into_libs=no # when you set need_version to no, make sure it does not cause -set_version # flags to be left without arguments need_version=unknown case $host_os in aix3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' shlibpath_var=LIBPATH # AIX 3 has no versioning support, so we append a major version to the name. soname_spec='${libname}${release}${shared_ext}$major' ;; aix[4-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no hardcode_into_libs=yes if test "$host_cpu" = ia64; then # AIX 5 supports IA64 library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH else # With GCC up to 2.95.x, collect2 would create an import file # for dependence libraries. The import file would start with # the line `#! .'. This would cause the generated library to # depend on `.', always an invalid library. This was fixed in # development snapshots of GCC prior to 3.0. case $host_os in aix4 | aix4.[01] | aix4.[01].*) if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' echo ' yes ' echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then : else can_build_shared=no fi ;; esac # AIX (on Power*) has no versioning support, so currently we can not hardcode correct # soname into executable. Probably we can add versioning support to # collect2, so additional links can be useful in future. if test "$aix_use_runtimelinking" = yes; then # If using run time linking (on AIX 4.2 or later) use lib.so # instead of lib.a to let people know that these are not # typical AIX shared libraries. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' else # We preserve .a as extension for shared libraries through AIX4.2 # and later when we are not doing run time linking. library_names_spec='${libname}${release}.a $libname.a' soname_spec='${libname}${release}${shared_ext}$major' fi shlibpath_var=LIBPATH fi ;; amigaos*) case $host_cpu in powerpc) # Since July 2007 AmigaOS4 officially supports .so libraries. # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' ;; m68k) library_names_spec='$libname.ixlibrary $libname.a' # Create ${libname}_ixlibrary.a entries in /sys/libs. finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' ;; esac ;; beos*) library_names_spec='${libname}${shared_ext}' dynamic_linker="$host_os ld.so" shlibpath_var=LIBRARY_PATH ;; bsdi[45]*) version_type=linux # correct to gnu/linux during the next big refactor need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" # the default ld.so.conf also contains /usr/contrib/lib and # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow # libtool to hard-code these into programs ;; cygwin* | mingw* | pw32* | cegcc*) version_type=windows shrext_cmds=".dll" need_version=no need_lib_prefix=no case $GCC,$cc_basename in yes,*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes case $host_os in cygwin*) # Cygwin DLLs use 'cyg' prefix rather than 'lib' soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api" ;; mingw* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; pw32*) # pw32 DLLs use 'pw' prefix rather than 'lib' library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; esac dynamic_linker='Win32 ld.exe' ;; *,cl*) # Native MSVC libname_spec='$name' soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' library_names_spec='${libname}.dll.lib' case $build_os in mingw*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' for lt_path in $LIB do IFS=$lt_save_ifs # Let DOS variable expansion print the short 8.3 style file name. lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" done IFS=$lt_save_ifs # Convert to MSYS style. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'` ;; cygwin*) # Convert to unix form, then to dos form, then back to unix form # but this time dos style (no spaces!) so that the unix form looks # like /cygdrive/c/PROGRA~1:/cygdr... sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` ;; *) sys_lib_search_path_spec="$LIB" if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then # It is most probably a Windows format PATH. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` else sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` fi # FIXME: find the short name or the path components, as spaces are # common. (e.g. "Program Files" -> "PROGRA~1") ;; esac # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes dynamic_linker='Win32 link.exe' ;; *) # Assume MSVC wrapper library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' dynamic_linker='Win32 ld.exe' ;; esac # FIXME: first we should search . and the directory the executable is in shlibpath_var=PATH ;; darwin* | rhapsody*) dynamic_linker="$host_os dyld" version_type=darwin need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' soname_spec='${libname}${release}${major}$shared_ext' shlibpath_overrides_runpath=yes shlibpath_var=DYLD_LIBRARY_PATH shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib" sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' ;; dgux*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; freebsd* | dragonfly*) # DragonFly does not have aout. When/if they implement a new # versioning mechanism, adjust this. if test -x /usr/bin/objformat; then objformat=`/usr/bin/objformat` else case $host_os in freebsd[23].*) objformat=aout ;; *) objformat=elf ;; esac fi version_type=freebsd-$objformat case $version_type in freebsd-elf*) library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' need_version=no need_lib_prefix=no ;; freebsd-*) library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' need_version=yes ;; esac shlibpath_var=LD_LIBRARY_PATH case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes ;; freebsd3.[01]* | freebsdelf3.[01]*) shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; *) # from 4.6 on, and DragonFly shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; esac ;; haiku*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no dynamic_linker="$host_os runtime_loader" library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=yes sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' hardcode_into_libs=yes ;; hpux9* | hpux10* | hpux11*) # Give a soname corresponding to the major version so that dld.sl refuses to # link against other versions. version_type=sunos need_lib_prefix=no need_version=no case $host_cpu in ia64*) shrext_cmds='.so' hardcode_into_libs=yes dynamic_linker="$host_os dld.so" shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' if test "X$HPUX_IA64_MODE" = X32; then sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" else sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" fi sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; hppa*64*) shrext_cmds='.sl' hardcode_into_libs=yes dynamic_linker="$host_os dld.sl" shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; *) shrext_cmds='.sl' dynamic_linker="$host_os dld.sl" shlibpath_var=SHLIB_PATH shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' ;; esac # HP-UX runs *really* slowly unless shared libraries are mode 555, ... postinstall_cmds='chmod 555 $lib' # or fails outright, so override atomically: install_override_mode=555 ;; interix[3-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; irix5* | irix6* | nonstopux*) case $host_os in nonstopux*) version_type=nonstopux ;; *) if test "$lt_cv_prog_gnu_ld" = yes; then version_type=linux # correct to gnu/linux during the next big refactor else version_type=irix fi ;; esac need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' case $host_os in irix5* | nonstopux*) libsuff= shlibsuff= ;; *) case $LD in # libtool.m4 will add one of these switches to LD *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= libmagic=32-bit;; *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 libmagic=N32;; *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 libmagic=64-bit;; *) libsuff= shlibsuff= libmagic=never-match;; esac ;; esac shlibpath_var=LD_LIBRARY${shlibsuff}_PATH shlibpath_overrides_runpath=no sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" hardcode_into_libs=yes ;; # No shared lib support for Linux oldld, aout, or coff. linux*oldld* | linux*aout* | linux*coff*) dynamic_linker=no ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no # Some binutils ld are patched to set DT_RUNPATH if ${lt_cv_shlibpath_overrides_runpath+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$lt_prog_compiler_wl\"; \ LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec\"" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : if ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then : lt_cv_shlibpath_overrides_runpath=yes fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS libdir=$save_libdir fi shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on # powerpc, because MkLinux only supported shared libraries with the # GNU dynamic linker. Since this was broken with cross compilers, # most powerpc-linux boxes support dynamic linking these days and # people can always --disable-shared, the test was removed, and we # assume the GNU/Linux dynamic linker is in use. dynamic_linker='GNU/Linux ld.so' ;; netbsdelf*-gnu) version_type=linux need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='NetBSD ld.elf_so' ;; netbsd*) version_type=sunos need_lib_prefix=no need_version=no if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' dynamic_linker='NetBSD (a.out) ld.so' else library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='NetBSD ld.elf_so' fi shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; *nto* | *qnx*) version_type=qnx need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='ldqnx.so' ;; openbsd*) version_type=sunos sys_lib_dlsearch_path_spec="/usr/lib" need_lib_prefix=no # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. case $host_os in openbsd3.3 | openbsd3.3.*) need_version=yes ;; *) need_version=no ;; esac library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' shlibpath_var=LD_LIBRARY_PATH if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then case $host_os in openbsd2.[89] | openbsd2.[89].*) shlibpath_overrides_runpath=no ;; *) shlibpath_overrides_runpath=yes ;; esac else shlibpath_overrides_runpath=yes fi ;; os2*) libname_spec='$name' shrext_cmds=".dll" need_lib_prefix=no library_names_spec='$libname${shared_ext} $libname.a' dynamic_linker='OS/2 ld.exe' shlibpath_var=LIBPATH ;; osf3* | osf4* | osf5*) version_type=osf need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" ;; rdos*) dynamic_linker=no ;; solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes # ldd complains unless libraries are executable postinstall_cmds='chmod +x $lib' ;; sunos4*) version_type=sunos library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes if test "$with_gnu_ld" = yes; then need_lib_prefix=no fi need_version=yes ;; sysv4 | sysv4.3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH case $host_vendor in sni) shlibpath_overrides_runpath=no need_lib_prefix=no runpath_var=LD_RUN_PATH ;; siemens) need_lib_prefix=no ;; motorola) need_lib_prefix=no need_version=no shlibpath_overrides_runpath=no sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' ;; esac ;; sysv4*MP*) if test -d /usr/nec ;then version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' soname_spec='$libname${shared_ext}.$major' shlibpath_var=LD_LIBRARY_PATH fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) version_type=freebsd-elf need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes if test "$with_gnu_ld" = yes; then sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' else sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' case $host_os in sco3.2v5*) sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" ;; esac fi sys_lib_dlsearch_path_spec='/usr/lib' ;; tpf*) # TPF is a cross-target only. Preferred cross-host = GNU/Linux. version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; uts4*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; *) dynamic_linker=no ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5 $as_echo "$dynamic_linker" >&6; } test "$dynamic_linker" = no && can_build_shared=no variables_saved_for_relink="PATH $shlibpath_var $runpath_var" if test "$GCC" = yes; then variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" fi if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" fi if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5 $as_echo_n "checking how to hardcode library paths into programs... " >&6; } hardcode_action= if test -n "$hardcode_libdir_flag_spec" || test -n "$runpath_var" || test "X$hardcode_automatic" = "Xyes" ; then # We can hardcode non-existent directories. if test "$hardcode_direct" != no && # If the only mechanism to avoid hardcoding is shlibpath_var, we # have to relink, otherwise we might link with an installed library # when we should be linking with a yet-to-be-installed one ## test "$_LT_TAGVAR(hardcode_shlibpath_var, )" != no && test "$hardcode_minus_L" != no; then # Linking always hardcodes the temporary library directory. hardcode_action=relink else # We can link without hardcoding, and we can hardcode nonexisting dirs. hardcode_action=immediate fi else # We cannot hardcode anything, or else we can only hardcode existing # directories. hardcode_action=unsupported fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action" >&5 $as_echo "$hardcode_action" >&6; } if test "$hardcode_action" = relink || test "$inherit_rpath" = yes; then # Fast installation is not supported enable_fast_install=no elif test "$shlibpath_overrides_runpath" = yes || test "$enable_shared" = no; then # Fast installation is not necessary enable_fast_install=needless fi if test "x$enable_dlopen" != xyes; then enable_dlopen=unknown enable_dlopen_self=unknown enable_dlopen_self_static=unknown else lt_cv_dlopen=no lt_cv_dlopen_libs= case $host_os in beos*) lt_cv_dlopen="load_add_on" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ;; mingw* | pw32* | cegcc*) lt_cv_dlopen="LoadLibrary" lt_cv_dlopen_libs= ;; cygwin*) lt_cv_dlopen="dlopen" lt_cv_dlopen_libs= ;; darwin*) # if libdl is installed we need to link against it { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 $as_echo_n "checking for dlopen in -ldl... " >&6; } if ${ac_cv_lib_dl_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dl_dlopen=yes else ac_cv_lib_dl_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 $as_echo "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes; then : lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" else lt_cv_dlopen="dyld" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes fi ;; *) ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load" if test "x$ac_cv_func_shl_load" = xyes; then : lt_cv_dlopen="shl_load" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5 $as_echo_n "checking for shl_load in -ldld... " >&6; } if ${ac_cv_lib_dld_shl_load+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char shl_load (); int main () { return shl_load (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dld_shl_load=yes else ac_cv_lib_dld_shl_load=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5 $as_echo "$ac_cv_lib_dld_shl_load" >&6; } if test "x$ac_cv_lib_dld_shl_load" = xyes; then : lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld" else ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen" if test "x$ac_cv_func_dlopen" = xyes; then : lt_cv_dlopen="dlopen" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 $as_echo_n "checking for dlopen in -ldl... " >&6; } if ${ac_cv_lib_dl_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dl_dlopen=yes else ac_cv_lib_dl_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 $as_echo "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes; then : lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5 $as_echo_n "checking for dlopen in -lsvld... " >&6; } if ${ac_cv_lib_svld_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lsvld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_svld_dlopen=yes else ac_cv_lib_svld_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5 $as_echo "$ac_cv_lib_svld_dlopen" >&6; } if test "x$ac_cv_lib_svld_dlopen" = xyes; then : lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5 $as_echo_n "checking for dld_link in -ldld... " >&6; } if ${ac_cv_lib_dld_dld_link+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dld_link (); int main () { return dld_link (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dld_dld_link=yes else ac_cv_lib_dld_dld_link=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5 $as_echo "$ac_cv_lib_dld_dld_link" >&6; } if test "x$ac_cv_lib_dld_dld_link" = xyes; then : lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld" fi fi fi fi fi fi ;; esac if test "x$lt_cv_dlopen" != xno; then enable_dlopen=yes else enable_dlopen=no fi case $lt_cv_dlopen in dlopen) save_CPPFLAGS="$CPPFLAGS" test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" save_LDFLAGS="$LDFLAGS" wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" save_LIBS="$LIBS" LIBS="$lt_cv_dlopen_libs $LIBS" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program can dlopen itself" >&5 $as_echo_n "checking whether a program can dlopen itself... " >&6; } if ${lt_cv_dlopen_self+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : lt_cv_dlopen_self=cross else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF #line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisbility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; } _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then (./conftest; exit; ) >&5 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;; x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;; x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;; esac else : # compilation failed lt_cv_dlopen_self=no fi fi rm -fr conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5 $as_echo "$lt_cv_dlopen_self" >&6; } if test "x$lt_cv_dlopen_self" = xyes; then wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a statically linked program can dlopen itself" >&5 $as_echo_n "checking whether a statically linked program can dlopen itself... " >&6; } if ${lt_cv_dlopen_self_static+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : lt_cv_dlopen_self_static=cross else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF #line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisbility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; } _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then (./conftest; exit; ) >&5 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;; x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;; x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;; esac else : # compilation failed lt_cv_dlopen_self_static=no fi fi rm -fr conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self_static" >&5 $as_echo "$lt_cv_dlopen_self_static" >&6; } fi CPPFLAGS="$save_CPPFLAGS" LDFLAGS="$save_LDFLAGS" LIBS="$save_LIBS" ;; esac case $lt_cv_dlopen_self in yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; *) enable_dlopen_self=unknown ;; esac case $lt_cv_dlopen_self_static in yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; *) enable_dlopen_self_static=unknown ;; esac fi striplib= old_striplib= { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stripping libraries is possible" >&5 $as_echo_n "checking whether stripping libraries is possible... " >&6; } if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" test -z "$striplib" && striplib="$STRIP --strip-unneeded" { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else # FIXME - insert some real tests, host_os isn't really good enough case $host_os in darwin*) if test -n "$STRIP" ; then striplib="$STRIP -x" old_striplib="$STRIP -S" { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi ;; *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } ;; esac fi # Report which library types will actually be built { $as_echo "$as_me:${as_lineno-$LINENO}: checking if libtool supports shared libraries" >&5 $as_echo_n "checking if libtool supports shared libraries... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $can_build_shared" >&5 $as_echo "$can_build_shared" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries" >&5 $as_echo_n "checking whether to build shared libraries... " >&6; } test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[4-9]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5 $as_echo "$enable_shared" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries" >&5 $as_echo_n "checking whether to build static libraries... " >&6; } # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_static" >&5 $as_echo "$enable_static" >&6; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CC="$lt_save_CC" ac_config_commands="$ac_config_commands libtool" # Only expand once: { $as_echo "$as_me:${as_lineno-$LINENO}: checking for automake version >= 1.11" >&5 $as_echo_n "checking for automake version >= 1.11... " >&6; } sf_am_version=`automake --version | head -n 1 | awk '/^automake/ {print $NF}'` # Used to indicate true or false condition ax_compare_version=false # Convert the two version strings to be compared into a format that # allows a simple string comparison. The end result is that a version # string of the form 1.12.5-r617 will be converted to the form # 0001001200050617. In other words, each number is zero padded to four # digits, and non digits are removed. ax_compare_version_A=`echo "1.11" | sed -e 's/\([0-9]*\)/Z\1Z/g' \ -e 's/Z\([0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/[^0-9]//g'` ax_compare_version_B=`echo "$sf_am_version" | sed -e 's/\([0-9]*\)/Z\1Z/g' \ -e 's/Z\([0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/[^0-9]//g'` ax_compare_version=`echo "x$ax_compare_version_A x$ax_compare_version_B" | sed 's/^ *//' | sort | sed "s/x${ax_compare_version_A}/true/;s/x${ax_compare_version_B}/false/;1q"` if test "$ax_compare_version" = "true" ; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $sf_am_version is ok" >&5 $as_echo "$sf_am_version is ok" >&6; } else as_fn_error $? "found $sf_am_version - you must upgrade automake " "$LINENO" 5 fi #CHECK_AUTOCONF # Configure pkg-config if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_PKG_CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else case $PKG_CONFIG in [\\/]* | ?:[\\/]*) ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi PKG_CONFIG=$ac_cv_path_PKG_CONFIG if test -n "$PKG_CONFIG"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PKG_CONFIG" >&5 $as_echo "$PKG_CONFIG" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_path_PKG_CONFIG"; then ac_pt_PKG_CONFIG=$PKG_CONFIG # Extract the first word of "pkg-config", so it can be a program name with args. set dummy pkg-config; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_ac_pt_PKG_CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else case $ac_pt_PKG_CONFIG in [\\/]* | ?:[\\/]*) ac_cv_path_ac_pt_PKG_CONFIG="$ac_pt_PKG_CONFIG" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_ac_pt_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi ac_pt_PKG_CONFIG=$ac_cv_path_ac_pt_PKG_CONFIG if test -n "$ac_pt_PKG_CONFIG"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKG_CONFIG" >&5 $as_echo "$ac_pt_PKG_CONFIG" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_pt_PKG_CONFIG" = x; then PKG_CONFIG="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac PKG_CONFIG=$ac_pt_PKG_CONFIG fi else PKG_CONFIG="$ac_cv_path_PKG_CONFIG" fi fi if test -n "$PKG_CONFIG"; then _pkg_min_version=0.9.0 { $as_echo "$as_me:${as_lineno-$LINENO}: checking pkg-config is at least version $_pkg_min_version" >&5 $as_echo_n "checking pkg-config is at least version $_pkg_min_version... " >&6; } if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } PKG_CONFIG="" fi fi ac_config_headers="$ac_config_headers config.h" # Codec plugin loading uses dlopen, so we need to check for it here. enable_dlopen=yes # Checks for programs. ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu if test -z "$CXX"; then if test -n "$CCC"; then CXX=$CCC else if test -n "$ac_tool_prefix"; then for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CXX+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CXX"; then ac_cv_prog_CXX="$CXX" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CXX="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CXX=$ac_cv_prog_CXX if test -n "$CXX"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 $as_echo "$CXX" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CXX" && break done fi if test -z "$CXX"; then ac_ct_CXX=$CXX for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CXX+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CXX"; then ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CXX="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CXX=$ac_cv_prog_ac_ct_CXX if test -n "$ac_ct_CXX"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CXX" >&5 $as_echo "$ac_ct_CXX" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CXX" && break done if test "x$ac_ct_CXX" = x; then CXX="g++" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CXX=$ac_ct_CXX fi fi fi fi # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C++ compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C++ compiler" >&5 $as_echo_n "checking whether we are using the GNU C++ compiler... " >&6; } if ${ac_cv_cxx_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_cxx_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cxx_compiler_gnu" >&5 $as_echo "$ac_cv_cxx_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GXX=yes else GXX= fi ac_test_CXXFLAGS=${CXXFLAGS+set} ac_save_CXXFLAGS=$CXXFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX accepts -g" >&5 $as_echo_n "checking whether $CXX accepts -g... " >&6; } if ${ac_cv_prog_cxx_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_cxx_werror_flag=$ac_cxx_werror_flag ac_cxx_werror_flag=yes ac_cv_prog_cxx_g=no CXXFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_cv_prog_cxx_g=yes else CXXFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : else ac_cxx_werror_flag=$ac_save_cxx_werror_flag CXXFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_cv_prog_cxx_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cxx_werror_flag=$ac_save_cxx_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cxx_g" >&5 $as_echo "$ac_cv_prog_cxx_g" >&6; } if test "$ac_test_CXXFLAGS" = set; then CXXFLAGS=$ac_save_CXXFLAGS elif test $ac_cv_prog_cxx_g = yes; then if test "$GXX" = yes; then CXXFLAGS="-g -O2" else CXXFLAGS="-g" fi else if test "$GXX" = yes; then CXXFLAGS="-O2" else CXXFLAGS= fi fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu depcc="$CXX" am_compiler_list= { $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 $as_echo_n "checking dependency style of $depcc... " >&6; } if ${am_cv_CXX_dependencies_compiler_type+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named `D' -- because `-MD' means `put the output # in D'. rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_CXX_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` fi am__universal=false case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with # Solaris 8's {/usr,}/bin/sh. touch sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with `-c' and `-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle `-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # after this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok `-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_CXX_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_CXX_dependencies_compiler_type=none fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_CXX_dependencies_compiler_type" >&5 $as_echo "$am_cv_CXX_dependencies_compiler_type" >&6; } CXXDEPMODE=depmode=$am_cv_CXX_dependencies_compiler_type if test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CXX_dependencies_compiler_type" = gcc3; then am__fastdepCXX_TRUE= am__fastdepCXX_FALSE='#' else am__fastdepCXX_TRUE='#' am__fastdepCXX_FALSE= fi func_stripname_cnf () { case ${2} in .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;; *) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;; esac } # func_stripname_cnf if test -n "$CXX" && ( test "X$CXX" != "Xno" && ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) || (test "X$CXX" != "Xg++"))) ; then ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C++ preprocessor" >&5 $as_echo_n "checking how to run the C++ preprocessor... " >&6; } if test -z "$CXXCPP"; then if ${ac_cv_prog_CXXCPP+:} false; then : $as_echo_n "(cached) " >&6 else # Double quotes because CXXCPP needs to be expanded for CXXCPP in "$CXX -E" "/lib/cpp" do ac_preproc_ok=false for ac_cxx_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : break fi done ac_cv_prog_CXXCPP=$CXXCPP fi CXXCPP=$ac_cv_prog_CXXCPP else ac_cv_prog_CXXCPP=$CXXCPP fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXXCPP" >&5 $as_echo "$CXXCPP" >&6; } ac_preproc_ok=false for ac_cxx_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C++ preprocessor \"$CXXCPP\" fails sanity check See \`config.log' for more details" "$LINENO" 5; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu else _lt_caught_CXX_error=yes fi ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu archive_cmds_need_lc_CXX=no allow_undefined_flag_CXX= always_export_symbols_CXX=no archive_expsym_cmds_CXX= compiler_needs_object_CXX=no export_dynamic_flag_spec_CXX= hardcode_direct_CXX=no hardcode_direct_absolute_CXX=no hardcode_libdir_flag_spec_CXX= hardcode_libdir_separator_CXX= hardcode_minus_L_CXX=no hardcode_shlibpath_var_CXX=unsupported hardcode_automatic_CXX=no inherit_rpath_CXX=no module_cmds_CXX= module_expsym_cmds_CXX= link_all_deplibs_CXX=unknown old_archive_cmds_CXX=$old_archive_cmds reload_flag_CXX=$reload_flag reload_cmds_CXX=$reload_cmds no_undefined_flag_CXX= whole_archive_flag_spec_CXX= enable_shared_with_static_runtimes_CXX=no # Source file extension for C++ test sources. ac_ext=cpp # Object file extension for compiled C++ test sources. objext=o objext_CXX=$objext # No sense in running all these tests if we already determined that # the CXX compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test "$_lt_caught_CXX_error" != yes; then # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(int, char *[]) { return(0); }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # save warnings/boilerplate of simple test code ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" >conftest.$ac_ext eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_compiler_boilerplate=`cat conftest.err` $RM conftest* ac_outfile=conftest.$ac_objext echo "$lt_simple_link_test_code" >conftest.$ac_ext eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_LD=$LD lt_save_GCC=$GCC GCC=$GXX lt_save_with_gnu_ld=$with_gnu_ld lt_save_path_LD=$lt_cv_path_LD if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx else $as_unset lt_cv_prog_gnu_ld fi if test -n "${lt_cv_path_LDCXX+set}"; then lt_cv_path_LD=$lt_cv_path_LDCXX else $as_unset lt_cv_path_LD fi test -z "${LDCXX+set}" || LD=$LDCXX CC=${CXX-"c++"} CFLAGS=$CXXFLAGS compiler=$CC compiler_CXX=$CC for cc_temp in $compiler""; do case $cc_temp in compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; \-*) ;; *) break;; esac done cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` if test -n "$compiler"; then # We don't want -fno-exception when compiling C++ code, so set the # no_builtin_flag separately if test "$GXX" = yes; then lt_prog_compiler_no_builtin_flag_CXX=' -fno-builtin' else lt_prog_compiler_no_builtin_flag_CXX= fi if test "$GXX" = yes; then # Set up default GNU C++ configuration # Check whether --with-gnu-ld was given. if test "${with_gnu_ld+set}" = set; then : withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes else with_gnu_ld=no fi ac_prog=ld if test "$GCC" = yes; then # Check if gcc -print-prog-name=ld gives a path. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 $as_echo_n "checking for ld used by $CC... " >&6; } case $host in *-*-mingw*) # gcc leaves a trailing carriage return which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [\\/]* | ?:[\\/]*) re_direlt='/[^/][^/]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD="$ac_prog" ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test "$with_gnu_ld" = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 $as_echo_n "checking for GNU ld... " >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5 $as_echo_n "checking for non-GNU ld... " >&6; } fi if ${lt_cv_path_LD+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$LD"; then lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD="$ac_dir/$ac_prog" # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &5 $as_echo "$LD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5 $as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; } if ${lt_cv_prog_gnu_ld+:} false; then : $as_echo_n "(cached) " >&6 else # I'd rather use --version here, but apparently some GNU lds only accept -v. case `$LD -v 2>&1 &5 $as_echo "$lt_cv_prog_gnu_ld" >&6; } with_gnu_ld=$lt_cv_prog_gnu_ld # Check if GNU C++ uses GNU ld as the underlying linker, since the # archiving commands below assume that GNU ld is being used. if test "$with_gnu_ld" = yes; then archive_cmds_CXX='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds_CXX='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' export_dynamic_flag_spec_CXX='${wl}--export-dynamic' # If archive_cmds runs LD, not CC, wlarc should be empty # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to # investigate it a little bit more. (MM) wlarc='${wl}' # ancient GNU ld didn't support --whole-archive et. al. if eval "`$CC -print-prog-name=ld` --help 2>&1" | $GREP 'no-whole-archive' > /dev/null; then whole_archive_flag_spec_CXX="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' else whole_archive_flag_spec_CXX= fi else with_gnu_ld=no wlarc= # A generic and very simple default shared library creation # command for GNU C++ for the case where it uses the native # linker, instead of GNU ld. If possible, this setting should # overridden to take advantage of the native linker features on # the platform it is being used on. archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' fi # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else GXX=no with_gnu_ld=no wlarc= fi # PORTME: fill in a description of your system's C++ link characteristics { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 $as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } ld_shlibs_CXX=yes case $host_os in aix3*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; aix[4-9]*) if test "$host_cpu" = ia64; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag="" else aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # need to do runtime linking. case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*) for ld_flag in $LDFLAGS; do case $ld_flag in *-brtl*) aix_use_runtimelinking=yes break ;; esac done ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. archive_cmds_CXX='' hardcode_direct_CXX=yes hardcode_direct_absolute_CXX=yes hardcode_libdir_separator_CXX=':' link_all_deplibs_CXX=yes file_list_spec_CXX='${wl}-f,' if test "$GXX" = yes; then case $host_os in aix4.[012]|aix4.[012].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`${CC} -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 hardcode_direct_CXX=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking hardcode_minus_L_CXX=yes hardcode_libdir_flag_spec_CXX='-L$libdir' hardcode_libdir_separator_CXX= fi esac shared_flag='-shared' if test "$aix_use_runtimelinking" = yes; then shared_flag="$shared_flag "'${wl}-G' fi else # not using gcc if test "$host_cpu" = ia64; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test "$aix_use_runtimelinking" = yes; then shared_flag='${wl}-G' else shared_flag='${wl}-bM:SRE' fi fi fi export_dynamic_flag_spec_CXX='${wl}-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to # export. always_export_symbols_CXX=yes if test "$aix_use_runtimelinking" = yes; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. allow_undefined_flag_CXX='-berok' # Determine the default libpath from the value encoded in an empty # executable. if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath__CXX+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath__CXX=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath__CXX"; then lt_cv_aix_libpath__CXX=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath__CXX"; then lt_cv_aix_libpath__CXX="/usr/lib:/lib" fi fi aix_libpath=$lt_cv_aix_libpath__CXX fi hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath" archive_expsym_cmds_CXX='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" else if test "$host_cpu" = ia64; then hardcode_libdir_flag_spec_CXX='${wl}-R $libdir:/usr/lib:/lib' allow_undefined_flag_CXX="-z nodefs" archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath__CXX+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath__CXX=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath__CXX"; then lt_cv_aix_libpath__CXX=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath__CXX"; then lt_cv_aix_libpath__CXX="/usr/lib:/lib" fi fi aix_libpath=$lt_cv_aix_libpath__CXX fi hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. no_undefined_flag_CXX=' ${wl}-bernotok' allow_undefined_flag_CXX=' ${wl}-berok' if test "$with_gnu_ld" = yes; then # We only use this code for GNU lds that support --whole-archive. whole_archive_flag_spec_CXX='${wl}--whole-archive$convenience ${wl}--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives whole_archive_flag_spec_CXX='$convenience' fi archive_cmds_need_lc_CXX=yes # This is similar to how AIX traditionally builds its shared # libraries. archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' fi fi ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then allow_undefined_flag_CXX=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME archive_cmds_CXX='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' else ld_shlibs_CXX=no fi ;; chorus*) case $cc_basename in *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac ;; cygwin* | mingw* | pw32* | cegcc*) case $GXX,$cc_basename in ,cl* | no,cl*) # Native MSVC # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. hardcode_libdir_flag_spec_CXX=' ' allow_undefined_flag_CXX=unsupported always_export_symbols_CXX=yes file_list_spec_CXX='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. archive_cmds_CXX='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' archive_expsym_cmds_CXX='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then $SED -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; else $SED -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, CXX)='true' enable_shared_with_static_runtimes_CXX=yes # Don't use ranlib old_postinstall_cmds_CXX='chmod 644 $oldlib' postlink_cmds_CXX='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile="$lt_outputfile.exe" lt_tool_outputfile="$lt_tool_outputfile.exe" ;; esac~ func_to_tool_file "$lt_outputfile"~ if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # g++ # _LT_TAGVAR(hardcode_libdir_flag_spec, CXX) is actually meaningless, # as there is no search path for DLLs. hardcode_libdir_flag_spec_CXX='-L$libdir' export_dynamic_flag_spec_CXX='${wl}--export-all-symbols' allow_undefined_flag_CXX=unsupported always_export_symbols_CXX=no enable_shared_with_static_runtimes_CXX=yes if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file (1st line # is EXPORTS), use it as is; otherwise, prepend... archive_expsym_cmds_CXX='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else ld_shlibs_CXX=no fi ;; esac ;; darwin* | rhapsody*) archive_cmds_need_lc_CXX=no hardcode_direct_CXX=no hardcode_automatic_CXX=yes hardcode_shlibpath_var_CXX=unsupported if test "$lt_cv_ld_force_load" = "yes"; then whole_archive_flag_spec_CXX='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' else whole_archive_flag_spec_CXX='' fi link_all_deplibs_CXX=yes allow_undefined_flag_CXX="$_lt_dar_allow_undefined" case $cc_basename in ifort*) _lt_dar_can_shared=yes ;; *) _lt_dar_can_shared=$GCC ;; esac if test "$_lt_dar_can_shared" = "yes"; then output_verbose_link_cmd=func_echo_all archive_cmds_CXX="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" module_cmds_CXX="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" archive_expsym_cmds_CXX="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" module_expsym_cmds_CXX="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" if test "$lt_cv_apple_cc_single_mod" != "yes"; then archive_cmds_CXX="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}" archive_expsym_cmds_CXX="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}" fi else ld_shlibs_CXX=no fi ;; dgux*) case $cc_basename in ec++*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; ghcx*) # Green Hills C++ Compiler # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac ;; freebsd2.*) # C++ shared libraries reported to be fairly broken before # switch to ELF ld_shlibs_CXX=no ;; freebsd-elf*) archive_cmds_need_lc_CXX=no ;; freebsd* | dragonfly*) # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF # conventions ld_shlibs_CXX=yes ;; haiku*) archive_cmds_CXX='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' link_all_deplibs_CXX=yes ;; hpux9*) hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir' hardcode_libdir_separator_CXX=: export_dynamic_flag_spec_CXX='${wl}-E' hardcode_direct_CXX=yes hardcode_minus_L_CXX=yes # Not in the search PATH, # but as the default # location of the library. case $cc_basename in CC*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; aCC*) archive_cmds_CXX='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes; then archive_cmds_CXX='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' else # FIXME: insert proper C++ library support ld_shlibs_CXX=no fi ;; esac ;; hpux10*|hpux11*) if test $with_gnu_ld = no; then hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir' hardcode_libdir_separator_CXX=: case $host_cpu in hppa*64*|ia64*) ;; *) export_dynamic_flag_spec_CXX='${wl}-E' ;; esac fi case $host_cpu in hppa*64*|ia64*) hardcode_direct_CXX=no hardcode_shlibpath_var_CXX=no ;; *) hardcode_direct_CXX=yes hardcode_direct_absolute_CXX=yes hardcode_minus_L_CXX=yes # Not in the search PATH, # but as the default # location of the library. ;; esac case $cc_basename in CC*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; aCC*) case $host_cpu in hppa*64*) archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes; then if test $with_gnu_ld = no; then case $host_cpu in hppa*64*) archive_cmds_CXX='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) archive_cmds_CXX='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) archive_cmds_CXX='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac fi else # FIXME: insert proper C++ library support ld_shlibs_CXX=no fi ;; esac ;; interix[3-9]*) hardcode_direct_CXX=no hardcode_shlibpath_var_CXX=no hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' export_dynamic_flag_spec_CXX='${wl}-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. archive_cmds_CXX='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' archive_expsym_cmds_CXX='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; irix5* | irix6*) case $cc_basename in CC*) # SGI C++ archive_cmds_CXX='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' # Archives containing C++ object files must be created using # "CC -ar", where "CC" is the IRIX C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. old_archive_cmds_CXX='$CC -ar -WR,-u -o $oldlib $oldobjs' ;; *) if test "$GXX" = yes; then if test "$with_gnu_ld" = no; then archive_cmds_CXX='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' else archive_cmds_CXX='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` -o $lib' fi fi link_all_deplibs_CXX=yes ;; esac hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator_CXX=: inherit_rpath_CXX=yes ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' archive_expsym_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' export_dynamic_flag_spec_CXX='${wl}--export-dynamic' # Archives containing C++ object files must be created using # "CC -Bstatic", where "CC" is the KAI C++ compiler. old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs' ;; icpc* | ecpc* ) # Intel C++ with_gnu_ld=yes # version 8.0 and above of icpc choke on multiply defined symbols # if we add $predep_objects and $postdep_objects, however 7.1 and # earlier do not add the objects themselves. case `$CC -V 2>&1` in *"Version 7."*) archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' ;; *) # Version 8.0 or newer tmp_idyn= case $host_cpu in ia64*) tmp_idyn=' -i_dynamic';; esac archive_cmds_CXX='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds_CXX='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' ;; esac archive_cmds_need_lc_CXX=no hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' export_dynamic_flag_spec_CXX='${wl}--export-dynamic' whole_archive_flag_spec_CXX='${wl}--whole-archive$convenience ${wl}--no-whole-archive' ;; pgCC* | pgcpp*) # Portland Group C++ compiler case `$CC -V` in *pgCC\ [1-5].* | *pgcpp\ [1-5].*) prelink_cmds_CXX='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~ compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"' old_archive_cmds_CXX='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~ $AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~ $RANLIB $oldlib' archive_cmds_CXX='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' archive_expsym_cmds_CXX='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' ;; *) # Version 6 and above use weak symbols archive_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' archive_expsym_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' ;; esac hardcode_libdir_flag_spec_CXX='${wl}--rpath ${wl}$libdir' export_dynamic_flag_spec_CXX='${wl}--export-dynamic' whole_archive_flag_spec_CXX='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' ;; cxx*) # Compaq C++ archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols' runpath_var=LD_RUN_PATH hardcode_libdir_flag_spec_CXX='-rpath $libdir' hardcode_libdir_separator_CXX=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed' ;; xl* | mpixl* | bgxl*) # IBM XL 8.0 on PPC, with GNU ld hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' export_dynamic_flag_spec_CXX='${wl}--export-dynamic' archive_cmds_CXX='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' if test "x$supports_anon_versioning" = xyes; then archive_expsym_cmds_CXX='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' fi ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 no_undefined_flag_CXX=' -zdefs' archive_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' archive_expsym_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols' hardcode_libdir_flag_spec_CXX='-R$libdir' whole_archive_flag_spec_CXX='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' compiler_needs_object_CXX=yes # Not sure whether something based on # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 # would be better. output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. old_archive_cmds_CXX='$CC -xar -o $oldlib $oldobjs' ;; esac ;; esac ;; lynxos*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; m88k*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; mvs*) case $cc_basename in cxx*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds_CXX='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' wlarc= hardcode_libdir_flag_spec_CXX='-R$libdir' hardcode_direct_CXX=yes hardcode_shlibpath_var_CXX=no fi # Workaround some broken pre-1.5 toolchains output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' ;; *nto* | *qnx*) ld_shlibs_CXX=yes ;; openbsd2*) # C++ shared libraries are fairly broken ld_shlibs_CXX=no ;; openbsd*) if test -f /usr/libexec/ld.so; then hardcode_direct_CXX=yes hardcode_shlibpath_var_CXX=no hardcode_direct_absolute_CXX=yes archive_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then archive_expsym_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib' export_dynamic_flag_spec_CXX='${wl}-E' whole_archive_flag_spec_CXX="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' fi output_verbose_link_cmd=func_echo_all else ld_shlibs_CXX=no fi ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' hardcode_libdir_separator_CXX=: # Archives containing C++ object files must be created using # the KAI C++ compiler. case $host in osf3*) old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs' ;; *) old_archive_cmds_CXX='$CC -o $oldlib $oldobjs' ;; esac ;; RCC*) # Rational C++ 2.4.1 # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; cxx*) case $host in osf3*) allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*' archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && func_echo_all "${wl}-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' ;; *) allow_undefined_flag_CXX=' -expect_unresolved \*' archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' archive_expsym_cmds_CXX='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ echo "-hidden">> $lib.exp~ $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~ $RM $lib.exp' hardcode_libdir_flag_spec_CXX='-rpath $libdir' ;; esac hardcode_libdir_separator_CXX=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes && test "$with_gnu_ld" = no; then allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*' case $host in osf3*) archive_cmds_CXX='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' ;; *) archive_cmds_CXX='$CC -shared $pic_flag -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' ;; esac hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator_CXX=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # FIXME: insert proper C++ library support ld_shlibs_CXX=no fi ;; esac ;; psos*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; lcc*) # Lucid # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ archive_cmds_need_lc_CXX=yes no_undefined_flag_CXX=' -zdefs' archive_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' archive_expsym_cmds_CXX='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' hardcode_libdir_flag_spec_CXX='-R$libdir' hardcode_shlibpath_var_CXX=no case $host_os in solaris2.[0-5] | solaris2.[0-5].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands `-z linker_flag'. # Supported since Solaris 2.6 (maybe 2.5.1?) whole_archive_flag_spec_CXX='-z allextract$convenience -z defaultextract' ;; esac link_all_deplibs_CXX=yes output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. old_archive_cmds_CXX='$CC -xar -o $oldlib $oldobjs' ;; gcx*) # Green Hills C++ Compiler archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' # The C++ compiler must be used to create the archive. old_archive_cmds_CXX='$CC $LDFLAGS -archive -o $oldlib $oldobjs' ;; *) # GNU C++ compiler with Solaris linker if test "$GXX" = yes && test "$with_gnu_ld" = no; then no_undefined_flag_CXX=' ${wl}-z ${wl}defs' if $CC --version | $GREP -v '^2\.7' > /dev/null; then archive_cmds_CXX='$CC -shared $pic_flag -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' archive_expsym_cmds_CXX='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # g++ 2.7 appears to require `-G' NOT `-shared' on this # platform. archive_cmds_CXX='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' archive_expsym_cmds_CXX='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' fi hardcode_libdir_flag_spec_CXX='${wl}-R $wl$libdir' case $host_os in solaris2.[0-5] | solaris2.[0-5].*) ;; *) whole_archive_flag_spec_CXX='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' ;; esac fi ;; esac ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) no_undefined_flag_CXX='${wl}-z,text' archive_cmds_need_lc_CXX=no hardcode_shlibpath_var_CXX=no runpath_var='LD_RUN_PATH' case $cc_basename in CC*) archive_cmds_CXX='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds_CXX='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; *) archive_cmds_CXX='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds_CXX='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We can NOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. no_undefined_flag_CXX='${wl}-z,text' allow_undefined_flag_CXX='${wl}-z,nodefs' archive_cmds_need_lc_CXX=no hardcode_shlibpath_var_CXX=no hardcode_libdir_flag_spec_CXX='${wl}-R,$libdir' hardcode_libdir_separator_CXX=':' link_all_deplibs_CXX=yes export_dynamic_flag_spec_CXX='${wl}-Bexport' runpath_var='LD_RUN_PATH' case $cc_basename in CC*) archive_cmds_CXX='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds_CXX='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' old_archive_cmds_CXX='$CC -Tprelink_objects $oldobjs~ '"$old_archive_cmds_CXX" reload_cmds_CXX='$CC -Tprelink_objects $reload_objs~ '"$reload_cmds_CXX" ;; *) archive_cmds_CXX='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds_CXX='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac ;; vxworks*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs_CXX" >&5 $as_echo "$ld_shlibs_CXX" >&6; } test "$ld_shlibs_CXX" = no && can_build_shared=no GCC_CXX="$GXX" LD_CXX="$LD" ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... # Dependencies to place before and after the object being linked: predep_objects_CXX= postdep_objects_CXX= predeps_CXX= postdeps_CXX= compiler_lib_search_path_CXX= cat > conftest.$ac_ext <<_LT_EOF class Foo { public: Foo (void) { a = 0; } private: int a; }; _LT_EOF _lt_libdeps_save_CFLAGS=$CFLAGS case "$CC $CFLAGS " in #( *\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;; *\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;; *\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;; esac if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then # Parse the compiler output and extract the necessary # objects, libraries and library flags. # Sentinel used to keep track of whether or not we are before # the conftest object file. pre_test_object_deps_done=no for p in `eval "$output_verbose_link_cmd"`; do case ${prev}${p} in -L* | -R* | -l*) # Some compilers place space between "-{L,R}" and the path. # Remove the space. if test $p = "-L" || test $p = "-R"; then prev=$p continue fi # Expand the sysroot to ease extracting the directories later. if test -z "$prev"; then case $p in -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;; -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;; -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;; esac fi case $p in =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;; esac if test "$pre_test_object_deps_done" = no; then case ${prev} in -L | -R) # Internal compiler library paths should come after those # provided the user. The postdeps already come after the # user supplied libs so there is no need to process them. if test -z "$compiler_lib_search_path_CXX"; then compiler_lib_search_path_CXX="${prev}${p}" else compiler_lib_search_path_CXX="${compiler_lib_search_path_CXX} ${prev}${p}" fi ;; # The "-l" case would never come before the object being # linked, so don't bother handling this case. esac else if test -z "$postdeps_CXX"; then postdeps_CXX="${prev}${p}" else postdeps_CXX="${postdeps_CXX} ${prev}${p}" fi fi prev= ;; *.lto.$objext) ;; # Ignore GCC LTO objects *.$objext) # This assumes that the test object file only shows up # once in the compiler output. if test "$p" = "conftest.$objext"; then pre_test_object_deps_done=yes continue fi if test "$pre_test_object_deps_done" = no; then if test -z "$predep_objects_CXX"; then predep_objects_CXX="$p" else predep_objects_CXX="$predep_objects_CXX $p" fi else if test -z "$postdep_objects_CXX"; then postdep_objects_CXX="$p" else postdep_objects_CXX="$postdep_objects_CXX $p" fi fi ;; *) ;; # Ignore the rest. esac done # Clean up. rm -f a.out a.exe else echo "libtool.m4: error: problem compiling CXX test program" fi $RM -f confest.$objext CFLAGS=$_lt_libdeps_save_CFLAGS # PORTME: override above test on systems where it is broken case $host_os in interix[3-9]*) # Interix 3.5 installs completely hosed .la files for C++, so rather than # hack all around it, let's just trust "g++" to DTRT. predep_objects_CXX= postdep_objects_CXX= postdeps_CXX= ;; linux*) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 # The more standards-conforming stlport4 library is # incompatible with the Cstd library. Avoid specifying # it if it's in CXXFLAGS. Ignore libCrun as # -library=stlport4 depends on it. case " $CXX $CXXFLAGS " in *" -library=stlport4 "*) solaris_use_stlport4=yes ;; esac if test "$solaris_use_stlport4" != yes; then postdeps_CXX='-library=Cstd -library=Crun' fi ;; esac ;; solaris*) case $cc_basename in CC* | sunCC*) # The more standards-conforming stlport4 library is # incompatible with the Cstd library. Avoid specifying # it if it's in CXXFLAGS. Ignore libCrun as # -library=stlport4 depends on it. case " $CXX $CXXFLAGS " in *" -library=stlport4 "*) solaris_use_stlport4=yes ;; esac # Adding this requires a known-good setup of shared libraries for # Sun compiler versions before 5.6, else PIC objects from an old # archive will be linked into the output, leading to subtle bugs. if test "$solaris_use_stlport4" != yes; then postdeps_CXX='-library=Cstd -library=Crun' fi ;; esac ;; esac case " $postdeps_CXX " in *" -lc "*) archive_cmds_need_lc_CXX=no ;; esac compiler_lib_search_dirs_CXX= if test -n "${compiler_lib_search_path_CXX}"; then compiler_lib_search_dirs_CXX=`echo " ${compiler_lib_search_path_CXX}" | ${SED} -e 's! -L! !g' -e 's!^ !!'` fi lt_prog_compiler_wl_CXX= lt_prog_compiler_pic_CXX= lt_prog_compiler_static_CXX= # C++ specific cases for pic, static, wl, etc. if test "$GXX" = yes; then lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_static_CXX='-static' case $host_os in aix*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor lt_prog_compiler_static_CXX='-Bstatic' fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support lt_prog_compiler_pic_CXX='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the `-m68020' flag to GCC prevents building anything better, # like `-m68040'. lt_prog_compiler_pic_CXX='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries lt_prog_compiler_pic_CXX='-DDLL_EXPORT' ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files lt_prog_compiler_pic_CXX='-fno-common' ;; *djgpp*) # DJGPP does not support shared libraries at all lt_prog_compiler_pic_CXX= ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. lt_prog_compiler_static_CXX= ;; interix[3-9]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; sysv4*MP*) if test -d /usr/nec; then lt_prog_compiler_pic_CXX=-Kconform_pic fi ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) ;; *) lt_prog_compiler_pic_CXX='-fPIC' ;; esac ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic_CXX='-fPIC -shared' ;; *) lt_prog_compiler_pic_CXX='-fPIC' ;; esac else case $host_os in aix[4-9]*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor lt_prog_compiler_static_CXX='-Bstatic' else lt_prog_compiler_static_CXX='-bnso -bI:/lib/syscalls.exp' fi ;; chorus*) case $cc_basename in cxch68*) # Green Hills C++ Compiler # _LT_TAGVAR(lt_prog_compiler_static, CXX)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" ;; esac ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). lt_prog_compiler_pic_CXX='-DDLL_EXPORT' ;; dgux*) case $cc_basename in ec++*) lt_prog_compiler_pic_CXX='-KPIC' ;; ghcx*) # Green Hills C++ Compiler lt_prog_compiler_pic_CXX='-pic' ;; *) ;; esac ;; freebsd* | dragonfly*) # FreeBSD uses GNU C++ ;; hpux9* | hpux10* | hpux11*) case $cc_basename in CC*) lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_static_CXX='${wl}-a ${wl}archive' if test "$host_cpu" != ia64; then lt_prog_compiler_pic_CXX='+Z' fi ;; aCC*) lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_static_CXX='${wl}-a ${wl}archive' case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) lt_prog_compiler_pic_CXX='+Z' ;; esac ;; *) ;; esac ;; interix*) # This is c89, which is MS Visual C++ (no shared libs) # Anyone wants to do a port? ;; irix5* | irix6* | nonstopux*) case $cc_basename in CC*) lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_static_CXX='-non_shared' # CC pic flag -KPIC is the default. ;; *) ;; esac ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in KCC*) # KAI C++ Compiler lt_prog_compiler_wl_CXX='--backend -Wl,' lt_prog_compiler_pic_CXX='-fPIC' ;; ecpc* ) # old Intel C++ for x86_64 which still supported -KPIC. lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_pic_CXX='-KPIC' lt_prog_compiler_static_CXX='-static' ;; icpc* ) # Intel C++, used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_pic_CXX='-fPIC' lt_prog_compiler_static_CXX='-static' ;; pgCC* | pgcpp*) # Portland Group C++ compiler lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_pic_CXX='-fpic' lt_prog_compiler_static_CXX='-Bstatic' ;; cxx*) # Compaq C++ # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. lt_prog_compiler_pic_CXX= lt_prog_compiler_static_CXX='-non_shared' ;; xlc* | xlC* | bgxl[cC]* | mpixl[cC]*) # IBM XL 8.0, 9.0 on PPC and BlueGene lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_pic_CXX='-qpic' lt_prog_compiler_static_CXX='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 lt_prog_compiler_pic_CXX='-KPIC' lt_prog_compiler_static_CXX='-Bstatic' lt_prog_compiler_wl_CXX='-Qoption ld ' ;; esac ;; esac ;; lynxos*) ;; m88k*) ;; mvs*) case $cc_basename in cxx*) lt_prog_compiler_pic_CXX='-W c,exportall' ;; *) ;; esac ;; netbsd* | netbsdelf*-gnu) ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic_CXX='-fPIC -shared' ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) lt_prog_compiler_wl_CXX='--backend -Wl,' ;; RCC*) # Rational C++ 2.4.1 lt_prog_compiler_pic_CXX='-pic' ;; cxx*) # Digital/Compaq C++ lt_prog_compiler_wl_CXX='-Wl,' # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. lt_prog_compiler_pic_CXX= lt_prog_compiler_static_CXX='-non_shared' ;; *) ;; esac ;; psos*) ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ lt_prog_compiler_pic_CXX='-KPIC' lt_prog_compiler_static_CXX='-Bstatic' lt_prog_compiler_wl_CXX='-Qoption ld ' ;; gcx*) # Green Hills C++ Compiler lt_prog_compiler_pic_CXX='-PIC' ;; *) ;; esac ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x lt_prog_compiler_pic_CXX='-pic' lt_prog_compiler_static_CXX='-Bstatic' ;; lcc*) # Lucid lt_prog_compiler_pic_CXX='-pic' ;; *) ;; esac ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) case $cc_basename in CC*) lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_pic_CXX='-KPIC' lt_prog_compiler_static_CXX='-Bstatic' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 lt_prog_compiler_pic_CXX='-KPIC' ;; *) ;; esac ;; vxworks*) ;; *) lt_prog_compiler_can_build_shared_CXX=no ;; esac fi case $host_os in # For platforms which do not support PIC, -DPIC is meaningless: *djgpp*) lt_prog_compiler_pic_CXX= ;; *) lt_prog_compiler_pic_CXX="$lt_prog_compiler_pic_CXX -DPIC" ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5 $as_echo_n "checking for $compiler option to produce PIC... " >&6; } if ${lt_cv_prog_compiler_pic_CXX+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic_CXX=$lt_prog_compiler_pic_CXX fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_CXX" >&5 $as_echo "$lt_cv_prog_compiler_pic_CXX" >&6; } lt_prog_compiler_pic_CXX=$lt_cv_prog_compiler_pic_CXX # # Check to make sure the PIC flag actually works. # if test -n "$lt_prog_compiler_pic_CXX"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works" >&5 $as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works... " >&6; } if ${lt_cv_prog_compiler_pic_works_CXX+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic_works_CXX=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$lt_prog_compiler_pic_CXX -DPIC" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_pic_works_CXX=yes fi fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works_CXX" >&5 $as_echo "$lt_cv_prog_compiler_pic_works_CXX" >&6; } if test x"$lt_cv_prog_compiler_pic_works_CXX" = xyes; then case $lt_prog_compiler_pic_CXX in "" | " "*) ;; *) lt_prog_compiler_pic_CXX=" $lt_prog_compiler_pic_CXX" ;; esac else lt_prog_compiler_pic_CXX= lt_prog_compiler_can_build_shared_CXX=no fi fi # # Check to make sure the static flag actually works. # wl=$lt_prog_compiler_wl_CXX eval lt_tmp_static_flag=\"$lt_prog_compiler_static_CXX\" { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5 $as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } if ${lt_cv_prog_compiler_static_works_CXX+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_static_works_CXX=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS $lt_tmp_static_flag" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_static_works_CXX=yes fi else lt_cv_prog_compiler_static_works_CXX=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works_CXX" >&5 $as_echo "$lt_cv_prog_compiler_static_works_CXX" >&6; } if test x"$lt_cv_prog_compiler_static_works_CXX" = xyes; then : else lt_prog_compiler_static_CXX= fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o_CXX+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o_CXX=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o_CXX=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o_CXX" >&5 $as_echo "$lt_cv_prog_compiler_c_o_CXX" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o_CXX+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o_CXX=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o_CXX=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o_CXX" >&5 $as_echo "$lt_cv_prog_compiler_c_o_CXX" >&6; } hard_links="nottested" if test "$lt_cv_prog_compiler_c_o_CXX" = no && test "$need_locks" != no; then # do not overwrite the value of need_locks provided by the user { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5 $as_echo_n "checking if we can lock with hard links... " >&6; } hard_links=yes $RM conftest* ln conftest.a conftest.b 2>/dev/null && hard_links=no touch conftest.a ln conftest.a conftest.b 2>&5 || hard_links=no ln conftest.a conftest.b 2>/dev/null && hard_links=no { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5 $as_echo "$hard_links" >&6; } if test "$hard_links" = no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 $as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} need_locks=warn fi else need_locks=no fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 $as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' exclude_expsyms_CXX='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*' case $host_os in aix[4-9]*) # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to AIX nm, but means don't demangle with GNU nm # Also, AIX nm treats weak defined symbols like other global defined # symbols, whereas GNU nm marks them as "W". if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then export_symbols_cmds_CXX='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' else export_symbols_cmds_CXX='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' fi ;; pw32*) export_symbols_cmds_CXX="$ltdll_cmds" ;; cygwin* | mingw* | cegcc*) case $cc_basename in cl*) exclude_expsyms_CXX='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' ;; *) export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols' exclude_expsyms_CXX='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname' ;; esac ;; linux* | k*bsd*-gnu | gnu*) link_all_deplibs_CXX=no ;; *) export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs_CXX" >&5 $as_echo "$ld_shlibs_CXX" >&6; } test "$ld_shlibs_CXX" = no && can_build_shared=no with_gnu_ld_CXX=$with_gnu_ld # # Do we need to explicitly link libc? # case "x$archive_cmds_need_lc_CXX" in x|xyes) # Assume -lc should be added archive_cmds_need_lc_CXX=yes if test "$enable_shared" = yes && test "$GCC" = yes; then case $archive_cmds_CXX in *'~'*) # FIXME: we may have to deal with multi-command sequences. ;; '$CC '*) # Test whether the compiler implicitly links with -lc since on some # systems, -lgcc has to come before -lc. If gcc already passes -lc # to ld, don't add -lc before -lgcc. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5 $as_echo_n "checking whether -lc should be explicitly linked in... " >&6; } if ${lt_cv_archive_cmds_need_lc_CXX+:} false; then : $as_echo_n "(cached) " >&6 else $RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } 2>conftest.err; then soname=conftest lib=conftest libobjs=conftest.$ac_objext deplibs= wl=$lt_prog_compiler_wl_CXX pic_flag=$lt_prog_compiler_pic_CXX compiler_flags=-v linker_flags=-v verstring= output_objdir=. libname=conftest lt_save_allow_undefined_flag=$allow_undefined_flag_CXX allow_undefined_flag_CXX= if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds_CXX 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5 (eval $archive_cmds_CXX 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } then lt_cv_archive_cmds_need_lc_CXX=no else lt_cv_archive_cmds_need_lc_CXX=yes fi allow_undefined_flag_CXX=$lt_save_allow_undefined_flag else cat conftest.err 1>&5 fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc_CXX" >&5 $as_echo "$lt_cv_archive_cmds_need_lc_CXX" >&6; } archive_cmds_need_lc_CXX=$lt_cv_archive_cmds_need_lc_CXX ;; esac fi ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5 $as_echo_n "checking dynamic linker characteristics... " >&6; } library_names_spec= libname_spec='lib$name' soname_spec= shrext_cmds=".so" postinstall_cmds= postuninstall_cmds= finish_cmds= finish_eval= shlibpath_var= shlibpath_overrides_runpath=unknown version_type=none dynamic_linker="$host_os ld.so" sys_lib_dlsearch_path_spec="/lib /usr/lib" need_lib_prefix=unknown hardcode_into_libs=no # when you set need_version to no, make sure it does not cause -set_version # flags to be left without arguments need_version=unknown case $host_os in aix3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' shlibpath_var=LIBPATH # AIX 3 has no versioning support, so we append a major version to the name. soname_spec='${libname}${release}${shared_ext}$major' ;; aix[4-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no hardcode_into_libs=yes if test "$host_cpu" = ia64; then # AIX 5 supports IA64 library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH else # With GCC up to 2.95.x, collect2 would create an import file # for dependence libraries. The import file would start with # the line `#! .'. This would cause the generated library to # depend on `.', always an invalid library. This was fixed in # development snapshots of GCC prior to 3.0. case $host_os in aix4 | aix4.[01] | aix4.[01].*) if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' echo ' yes ' echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then : else can_build_shared=no fi ;; esac # AIX (on Power*) has no versioning support, so currently we can not hardcode correct # soname into executable. Probably we can add versioning support to # collect2, so additional links can be useful in future. if test "$aix_use_runtimelinking" = yes; then # If using run time linking (on AIX 4.2 or later) use lib.so # instead of lib.a to let people know that these are not # typical AIX shared libraries. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' else # We preserve .a as extension for shared libraries through AIX4.2 # and later when we are not doing run time linking. library_names_spec='${libname}${release}.a $libname.a' soname_spec='${libname}${release}${shared_ext}$major' fi shlibpath_var=LIBPATH fi ;; amigaos*) case $host_cpu in powerpc) # Since July 2007 AmigaOS4 officially supports .so libraries. # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' ;; m68k) library_names_spec='$libname.ixlibrary $libname.a' # Create ${libname}_ixlibrary.a entries in /sys/libs. finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' ;; esac ;; beos*) library_names_spec='${libname}${shared_ext}' dynamic_linker="$host_os ld.so" shlibpath_var=LIBRARY_PATH ;; bsdi[45]*) version_type=linux # correct to gnu/linux during the next big refactor need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" # the default ld.so.conf also contains /usr/contrib/lib and # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow # libtool to hard-code these into programs ;; cygwin* | mingw* | pw32* | cegcc*) version_type=windows shrext_cmds=".dll" need_version=no need_lib_prefix=no case $GCC,$cc_basename in yes,*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes case $host_os in cygwin*) # Cygwin DLLs use 'cyg' prefix rather than 'lib' soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; mingw* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; pw32*) # pw32 DLLs use 'pw' prefix rather than 'lib' library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; esac dynamic_linker='Win32 ld.exe' ;; *,cl*) # Native MSVC libname_spec='$name' soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' library_names_spec='${libname}.dll.lib' case $build_os in mingw*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' for lt_path in $LIB do IFS=$lt_save_ifs # Let DOS variable expansion print the short 8.3 style file name. lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" done IFS=$lt_save_ifs # Convert to MSYS style. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'` ;; cygwin*) # Convert to unix form, then to dos form, then back to unix form # but this time dos style (no spaces!) so that the unix form looks # like /cygdrive/c/PROGRA~1:/cygdr... sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` ;; *) sys_lib_search_path_spec="$LIB" if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then # It is most probably a Windows format PATH. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` else sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` fi # FIXME: find the short name or the path components, as spaces are # common. (e.g. "Program Files" -> "PROGRA~1") ;; esac # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes dynamic_linker='Win32 link.exe' ;; *) # Assume MSVC wrapper library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' dynamic_linker='Win32 ld.exe' ;; esac # FIXME: first we should search . and the directory the executable is in shlibpath_var=PATH ;; darwin* | rhapsody*) dynamic_linker="$host_os dyld" version_type=darwin need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' soname_spec='${libname}${release}${major}$shared_ext' shlibpath_overrides_runpath=yes shlibpath_var=DYLD_LIBRARY_PATH shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' ;; dgux*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; freebsd* | dragonfly*) # DragonFly does not have aout. When/if they implement a new # versioning mechanism, adjust this. if test -x /usr/bin/objformat; then objformat=`/usr/bin/objformat` else case $host_os in freebsd[23].*) objformat=aout ;; *) objformat=elf ;; esac fi version_type=freebsd-$objformat case $version_type in freebsd-elf*) library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' need_version=no need_lib_prefix=no ;; freebsd-*) library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' need_version=yes ;; esac shlibpath_var=LD_LIBRARY_PATH case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes ;; freebsd3.[01]* | freebsdelf3.[01]*) shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; *) # from 4.6 on, and DragonFly shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; esac ;; haiku*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no dynamic_linker="$host_os runtime_loader" library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=yes sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' hardcode_into_libs=yes ;; hpux9* | hpux10* | hpux11*) # Give a soname corresponding to the major version so that dld.sl refuses to # link against other versions. version_type=sunos need_lib_prefix=no need_version=no case $host_cpu in ia64*) shrext_cmds='.so' hardcode_into_libs=yes dynamic_linker="$host_os dld.so" shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' if test "X$HPUX_IA64_MODE" = X32; then sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" else sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" fi sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; hppa*64*) shrext_cmds='.sl' hardcode_into_libs=yes dynamic_linker="$host_os dld.sl" shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; *) shrext_cmds='.sl' dynamic_linker="$host_os dld.sl" shlibpath_var=SHLIB_PATH shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' ;; esac # HP-UX runs *really* slowly unless shared libraries are mode 555, ... postinstall_cmds='chmod 555 $lib' # or fails outright, so override atomically: install_override_mode=555 ;; interix[3-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; irix5* | irix6* | nonstopux*) case $host_os in nonstopux*) version_type=nonstopux ;; *) if test "$lt_cv_prog_gnu_ld" = yes; then version_type=linux # correct to gnu/linux during the next big refactor else version_type=irix fi ;; esac need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' case $host_os in irix5* | nonstopux*) libsuff= shlibsuff= ;; *) case $LD in # libtool.m4 will add one of these switches to LD *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= libmagic=32-bit;; *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 libmagic=N32;; *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 libmagic=64-bit;; *) libsuff= shlibsuff= libmagic=never-match;; esac ;; esac shlibpath_var=LD_LIBRARY${shlibsuff}_PATH shlibpath_overrides_runpath=no sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" hardcode_into_libs=yes ;; # No shared lib support for Linux oldld, aout, or coff. linux*oldld* | linux*aout* | linux*coff*) dynamic_linker=no ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no # Some binutils ld are patched to set DT_RUNPATH if ${lt_cv_shlibpath_overrides_runpath+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$lt_prog_compiler_wl_CXX\"; \ LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec_CXX\"" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : if ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then : lt_cv_shlibpath_overrides_runpath=yes fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS libdir=$save_libdir fi shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on # powerpc, because MkLinux only supported shared libraries with the # GNU dynamic linker. Since this was broken with cross compilers, # most powerpc-linux boxes support dynamic linking these days and # people can always --disable-shared, the test was removed, and we # assume the GNU/Linux dynamic linker is in use. dynamic_linker='GNU/Linux ld.so' ;; netbsdelf*-gnu) version_type=linux need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='NetBSD ld.elf_so' ;; netbsd*) version_type=sunos need_lib_prefix=no need_version=no if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' dynamic_linker='NetBSD (a.out) ld.so' else library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='NetBSD ld.elf_so' fi shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; *nto* | *qnx*) version_type=qnx need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='ldqnx.so' ;; openbsd*) version_type=sunos sys_lib_dlsearch_path_spec="/usr/lib" need_lib_prefix=no # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. case $host_os in openbsd3.3 | openbsd3.3.*) need_version=yes ;; *) need_version=no ;; esac library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' shlibpath_var=LD_LIBRARY_PATH if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then case $host_os in openbsd2.[89] | openbsd2.[89].*) shlibpath_overrides_runpath=no ;; *) shlibpath_overrides_runpath=yes ;; esac else shlibpath_overrides_runpath=yes fi ;; os2*) libname_spec='$name' shrext_cmds=".dll" need_lib_prefix=no library_names_spec='$libname${shared_ext} $libname.a' dynamic_linker='OS/2 ld.exe' shlibpath_var=LIBPATH ;; osf3* | osf4* | osf5*) version_type=osf need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" ;; rdos*) dynamic_linker=no ;; solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes # ldd complains unless libraries are executable postinstall_cmds='chmod +x $lib' ;; sunos4*) version_type=sunos library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes if test "$with_gnu_ld" = yes; then need_lib_prefix=no fi need_version=yes ;; sysv4 | sysv4.3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH case $host_vendor in sni) shlibpath_overrides_runpath=no need_lib_prefix=no runpath_var=LD_RUN_PATH ;; siemens) need_lib_prefix=no ;; motorola) need_lib_prefix=no need_version=no shlibpath_overrides_runpath=no sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' ;; esac ;; sysv4*MP*) if test -d /usr/nec ;then version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' soname_spec='$libname${shared_ext}.$major' shlibpath_var=LD_LIBRARY_PATH fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) version_type=freebsd-elf need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes if test "$with_gnu_ld" = yes; then sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' else sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' case $host_os in sco3.2v5*) sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" ;; esac fi sys_lib_dlsearch_path_spec='/usr/lib' ;; tpf*) # TPF is a cross-target only. Preferred cross-host = GNU/Linux. version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; uts4*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; *) dynamic_linker=no ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5 $as_echo "$dynamic_linker" >&6; } test "$dynamic_linker" = no && can_build_shared=no variables_saved_for_relink="PATH $shlibpath_var $runpath_var" if test "$GCC" = yes; then variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" fi if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" fi if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5 $as_echo_n "checking how to hardcode library paths into programs... " >&6; } hardcode_action_CXX= if test -n "$hardcode_libdir_flag_spec_CXX" || test -n "$runpath_var_CXX" || test "X$hardcode_automatic_CXX" = "Xyes" ; then # We can hardcode non-existent directories. if test "$hardcode_direct_CXX" != no && # If the only mechanism to avoid hardcoding is shlibpath_var, we # have to relink, otherwise we might link with an installed library # when we should be linking with a yet-to-be-installed one ## test "$_LT_TAGVAR(hardcode_shlibpath_var, CXX)" != no && test "$hardcode_minus_L_CXX" != no; then # Linking always hardcodes the temporary library directory. hardcode_action_CXX=relink else # We can link without hardcoding, and we can hardcode nonexisting dirs. hardcode_action_CXX=immediate fi else # We cannot hardcode anything, or else we can only hardcode existing # directories. hardcode_action_CXX=unsupported fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action_CXX" >&5 $as_echo "$hardcode_action_CXX" >&6; } if test "$hardcode_action_CXX" = relink || test "$inherit_rpath_CXX" = yes; then # Fast installation is not supported enable_fast_install=no elif test "$shlibpath_overrides_runpath" = yes || test "$enable_shared" = no; then # Fast installation is not necessary enable_fast_install=needless fi fi # test -n "$compiler" CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS LDCXX=$LD LD=$lt_save_LD GCC=$lt_save_GCC with_gnu_ld=$lt_save_with_gnu_ld lt_cv_path_LDCXX=$lt_cv_path_LD lt_cv_path_LD=$lt_save_path_LD lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld fi # test "$_lt_caught_CXX_error" != yes ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" fi fi fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CC" && break done if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi fi fi test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH See \`config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; } if ${ac_cv_c_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 $as_echo "$ac_cv_c_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GCC=yes else GCC= fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 $as_echo_n "checking whether $CC accepts -g... " >&6; } if ${ac_cv_prog_cc_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes else CFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 $as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; } if ${ac_cv_prog_cc_c89+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include struct stat; /* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ struct buf { int x; }; FILE * (*rcsopen) (struct buf *, struct stat *, int); static char *e (p, i) char **p; int i; { return p[i]; } static char *f (char * (*g) (char **, int), char **p, ...) { char *s; va_list v; va_start (v,p); s = g (p, va_arg (v,int)); va_end (v); return s; } /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not '\xHH' hex character constants. These don't provoke an error unfortunately, instead are silently treated as 'x'. The following induces an error, until -std is added to get proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an array size at least. It's necessary to write '\x00'==0 to get something that's true only with -std. */ int osf4_cc_array ['\x00' == 0 ? 1 : -1]; /* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters inside strings and character constants. */ #define FOO(x) 'x' int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); int argc; char **argv; int main () { return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; ; return 0; } _ACEOF for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_c89=$ac_arg fi rm -f core conftest.err conftest.$ac_objext test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC fi # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 $as_echo "none needed" >&6; } ;; xno) { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 $as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 $as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac if test "x$ac_cv_prog_cc_c89" != xno; then : fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu depcc="$CC" am_compiler_list= { $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 $as_echo_n "checking dependency style of $depcc... " >&6; } if ${am_cv_CC_dependencies_compiler_type+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named `D' -- because `-MD' means `put the output # in D'. rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_CC_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` fi am__universal=false case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with # Solaris 8's {/usr,}/bin/sh. touch sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with `-c' and `-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle `-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # after this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok `-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_CC_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_CC_dependencies_compiler_type=none fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_CC_dependencies_compiler_type" >&5 $as_echo "$am_cv_CC_dependencies_compiler_type" >&6; } CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type if test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then am__fastdepCC_TRUE= am__fastdepCC_FALSE='#' else am__fastdepCC_TRUE='#' am__fastdepCC_FALSE= fi # Check for cross compilation if test x$cross_compiling = xyes; then CROSS_COMPILING_TRUE= CROSS_COMPILING_FALSE='#' else CROSS_COMPILING_TRUE='#' CROSS_COMPILING_FALSE= fi # Dynamic extenition { $as_echo "$as_me:${as_lineno-$LINENO}: checking for default shared object extenetion" >&5 $as_echo_n "checking for default shared object extenetion... " >&6; } case ${host} in *-apple-darwin*) DYNEXT=".dylib" ;; *) DYNEXT=".so" ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${DYNEXT} " >&5 $as_echo "${DYNEXT} " >&6; } # Checks for libraries. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for CoreAudio" >&5 $as_echo_n "checking for CoreAudio... " >&6; } if test "`uname`" == "Darwin"; then CA_LIBS="-framework CoreAudio -framework AudioToolbox" { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } if true; then COREAUDIO_DRIVERS_TRUE= COREAUDIO_DRIVERS_FALSE='#' else COREAUDIO_DRIVERS_TRUE='#' COREAUDIO_DRIVERS_FALSE= fi else CA_LIBS="" { $as_echo "$as_me:${as_lineno-$LINENO}: result: not needed" >&5 $as_echo "not needed" >&6; } if false; then COREAUDIO_DRIVERS_TRUE= COREAUDIO_DRIVERS_FALSE='#' else COREAUDIO_DRIVERS_TRUE='#' COREAUDIO_DRIVERS_FALSE= fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Carbon" >&5 $as_echo_n "checking for Carbon... " >&6; } if test "`uname`" == "Darwin"; then CARBON_LIBS="-framework Carbon" { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else CARBON_LIBS="" { $as_echo "$as_me:${as_lineno-$LINENO}: result: not needed" >&5 $as_echo "not needed" >&6; } fi #CHECK_LIBRT # Check for SpanDSP library { $as_echo "$as_me:${as_lineno-$LINENO}: checking for libspandsp >= 0.0.2pre26" >&5 $as_echo_n "checking for libspandsp >= 0.0.2pre26... " >&6; } # Unset withval, as AC_ARG_WITH does not unset it withval= # Check whether --with-spandsp-includedir was given. if test "${with_spandsp_includedir+set}" = set; then : withval=$with_spandsp_includedir; fi # If withval is set, use that. If not and homeval is set, use # $homeval/include. If neither, use null. includeval=${withval} withval= # Process the --with-spansdp-libdir argument which gives the libgsm library # directory. # Check whether --with-spandsp-libdir was given. if test "${with_spandsp_libdir+set}" = set; then : withval=$with_spandsp_libdir; fi libval=${withval} # Check for spansdp.h in the specified include directory if any, and a number # of other likely places. for dir in $includeval /usr/local/include /usr/include /sw/include; do if test -f "$dir/spandsp.h"; then found_spandsp_include="yes"; includeval=$dir break; fi done # Check for libspansdp.{so,a} in the specified lib directory if any, and a # number of other likely places. for dir in $libval /usr/local/lib /usr/lib /usr/lib64 /sw/lib; do if test -f "$dir/libspandsp.so" -o -f "$dir/libspandsp.la"; then found_spandsp_lib="yes"; libval=$dir break; fi done # Test that we've been able to find both directories, and set the various # makefile variables. if test x_$found_spandsp_include != x_yes -o x_$found_spandsp_lib != x_yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: not found" >&5 $as_echo "not found" >&6; } else # testing for proper version ac_spandsp_ok=false ac_spandsp_new=false ac_spandsp_g726valid=false if test -f "$includeval/spandsp/g722.h" -o -f "$includeval/spandsp/g726.h"; then OLD_CFLAGS=$CFLAGS OLD_LDFLAGS=$LDFLAGS CFLAGS+=" -I$includeval" LDFLAGS+=" -L$libval -lspandsp" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include int main () { void* p = g726_init(0, 16000, G726_ENCODING_LINEAR, G726_PACKING_LEFT); void* q = g722_encode_init(0, 64000, 0); return p!=q; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_libspandsp_newstyle=true else ac_libspandsp_newstyle=false fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test "$ac_libspandsp_newstyle" = false; then cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include int main () { void* p = g726_init(0, 16000, G726_ENCODING_LINEAR, G726_PACKING_LEFT); void* q = g722_encode_init(0, 64000, 0); return p!=q; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_libspandsp_newstyle=true else ac_libspandsp_newstyle=false fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi CFLAGS=$OLD_CFLAGS LDFLAGS=$OLD_LDFLAGS if test "$ac_libspandsp_newstyle" = false; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: ac_libspandsp_newstyle == false" >&5 $as_echo "$as_me: WARNING: ac_libspandsp_newstyle == false" >&2;} OLD_CFLAGS=$CFLAGS OLD_LDFLAGS=$LDFLAGS CFLAGS+=" -I$includeval" LDFLAGS+=" -L$libval -lspandsp" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include int main () { void* p = g726_init(0, 16000, G726_ENCODING_LINEAR, 1); void* q = g722_encode_init(0, 64000, 0); return p!=q; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_libspandsp_oldstyle=true else ac_libspandsp_oldstyle=false fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CFLAGS=$OLD_CFLAGS LDFLAGS=$OLD_LDFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: ac_libspandsp_oldstyle = $ac_libspandsp_oldstyle" >&5 $as_echo "$as_me: WARNING: ac_libspandsp_oldstyle = $ac_libspandsp_oldstyle" >&2;} if test "$ac_libspandsp_oldstyle" = true; then $as_echo "#define HAVE_OLD_LIBSPANDSP 1" >>confdefs.h ac_spandsp_ok=true fi else ac_spandsp_ok=true fi fi if test "$ac_spandsp_ok" = true -a "$ac_libspandsp_newstyle" = true; then ac_spandsp_new=true ac_spandsp_g726valid=true fi if test "$ac_spandsp_ok" = true; then if test "$ac_spandsp_new" = true; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: old version of libspandsp" >&5 $as_echo "old version of libspandsp" >&6; } fi SPANDSP_CFLAGS="-I$includeval" SPANDSP_CXXFLAGS="-I$includeval" SPANDSP_LIBS="-lspandsp" SPANDSP_LDFLAGS="-L$libval" else as_fn_error $? "invalid version of spandsplib" "$LINENO" 5 fi if test "$ac_spandsp_ok" = true -a "$ac_spandsp_new" = false; then withval= # Check whether --with-spandsp-validg726 was given. if test "${with_spandsp_validg726+set}" = set; then : withval=$with_spandsp_validg726; fi if test "$withval" = "yes" -o "$withval" = "ok" ; then ac_spandsp_g726valid=true else # Need to check G726 packing { $as_echo "$as_me:${as_lineno-$LINENO}: checking for libspandsp G726 packing" >&5 $as_echo_n "checking for libspandsp G726 packing... " >&6; } OLD_CFLAGS=$CFLAGS OLD_LDFLAGS=$LDFLAGS CFLAGS+=" $SPANDSP_CFLAGS" LDFLAGS+=" $SPANDSP_LDFLAGS $SPANDSP_LIBS" if test "$cross_compiling" = yes; then : ac_spandsp_g726valid=false else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include int main() { void* p = g726_init(0, 16000, G726_ENCODING_LINEAR, 1); uint16_t data[16]; const uint16_t vdata[4] = {0xc, 0xc, 0xc, 0x3c}; uint8_t packed[4] = {1, 54}; int len, i; len = g726_decode(p, data, packed, 2); for (i = 0; i < 4; i++) { if ( data[i] != vdata[i] ) return -1; } return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : ac_spandsp_g726valid=true else ac_spandsp_g726valid=false fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi CFLAGS=$OLD_CFLAGS LDFLAGS=$OLD_LDFLAGS if test "$ac_spandsp_g726valid" = true; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: incorrect" >&5 $as_echo "incorrect" >&6; } fi fi fi fi # Enable use of code that uses speex dsp library { $as_echo "$as_me:${as_lineno-$LINENO}: checking if speex dsp usage is enabled" >&5 $as_echo_n "checking if speex dsp usage is enabled... " >&6; } speex_dsp_enabled=no; # Check whether --enable-speex-dsp was given. if test "${enable_speex_dsp+set}" = set; then : enableval=$enable_speex_dsp; case "${enableval}" in yes) { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; }; speex_dsp_enabled=yes ;; no) { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } ;; *) as_fn_error $? "bad value ${enableval} for --enable-speex-dsp" "$LINENO" 5 ;; esac else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi # Check to see if speex dsp was selected, and speex usage has not been # checked and configured if test "x$speex_dsp_enabled" == "xyes" -a "x$speex_detected" == "x"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for libspeex >= 1.2rc1" >&5 $as_echo_n "checking for libspeex >= 1.2rc1... " >&6; } # Check if the user wished to force usage of contrib version of speex contrib_speex_enabled=no; # Check whether --enable-contrib-speex was given. if test "${enable_contrib_speex+set}" = set; then : enableval=$enable_contrib_speex; case "${enableval}" in yes) contrib_speex_enabled=yes ;; no) contrib_speex_enabled=no ;; *) as_fn_error $? "bad value ${enableval} for --enable-contrib-speex" "$LINENO" 5 ;; esac else contrib_speex_enabled=no fi # Detect if speex is installed. speex_detected=no; if test "x$contrib_speex_enabled" == "xno"; then pkg_failed=no { $as_echo "$as_me:${as_lineno-$LINENO}: checking for SPEEX" >&5 $as_echo_n "checking for SPEEX... " >&6; } if test -n "$SPEEX_CFLAGS"; then pkg_cv_SPEEX_CFLAGS="$SPEEX_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"speex >= 1.2rc1\""; } >&5 ($PKG_CONFIG --exists --print-errors "speex >= 1.2rc1") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_SPEEX_CFLAGS=`$PKG_CONFIG --cflags "speex >= 1.2rc1" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$SPEEX_LIBS"; then pkg_cv_SPEEX_LIBS="$SPEEX_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"speex >= 1.2rc1\""; } >&5 ($PKG_CONFIG --exists --print-errors "speex >= 1.2rc1") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_SPEEX_LIBS=`$PKG_CONFIG --libs "speex >= 1.2rc1" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then SPEEX_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "speex >= 1.2rc1" 2>&1` else SPEEX_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "speex >= 1.2rc1" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$SPEEX_PKG_ERRORS" >&5 speex_detected=no; contrib_speex_enabled=yes elif test $pkg_failed = untried; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } speex_detected=no; contrib_speex_enabled=yes else SPEEX_CFLAGS=$pkg_cv_SPEEX_CFLAGS SPEEX_LIBS=$pkg_cv_SPEEX_LIBS { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } SPEEXDSP_CFLAGS C compiler flags for SPEEXDSP, overriding pkg-config SPEEXDSP_LIBS linker flags for SPEEXDSP, overriding pkg-config pkg_failed=no { $as_echo "$as_me:${as_lineno-$LINENO}: checking for SPEEXDSP" >&5 $as_echo_n "checking for SPEEXDSP... " >&6; } if test -n "$SPEEXDSP_CFLAGS"; then pkg_cv_SPEEXDSP_CFLAGS="$SPEEXDSP_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"speexdsp >= 1.2rc1\""; } >&5 ($PKG_CONFIG --exists --print-errors "speexdsp >= 1.2rc1") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_SPEEXDSP_CFLAGS=`$PKG_CONFIG --cflags "speexdsp >= 1.2rc1" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$SPEEXDSP_LIBS"; then pkg_cv_SPEEXDSP_LIBS="$SPEEXDSP_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"speexdsp >= 1.2rc1\""; } >&5 ($PKG_CONFIG --exists --print-errors "speexdsp >= 1.2rc1") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_SPEEXDSP_LIBS=`$PKG_CONFIG --libs "speexdsp >= 1.2rc1" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then SPEEXDSP_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "speexdsp >= 1.2rc1" 2>&1` else SPEEXDSP_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "speexdsp >= 1.2rc1" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$SPEEXDSP_PKG_ERRORS" >&5 speex_detected=no; contrib_speex_enabled=yes elif test $pkg_failed = untried; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } speex_detected=no; contrib_speex_enabled=yes else SPEEXDSP_CFLAGS=$pkg_cv_SPEEXDSP_CFLAGS SPEEXDSP_LIBS=$pkg_cv_SPEEXDSP_LIBS { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } speex_detected=yes fi fi pkg_failed=no if test -n "$SPEEX_LIBDIR"; then pkg_cv_SPEEX_LIBDIR="$SPEEX_LIBDIR" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"speex >= 1.2rc1\""; } >&5 ($PKG_CONFIG --exists --print-errors "speex >= 1.2rc1") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_SPEEX_LIBDIR=`$PKG_CONFIG --variable=libdir "speex >= 1.2rc1" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test "x$pkg_failed" = "xuntried"; then as_fn_error $? "Failed to get the speex library directory from pkg-config!" "$LINENO" 5 else SPEEX_STATIC_LIB=${SPEEX_LIBDIR}/libspeex.a SPEEXDSP_STATIC_LIB=${SPEEX_LIBDIR}/libspeexdsp.a fi fi # if contrib speex is selected, use it. if test "x$contrib_speex_enabled" == "xyes" ; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: using svn version" >&5 $as_echo "using svn version" >&6; } SPEEX_ROOT='${top_srcdir}/../sipXmediaLib/contrib/libspeex' SPEEX_CFLAGS="-I${SPEEX_ROOT}/include" SPEEX_CFLAGS+=' -I${top_builddir}/sipXmediaLib/contrib/libspeex/include' SPEEX_STATIC_LIB='${top_builddir}/sipXmediaLib/contrib/libspeex/libspeex/.libs/libspeex.a' SPEEX_LIBS=${SPEEX_STATIC_LIB} SPEEXDSP_STATIC_LIB='${top_builddir}/sipXmediaLib/contrib/libspeex/libspeex/.libs/libspeexdsp.a' SPEEXDSP_LIBS=${SPEEXDSP_STATIC_LIB} elif test "x$speex_detected" == "xyes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } else as_fn_error $? "No speex found!" "$LINENO" 5 fi fi if test "x$speex_dsp_enabled" == "xyes"; then # Specify to enable speex dsp code CFLAGS="${CFLAGS} -DHAVE_SPEEX" ; CXXFLAGS="${CXXFLAGS} -DHAVE_SPEEX" fi # Look for GSM and Speex codecs { $as_echo "$as_me:${as_lineno-$LINENO}: checking for libgsm >= 1.0.10" >&5 $as_echo_n "checking for libgsm >= 1.0.10... " >&6; } # Check whether --enable-codec-gsm was given. if test "${enable_codec_gsm+set}" = set; then : enableval=$enable_codec_gsm; case "${enableval}" in auto) # Unset withval, as AC_ARG_WITH does not unset it withval= # Process the --with-gsm argument which gives the libgsm base directory. # Check whether --with-gsm was given. if test "${with_gsm+set}" = set; then : withval=$with_gsm; else with_gsm= fi homeval=$withval # Have to unset withval so we can tell if --with-gsm-includedir was # specified, as AC_ARG_WITH will not unset withval if the option is not # there! withval= # Process the --with-gsm-includedir argument which gives the libgsm include # directory. # Check whether --with-gsm-includedir was given. if test "${with_gsm_includedir+set}" = set; then : withval=$with_gsm_includedir; fi # If withval is set, use that. If not and homeval is set, use # $homeval/include. If neither, use null. includeval=${withval:-${homeval:+$homeval/inc}} withval= # Process the --with-gsm-libdir argument which gives the libgsm library # directory. # Check whether --with-gsm-libdir was given. if test "${with_gsm_libdir+set}" = set; then : withval=$with_gsm_libdir; fi libval=${withval:-${homeval:+$homeval/lib}} # Check for gsm.h in the specified include directory if any, and a number # of other likely places. for dir in $includeval /usr/local/include /usr/local/gsm/inc /usr/include /usr/include/gsm /sw/include; do if test -f "$dir/gsm.h"; then found_gsm_include="yes"; includeval=$dir break; fi done # Check for libgsm.{so,a} in the specified lib directory if any, and a # number of other likely places. for dir in $libval /usr/local/lib /usr/local/gsm/lib /usr/lib /usr/lib64 /sw/lib; do if test -f "$dir/libgsm.so" -o -f "$dir/libgsm.a"; then found_gsm_lib="yes"; libval=$dir break; fi done # Test that we've been able to find both directories, and set the various # makefile variables. if test x_$found_gsm_include != x_yes -o x_$found_gsm_lib != x_yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: not found" >&5 $as_echo "not found" >&6; } else ## Test for version gsm_major_version=`grep "GSM_MAJOR" $includeval/gsm.h | \ sed 's/^#define[ \t]\+GSM_MAJOR[ \t]\+\([0-9]\+\)/\1/'` gsm_minor_version=`grep "GSM_MINOR" $includeval/gsm.h | \ sed 's/^#define[ \t]\+GSM_MINOR[ \t]\+\([0-9]\+\)/\1/'` gsm_patchlevel_version=`grep "GSM_PATCHLEVEL" $includeval/gsm.h | \ sed 's/^#define[ \t]\+GSM_PATCHLEVEL[ \t]\+\([0-9]\+\)/\1/'` gsm_ver="$gsm_major_version.$gsm_minor_version.$gsm_patchlevel_version" # Used to indicate true or false condition ax_compare_version=false # Convert the two version strings to be compared into a format that # allows a simple string comparison. The end result is that a version # string of the form 1.12.5-r617 will be converted to the form # 0001001200050617. In other words, each number is zero padded to four # digits, and non digits are removed. ax_compare_version_A=`echo "$gsm_ver" | sed -e 's/\([0-9]*\)/Z\1Z/g' \ -e 's/Z\([0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/[^0-9]//g'` ax_compare_version_B=`echo "1.0.10" | sed -e 's/\([0-9]*\)/Z\1Z/g' \ -e 's/Z\([0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/[^0-9]//g'` ax_compare_version=`echo "x$ax_compare_version_A x$ax_compare_version_B" | sed 's/^ *//' | sort -r | sed "s/x${ax_compare_version_A}/true/;s/x${ax_compare_version_B}/false/;1q"` if test "$ax_compare_version" = "true" ; then : fi if test "x_$ax_compare_version" = "x_false"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: too old (found version $gsm_ver)" >&5 $as_echo "too old (found version $gsm_ver)" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: $gsm_ver is ok" >&5 $as_echo "$gsm_ver is ok" >&6; } # Enable this when we begin using config.h #AC_DEFINE(HAVE_GSM, [1], [Defined if libgsm is present]) CFLAGS="${CFLAGS} -DHAVE_GSM" CXXFLAGS="${CXXFLAGS} -DHAVE_GSM" GSM_CFLAGS="-I$includeval" GSM_CXXFLAGS="-I$includeval" GSM_LIBS="-lgsm" GSM_LDFLAGS="-L$libval" GSM_TARGET="plggsm" PLUGINS="${PLUGINS} GSM" fi fi ;; yes) # Unset withval, as AC_ARG_WITH does not unset it withval= # Process the --with-gsm argument which gives the libgsm base directory. # Check whether --with-gsm was given. if test "${with_gsm+set}" = set; then : withval=$with_gsm; else with_gsm= fi homeval=$withval # Have to unset withval so we can tell if --with-gsm-includedir was # specified, as AC_ARG_WITH will not unset withval if the option is not # there! withval= # Process the --with-gsm-includedir argument which gives the libgsm include # directory. # Check whether --with-gsm-includedir was given. if test "${with_gsm_includedir+set}" = set; then : withval=$with_gsm_includedir; fi # If withval is set, use that. If not and homeval is set, use # $homeval/include. If neither, use null. includeval=${withval:-${homeval:+$homeval/inc}} withval= # Process the --with-gsm-libdir argument which gives the libgsm library # directory. # Check whether --with-gsm-libdir was given. if test "${with_gsm_libdir+set}" = set; then : withval=$with_gsm_libdir; fi libval=${withval:-${homeval:+$homeval/lib}} # Check for gsm.h in the specified include directory if any, and a number # of other likely places. for dir in $includeval /usr/local/include /usr/local/gsm/inc /usr/include /usr/include/gsm /sw/include; do if test -f "$dir/gsm.h"; then found_gsm_include="yes"; includeval=$dir break; fi done # Check for libgsm.{so,a} in the specified lib directory if any, and a # number of other likely places. for dir in $libval /usr/local/lib /usr/local/gsm/lib /usr/lib /usr/lib64 /sw/lib; do if test -f "$dir/libgsm.so" -o -f "$dir/libgsm.a"; then found_gsm_lib="yes"; libval=$dir break; fi done # Test that we've been able to find both directories, and set the various # makefile variables. if test x_$found_gsm_include != x_yes -o x_$found_gsm_lib != x_yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: not found" >&5 $as_echo "not found" >&6; } else ## Test for version gsm_major_version=`grep "GSM_MAJOR" $includeval/gsm.h | \ sed 's/^#define[ \t]\+GSM_MAJOR[ \t]\+\([0-9]\+\)/\1/'` gsm_minor_version=`grep "GSM_MINOR" $includeval/gsm.h | \ sed 's/^#define[ \t]\+GSM_MINOR[ \t]\+\([0-9]\+\)/\1/'` gsm_patchlevel_version=`grep "GSM_PATCHLEVEL" $includeval/gsm.h | \ sed 's/^#define[ \t]\+GSM_PATCHLEVEL[ \t]\+\([0-9]\+\)/\1/'` gsm_ver="$gsm_major_version.$gsm_minor_version.$gsm_patchlevel_version" # Used to indicate true or false condition ax_compare_version=false # Convert the two version strings to be compared into a format that # allows a simple string comparison. The end result is that a version # string of the form 1.12.5-r617 will be converted to the form # 0001001200050617. In other words, each number is zero padded to four # digits, and non digits are removed. ax_compare_version_A=`echo "$gsm_ver" | sed -e 's/\([0-9]*\)/Z\1Z/g' \ -e 's/Z\([0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/[^0-9]//g'` ax_compare_version_B=`echo "1.0.10" | sed -e 's/\([0-9]*\)/Z\1Z/g' \ -e 's/Z\([0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/[^0-9]//g'` ax_compare_version=`echo "x$ax_compare_version_A x$ax_compare_version_B" | sed 's/^ *//' | sort -r | sed "s/x${ax_compare_version_A}/true/;s/x${ax_compare_version_B}/false/;1q"` if test "$ax_compare_version" = "true" ; then : fi if test "x_$ax_compare_version" = "x_false"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: too old (found version $gsm_ver)" >&5 $as_echo "too old (found version $gsm_ver)" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: $gsm_ver is ok" >&5 $as_echo "$gsm_ver is ok" >&6; } # Enable this when we begin using config.h #AC_DEFINE(HAVE_GSM, [1], [Defined if libgsm is present]) CFLAGS="${CFLAGS} -DHAVE_GSM" CXXFLAGS="${CXXFLAGS} -DHAVE_GSM" GSM_CFLAGS="-I$includeval" GSM_CXXFLAGS="-I$includeval" GSM_LIBS="-lgsm" GSM_LDFLAGS="-L$libval" GSM_TARGET="plggsm" PLUGINS="${PLUGINS} GSM" fi fi ;; no) { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5 $as_echo "disabled" >&6; } ;; *) as_fn_error $? "bad value ${enableval} for --enable-codec-gsm" "$LINENO" 5 ;; esac else # Unset withval, as AC_ARG_WITH does not unset it withval= # Process the --with-gsm argument which gives the libgsm base directory. # Check whether --with-gsm was given. if test "${with_gsm+set}" = set; then : withval=$with_gsm; else with_gsm= fi homeval=$withval # Have to unset withval so we can tell if --with-gsm-includedir was # specified, as AC_ARG_WITH will not unset withval if the option is not # there! withval= # Process the --with-gsm-includedir argument which gives the libgsm include # directory. # Check whether --with-gsm-includedir was given. if test "${with_gsm_includedir+set}" = set; then : withval=$with_gsm_includedir; fi # If withval is set, use that. If not and homeval is set, use # $homeval/include. If neither, use null. includeval=${withval:-${homeval:+$homeval/inc}} withval= # Process the --with-gsm-libdir argument which gives the libgsm library # directory. # Check whether --with-gsm-libdir was given. if test "${with_gsm_libdir+set}" = set; then : withval=$with_gsm_libdir; fi libval=${withval:-${homeval:+$homeval/lib}} # Check for gsm.h in the specified include directory if any, and a number # of other likely places. for dir in $includeval /usr/local/include /usr/local/gsm/inc /usr/include /usr/include/gsm /sw/include; do if test -f "$dir/gsm.h"; then found_gsm_include="yes"; includeval=$dir break; fi done # Check for libgsm.{so,a} in the specified lib directory if any, and a # number of other likely places. for dir in $libval /usr/local/lib /usr/local/gsm/lib /usr/lib /usr/lib64 /sw/lib; do if test -f "$dir/libgsm.so" -o -f "$dir/libgsm.a"; then found_gsm_lib="yes"; libval=$dir break; fi done # Test that we've been able to find both directories, and set the various # makefile variables. if test x_$found_gsm_include != x_yes -o x_$found_gsm_lib != x_yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: not found" >&5 $as_echo "not found" >&6; } else ## Test for version gsm_major_version=`grep "GSM_MAJOR" $includeval/gsm.h | \ sed 's/^#define[ \t]\+GSM_MAJOR[ \t]\+\([0-9]\+\)/\1/'` gsm_minor_version=`grep "GSM_MINOR" $includeval/gsm.h | \ sed 's/^#define[ \t]\+GSM_MINOR[ \t]\+\([0-9]\+\)/\1/'` gsm_patchlevel_version=`grep "GSM_PATCHLEVEL" $includeval/gsm.h | \ sed 's/^#define[ \t]\+GSM_PATCHLEVEL[ \t]\+\([0-9]\+\)/\1/'` gsm_ver="$gsm_major_version.$gsm_minor_version.$gsm_patchlevel_version" # Used to indicate true or false condition ax_compare_version=false # Convert the two version strings to be compared into a format that # allows a simple string comparison. The end result is that a version # string of the form 1.12.5-r617 will be converted to the form # 0001001200050617. In other words, each number is zero padded to four # digits, and non digits are removed. ax_compare_version_A=`echo "$gsm_ver" | sed -e 's/\([0-9]*\)/Z\1Z/g' \ -e 's/Z\([0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/[^0-9]//g'` ax_compare_version_B=`echo "1.0.10" | sed -e 's/\([0-9]*\)/Z\1Z/g' \ -e 's/Z\([0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/Z\([0-9][0-9][0-9]\)Z/Z0\1Z/g' \ -e 's/[^0-9]//g'` ax_compare_version=`echo "x$ax_compare_version_A x$ax_compare_version_B" | sed 's/^ *//' | sort -r | sed "s/x${ax_compare_version_A}/true/;s/x${ax_compare_version_B}/false/;1q"` if test "$ax_compare_version" = "true" ; then : fi if test "x_$ax_compare_version" = "x_false"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: too old (found version $gsm_ver)" >&5 $as_echo "too old (found version $gsm_ver)" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: $gsm_ver is ok" >&5 $as_echo "$gsm_ver is ok" >&6; } # Enable this when we begin using config.h #AC_DEFINE(HAVE_GSM, [1], [Defined if libgsm is present]) CFLAGS="${CFLAGS} -DHAVE_GSM" CXXFLAGS="${CXXFLAGS} -DHAVE_GSM" GSM_CFLAGS="-I$includeval" GSM_CXXFLAGS="-I$includeval" GSM_LIBS="-lgsm" GSM_LDFLAGS="-L$libval" GSM_TARGET="plggsm" PLUGINS="${PLUGINS} GSM" fi fi fi if test ! -z "$GSM_TARGET"; then BUILD_CODEC_GSM_TRUE= BUILD_CODEC_GSM_FALSE='#' else BUILD_CODEC_GSM_TRUE='#' BUILD_CODEC_GSM_FALSE= fi # Check whether --enable-codec-speex was given. if test "${enable_codec_speex+set}" = set; then : enableval=$enable_codec_speex; case "${enableval}" in static) CODEC_SPEEX_STATIC=true # Check to see if speex dsp was selected, and speex usage has not been # checked and configured if test "x$codec_speex_enabled" == "xyes" -a "x$speex_detected" == "x"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for libspeex >= 1.2rc1" >&5 $as_echo_n "checking for libspeex >= 1.2rc1... " >&6; } # Check if the user wished to force usage of contrib version of speex contrib_speex_enabled=no; # Check whether --enable-contrib-speex was given. if test "${enable_contrib_speex+set}" = set; then : enableval=$enable_contrib_speex; case "${enableval}" in yes) contrib_speex_enabled=yes ;; no) contrib_speex_enabled=no ;; *) as_fn_error $? "bad value ${enableval} for --enable-contrib-speex" "$LINENO" 5 ;; esac else contrib_speex_enabled=no fi # Detect if speex is installed. speex_detected=no; if test "x$contrib_speex_enabled" == "xno"; then pkg_failed=no { $as_echo "$as_me:${as_lineno-$LINENO}: checking for SPEEX" >&5 $as_echo_n "checking for SPEEX... " >&6; } if test -n "$SPEEX_CFLAGS"; then pkg_cv_SPEEX_CFLAGS="$SPEEX_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"speex >= 1.2rc1\""; } >&5 ($PKG_CONFIG --exists --print-errors "speex >= 1.2rc1") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_SPEEX_CFLAGS=`$PKG_CONFIG --cflags "speex >= 1.2rc1" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$SPEEX_LIBS"; then pkg_cv_SPEEX_LIBS="$SPEEX_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"speex >= 1.2rc1\""; } >&5 ($PKG_CONFIG --exists --print-errors "speex >= 1.2rc1") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_SPEEX_LIBS=`$PKG_CONFIG --libs "speex >= 1.2rc1" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then SPEEX_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "speex >= 1.2rc1" 2>&1` else SPEEX_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "speex >= 1.2rc1" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$SPEEX_PKG_ERRORS" >&5 speex_detected=no; contrib_speex_enabled=yes elif test $pkg_failed = untried; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } speex_detected=no; contrib_speex_enabled=yes else SPEEX_CFLAGS=$pkg_cv_SPEEX_CFLAGS SPEEX_LIBS=$pkg_cv_SPEEX_LIBS { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } pkg_failed=no { $as_echo "$as_me:${as_lineno-$LINENO}: checking for SPEEXDSP" >&5 $as_echo_n "checking for SPEEXDSP... " >&6; } if test -n "$SPEEXDSP_CFLAGS"; then pkg_cv_SPEEXDSP_CFLAGS="$SPEEXDSP_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"speexdsp >= 1.2rc1\""; } >&5 ($PKG_CONFIG --exists --print-errors "speexdsp >= 1.2rc1") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_SPEEXDSP_CFLAGS=`$PKG_CONFIG --cflags "speexdsp >= 1.2rc1" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$SPEEXDSP_LIBS"; then pkg_cv_SPEEXDSP_LIBS="$SPEEXDSP_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"speexdsp >= 1.2rc1\""; } >&5 ($PKG_CONFIG --exists --print-errors "speexdsp >= 1.2rc1") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_SPEEXDSP_LIBS=`$PKG_CONFIG --libs "speexdsp >= 1.2rc1" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then SPEEXDSP_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "speexdsp >= 1.2rc1" 2>&1` else SPEEXDSP_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "speexdsp >= 1.2rc1" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$SPEEXDSP_PKG_ERRORS" >&5 speex_detected=no; contrib_speex_enabled=yes elif test $pkg_failed = untried; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } speex_detected=no; contrib_speex_enabled=yes else SPEEXDSP_CFLAGS=$pkg_cv_SPEEXDSP_CFLAGS SPEEXDSP_LIBS=$pkg_cv_SPEEXDSP_LIBS { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } speex_detected=yes fi fi pkg_failed=no if test -n "$SPEEX_LIBDIR"; then pkg_cv_SPEEX_LIBDIR="$SPEEX_LIBDIR" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"speex >= 1.2rc1\""; } >&5 ($PKG_CONFIG --exists --print-errors "speex >= 1.2rc1") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_SPEEX_LIBDIR=`$PKG_CONFIG --variable=libdir "speex >= 1.2rc1" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test "x$pkg_failed" = "xuntried"; then as_fn_error $? "Failed to get the speex library directory from pkg-config!" "$LINENO" 5 else SPEEX_STATIC_LIB=${SPEEX_LIBDIR}/libspeex.a SPEEXDSP_STATIC_LIB=${SPEEX_LIBDIR}/libspeexdsp.a fi fi # if contrib speex is selected, use it. if test "x$contrib_speex_enabled" == "xyes" ; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: using svn version" >&5 $as_echo "using svn version" >&6; } SPEEX_ROOT='${top_srcdir}/../sipXmediaLib/contrib/libspeex' SPEEX_CFLAGS="-I${SPEEX_ROOT}/include" SPEEX_CFLAGS+=' -I${top_builddir}/sipXmediaLib/contrib/libspeex/include' SPEEX_STATIC_LIB='${top_builddir}/sipXmediaLib/contrib/libspeex/libspeex/.libs/libspeex.a' SPEEX_LIBS=${SPEEX_STATIC_LIB} SPEEXDSP_STATIC_LIB='${top_builddir}/sipXmediaLib/contrib/libspeex/libspeex/.libs/libspeexdsp.a' SPEEXDSP_LIBS=${SPEEXDSP_STATIC_LIB} elif test "x$speex_detected" == "xyes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } else as_fn_error $? "No speex found!" "$LINENO" 5 fi fi PLUGINS="${PLUGINS} SPEEX" SPEEX_TARGET="plgspeex" $as_echo "#define CODEC_SPEEX_STATIC 1" >>confdefs.h STATIC_CODEC_LIBS="${STATIC_CODEC_LIBS} mp/codecs/plgspeex/codec_speex.la" ;; yes) # Check to see if speex dsp was selected, and speex usage has not been # checked and configured if test "x$codec_speex_enabled" == "xyes" -a "x$speex_detected" == "x"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for libspeex >= 1.2rc1" >&5 $as_echo_n "checking for libspeex >= 1.2rc1... " >&6; } # Check if the user wished to force usage of contrib version of speex contrib_speex_enabled=no; # Check whether --enable-contrib-speex was given. if test "${enable_contrib_speex+set}" = set; then : enableval=$enable_contrib_speex; case "${enableval}" in yes) contrib_speex_enabled=yes ;; no) contrib_speex_enabled=no ;; *) as_fn_error $? "bad value ${enableval} for --enable-contrib-speex" "$LINENO" 5 ;; esac else contrib_speex_enabled=no fi # Detect if speex is installed. speex_detected=no; if test "x$contrib_speex_enabled" == "xno"; then pkg_failed=no { $as_echo "$as_me:${as_lineno-$LINENO}: checking for SPEEX" >&5 $as_echo_n "checking for SPEEX... " >&6; } if test -n "$SPEEX_CFLAGS"; then pkg_cv_SPEEX_CFLAGS="$SPEEX_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"speex >= 1.2rc1\""; } >&5 ($PKG_CONFIG --exists --print-errors "speex >= 1.2rc1") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_SPEEX_CFLAGS=`$PKG_CONFIG --cflags "speex >= 1.2rc1" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$SPEEX_LIBS"; then pkg_cv_SPEEX_LIBS="$SPEEX_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"speex >= 1.2rc1\""; } >&5 ($PKG_CONFIG --exists --print-errors "speex >= 1.2rc1") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_SPEEX_LIBS=`$PKG_CONFIG --libs "speex >= 1.2rc1" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then SPEEX_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "speex >= 1.2rc1" 2>&1` else SPEEX_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "speex >= 1.2rc1" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$SPEEX_PKG_ERRORS" >&5 speex_detected=no; contrib_speex_enabled=yes elif test $pkg_failed = untried; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } speex_detected=no; contrib_speex_enabled=yes else SPEEX_CFLAGS=$pkg_cv_SPEEX_CFLAGS SPEEX_LIBS=$pkg_cv_SPEEX_LIBS { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } pkg_failed=no { $as_echo "$as_me:${as_lineno-$LINENO}: checking for SPEEXDSP" >&5 $as_echo_n "checking for SPEEXDSP... " >&6; } if test -n "$SPEEXDSP_CFLAGS"; then pkg_cv_SPEEXDSP_CFLAGS="$SPEEXDSP_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"speexdsp >= 1.2rc1\""; } >&5 ($PKG_CONFIG --exists --print-errors "speexdsp >= 1.2rc1") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_SPEEXDSP_CFLAGS=`$PKG_CONFIG --cflags "speexdsp >= 1.2rc1" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$SPEEXDSP_LIBS"; then pkg_cv_SPEEXDSP_LIBS="$SPEEXDSP_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"speexdsp >= 1.2rc1\""; } >&5 ($PKG_CONFIG --exists --print-errors "speexdsp >= 1.2rc1") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_SPEEXDSP_LIBS=`$PKG_CONFIG --libs "speexdsp >= 1.2rc1" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then SPEEXDSP_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "speexdsp >= 1.2rc1" 2>&1` else SPEEXDSP_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "speexdsp >= 1.2rc1" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$SPEEXDSP_PKG_ERRORS" >&5 speex_detected=no; contrib_speex_enabled=yes elif test $pkg_failed = untried; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } speex_detected=no; contrib_speex_enabled=yes else SPEEXDSP_CFLAGS=$pkg_cv_SPEEXDSP_CFLAGS SPEEXDSP_LIBS=$pkg_cv_SPEEXDSP_LIBS { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } speex_detected=yes fi fi pkg_failed=no if test -n "$SPEEX_LIBDIR"; then pkg_cv_SPEEX_LIBDIR="$SPEEX_LIBDIR" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"speex >= 1.2rc1\""; } >&5 ($PKG_CONFIG --exists --print-errors "speex >= 1.2rc1") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_SPEEX_LIBDIR=`$PKG_CONFIG --variable=libdir "speex >= 1.2rc1" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test "x$pkg_failed" = "xuntried"; then as_fn_error $? "Failed to get the speex library directory from pkg-config!" "$LINENO" 5 else SPEEX_STATIC_LIB=${SPEEX_LIBDIR}/libspeex.a SPEEXDSP_STATIC_LIB=${SPEEX_LIBDIR}/libspeexdsp.a fi fi # if contrib speex is selected, use it. if test "x$contrib_speex_enabled" == "xyes" ; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: using svn version" >&5 $as_echo "using svn version" >&6; } SPEEX_ROOT='${top_srcdir}/../sipXmediaLib/contrib/libspeex' SPEEX_CFLAGS="-I${SPEEX_ROOT}/include" SPEEX_CFLAGS+=' -I${top_builddir}/sipXmediaLib/contrib/libspeex/include' SPEEX_STATIC_LIB='${top_builddir}/sipXmediaLib/contrib/libspeex/libspeex/.libs/libspeex.a' SPEEX_LIBS=${SPEEX_STATIC_LIB} SPEEXDSP_STATIC_LIB='${top_builddir}/sipXmediaLib/contrib/libspeex/libspeex/.libs/libspeexdsp.a' SPEEXDSP_LIBS=${SPEEXDSP_STATIC_LIB} elif test "x$speex_detected" == "xyes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } else as_fn_error $? "No speex found!" "$LINENO" 5 fi fi PLUGINS="${PLUGINS} SPEEX" SPEEX_TARGET="plgspeex" ;; no) ;; *) as_fn_error $? "bad value ${enableval} for --enable-codec-speex" "$LINENO" 5 ;; esac fi if test ! -z "$SPEEX_TARGET"; then BUILD_CODEC_SPEEX_TRUE= BUILD_CODEC_SPEEX_FALSE='#' else BUILD_CODEC_SPEEX_TRUE='#' BUILD_CODEC_SPEEX_FALSE= fi if test "$CODEC_SPEEX_STATIC" = true; then SPEEX_STATIC_TRUE= SPEEX_STATIC_FALSE='#' else SPEEX_STATIC_TRUE='#' SPEEX_STATIC_FALSE= fi # Check whether --enable-codec-ilbc was given. if test "${enable_codec_ilbc+set}" = set; then : enableval=$enable_codec_ilbc; case "${enableval}" in auto) # Currently only iLBC in contrib supported PLUGINS="${PLUGINS} iLBC" ILBC_INCLUDE="-I${PWD}/sipXmediaLib/contrib/libilbc/include" ILBC_LIB_ROOT="${PWD}/sipXmediaLib/contrib/libilbc/" ILBC_LIB_TARGET="lib/libilbc.a" ILBC_TARGET="plgilbc" ;; yes) # Currently only iLBC in contrib supported PLUGINS="${PLUGINS} iLBC" ILBC_INCLUDE="-I${PWD}/sipXmediaLib/contrib/libilbc/include" ILBC_LIB_ROOT="${PWD}/sipXmediaLib/contrib/libilbc/" ILBC_LIB_TARGET="lib/libilbc.a" ILBC_TARGET="plgilbc" ;; no) { $as_echo "$as_me:${as_lineno-$LINENO}: result: Codec iLBC was disabled" >&5 $as_echo "Codec iLBC was disabled" >&6; } ;; *) as_fn_error $? "bad value ${enableval} for --enable-codec-ilbc" "$LINENO" 5 ;; esac else # Currently only iLBC in contrib supported PLUGINS="${PLUGINS} iLBC" ILBC_INCLUDE="-I${PWD}/sipXmediaLib/contrib/libilbc/include" ILBC_LIB_ROOT="${PWD}/sipXmediaLib/contrib/libilbc/" ILBC_LIB_TARGET="lib/libilbc.a" ILBC_TARGET="plgilbc" fi if test ! -z "$ILBC_TARGET"; then BUILD_CODEC_ILBC_TRUE= BUILD_CODEC_ILBC_FALSE='#' else BUILD_CODEC_ILBC_TRUE='#' BUILD_CODEC_ILBC_FALSE= fi # Check whether --enable-codec-pcmapcmu was given. if test "${enable_codec_pcmapcmu+set}" = set; then : enableval=$enable_codec_pcmapcmu; case "${enableval}" in static) CODEC_PCMAPCMU_STATIC=true PLUGINS="${PLUGINS} PCMA_PCMU" PCMAPCMU_TARGET="plgpcmapcmu" $as_echo "#define CODEC_PCMA_PCMU_STATIC 1" >>confdefs.h STATIC_CODEC_LIBS="${STATIC_CODEC_LIBS} mp/codecs/plgpcmapcmu/codec_pcmapcmu.la" ;; auto) PLUGINS="${PLUGINS} PCMA_PCMU" PCMAPCMU_TARGET="plgpcmapcmu" ;; yes) PLUGINS="${PLUGINS} PCMA_PCMU" PCMAPCMU_TARGET="plgpcmapcmu" ;; no) { $as_echo "$as_me:${as_lineno-$LINENO}: result: Codecs PCMA & PCMU was disabled" >&5 $as_echo "Codecs PCMA & PCMU was disabled" >&6; } ;; *) as_fn_error $? "bad value ${enableval} for --enable-codec-pcmapcmu" "$LINENO" 5 ;; esac else PLUGINS="${PLUGINS} PCMA_PCMU" PCMAPCMU_TARGET="plgpcmapcmu" fi if test ! -z "$PCMAPCMU_TARGET"; then BUILD_CODEC_PCMAPCMU_TRUE= BUILD_CODEC_PCMAPCMU_FALSE='#' else BUILD_CODEC_PCMAPCMU_TRUE='#' BUILD_CODEC_PCMAPCMU_FALSE= fi if test "$CODEC_PCMAPCMU_STATIC" = true; then PCMAPCMU_STATIC_TRUE= PCMAPCMU_STATIC_FALSE='#' else PCMAPCMU_STATIC_TRUE='#' PCMAPCMU_STATIC_FALSE= fi # Check whether --enable-codec-tones was given. if test "${enable_codec_tones+set}" = set; then : enableval=$enable_codec_tones; case "${enableval}" in static) CODEC_TONES_STATIC=true PLUGINS="${PLUGINS} TONES" TONES_TARGET="plgtones" $as_echo "#define CODEC_TONES_STATIC 1" >>confdefs.h STATIC_CODEC_LIBS="${STATIC_CODEC_LIBS} mp/codecs/plgtones/codec_tones.la" ;; auto) PLUGINS="${PLUGINS} TONES" TONES_TARGET="plgtones" ;; yes) PLUGINS="${PLUGINS} TONES" TONES_TARGET="plgtones" ;; no) { $as_echo "$as_me:${as_lineno-$LINENO}: result: Codec Tones was disabled" >&5 $as_echo "Codec Tones was disabled" >&6; } ;; *) as_fn_error $? "bad value ${enableval} for --enable-codec-tones" "$LINENO" 5 ;; esac else PLUGINS="${PLUGINS} TONES" TONES_TARGET="plgtones" fi if test ! -z "$TONES_TARGET"; then BUILD_CODEC_TONES_TRUE= BUILD_CODEC_TONES_FALSE='#' else BUILD_CODEC_TONES_TRUE='#' BUILD_CODEC_TONES_FALSE= fi if test "$CODEC_TONES_STATIC" = true; then TONES_STATIC_TRUE= TONES_STATIC_FALSE='#' else TONES_STATIC_TRUE='#' TONES_STATIC_FALSE= fi # Check whether --enable-codec-l16 was given. if test "${enable_codec_l16+set}" = set; then : enableval=$enable_codec_l16; case "${enableval}" in static) CODEC_L16_STATIC=true PLUGINS="${PLUGINS} L16" L16_TARGET="plgl16" $as_echo "#define CODEC_L16_STATIC 1" >>confdefs.h STATIC_CODEC_LIBS="${STATIC_CODEC_LIBS} mp/codecs/plgl16/codec_l16.la" ;; auto) { $as_echo "$as_me:${as_lineno-$LINENO}: result: Codec L16 was disabled" >&5 $as_echo "Codec L16 was disabled" >&6; } ;; yes) PLUGINS="${PLUGINS} L16" L16_TARGET="plgl16" ;; no) { $as_echo "$as_me:${as_lineno-$LINENO}: result: Codec L16 was disabled" >&5 $as_echo "Codec L16 was disabled" >&6; } ;; *) as_fn_error $? "bad value ${enableval} for --enable-codec-l16" "$LINENO" 5 ;; esac else PLUGINS="${PLUGINS} L16" L16_TARGET="plgl16" fi if test ! -z "$L16_TARGET"; then BUILD_CODEC_L16_TRUE= BUILD_CODEC_L16_FALSE='#' else BUILD_CODEC_L16_TRUE='#' BUILD_CODEC_L16_FALSE= fi if test "$CODEC_L16_STATIC" = true; then L16_STATIC_TRUE= L16_STATIC_FALSE='#' else L16_STATIC_TRUE='#' L16_STATIC_FALSE= fi # Check whether --enable-codec-g726 was given. if test "${enable_codec_g726+set}" = set; then : enableval=$enable_codec_g726; case "${enableval}" in static) CODEC_G726_STATIC=true if test x_$SPANDSP_CFLAGS != x_ -a "$ac_spandsp_g726valid" = true; then PLUGINS="${PLUGINS} G.726" G726_TARGET="plgg726" fi if test "$G726_TARGET" != ""; then $as_echo "#define CODEC_G726_STATIC 1" >>confdefs.h LDFLAGS="$LDFLAGS $SPANDSP_LDFLAGS $SPANDSP_LIBS" STATIC_CODEC_LIBS="${STATIC_CODEC_LIBS} mp/codecs/plgg726/codec_g726.la" fi ;; auto) if test x_$SPANDSP_CFLAGS != x_ -a "$ac_spandsp_g726valid" = true; then PLUGINS="${PLUGINS} G.726" G726_TARGET="plgg726" fi ;; yes) if test x_$SPANDSP_CFLAGS != x_ -a "$ac_spandsp_g726valid" = true; then PLUGINS="${PLUGINS} G.726" G726_TARGET="plgg726" fi ;; no) { $as_echo "$as_me:${as_lineno-$LINENO}: result: Codec G.726 was disabled" >&5 $as_echo "Codec G.726 was disabled" >&6; } ;; *) as_fn_error $? "bad value ${enableval} for --enable-codec-g726" "$LINENO" 5 ;; esac else if test x_$SPANDSP_CFLAGS != x_ -a "$ac_spandsp_g726valid" = true; then PLUGINS="${PLUGINS} G.726" G726_TARGET="plgg726" fi fi if test ! -z "$G726_TARGET"; then BUILD_CODEC_G726_TRUE= BUILD_CODEC_G726_FALSE='#' else BUILD_CODEC_G726_TRUE='#' BUILD_CODEC_G726_FALSE= fi if test "$CODEC_G726_STATIC" = true; then G726_STATIC_TRUE= G726_STATIC_FALSE='#' else G726_STATIC_TRUE='#' G726_STATIC_FALSE= fi # Check whether --enable-codec-g722 was given. if test "${enable_codec_g722+set}" = set; then : enableval=$enable_codec_g722; case "${enableval}" in static) CODEC_G722_STATIC=true # Currently only iLBC in contrib supported if test x_$SPANDSP_CFLAGS != x_; then PLUGINS="${PLUGINS} G.722" G722_TARGET="plgg722" fi if test "$G722_TARGET" != ""; then $as_echo "#define CODEC_G722_STATIC 1" >>confdefs.h LDFLAGS="$LDFLAGS $SPANDSP_LDFLAGS $SPANDSP_LIBS" STATIC_CODEC_LIBS="${STATIC_CODEC_LIBS} mp/codecs/plgg722/codec_g722.la" fi ;; auto) # Currently only iLBC in contrib supported if test x_$SPANDSP_CFLAGS != x_; then PLUGINS="${PLUGINS} G.722" G722_TARGET="plgg722" fi ;; yes) # Currently only iLBC in contrib supported if test x_$SPANDSP_CFLAGS != x_; then PLUGINS="${PLUGINS} G.722" G722_TARGET="plgg722" fi ;; no) { $as_echo "$as_me:${as_lineno-$LINENO}: result: Codec G.722 was disabled" >&5 $as_echo "Codec G.722 was disabled" >&6; } ;; *) as_fn_error $? "bad value ${enableval} for --enable-codec-g722" "$LINENO" 5 ;; esac else # Currently only iLBC in contrib supported if test x_$SPANDSP_CFLAGS != x_; then PLUGINS="${PLUGINS} G.722" G722_TARGET="plgg722" fi fi if test ! -z "$G722_TARGET"; then BUILD_CODEC_G722_TRUE= BUILD_CODEC_G722_FALSE='#' else BUILD_CODEC_G722_TRUE='#' BUILD_CODEC_G722_FALSE= fi if test "$CODEC_G722_STATIC" = true; then G722_STATIC_TRUE= G722_STATIC_FALSE='#' else G722_STATIC_TRUE='#' G722_STATIC_FALSE= fi amr_enable=false; # Check whether --enable-codec-amr was given. if test "${enable_codec_amr+set}" = set; then : enableval=$enable_codec_amr; if test ${enableval} = yes; then amr_enable=true; else if test ${enableval} = no; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: Codec AMR was disabled" >&5 $as_echo "Codec AMR was disabled" >&6; } else as_fn_error $? "bad value ${enableval} for --enable-codec-amr" "$LINENO" 5 fi fi else amr_enable=false fi if (test "x$amr_enable" = "xtrue"); then # Currently only iLBC in contrib supported PLUGINS="${PLUGINS} AMR" AMR_TARGET="plgamr" AMRNB_INCLUDE="-I${PWD}/sipXmediaLib/contrib/libamrnb/" AMRNB_LIB_ROOT="${PWD}/sipXmediaLib/contrib/libamrnb/" # amr narrowband codec has it's own configure, # so be sure to call it. subdirs="$subdirs sipXmediaLib/contrib/libamrnb/" fi if test "x$amr_enable" == "xtrue"; then AMRNB_TRUE= AMRNB_FALSE='#' else AMRNB_TRUE='#' AMRNB_FALSE= fi amrwb_enable=false; # Check whether --enable-codec-amrwb was given. if test "${enable_codec_amrwb+set}" = set; then : enableval=$enable_codec_amrwb; if test ${enableval} = yes; then amrwb_enable=true; else if test ${enableval} = no; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: Codec AMRWB was disabled" >&5 $as_echo "Codec AMRWB was disabled" >&6; } else as_fn_error $? "bad value ${enableval} for --enable-codec-amrwb" "$LINENO" 5 fi fi else amrwb_enable=false fi if (test "x$amrwb_enable" = "xtrue"); then # Currently only iLBC in contrib supported PLUGINS="${PLUGINS} AMR-WB" AMRWB_TARGET="plgamrwb" AMRWB_INCLUDE="-I${PWD}/sipXmediaLib/contrib/libamrwb/" AMRWB_LIB_ROOT="${PWD}/sipXmediaLib/contrib/libamrwb/" # amr wideband codec has it's own configure, # so be sure to call it. subdirs="$subdirs sipXmediaLib/contrib/libamrwb/" fi if test "x$amrwb_enable" == "xtrue"; then AMRWB_TRUE= AMRWB_FALSE='#' else AMRWB_TRUE='#' AMRWB_FALSE= fi # Check whether --enable-codec-opus was given. if test "${enable_codec_opus+set}" = set; then : enableval=$enable_codec_opus; case "${enableval}" in static) CODEC_OPUS_STATIC=true PLUGINS="${PLUGINS} OPUS" OPUS_TARGET="plgopus" OPUS_CFLAGS="-I/usr/include/opus" OPUS_LIBS="-lopus" if test "$OPUS_TARGET" != ""; then $as_echo "#define CODEC_OPUS_STATIC 1" >>confdefs.h LDFLAGS="$LDFLAGS" STATIC_CODEC_LIBS="${STATIC_CODEC_LIBS} mp/codecs/plgopus/codec_opus.la" fi ;; auto) PLUGINS="${PLUGINS} OPUS" OPUS_TARGET="plgopus" OPUS_CFLAGS="-I/usr/include/opus" OPUS_LIBS="-lopus" ;; yes) PLUGINS="${PLUGINS} OPUS" OPUS_TARGET="plgopus" OPUS_CFLAGS="-I/usr/include/opus" OPUS_LIBS="-lopus" ;; no) { $as_echo "$as_me:${as_lineno-$LINENO}: result: Codec Opus was disabled" >&5 $as_echo "Codec Opus was disabled" >&6; } ;; *) as_fn_error $? "bad value ${enableval} for --enable-codec-opus" "$LINENO" 5 ;; esac else PLUGINS="${PLUGINS} OPUS" OPUS_TARGET="plgopus" OPUS_CFLAGS="-I/usr/include/opus" OPUS_LIBS="-lopus" fi if test ! -z "$OPUS_TARGET"; then BUILD_CODEC_OPUS_TRUE= BUILD_CODEC_OPUS_FALSE='#' else BUILD_CODEC_OPUS_TRUE='#' BUILD_CODEC_OPUS_FALSE= fi if test "$CODEC_OPUS_STATIC" = true; then OPUS_STATIC_TRUE= OPUS_STATIC_FALSE='#' else OPUS_STATIC_TRUE='#' OPUS_STATIC_FALSE= fi # PCRE is mandatory pkg_failed=no { $as_echo "$as_me:${as_lineno-$LINENO}: checking for DEPS_PCRE" >&5 $as_echo_n "checking for DEPS_PCRE... " >&6; } if test -n "$DEPS_PCRE_CFLAGS"; then pkg_cv_DEPS_PCRE_CFLAGS="$DEPS_PCRE_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libpcre >= 4.5\""; } >&5 ($PKG_CONFIG --exists --print-errors "libpcre >= 4.5") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_DEPS_PCRE_CFLAGS=`$PKG_CONFIG --cflags "libpcre >= 4.5" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$DEPS_PCRE_LIBS"; then pkg_cv_DEPS_PCRE_LIBS="$DEPS_PCRE_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"libpcre >= 4.5\""; } >&5 ($PKG_CONFIG --exists --print-errors "libpcre >= 4.5") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_DEPS_PCRE_LIBS=`$PKG_CONFIG --libs "libpcre >= 4.5" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then DEPS_PCRE_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "libpcre >= 4.5" 2>&1` else DEPS_PCRE_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "libpcre >= 4.5" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$DEPS_PCRE_PKG_ERRORS" >&5 as_fn_error $? "Package requirements (libpcre >= 4.5) were not met: $DEPS_PCRE_PKG_ERRORS Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. Alternatively, you may set the environment variables DEPS_PCRE_CFLAGS and DEPS_PCRE_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details." "$LINENO" 5 elif test $pkg_failed = untried; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "The pkg-config script could not be found or is too old. Make sure it is in your PATH or set the PKG_CONFIG environment variable to the full path to pkg-config. Alternatively, you may set the environment variables DEPS_PCRE_CFLAGS and DEPS_PCRE_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details. To get pkg-config, see . See \`config.log' for more details" "$LINENO" 5; } else DEPS_PCRE_CFLAGS=$pkg_cv_DEPS_PCRE_CFLAGS DEPS_PCRE_LIBS=$pkg_cv_DEPS_PCRE_LIBS { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } fi # OpenSSL is mandatory, find it or configure fails: ac_fn_c_check_header_mongrel "$LINENO" "openssl/ssl.h" "ac_cv_header_openssl_ssl_h" "$ac_includes_default" if test "x$ac_cv_header_openssl_ssl_h" = xyes; then : else ac_fn_c_check_header_compile "$LINENO" "openssl/ssl.h" "ac_cv_header_openssl_ssl_h" "krb5.h " if test "x$ac_cv_header_openssl_ssl_h" = xyes; then : else ac_fn_c_check_header_mongrel "$LINENO" "ssl.h" "ac_cv_header_ssl_h" "$ac_includes_default" if test "x$ac_cv_header_ssl_h" = xyes; then : else ac_fn_c_check_header_compile "$LINENO" "ssl.h" "ac_cv_header_ssl_h" "krb5.h " if test "x$ac_cv_header_ssl_h" = xyes; then : else as_fn_error $? "Failed to find OpenSSL (ssl.h)" "$LINENO" 5 fi fi fi fi CPPFLAGS="${CPPFLAGS} -DHAVE_SSL" # Checks for header files. ac_header_dirent=no for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h; do as_ac_Header=`$as_echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh` { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_hdr that defines DIR" >&5 $as_echo_n "checking for $ac_hdr that defines DIR... " >&6; } if eval \${$as_ac_Header+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include <$ac_hdr> int main () { if ((DIR *) 0) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$as_ac_Header=yes" else eval "$as_ac_Header=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$as_ac_Header { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_hdr" | $as_tr_cpp` 1 _ACEOF ac_header_dirent=$ac_hdr; break fi done # Two versions of opendir et al. are in -ldir and -lx on SCO Xenix. if test $ac_header_dirent = dirent.h; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5 $as_echo_n "checking for library containing opendir... " >&6; } if ${ac_cv_search_opendir+:} false; then : $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char opendir (); int main () { return opendir (); ; return 0; } _ACEOF for ac_lib in '' dir; do if test -z "$ac_lib"; then ac_res="none required" else ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi if ac_fn_c_try_link "$LINENO"; then : ac_cv_search_opendir=$ac_res fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext if ${ac_cv_search_opendir+:} false; then : break fi done if ${ac_cv_search_opendir+:} false; then : else ac_cv_search_opendir=no fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_opendir" >&5 $as_echo "$ac_cv_search_opendir" >&6; } ac_res=$ac_cv_search_opendir if test "$ac_res" != no; then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" fi else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5 $as_echo_n "checking for library containing opendir... " >&6; } if ${ac_cv_search_opendir+:} false; then : $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char opendir (); int main () { return opendir (); ; return 0; } _ACEOF for ac_lib in '' x; do if test -z "$ac_lib"; then ac_res="none required" else ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi if ac_fn_c_try_link "$LINENO"; then : ac_cv_search_opendir=$ac_res fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext if ${ac_cv_search_opendir+:} false; then : break fi done if ${ac_cv_search_opendir+:} false; then : else ac_cv_search_opendir=no fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_opendir" >&5 $as_echo "$ac_cv_search_opendir" >&6; } ac_res=$ac_cv_search_opendir if test "$ac_res" != no; then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 $as_echo_n "checking for ANSI C header files... " >&6; } if ${ac_cv_header_stdc+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_stdc=yes else ac_cv_header_stdc=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "memchr" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "free" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. if test "$cross_compiling" = yes; then : : else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #if ((' ' & 0x0FF) == 0x020) # define ISLOWER(c) ('a' <= (c) && (c) <= 'z') # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else # define ISLOWER(c) \ (('a' <= (c) && (c) <= 'i') \ || ('j' <= (c) && (c) <= 'r') \ || ('s' <= (c) && (c) <= 'z')) # define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif #define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { int i; for (i = 0; i < 256; i++) if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) return 2; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : else ac_cv_header_stdc=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 $as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then $as_echo "#define STDC_HEADERS 1" >>confdefs.h fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for sys/wait.h that is POSIX.1 compatible" >&5 $as_echo_n "checking for sys/wait.h that is POSIX.1 compatible... " >&6; } if ${ac_cv_header_sys_wait_h+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #ifndef WEXITSTATUS # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8) #endif #ifndef WIFEXITED # define WIFEXITED(stat_val) (((stat_val) & 255) == 0) #endif int main () { int s; wait (&s); s = WIFEXITED (s) ? WEXITSTATUS (s) : 1; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_sys_wait_h=yes else ac_cv_header_sys_wait_h=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_sys_wait_h" >&5 $as_echo "$ac_cv_header_sys_wait_h" >&6; } if test $ac_cv_header_sys_wait_h = yes; then $as_echo "#define HAVE_SYS_WAIT_H 1" >>confdefs.h fi for ac_header in arpa/inet.h fcntl.h limits.h malloc.h netdb.h netinet/in.h stdlib.h string.h sys/ioctl.h sys/socket.h sys/time.h unistd.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done # Check CPPUnit - begin # can't be encapsulated as a function due to search path ordering issues # Check whether --with-cppunit-prefix was given. if test "${with_cppunit_prefix+set}" = set; then : withval=$with_cppunit_prefix; cppunit_config_prefix="$withval" else cppunit_config_prefix="" fi # Check whether --with-cppunit-exec-prefix was given. if test "${with_cppunit_exec_prefix+set}" = set; then : withval=$with_cppunit_exec_prefix; cppunit_config_exec_prefix="$withval" else cppunit_config_exec_prefix="" fi if test x$cppunit_config_exec_prefix != x ; then cppunit_config_args="$cppunit_config_args --exec-prefix=$cppunit_config_exec_prefix" if test x${CPPUNIT_CONFIG+set} != xset ; then CPPUNIT_CONFIG=$cppunit_config_exec_prefix/bin/cppunit-config fi fi if test x$cppunit_config_prefix != x ; then cppunit_config_args="$cppunit_config_args --prefix=$cppunit_config_prefix" if test x${CPPUNIT_CONFIG+set} != xset ; then CPPUNIT_CONFIG=$cppunit_config_prefix/bin/cppunit-config fi fi # Extract the first word of "cppunit-config", so it can be a program name with args. set dummy cppunit-config; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_CPPUNIT_CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else case $CPPUNIT_CONFIG in [\\/]* | ?:[\\/]*) ac_cv_path_CPPUNIT_CONFIG="$CPPUNIT_CONFIG" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_CPPUNIT_CONFIG="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS test -z "$ac_cv_path_CPPUNIT_CONFIG" && ac_cv_path_CPPUNIT_CONFIG="no" ;; esac fi CPPUNIT_CONFIG=$ac_cv_path_CPPUNIT_CONFIG if test -n "$CPPUNIT_CONFIG"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPPUNIT_CONFIG" >&5 $as_echo "$CPPUNIT_CONFIG" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi cppunit_version_min=1.9 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Cppunit - version >= $cppunit_version_min" >&5 $as_echo_n "checking for Cppunit - version >= $cppunit_version_min... " >&6; } no_cppunit="" if test "$CPPUNIT_CONFIG" = "no" ; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } no_cppunit=yes else CPPUNIT_CFLAGS=`$CPPUNIT_CONFIG --cflags` CPPUNIT_LIBS=`$CPPUNIT_CONFIG --libs` cppunit_version=`$CPPUNIT_CONFIG --version` cppunit_major_version=`echo $cppunit_version | \ sed 's/\([0-9]*\).\([0-9]*\).\([0-9]*\)/\1/'` cppunit_minor_version=`echo $cppunit_version | \ sed 's/\([0-9]*\).\([0-9]*\).\([0-9]*\)/\2/'` cppunit_micro_version=`echo $cppunit_version | \ sed 's/\([0-9]*\).\([0-9]*\).\([0-9]*\)/\3/'` cppunit_major_min=`echo $cppunit_version_min | \ sed 's/\([0-9]*\).\([0-9]*\).\([0-9]*\)/\1/'` if test "x${cppunit_major_min}" = "x" ; then cppunit_major_min=0 fi cppunit_minor_min=`echo $cppunit_version_min | \ sed 's/\([0-9]*\).\([0-9]*\).\([0-9]*\)/\2/'` if test "x${cppunit_minor_min}" = "x" ; then cppunit_minor_min=0 fi cppunit_micro_min=`echo $cppunit_version_min | \ sed 's/\([0-9]*\).\([0-9]*\).\([0-9]*\)/\3/'` if test "x${cppunit_micro_min}" = "x" ; then cppunit_micro_min=0 fi cppunit_version_proper=`expr \ $cppunit_major_version \> $cppunit_major_min \| \ $cppunit_major_version \= $cppunit_major_min \& \ $cppunit_minor_version \> $cppunit_minor_min \| \ $cppunit_major_version \= $cppunit_major_min \& \ $cppunit_minor_version \= $cppunit_minor_min \& \ $cppunit_micro_version \>= $cppunit_micro_min ` if test "$cppunit_version_proper" = "1" ; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cppunit_major_version.$cppunit_minor_version.$cppunit_micro_version" >&5 $as_echo "$cppunit_major_version.$cppunit_minor_version.$cppunit_micro_version" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } no_cppunit=yes fi fi if test "x$no_cppunit" = x ; then SIPX_UNIT_TARGET="sipxunit" else CPPUNIT_CFLAGS="" CPPUNIT_LIBS="" SIPX_UNIT_TARGET="sipxportunit" CPPUNIT_CFLAGS=' -DNO_CPPUNIT -I$(top_srcdir)/sipXportLib/src/test/sipxportunit ' { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \"cppunit not found\"" >&5 $as_echo "$as_me: WARNING: \"cppunit not found\"" >&2;} fi if test "x$SIPX_UNIT_TARGET" == "xsipxunit" ; then BUILD_SIPXUNIT_TRUE= BUILD_SIPXUNIT_FALSE='#' else BUILD_SIPXUNIT_TRUE='#' BUILD_SIPXUNIT_FALSE= fi if test "x$SIPX_UNIT_TARGET" == "xsipxportunit" ; then BUILD_SIPXPORTUNIT_TRUE= BUILD_SIPXPORTUNIT_FALSE='#' else BUILD_SIPXPORTUNIT_TRUE='#' BUILD_SIPXPORTUNIT_FALSE= fi # Check CPPUnit - end # Checks for typedefs, structures, and compiler characteristics. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for stdbool.h that conforms to C99" >&5 $as_echo_n "checking for stdbool.h that conforms to C99... " >&6; } if ${ac_cv_header_stdbool_h+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #ifndef bool "error: bool is not defined" #endif #ifndef false "error: false is not defined" #endif #if false "error: false is not 0" #endif #ifndef true "error: true is not defined" #endif #if true != 1 "error: true is not 1" #endif #ifndef __bool_true_false_are_defined "error: __bool_true_false_are_defined is not defined" #endif struct s { _Bool s: 1; _Bool t; } s; char a[true == 1 ? 1 : -1]; char b[false == 0 ? 1 : -1]; char c[__bool_true_false_are_defined == 1 ? 1 : -1]; char d[(bool) 0.5 == true ? 1 : -1]; /* See body of main program for 'e'. */ char f[(_Bool) 0.0 == false ? 1 : -1]; char g[true]; char h[sizeof (_Bool)]; char i[sizeof s.t]; enum { j = false, k = true, l = false * true, m = true * 256 }; /* The following fails for HP aC++/ANSI C B3910B A.05.55 [Dec 04 2003]. */ _Bool n[m]; char o[sizeof n == m * sizeof n[0] ? 1 : -1]; char p[-1 - (_Bool) 0 < 0 && -1 - (bool) 0 < 0 ? 1 : -1]; /* Catch a bug in an HP-UX C compiler. See http://gcc.gnu.org/ml/gcc-patches/2003-12/msg02303.html http://lists.gnu.org/archive/html/bug-coreutils/2005-11/msg00161.html */ _Bool q = true; _Bool *pq = &q; int main () { bool e = &s; *pq |= q; *pq |= ! q; /* Refer to every declared value, to avoid compiler optimizations. */ return (!a + !b + !c + !d + !e + !f + !g + !h + !i + !!j + !k + !!l + !m + !n + !o + !p + !q + !pq); ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_stdbool_h=yes else ac_cv_header_stdbool_h=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdbool_h" >&5 $as_echo "$ac_cv_header_stdbool_h" >&6; } ac_fn_c_check_type "$LINENO" "_Bool" "ac_cv_type__Bool" "$ac_includes_default" if test "x$ac_cv_type__Bool" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE__BOOL 1 _ACEOF fi if test $ac_cv_header_stdbool_h = yes; then $as_echo "#define HAVE_STDBOOL_H 1" >>confdefs.h fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5 $as_echo_n "checking for an ANSI C-conforming const... " >&6; } if ${ac_cv_c_const+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __cplusplus /* Ultrix mips cc rejects this sort of thing. */ typedef int charset[2]; const charset cs = { 0, 0 }; /* SunOS 4.1.1 cc rejects this. */ char const *const *pcpcc; char **ppc; /* NEC SVR4.0.2 mips cc rejects this. */ struct point {int x, y;}; static struct point const zero = {0,0}; /* AIX XL C 1.02.0.0 rejects this. It does not let you subtract one const X* pointer from another in an arm of an if-expression whose if-part is not a constant expression */ const char *g = "string"; pcpcc = &g + (g ? g-g : 0); /* HPUX 7.0 cc rejects these. */ ++pcpcc; ppc = (char**) pcpcc; pcpcc = (char const *const *) ppc; { /* SCO 3.2v4 cc rejects this sort of thing. */ char tx; char *t = &tx; char const *s = 0 ? (char *) 0 : (char const *) 0; *t++ = 0; if (s) return 0; } { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ int x[] = {25, 17}; const int *foo = &x[0]; ++foo; } { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ typedef const int *iptr; iptr p = 0; ++p; } { /* AIX XL C 1.02.0.0 rejects this sort of thing, saying "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ struct s { int j; const int *ap[3]; } bx; struct s *b = &bx; b->j = 5; } { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ const int foo = 10; if (!foo) return 0; } return !cs[0] && !zero.x; #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_const=yes else ac_cv_c_const=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5 $as_echo "$ac_cv_c_const" >&6; } if test $ac_cv_c_const = no; then $as_echo "#define const /**/" >>confdefs.h fi ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default" if test "x$ac_cv_type_size_t" = xyes; then : else cat >>confdefs.h <<_ACEOF #define size_t unsigned int _ACEOF fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether time.h and sys/time.h may both be included" >&5 $as_echo_n "checking whether time.h and sys/time.h may both be included... " >&6; } if ${ac_cv_header_time+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include int main () { if ((struct tm *) 0) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_time=yes else ac_cv_header_time=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_time" >&5 $as_echo "$ac_cv_header_time" >&6; } if test $ac_cv_header_time = yes; then $as_echo "#define TIME_WITH_SYS_TIME 1" >>confdefs.h fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether struct tm is in sys/time.h or time.h" >&5 $as_echo_n "checking whether struct tm is in sys/time.h or time.h... " >&6; } if ${ac_cv_struct_tm+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main () { struct tm tm; int *p = &tm.tm_sec; return !p; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_struct_tm=time.h else ac_cv_struct_tm=sys/time.h fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_struct_tm" >&5 $as_echo "$ac_cv_struct_tm" >&6; } if test $ac_cv_struct_tm = sys/time.h; then $as_echo "#define TM_IN_SYS_TIME 1" >>confdefs.h fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for uid_t in sys/types.h" >&5 $as_echo_n "checking for uid_t in sys/types.h... " >&6; } if ${ac_cv_type_uid_t+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "uid_t" >/dev/null 2>&1; then : ac_cv_type_uid_t=yes else ac_cv_type_uid_t=no fi rm -f conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_uid_t" >&5 $as_echo "$ac_cv_type_uid_t" >&6; } if test $ac_cv_type_uid_t = no; then $as_echo "#define uid_t int" >>confdefs.h $as_echo "#define gid_t int" >>confdefs.h fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for working volatile" >&5 $as_echo_n "checking for working volatile... " >&6; } if ${ac_cv_c_volatile+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { volatile int x; int * volatile y = (int *) 0; return !x && !y; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_volatile=yes else ac_cv_c_volatile=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_volatile" >&5 $as_echo "$ac_cv_c_volatile" >&6; } if test $ac_cv_c_volatile = no; then $as_echo "#define volatile /**/" >>confdefs.h fi # Checks for library functions. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether closedir returns void" >&5 $as_echo_n "checking whether closedir returns void... " >&6; } if ${ac_cv_func_closedir_void+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : ac_cv_func_closedir_void=yes else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default #include <$ac_header_dirent> #ifndef __cplusplus int closedir (); #endif int main () { return closedir (opendir (".")) != 0; ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : ac_cv_func_closedir_void=no else ac_cv_func_closedir_void=yes fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_closedir_void" >&5 $as_echo "$ac_cv_func_closedir_void" >&6; } if test $ac_cv_func_closedir_void = yes; then $as_echo "#define CLOSEDIR_VOID 1" >>confdefs.h fi ac_fn_c_check_type "$LINENO" "pid_t" "ac_cv_type_pid_t" "$ac_includes_default" if test "x$ac_cv_type_pid_t" = xyes; then : else cat >>confdefs.h <<_ACEOF #define pid_t int _ACEOF fi for ac_header in vfork.h do : ac_fn_c_check_header_mongrel "$LINENO" "vfork.h" "ac_cv_header_vfork_h" "$ac_includes_default" if test "x$ac_cv_header_vfork_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_VFORK_H 1 _ACEOF fi done for ac_func in fork vfork do : as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" if eval test \"x\$"$as_ac_var"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi done if test "x$ac_cv_func_fork" = xyes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for working fork" >&5 $as_echo_n "checking for working fork... " >&6; } if ${ac_cv_func_fork_works+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : ac_cv_func_fork_works=cross else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int main () { /* By Ruediger Kuhlmann. */ return fork () < 0; ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : ac_cv_func_fork_works=yes else ac_cv_func_fork_works=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_fork_works" >&5 $as_echo "$ac_cv_func_fork_works" >&6; } else ac_cv_func_fork_works=$ac_cv_func_fork fi if test "x$ac_cv_func_fork_works" = xcross; then case $host in *-*-amigaos* | *-*-msdosdjgpp*) # Override, as these systems have only a dummy fork() stub ac_cv_func_fork_works=no ;; *) ac_cv_func_fork_works=yes ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: result $ac_cv_func_fork_works guessed because of cross compilation" >&5 $as_echo "$as_me: WARNING: result $ac_cv_func_fork_works guessed because of cross compilation" >&2;} fi ac_cv_func_vfork_works=$ac_cv_func_vfork if test "x$ac_cv_func_vfork" = xyes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for working vfork" >&5 $as_echo_n "checking for working vfork... " >&6; } if ${ac_cv_func_vfork_works+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : ac_cv_func_vfork_works=cross else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Thanks to Paul Eggert for this test. */ $ac_includes_default #include #ifdef HAVE_VFORK_H # include #endif /* On some sparc systems, changes by the child to local and incoming argument registers are propagated back to the parent. The compiler is told about this with #include , but some compilers (e.g. gcc -O) don't grok . Test for this by using a static variable whose address is put into a register that is clobbered by the vfork. */ static void #ifdef __cplusplus sparc_address_test (int arg) # else sparc_address_test (arg) int arg; #endif { static pid_t child; if (!child) { child = vfork (); if (child < 0) { perror ("vfork"); _exit(2); } if (!child) { arg = getpid(); write(-1, "", 0); _exit (arg); } } } int main () { pid_t parent = getpid (); pid_t child; sparc_address_test (0); child = vfork (); if (child == 0) { /* Here is another test for sparc vfork register problems. This test uses lots of local variables, at least as many local variables as main has allocated so far including compiler temporaries. 4 locals are enough for gcc 1.40.3 on a Solaris 4.1.3 sparc, but we use 8 to be safe. A buggy compiler should reuse the register of parent for one of the local variables, since it will think that parent can't possibly be used any more in this routine. Assigning to the local variable will thus munge parent in the parent process. */ pid_t p = getpid(), p1 = getpid(), p2 = getpid(), p3 = getpid(), p4 = getpid(), p5 = getpid(), p6 = getpid(), p7 = getpid(); /* Convince the compiler that p..p7 are live; otherwise, it might use the same hardware register for all 8 local variables. */ if (p != p1 || p != p2 || p != p3 || p != p4 || p != p5 || p != p6 || p != p7) _exit(1); /* On some systems (e.g. IRIX 3.3), vfork doesn't separate parent from child file descriptors. If the child closes a descriptor before it execs or exits, this munges the parent's descriptor as well. Test for this by closing stdout in the child. */ _exit(close(fileno(stdout)) != 0); } else { int status; struct stat st; while (wait(&status) != child) ; return ( /* Was there some problem with vforking? */ child < 0 /* Did the child fail? (This shouldn't happen.) */ || status /* Did the vfork/compiler bug occur? */ || parent != getpid() /* Did the file descriptor bug occur? */ || fstat(fileno(stdout), &st) != 0 ); } } _ACEOF if ac_fn_c_try_run "$LINENO"; then : ac_cv_func_vfork_works=yes else ac_cv_func_vfork_works=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_vfork_works" >&5 $as_echo "$ac_cv_func_vfork_works" >&6; } fi; if test "x$ac_cv_func_fork_works" = xcross; then ac_cv_func_vfork_works=$ac_cv_func_vfork { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: result $ac_cv_func_vfork_works guessed because of cross compilation" >&5 $as_echo "$as_me: WARNING: result $ac_cv_func_vfork_works guessed because of cross compilation" >&2;} fi if test "x$ac_cv_func_vfork_works" = xyes; then $as_echo "#define HAVE_WORKING_VFORK 1" >>confdefs.h else $as_echo "#define vfork fork" >>confdefs.h fi if test "x$ac_cv_func_fork_works" = xyes; then $as_echo "#define HAVE_WORKING_FORK 1" >>confdefs.h fi if test $ac_cv_c_compiler_gnu = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC needs -traditional" >&5 $as_echo_n "checking whether $CC needs -traditional... " >&6; } if ${ac_cv_prog_gcc_traditional+:} false; then : $as_echo_n "(cached) " >&6 else ac_pattern="Autoconf.*'x'" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include Autoconf TIOCGETP _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "$ac_pattern" >/dev/null 2>&1; then : ac_cv_prog_gcc_traditional=yes else ac_cv_prog_gcc_traditional=no fi rm -f conftest* if test $ac_cv_prog_gcc_traditional = no; then cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include Autoconf TCGETA _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "$ac_pattern" >/dev/null 2>&1; then : ac_cv_prog_gcc_traditional=yes fi rm -f conftest* fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_gcc_traditional" >&5 $as_echo "$ac_cv_prog_gcc_traditional" >&6; } if test $ac_cv_prog_gcc_traditional = yes; then CC="$CC -traditional" fi fi for ac_header in stdlib.h do : ac_fn_c_check_header_mongrel "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" "$ac_includes_default" if test "x$ac_cv_header_stdlib_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_STDLIB_H 1 _ACEOF fi done { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible malloc" >&5 $as_echo_n "checking for GNU libc compatible malloc... " >&6; } if ${ac_cv_func_malloc_0_nonnull+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : ac_cv_func_malloc_0_nonnull=no else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #if defined STDC_HEADERS || defined HAVE_STDLIB_H # include #else char *malloc (); #endif int main () { return ! malloc (0); ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : ac_cv_func_malloc_0_nonnull=yes else ac_cv_func_malloc_0_nonnull=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_malloc_0_nonnull" >&5 $as_echo "$ac_cv_func_malloc_0_nonnull" >&6; } if test $ac_cv_func_malloc_0_nonnull = yes; then : $as_echo "#define HAVE_MALLOC 1" >>confdefs.h else $as_echo "#define HAVE_MALLOC 0" >>confdefs.h case " $LIBOBJS " in *" malloc.$ac_objext "* ) ;; *) LIBOBJS="$LIBOBJS malloc.$ac_objext" ;; esac $as_echo "#define malloc rpl_malloc" >>confdefs.h fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for working memcmp" >&5 $as_echo_n "checking for working memcmp... " >&6; } if ${ac_cv_func_memcmp_working+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : ac_cv_func_memcmp_working=no else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int main () { /* Some versions of memcmp are not 8-bit clean. */ char c0 = '\100', c1 = '\200', c2 = '\201'; if (memcmp(&c0, &c2, 1) >= 0 || memcmp(&c1, &c2, 1) >= 0) return 1; /* The Next x86 OpenStep bug shows up only when comparing 16 bytes or more and with at least one buffer not starting on a 4-byte boundary. William Lewis provided this test program. */ { char foo[21]; char bar[21]; int i; for (i = 0; i < 4; i++) { char *a = foo + i; char *b = bar + i; strcpy (a, "--------01111111"); strcpy (b, "--------10000000"); if (memcmp (a, b, 16) >= 0) return 1; } return 0; } ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : ac_cv_func_memcmp_working=yes else ac_cv_func_memcmp_working=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_memcmp_working" >&5 $as_echo "$ac_cv_func_memcmp_working" >&6; } test $ac_cv_func_memcmp_working = no && case " $LIBOBJS " in *" memcmp.$ac_objext "* ) ;; *) LIBOBJS="$LIBOBJS memcmp.$ac_objext" ;; esac for ac_header in $ac_header_list do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default " if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done for ac_func in $ac_func_list do : as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" if eval test \"x\$"$as_ac_var"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi done { $as_echo "$as_me:${as_lineno-$LINENO}: checking for working mktime" >&5 $as_echo_n "checking for working mktime... " >&6; } if ${ac_cv_func_working_mktime+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : ac_cv_func_working_mktime=no else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Test program from Paul Eggert and Tony Leneis. */ #ifdef TIME_WITH_SYS_TIME # include # include #else # ifdef HAVE_SYS_TIME_H # include # else # include # endif #endif #include #include #ifdef HAVE_UNISTD_H # include #endif #ifndef HAVE_ALARM # define alarm(X) /* empty */ #endif /* Work around redefinition to rpl_putenv by other config tests. */ #undef putenv static time_t time_t_max; static time_t time_t_min; /* Values we'll use to set the TZ environment variable. */ static const char *tz_strings[] = { (const char *) 0, "TZ=GMT0", "TZ=JST-9", "TZ=EST+3EDT+2,M10.1.0/00:00:00,M2.3.0/00:00:00" }; #define N_STRINGS (sizeof (tz_strings) / sizeof (tz_strings[0])) /* Return 0 if mktime fails to convert a date in the spring-forward gap. Based on a problem report from Andreas Jaeger. */ static int spring_forward_gap () { /* glibc (up to about 1998-10-07) failed this test. */ struct tm tm; /* Use the portable POSIX.1 specification "TZ=PST8PDT,M4.1.0,M10.5.0" instead of "TZ=America/Vancouver" in order to detect the bug even on systems that don't support the Olson extension, or don't have the full zoneinfo tables installed. */ putenv ((char*) "TZ=PST8PDT,M4.1.0,M10.5.0"); tm.tm_year = 98; tm.tm_mon = 3; tm.tm_mday = 5; tm.tm_hour = 2; tm.tm_min = 0; tm.tm_sec = 0; tm.tm_isdst = -1; return mktime (&tm) != (time_t) -1; } static int mktime_test1 (time_t now) { struct tm *lt; return ! (lt = localtime (&now)) || mktime (lt) == now; } static int mktime_test (time_t now) { return (mktime_test1 (now) && mktime_test1 ((time_t) (time_t_max - now)) && mktime_test1 ((time_t) (time_t_min + now))); } static int irix_6_4_bug () { /* Based on code from Ariel Faigon. */ struct tm tm; tm.tm_year = 96; tm.tm_mon = 3; tm.tm_mday = 0; tm.tm_hour = 0; tm.tm_min = 0; tm.tm_sec = 0; tm.tm_isdst = -1; mktime (&tm); return tm.tm_mon == 2 && tm.tm_mday == 31; } static int bigtime_test (int j) { struct tm tm; time_t now; tm.tm_year = tm.tm_mon = tm.tm_mday = tm.tm_hour = tm.tm_min = tm.tm_sec = j; now = mktime (&tm); if (now != (time_t) -1) { struct tm *lt = localtime (&now); if (! (lt && lt->tm_year == tm.tm_year && lt->tm_mon == tm.tm_mon && lt->tm_mday == tm.tm_mday && lt->tm_hour == tm.tm_hour && lt->tm_min == tm.tm_min && lt->tm_sec == tm.tm_sec && lt->tm_yday == tm.tm_yday && lt->tm_wday == tm.tm_wday && ((lt->tm_isdst < 0 ? -1 : 0 < lt->tm_isdst) == (tm.tm_isdst < 0 ? -1 : 0 < tm.tm_isdst)))) return 0; } return 1; } static int year_2050_test () { /* The correct answer for 2050-02-01 00:00:00 in Pacific time, ignoring leap seconds. */ unsigned long int answer = 2527315200UL; struct tm tm; time_t t; tm.tm_year = 2050 - 1900; tm.tm_mon = 2 - 1; tm.tm_mday = 1; tm.tm_hour = tm.tm_min = tm.tm_sec = 0; tm.tm_isdst = -1; /* Use the portable POSIX.1 specification "TZ=PST8PDT,M4.1.0,M10.5.0" instead of "TZ=America/Vancouver" in order to detect the bug even on systems that don't support the Olson extension, or don't have the full zoneinfo tables installed. */ putenv ((char*) "TZ=PST8PDT,M4.1.0,M10.5.0"); t = mktime (&tm); /* Check that the result is either a failure, or close enough to the correct answer that we can assume the discrepancy is due to leap seconds. */ return (t == (time_t) -1 || (0 < t && answer - 120 <= t && t <= answer + 120)); } int main () { time_t t, delta; int i, j; /* This test makes some buggy mktime implementations loop. Give up after 60 seconds; a mktime slower than that isn't worth using anyway. */ alarm (60); for (;;) { t = (time_t_max << 1) + 1; if (t <= time_t_max) break; time_t_max = t; } time_t_min = - ((time_t) ~ (time_t) 0 == (time_t) -1) - time_t_max; delta = time_t_max / 997; /* a suitable prime number */ for (i = 0; i < N_STRINGS; i++) { if (tz_strings[i]) putenv ((char*) tz_strings[i]); for (t = 0; t <= time_t_max - delta; t += delta) if (! mktime_test (t)) return 1; if (! (mktime_test ((time_t) 1) && mktime_test ((time_t) (60 * 60)) && mktime_test ((time_t) (60 * 60 * 24)))) return 1; for (j = 1; ; j <<= 1) if (! bigtime_test (j)) return 1; else if (INT_MAX / 2 < j) break; if (! bigtime_test (INT_MAX)) return 1; } return ! (irix_6_4_bug () && spring_forward_gap () && year_2050_test ()); } _ACEOF if ac_fn_c_try_run "$LINENO"; then : ac_cv_func_working_mktime=yes else ac_cv_func_working_mktime=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_working_mktime" >&5 $as_echo "$ac_cv_func_working_mktime" >&6; } if test $ac_cv_func_working_mktime = no; then case " $LIBOBJS " in *" mktime.$ac_objext "* ) ;; *) LIBOBJS="$LIBOBJS mktime.$ac_objext" ;; esac fi for ac_header in sys/select.h sys/socket.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done { $as_echo "$as_me:${as_lineno-$LINENO}: checking types of arguments for select" >&5 $as_echo_n "checking types of arguments for select... " >&6; } if ${ac_cv_func_select_args+:} false; then : $as_echo_n "(cached) " >&6 else for ac_arg234 in 'fd_set *' 'int *' 'void *'; do for ac_arg1 in 'int' 'size_t' 'unsigned long int' 'unsigned int'; do for ac_arg5 in 'struct timeval *' 'const struct timeval *'; do cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default #ifdef HAVE_SYS_SELECT_H # include #endif #ifdef HAVE_SYS_SOCKET_H # include #endif int main () { extern int select ($ac_arg1, $ac_arg234, $ac_arg234, $ac_arg234, $ac_arg5); ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_func_select_args="$ac_arg1,$ac_arg234,$ac_arg5"; break 3 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done done done # Provide a safe default value. : "${ac_cv_func_select_args=int,int *,struct timeval *}" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_select_args" >&5 $as_echo "$ac_cv_func_select_args" >&6; } ac_save_IFS=$IFS; IFS=',' set dummy `echo "$ac_cv_func_select_args" | sed 's/\*/\*/g'` IFS=$ac_save_IFS shift cat >>confdefs.h <<_ACEOF #define SELECT_TYPE_ARG1 $1 _ACEOF cat >>confdefs.h <<_ACEOF #define SELECT_TYPE_ARG234 ($2) _ACEOF cat >>confdefs.h <<_ACEOF #define SELECT_TYPE_ARG5 ($3) _ACEOF rm -f conftest* { $as_echo "$as_me:${as_lineno-$LINENO}: checking return type of signal handlers" >&5 $as_echo_n "checking return type of signal handlers... " >&6; } if ${ac_cv_type_signal+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main () { return *(signal (0, 0)) (0) == 1; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_type_signal=int else ac_cv_type_signal=void fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_signal" >&5 $as_echo "$ac_cv_type_signal" >&6; } cat >>confdefs.h <<_ACEOF #define RETSIGTYPE $ac_cv_type_signal _ACEOF { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether lstat correctly handles trailing slash" >&5 $as_echo_n "checking whether lstat correctly handles trailing slash... " >&6; } if ${ac_cv_func_lstat_dereferences_slashed_symlink+:} false; then : $as_echo_n "(cached) " >&6 else rm -f conftest.sym conftest.file echo >conftest.file if test "$as_ln_s" = "ln -s" && ln -s conftest.file conftest.sym; then if test "$cross_compiling" = yes; then : ac_cv_func_lstat_dereferences_slashed_symlink=no else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int main () { struct stat sbuf; /* Linux will dereference the symlink and fail, as required by POSIX. That is better in the sense that it means we will not have to compile and use the lstat wrapper. */ return lstat ("conftest.sym/", &sbuf) == 0; ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : ac_cv_func_lstat_dereferences_slashed_symlink=yes else ac_cv_func_lstat_dereferences_slashed_symlink=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi else # If the `ln -s' command failed, then we probably don't even # have an lstat function. ac_cv_func_lstat_dereferences_slashed_symlink=no fi rm -f conftest.sym conftest.file fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_lstat_dereferences_slashed_symlink" >&5 $as_echo "$ac_cv_func_lstat_dereferences_slashed_symlink" >&6; } test $ac_cv_func_lstat_dereferences_slashed_symlink = yes && cat >>confdefs.h <<_ACEOF #define LSTAT_FOLLOWS_SLASHED_SYMLINK 1 _ACEOF if test "x$ac_cv_func_lstat_dereferences_slashed_symlink" = xno; then case " $LIBOBJS " in *" lstat.$ac_objext "* ) ;; *) LIBOBJS="$LIBOBJS lstat.$ac_objext" ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stat accepts an empty string" >&5 $as_echo_n "checking whether stat accepts an empty string... " >&6; } if ${ac_cv_func_stat_empty_string_bug+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : ac_cv_func_stat_empty_string_bug=yes else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int main () { struct stat sbuf; return stat ("", &sbuf) == 0; ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : ac_cv_func_stat_empty_string_bug=no else ac_cv_func_stat_empty_string_bug=yes fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_stat_empty_string_bug" >&5 $as_echo "$ac_cv_func_stat_empty_string_bug" >&6; } if test $ac_cv_func_stat_empty_string_bug = yes; then case " $LIBOBJS " in *" stat.$ac_objext "* ) ;; *) LIBOBJS="$LIBOBJS stat.$ac_objext" ;; esac cat >>confdefs.h <<_ACEOF #define HAVE_STAT_EMPTY_STRING_BUG 1 _ACEOF fi for ac_func in strftime do : ac_fn_c_check_func "$LINENO" "strftime" "ac_cv_func_strftime" if test "x$ac_cv_func_strftime" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_STRFTIME 1 _ACEOF else # strftime is in -lintl on SCO UNIX. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for strftime in -lintl" >&5 $as_echo_n "checking for strftime in -lintl... " >&6; } if ${ac_cv_lib_intl_strftime+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lintl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char strftime (); int main () { return strftime (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_intl_strftime=yes else ac_cv_lib_intl_strftime=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_intl_strftime" >&5 $as_echo "$ac_cv_lib_intl_strftime" >&6; } if test "x$ac_cv_lib_intl_strftime" = xyes; then : $as_echo "#define HAVE_STRFTIME 1" >>confdefs.h LIBS="-lintl $LIBS" fi fi done for ac_func in clock_gettime getcwd gethostbyname gethostname gettimeofday inet_ntoa localtime_r memchr memset mkdir putenv rmdir select setenv socket strchr strdup strerror strrchr strstr strtol strtoul tzset do : as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" if eval test \"x\$"$as_ac_var"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi done # Check for toplogy flowgraph interface # Check whether --enable-topology-graph was given. if test "${enable_topology_graph+set}" = set; then : enableval=$enable_topology_graph; case "${enableval}" in yes) INTERFACE_FLAGS=" -DENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY " INTERFACE_FLAGS+="-DDISABLE_DEFAULT_PHONE_MEDIA_INTERFACE_FACTORY " ;; no) INTERFACE_FLAGS=" " ;; *) as_fn_error $? "bad value ${enableval} for --enable-topology-graph" "$LINENO" 5 ;; esac else enableval= fi # SPEEX detection and configuration code inside general.m4 cannot do # sub-configure with AC_CONFIG_SUBDIRS, since it would be called more # than once, so do it here, where we know it only happens once. #if test "x$contrib_speex_enabled" == "xyes"; then # # speex codec has it's own configure, so be sure to call it. # AC_CONFIG_SUBDIRS([contrib/libspeex]) #fi # Specify a SPEEX_CONTRIB make variable conditional upon using contrib speex. if test "x$contrib_speex_enabled" == "xyes"; then SPEEX_CONTRIB_TRUE= SPEEX_CONTRIB_FALSE='#' else SPEEX_CONTRIB_TRUE='#' SPEEX_CONTRIB_FALSE= fi # declaring other codecs staff codeclibdir='${pkglibdir}/codecs' CPPFLAGS="${CPPFLAGS} -DDEFAULT_CODECS_PATH='\"${codeclibdir}\"' " # Check stream player setting # Check whether --enable-stream-player was given. if test "${enable_stream_player+set}" = set; then : enableval=$enable_stream_player; case "${enableval}" in no) disable_stream_player=true ;; yes) disable_stream_player=false ;; *) as_fn_error $? "bad value ${enableval} for --disable-media-player" "$LINENO" 5 ;; esac else disable_stream_player=false fi if test x$disable_stream_player = xtrue; then DISABLE_STREAM_PLAYER_TRUE= DISABLE_STREAM_PLAYER_FALSE='#' else DISABLE_STREAM_PLAYER_TRUE='#' DISABLE_STREAM_PLAYER_FALSE= fi if test ${disable_stream_player} = true; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: Stream player is disabled" >&5 $as_echo "Stream player is disabled" >&6; } CXXFLAGS+=" -DDISABLE_STREAM_PLAYER " fi ## TODO Remove cpu specifics and use make variables setup for this ## ## NOTES: ## -D__pingtel_on_posix__ - really used for linux v.s. other ## -D_REENTRANT - rougewave ? ## -fmessage-length=0 - ? ## SIPX_INCDIR=${includedir} SIPX_LIBDIR=${libdir} # Autoconf already provides a built-in abs_srcdir substitution, however, # while it specifies a root-directory rooted path, it can have relative # parts in the middle of it. For Doxygen STRIP_FROM_PATH, I need a full, # path to the project directory, without any relative bits at all. # Thus, sipx_abs_srcdir was conceived. abs_srcdir=`cd $srcdir && pwd` sipx_abs_srcdir=${abs_srcdir} SF_CXX_C_FLAGS="-D__pingtel_on_posix__ -D_linux_ -D_REENTRANT -D_FILE_OFFSET_BITS=64 -fmessage-length=0" SF_CXX_WARNINGS="-Wall -Wformat -Wwrite-strings -Wpointer-arith" CXXFLAGS="$CXXFLAGS $SF_CXX_C_FLAGS $SF_CXX_WARNINGS" CFLAGS="$CFLAGS $SF_CXX_C_FLAGS $SF_CXX_WARNINGS -Wnested-externs -Wmissing-declarations -Wmissing-prototypes" ## NOTE: These are not expanded (e.g. contain $(prefix)) and are only ## fit for Makefiles. You can however write a Makefile that transforms ## *.in to * with the concrete values. ## ## See sipXconfig/Makefile.am for an example. ## See autoconf manual 4.7.2 Installation Directory Variables for why it's restricted ## SIPX_BINDIR=${bindir} SIPX_CONFDIR=${sysconfdir}/sipxpbx SIPX_DATADIR=${datadir}/sipxpbx SIPX_LOGDIR=${localstatedir}/log/sipxpbx SIPX_RUNDIR=${localstatedir}/run/sipxpbx SIPX_TMPDIR=${localstatedir}/tmp SIPX_DBDIR=${localstatedir}/sipxdata/sipdb SIPX_SCHEMADIR=${datadir}/sipx/schema SIPX_DOCDIR=${datadir}/doc/sipx # temporary - see http://track.sipfoundry.org/browse/XPB-33 SIPX_VXMLDATADIR=${localstatedir}/sipxdata/mediaserver/data SIPX_PARKMUSICDIR=${localstatedir}/sipxdata/parkserver/music # temporary - see http://track.sipfoundry.org/browse/XPB-93 SIPX_BACKUPDIR=${localstatedir}/sipxdata/backup SIPX_CONFIGPHONEDIR=${localstatedir}/sipxdata/configserver/phone ## Used in a number of different project and subjective where this should really go ## INSTALL instruction assume default, otherwise safe to change/override test -z $wwwdir && wwwdir='${datadir}/www' test -z $SIPXPBXUSER && SIPXPBXUSER=sipxchange SIPXPHONECONF=${sysconfdir}/sipxphone SIPXPHONEDATA=${datadir}/sipxphone SIPXPHONELIB=${datadir}/sipxphone/lib # Check whether --enable-rpmbuild was given. if test "${enable_rpmbuild+set}" = set; then : enableval=$enable_rpmbuild; enable_rpmbuild=yes fi # Check whether --enable-buildnumber was given. if test "${enable_buildnumber+set}" = set; then : enableval=$enable_buildnumber; enable_buildnumber=yes fi # Check whether --enable-sip-tls was given. if test "${enable_sip_tls+set}" = set; then : enableval=$enable_sip_tls; else enable_sip_tls=no fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking Support for SIP over TLS" >&5 $as_echo_n "checking Support for SIP over TLS... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${enable_sip_tls}" >&5 $as_echo "${enable_sip_tls}" >&6; } if test "${enable_sip_tls}" = "yes" then CFLAGS="-DSIP_TLS $CFLAGS" CXXFLAGS="-DSIP_TLS $CXXFLAGS" fi if test x$enable_sip_tls = xyes; then BUILDTLS_TRUE= BUILDTLS_FALSE='#' else BUILDTLS_TRUE='#' BUILDTLS_FALSE= fi # Enable local audio support (microphone / speaker) # Check whether --enable-local-audio was given. if test "${enable_local_audio+set}" = set; then : enableval=$enable_local_audio; case "${enableval}" in yes) enable_local_audio=true ;; no) enable_local_audio=false ;; *) as_fn_error $? "bad value ${enableval} for --enable-local-audio" "$LINENO" 5 ;; esac else enable_local_audio=false fi if test x$enable_local_audio = xtrue; then ENABLE_LOCAL_AUDIO_TRUE= ENABLE_LOCAL_AUDIO_FALSE='#' else ENABLE_LOCAL_AUDIO_TRUE='#' ENABLE_LOCAL_AUDIO_FALSE= fi # Check whether --enable-doxygen was given. if test "${enable_doxygen+set}" = set; then : enableval=$enable_doxygen; else enable_doxygen=yes fi # Check whether --enable-dot was given. if test "${enable_dot+set}" = set; then : enableval=$enable_dot; fi # Check whether --enable-html-docs was given. if test "${enable_html_docs+set}" = set; then : enableval=$enable_html_docs; else enable_html_docs=yes fi # Check whether --enable-latex-docs was given. if test "${enable_latex_docs+set}" = set; then : enableval=$enable_latex_docs; else enable_latex_docs=no fi if test "x$enable_doxygen" = xno; then enable_doc=no else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for doxygen documentation processor" >&5 $as_echo_n "checking for doxygen documentation processor... " >&6; } # Extract the first word of "doxygen", so it can be a program name with args. set dummy doxygen; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_DOXYGEN+:} false; then : $as_echo_n "(cached) " >&6 else case $DOXYGEN in [\\/]* | ?:[\\/]*) ac_cv_path_DOXYGEN="$DOXYGEN" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_DOXYGEN="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi DOXYGEN=$ac_cv_path_DOXYGEN if test -n "$DOXYGEN"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DOXYGEN" >&5 $as_echo "$DOXYGEN" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$DOXYGEN" = x; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: could not find doxygen - disabled" >&5 $as_echo "$as_me: WARNING: could not find doxygen - disabled" >&2;} enable_doxygen=no enable_doc=no else enable_doc=yes # Extract the first word of "dot", so it can be a program name with args. set dummy dot; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_DOT+:} false; then : $as_echo_n "(cached) " >&6 else case $DOT in [\\/]* | ?:[\\/]*) ac_cv_path_DOT="$DOT" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_DOT="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi DOT=$ac_cv_path_DOT if test -n "$DOT"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DOT" >&5 $as_echo "$DOT" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi fi if test x$DOT = x; then if test "x$enable_dot" = xyes; then as_fn_error $? "could not find dot" "$LINENO" 5 fi enable_dot=no else enable_dot=yes fi if test x$enable_doc = xyes; then DOC_TRUE= DOC_FALSE='#' else DOC_TRUE='#' DOC_FALSE= fi if test x$enable_buildnumber = xyes; then USE_BLDNO_TRUE= USE_BLDNO_FALSE='#' else USE_BLDNO_TRUE='#' USE_BLDNO_FALSE= fi ## Sipviewer is written in java and compiled w/ant so allow someone ## w/o java or ant to effectively ignore anything about this # Check whether --enable-sipviewer was given. if test "${enable_sipviewer+set}" = set; then : enableval=$enable_sipviewer; else enable_sipviewer=no fi if test x$enable_sipviewer = xyes; then SIPVIEWER_TRUE= SIPVIEWER_FALSE='#' else SIPVIEWER_TRUE='#' SIPVIEWER_FALSE= fi if test x$enable_sipviewer = xyes then ## SIPViewer is only part of project that uses java, so restrict ## test only if installing sipviewer TRY_JAVA_HOME=`ls -dr /usr/java/* 2> /dev/null | head -n 1` for dir in $JAVA_HOME $JDK_HOME /usr/local/jdk /usr/local/java $TRY_JAVA_HOME; do # Extract the first word of "dt.jar", so it can be a program name with args. set dummy dt.jar; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_jar+:} false; then : $as_echo_n "(cached) " >&6 else case $jar in [\\/]* | ?:[\\/]*) ac_cv_path_jar="$jar" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $dir/lib do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_jar="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi jar=$ac_cv_path_jar if test -n "$jar"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $jar" >&5 $as_echo "$jar" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test x$jar != x; then found_jdk="yes"; JAVA_HOME=$dir break; fi done if test x_$found_jdk != x_yes; then as_fn_error $? "Cannot find dt.jar in expected location. You may try setting the JAVA_HOME environment variable if you haven't already done so" "$LINENO" 5 fi JAVA=$JAVA_HOME/jre/bin/java test -z $JAVAC_OPTIMIZED && JAVAC_OPTIMIZED=on test -z $JAVAC_DEBUG && JAVAC_DEBUG=off test -z $ANT_HOME || ANT_HOME_BIN=$ANT_HOME/bin for dir in $ANT_HOME_BIN $PATH /usr/local/ant/bin; do # only works because unix does not use ant.sh # Extract the first word of "ant$EXEEXT ant.bat", so it can be a program name with args. set dummy ant$EXEEXT ant.bat; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_ANT+:} false; then : $as_echo_n "(cached) " >&6 else case $ANT in [\\/]* | ?:[\\/]*) ac_cv_path_ANT="$ANT" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $dir do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_ANT="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi ANT=$ac_cv_path_ANT if test -n "$ANT"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ANT" >&5 $as_echo "$ANT" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test x$ANT != x; then found_ant="yes"; break; fi done if test x_$found_ant != x_yes; then as_fn_error $? "Cannot find ant program. Try setting ANT_HOME environment variable or use 'configure ANT=" "$LINENO" 5 fi fi if test x$enable_buildnumber = xyes; then USE_BLDNO_TRUE= USE_BLDNO_FALSE='#' else USE_BLDNO_TRUE='#' USE_BLDNO_FALSE= fi # RTL Lib RTL_LDFLAGS="" RTL_CXXFLAGS="" # RtlAudio withval= # Check whether --with-rtllibaudio was given. if test "${with_rtllibaudio+set}" = set; then : withval=$with_rtllibaudio; fi ac_external_rtlaudio=${withval} if test x${ac_external_rtlaudio} != x; then RTL_LDFLAGS+=" -l${ac_external_rtlaudio} " fi withval= # Check whether --with-rtllibaudio-path was given. if test "${with_rtllibaudio_path+set}" = set; then : withval=$with_rtllibaudio_path; fi ac_external_rtlaudio_path=${withval} if test x${ac_external_rtlaudio_path} != x; then RTL_LDFLAGS+=" -L${ac_external_rtlaudio_path} -Wl,--rpath -Wl,${ac_external_rtlaudio_path} " fi withval= # Check whether --with-rtllibaudio-inc-path was given. if test "${with_rtllibaudio_inc_path+set}" = set; then : withval=$with_rtllibaudio_inc_path; fi ac_external_rtlaudio_inc_path=${withval} if test x${ac_external_rtlaudio_inc_path} != x; then RTL_CXXFLAGS+=" -I${ac_external_rtlaudio_inc_path} " fi # Rtl withval= # Check whether --with-rtllib was given. if test "${with_rtllib+set}" = set; then : withval=$with_rtllib; fi ac_external_rtl=${withval} if test x${ac_external_rtl} != x; then RTL_LDFLAGS+=" -l${ac_external_rtl} " fi withval= # Check whether --with-rtllib-path was given. if test "${with_rtllib_path+set}" = set; then : withval=$with_rtllib_path; fi ac_external_rtl_path=${withval} if test x${ac_external_rtl_path} != x; then RTL_LDFLAGS+=" -L${ac_external_rtl_path} -Wl,--rpath -Wl,${ac_external_rtl_path} " fi withval= # Check whether --with-rtllib-inc-path was given. if test "${with_rtllib_inc_path+set}" = set; then : withval=$with_rtllib_inc_path; fi ac_external_rtl_inc_path=${withval} if test x${ac_external_rtl_inc_path} != x; then RTL_CXXFLAGS+=" -I${ac_external_rtl_inc_path} " fi # Rtl Defines # Check whether --enable-external-rtl-init was given. if test "${enable_external_rtl_init+set}" = set; then : enableval=$enable_external_rtl_init; case "${enableval}" in yes) ac_do_rtinit_define=true ;; no) ac_do_rtinit_define=false ;; *) as_fn_error $? "bad value ${enableval} for --enable-external-rtl-init" "$LINENO" 5 ;; esac else ac_do_rtinit_define=false fi if test x${ac_do_rtinit_define} != xfalse; then $as_echo "#define INIT_EXTERNAL_RTL_COLLECTOR 1" >>confdefs.h RTL_CXXFLAGS+=" -DINIT_EXTERNAL_RTL_COLLECTOR " fi # Check whether --enable-rtl was given. if test "${enable_rtl+set}" = set; then : enableval=$enable_rtl; case "${enableval}" in yes) ac_do_rtl_define=true ;; no) ac_do_rtl_define=false ;; *) as_fn_error $? "bad value ${enableval} for --enable-rtl" "$LINENO" 5 ;; esac else ac_do_rtl_define=false fi if test x${ac_do_rtl_define} != xfalse; then $as_echo "#define RTL_ENABLED 1" >>confdefs.h RTL_CXXFLAGS+=" -DRTL_ENABLED " fi # Check whether --enable-rtlaudio was given. if test "${enable_rtlaudio+set}" = set; then : enableval=$enable_rtlaudio; case "${enableval}" in yes) ac_do_rtlaudio_define=true ;; no) ac_do_rtlaudio_define=false ;; *) as_fn_error $? "bad value ${enableval} for --enable-rtlaudio" "$LINENO" 5 ;; esac else ac_do_rtlaudio_define=false fi if test x${ac_do_rtlaudio_define} != xfalse; then $as_echo "#define RTL_AUDIO_ENABLED 1" >>confdefs.h RTL_CXXFLAGS+=" -DRTL_AUDIO_ENABLED " fi # VAD withval= # Check whether --with-external-vad was given. if test "${with_external_vad+set}" = set; then : withval=$with_external_vad; fi ac_external_vad=${withval} withval= # Check whether --with-external-vad-path was given. if test "${with_external_vad_path+set}" = set; then : withval=$with_external_vad_path; fi ac_external_vad_path=${withval} if test x${ac_external_vad} != x; then $as_echo "#define EXTERNAL_VAD 1" >>confdefs.h EVAD_LDFLAGS="-l${ac_external_vad} " if test x${ac_external_vad_path} != x; then EVAD_LDFLAGS+=" -L${ac_external_vad_path} -Wl,--rpath -Wl,${ac_external_vad_path} " fi LDFLAGS+=" $EVAD_LDFLAGS " CXXFLAGS+=" -DEXTERNAL_VAD " fi # PLC withval= # Check whether --with-external-plc was given. if test "${with_external_plc+set}" = set; then : withval=$with_external_plc; fi ac_external_plc=${withval} withval= # Check whether --with-external-plc-path was given. if test "${with_external_plc_path+set}" = set; then : withval=$with_external_plc_path; fi ac_external_plc_path=${withval} if test x${ac_external_plc} != x; then $as_echo "#define EXTERNAL_PLC 1" >>confdefs.h EPLC_LDFLAGS="-l${ac_external_plc} " if test x${ac_external_plc_path} != x; then EPLC_LDFLAGS+=" -L${ac_external_plc_path} -Wl,--rpath -Wl,${ac_external_plc_path} " fi LDFLAGS+=" $EPLC_LDFLAGS " CXXFLAGS+=" -DEXTERNAL_PLC " fi # Jitter buffer estimation withval= # Check whether --with-external-jbe was given. if test "${with_external_jbe+set}" = set; then : withval=$with_external_jbe; fi ac_external_jbe=${withval} withval= # Check whether --with-external-jbe-path was given. if test "${with_external_jbe_path+set}" = set; then : withval=$with_external_jbe_path; fi ac_external_jbe_path=${withval} if test x${ac_external_jbe} != x; then $as_echo "#define EXTERNAL_JB_ESTIMATION 1" >>confdefs.h EJBE_LDFLAGS="-l${ac_external_jbe} " if test x${ac_external_jbe_path} != x; then EJBE_LDFLAGS+=" -L${ac_external_jbe_path} -Wl,--rpath -Wl,${ac_external_jbe_path} " fi LDFLAGS+=" $EJBE_LDFLAGS " CXXFLAGS+=" -DEXTERNAL_JB_ESTIMATION " fi # AGC withval= # Check whether --with-external-agc was given. if test "${with_external_agc+set}" = set; then : withval=$with_external_agc; fi ac_external_agc=${withval} withval= # Check whether --with-external-agc-path was given. if test "${with_external_agc_path+set}" = set; then : withval=$with_external_agc_path; fi ac_external_agc_path=${withval} if test x${ac_external_agc} != x; then $as_echo "#define EXTERNAL_AGC 1" >>confdefs.h EAGC_LDFLAGS="-l${ac_external_agc} " if test x${ac_external_agc_path} != x; then EAGC_LDFLAGS+=" -L${ac_external_agc_path} -Wl,--rpath -Wl,${ac_external_agc_path} " fi LDFLAGS+=" $EAGC_LDFLAGS " CXXFLAGS+=" -DEXTERNAL_AGC " fi # Speaker selection withval= # Check whether --with-external-ss was given. if test "${with_external_ss+set}" = set; then : withval=$with_external_ss; fi ac_external_ss=${withval} withval= # Check whether --with-external-ss-path was given. if test "${with_external_ss_path+set}" = set; then : withval=$with_external_ss_path; fi ac_external_ss_path=${withval} if test x${ac_external_ss} != x; then $as_echo "#define EXTERNAL_SS 1" >>confdefs.h SS_LDFLAGS="-l${ac_external_ss} " if test x${ac_external_ss_path} != x; then SS_LDFLAGS+=" -L${ac_external_ss_path} -Wl,--rpath -Wl,${ac_external_ss_path} " fi LDFLAGS+=" $SS_LDFLAGS " CXXFLAGS+=" -DEXTERNAL_SS " fi CXXFLAGS+=" $RTL_CXXFLAGS " LDFLAGS+=" ${RTL_LDFLAGS} " # Speaker selection enable # Check whether --enable-speaker-selection was given. if test "${enable_speaker_selection+set}" = set; then : enableval=$enable_speaker_selection; case "${enableval}" in yes) ac_enable_speaker_selection=true ;; no) ac_enable_speaker_selection=false ;; *) as_fn_error $? "bad value ${enableval} for --enable-speaker-selection" "$LINENO" 5 ;; esac else ac_enable_speaker_selection=false fi if test x${ac_enable_speaker_selection} != xfalse; then $as_echo "#define INSERT_SPEAKER_SELECTOR 1" >>confdefs.h CXXFLAGS+=" -DINSERT_SPEAKER_SELECTOR " fi # Conditionally use the GIPS audio libraries # Check whether --with-gipsneq was given. if test "${with_gipsneq+set}" = set; then : withval=$with_gipsneq; compile_with_gips=yes fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if link in with gips NetEQ" >&5 $as_echo_n "checking if link in with gips NetEQ... " >&6; } if test x$compile_with_gips = xyes then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } abs_srcdir=`cd $srcdir && pwd` { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gips includes" >&5 $as_echo_n "checking for gips includes... " >&6; } # Define HAVE_GIPS for c pre-processor GIPS_CPPFLAGS=-DHAVE_GIPS if test -e $withval/include/GIPS/Vendor_gips_typedefs.h then gips_dir=$withval elif test -e $abs_srcdir/../sipXbuild/vendors/gips/include/GIPS/Vendor_gips_typedefs.h then gips_dir=$abs_srcdir/../sipXbuild/vendors/gips else as_fn_error $? "GIPS/Vendor_gips_typedefs.h not found" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $gips_dir" >&5 $as_echo "$gips_dir" >&6; } # Add GIPS include path GIPSINC=$gips_dir/include # Add GIPS objects to be linked in GIPS_NEQ_OBJS=$gips_dir/GIPS_SuSE_i386.a CPPFLAGS="$CPPFLAGS $GIPS_CPPFLAGS -I$GIPSINC" # GIPS needs to be at the end of the list #LIBS="$LIBS $GIPS_OBJS" else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi # Check whether --with-gipsve was given. if test "${with_gipsve+set}" = set; then : withval=$with_gipsve; link_with_gipsve=yes fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if linking to gips voice engine" >&5 $as_echo_n "checking if linking to gips voice engine... " >&6; } if test x$link_with_gipsve = xyes then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } abs_srcdir=`cd $srcdir && pwd` { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gips includes" >&5 $as_echo_n "checking for gips includes... " >&6; } if test -e $abs_srcdir/../sipXbuild/vendors/gips/VoiceEngine/interface/GipsVoiceEngineLib.h then gips_dir=$abs_srcdir/../sipXbuild/vendors/gips else as_fn_error $? "sipXbuild/vendors/gips/VoiceEngine/interface/GipsVoiceEngineLib.h not found" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $gips_dir" >&5 $as_echo "$gips_dir" >&6; } # Add GIPS include path GIPSINC=$gips_dir/VoiceEngine/interface CPPFLAGS="$CPPFLAGS -I$gips_dir/include -I$GIPSINC -DVOICE_ENGINE" # Add GIPS objects to be linked in if test "`uname`" == "Darwin"; then GIPS_VE_OBJS="$gips_dir/VoiceEngine/libraries/VoiceEngine_mac_ppc_gcc.a" else GIPS_VE_OBJS="$gips_dir/VoiceEngine/libraries/VoiceEngine_Linux_Alsa_gcc.a" fi else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi SIPXMEDIA_VE_LIBS="$SIPXMEDIALIB/libsipXvoiceEngine.la" SIPXMEDIA_VE_STATIC_LIBS="$SIPXMEDIALIB/libsipXvoiceEngine.a" if test x$link_with_gipsve = xyes; then BUILDVE_TRUE= BUILDVE_FALSE='#' else BUILDVE_TRUE='#' BUILDVE_FALSE= fi # Check whether --with-gipsce was given. if test "${with_gipsce+set}" = set; then : withval=$with_gipsce; link_with_gipsce=yes fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if linking to gips conference engine" >&5 $as_echo_n "checking if linking to gips conference engine... " >&6; } if test x$link_with_gipsce = xyes then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } abs_srcdir=`cd $srcdir && pwd` { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gips includes" >&5 $as_echo_n "checking for gips includes... " >&6; } if test -e $abs_srcdir/../sipXbuild/vendors/gips/ConferenceEngine/interface/ConferenceEngine.h then gips_dir=$abs_srcdir/../sipXbuild/vendors/gips else as_fn_error $? "sipXbuild/vendors/gips/ConferenceEngine/interface/ConferenceEngine.h not found" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $gips_dir" >&5 $as_echo "$gips_dir" >&6; } # Add GIPS include path GIPSINC=$gips_dir/ConferenceEngine/interface CPPFLAGS="$CPPFLAGS -I$gips_dir/include -I$GIPSINC -DVOICE_ENGINE" # Add GIPS objects to be linked in GIPS_CE_OBJS="$gips_dir/ConferenceEngine/libraries/ConferenceEngine_Linux_gcc.a" else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi SIPXMEDIA_CE_LIBS="$SIPXMEDIALIB/libsipXconferenceEngine.la" if test x$link_with_gipsce = xyes; then BUILDCE_TRUE= BUILDCE_FALSE='#' else BUILDCE_TRUE='#' BUILDCE_FALSE= fi # Check whether --enable-video was given. if test "${enable_video+set}" = set; then : enableval=$enable_video; else enable_video=no fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for video (--enable-video)" >&5 $as_echo_n "checking for video (--enable-video)... " >&6; } if test x$enable_video != xno then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } VIDEO_DEFINE=-DVIDEO else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for wxWidgets" >&5 $as_echo_n "checking for wxWidgets... " >&6; } # Extract the first word of "wx-config", so it can be a program name with args. set dummy wx-config; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_WXWIDGETS_CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else case $WXWIDGETS_CONFIG in [\\/]* | ?:[\\/]*) ac_cv_path_WXWIDGETS_CONFIG="$WXWIDGETS_CONFIG" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_WXWIDGETS_CONFIG="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi WXWIDGETS_CONFIG=$ac_cv_path_WXWIDGETS_CONFIG if test -n "$WXWIDGETS_CONFIG"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $WXWIDGETS_CONFIG" >&5 $as_echo "$WXWIDGETS_CONFIG" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x_$WXWIDGETS_CONFIG" != "x_" then wxCflags=`$WXWIDGETS_CONFIG --cflags` WXWIDGETS_CFLAGS=$wxCflags wxCXXflags=`$WXWIDGETS_CONFIG --cxxflags` WXWIDGETS_CXXFLAGS=$wxCXXflags wxlibs=`$WXWIDGETS_CONFIG --libs` WXWIDGETS_LIBS=$wxlibs wxver=`$WXWIDGETS_CONFIG --version` { $as_echo "$as_me:${as_lineno-$LINENO}: checking wxWidgets revision" >&5 $as_echo_n "checking wxWidgets revision... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: found version $wxver" >&5 $as_echo "found version $wxver" >&6; } enable_wxwidgets=yes else enable_wxwidgets=no { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: no wx-config found - wxWidgets disabled" >&5 $as_echo "$as_me: WARNING: no wx-config found - wxWidgets disabled" >&2;} fi # Check whether --enable-sipx-ezphone was given. if test "${enable_sipx_ezphone+set}" = set; then : enableval=$enable_sipx_ezphone; else enable_sipx_ezphone=no fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking Building sipXezPhone" >&5 $as_echo_n "checking Building sipXezPhone... " >&6; } # If sipx-ezphone is requested, check for its prerequisites. if test x$enable_sipx_ezphone = xyes then if test x$enable_wxwidgets != xyes then as_fn_error $? "wxWidgets is required for sipXezPhone" "$LINENO" 5 enable_sipx_ezphone=no fi fi if test x$enable_sipx_ezphone = xyes; then BUILDEZPHONE_TRUE= BUILDEZPHONE_FALSE='#' else BUILDEZPHONE_TRUE='#' BUILDEZPHONE_FALSE= fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${enable_sipx_ezphone}" >&5 $as_echo "${enable_sipx_ezphone}" >&6; } # named is used in some sipXtackLib tests # Check whether --with-named was given. if test "${with_named+set}" = set; then : withval=$with_named; named_program=$withval else named_program="" fi if test x_$named_program != x_; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: Using named from --with-named $named_program" >&5 $as_echo "Using named from --with-named $named_program" >&6; } NAMED_PROGRAM=$named_program else # Extract the first word of "named", so it can be a program name with args. set dummy named; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_NAMED_PROGRAM+:} false; then : $as_echo_n "(cached) " >&6 else case $NAMED_PROGRAM in [\\/]* | ?:[\\/]*) ac_cv_path_NAMED_PROGRAM="$NAMED_PROGRAM" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR as_dummy="$PATH:/sbin:/usr/sbin:/usr/local/sbin " for as_dir in $as_dummy do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_NAMED_PROGRAM="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS test -z "$ac_cv_path_NAMED_PROGRAM" && ac_cv_path_NAMED_PROGRAM="named" ;; esac fi NAMED_PROGRAM=$ac_cv_path_NAMED_PROGRAM if test -n "$NAMED_PROGRAM"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NAMED_PROGRAM" >&5 $as_echo "$NAMED_PROGRAM" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if ! test -x $NAMED_PROGRAM; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Cannot execute $NAMED_PROGRAM. Tests that require it will not be executed." >&5 $as_echo "$as_me: WARNING: Cannot execute $NAMED_PROGRAM. Tests that require it will not be executed." >&2;} NAMED_PROGRAM="" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing clock_nanosleep" >&5 $as_echo_n "checking for library containing clock_nanosleep... " >&6; } if ${ac_cv_search_clock_nanosleep+:} false; then : $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char clock_nanosleep (); int main () { return clock_nanosleep (); ; return 0; } _ACEOF for ac_lib in '' rt posix4; do if test -z "$ac_lib"; then ac_res="none required" else ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi if ac_fn_c_try_link "$LINENO"; then : ac_cv_search_clock_nanosleep=$ac_res fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext if ${ac_cv_search_clock_nanosleep+:} false; then : break fi done if ${ac_cv_search_clock_nanosleep+:} false; then : else ac_cv_search_clock_nanosleep=no fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_clock_nanosleep" >&5 $as_echo "$ac_cv_search_clock_nanosleep" >&6; } ac_res=$ac_cv_search_clock_nanosleep if test "$ac_res" != no; then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" fi ac_config_files="$ac_config_files Makefile sipxtapi.spec bin/Makefile sipXcallLib/Makefile sipXcallLib/doc/Makefile sipXcallLib/examples/Makefile sipXcallLib/examples/sipXezPhone/Makefile sipXcallLib/include/Makefile sipXcallLib/src/Makefile sipXcallLib/src/test/Makefile sipXcallLib/src/test/tapi/Makefile sipXmediaAdapterLib/Makefile sipXmediaAdapterLib/interface/Makefile sipXmediaAdapterLib/sipXmediaMediaProcessing/Makefile sipXmediaAdapterLib/sipXmediaMediaProcessing/src/Makefile sipXmediaAdapterLib/sipXmediaMediaProcessing/src/test/Makefile sipXmediaAdapterLib/sipXmediaMediaProcessing/include/Makefile sipXmediaAdapterLib/examples/Makefile sipXmediaAdapterLib/doc/Makefile sipXmediaLib/Makefile sipXmediaLib/include/Makefile sipXmediaLib/src/Makefile sipXmediaLib/src/mp/codecs/Makefile sipXmediaLib/src/mp/codecs/plggsm/Makefile sipXmediaLib/src/mp/codecs/plgpcmapcmu/Makefile sipXmediaLib/src/mp/codecs/plgtones/Makefile sipXmediaLib/src/mp/codecs/plgl16/Makefile sipXmediaLib/src/mp/codecs/plgspeex/Makefile sipXmediaLib/src/mp/codecs/plgilbc/Makefile sipXmediaLib/src/mp/codecs/plgg726/Makefile sipXmediaLib/src/mp/codecs/plgg722/Makefile sipXmediaLib/src/mp/codecs/plgamr/Makefile sipXmediaLib/src/mp/codecs/plgamrwb/Makefile sipXmediaLib/src/mp/codecs/plgopus/Makefile sipXmediaLib/src/test/Makefile sipXmediaLib/doc/Makefile sipXportLib/Makefile sipXportLib/include/Makefile sipXportLib/src/Makefile sipXportLib/src/test/Makefile sipXportLib/src/test/sipxunit/Makefile sipXportLib/src/test/sipxportunit/Makefile sipXportLib/src/test/testplugin/Makefile sipXportLib/syslogviewer/Makefile sipXportLib/doc/Makefile sipXsdpLib/Makefile sipXsdpLib/include/Makefile sipXsdpLib/src/Makefile sipXsdpLib/src/test/Makefile sipXsdpLib/doc/Makefile sipXtackLib/Makefile sipXtackLib/include/Makefile sipXtackLib/src/Makefile sipXtackLib/meta/Makefile sipXtackLib/src/test/Makefile sipXtackLib/examples/Makefile sipXtackLib/examples/im/Makefile sipXtackLib/examples/xmlrpc/Makefile sipXtackLib/syslog2siptrace/Makefile sipXtackLib/siplog2siptrace/Makefile sipXtackLib/sipviewer/Makefile sipXtackLib/siptest/Makefile sipXtackLib/siptest/src/Makefile sipXtackLib/siptest/include/Makefile sipXtackLib/siptest/src/siptest/Makefile sipXtackLib/doc/Makefile" cat >confcache <<\_ACEOF # This file is a shell script that caches the results of configure # tests run on this system so they can be shared between configure # scripts and configure runs, see configure's option --config-cache. # It is not useful on other systems. If it contains results you don't # want to keep, you may remove or edit it. # # config.status only pays attention to the cache file if you give it # the --recheck option to rerun configure. # # `ac_cv_env_foo' variables (set or unset) will be overridden when # loading this file, other *unset* `ac_cv_foo' will be assigned the # following values. _ACEOF # The following way of writing the cache mishandles newlines in values, # but we know of no workaround that is simple, portable, and efficient. # So, we kill variables containing newlines. # Ultrix sh set writes to stderr and can't be redirected directly, # and sets the high bit in the cache file unless we assign to the vars. ( for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) # `set' does not quote correctly, so add quotes: double-quote # substitution turns \\\\ into \\, and sed turns \\ into \. sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" ;; #( *) # `set' quotes correctly as required by POSIX, so do not add quotes. sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) | sed ' /^ac_cv_env_/b end t clear :clear s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ t end s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ :end' >>confcache if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then if test "x$cache_file" != "x/dev/null"; then { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 $as_echo "$as_me: updating cache $cache_file" >&6;} if test ! -f "$cache_file" || test -h "$cache_file"; then cat confcache >"$cache_file" else case $cache_file in #( */* | ?:*) mv -f confcache "$cache_file"$$ && mv -f "$cache_file"$$ "$cache_file" ;; #( *) mv -f confcache "$cache_file" ;; esac fi fi else { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache test "x$prefix" = xNONE && prefix=$ac_default_prefix # Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' DEFS=-DHAVE_CONFIG_H ac_libobjs= ac_ltlibobjs= U= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs LTLIBOBJS=$ac_ltlibobjs if test -n "$EXEEXT"; then am__EXEEXT_TRUE= am__EXEEXT_FALSE='#' else am__EXEEXT_TRUE='#' am__EXEEXT_FALSE= fi if test -z "${AMDEP_TRUE}" && test -z "${AMDEP_FALSE}"; then as_fn_error $? "conditional \"AMDEP\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then as_fn_error $? "conditional \"am__fastdepCC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${am__fastdepCXX_TRUE}" && test -z "${am__fastdepCXX_FALSE}"; then as_fn_error $? "conditional \"am__fastdepCXX\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then as_fn_error $? "conditional \"am__fastdepCC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${CROSS_COMPILING_TRUE}" && test -z "${CROSS_COMPILING_FALSE}"; then as_fn_error $? "conditional \"CROSS_COMPILING\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${COREAUDIO_DRIVERS_TRUE}" && test -z "${COREAUDIO_DRIVERS_FALSE}"; then as_fn_error $? "conditional \"COREAUDIO_DRIVERS\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${COREAUDIO_DRIVERS_TRUE}" && test -z "${COREAUDIO_DRIVERS_FALSE}"; then as_fn_error $? "conditional \"COREAUDIO_DRIVERS\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_CODEC_GSM_TRUE}" && test -z "${BUILD_CODEC_GSM_FALSE}"; then as_fn_error $? "conditional \"BUILD_CODEC_GSM\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_CODEC_SPEEX_TRUE}" && test -z "${BUILD_CODEC_SPEEX_FALSE}"; then as_fn_error $? "conditional \"BUILD_CODEC_SPEEX\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${SPEEX_STATIC_TRUE}" && test -z "${SPEEX_STATIC_FALSE}"; then as_fn_error $? "conditional \"SPEEX_STATIC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_CODEC_ILBC_TRUE}" && test -z "${BUILD_CODEC_ILBC_FALSE}"; then as_fn_error $? "conditional \"BUILD_CODEC_ILBC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_CODEC_PCMAPCMU_TRUE}" && test -z "${BUILD_CODEC_PCMAPCMU_FALSE}"; then as_fn_error $? "conditional \"BUILD_CODEC_PCMAPCMU\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${PCMAPCMU_STATIC_TRUE}" && test -z "${PCMAPCMU_STATIC_FALSE}"; then as_fn_error $? "conditional \"PCMAPCMU_STATIC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_CODEC_TONES_TRUE}" && test -z "${BUILD_CODEC_TONES_FALSE}"; then as_fn_error $? "conditional \"BUILD_CODEC_TONES\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${TONES_STATIC_TRUE}" && test -z "${TONES_STATIC_FALSE}"; then as_fn_error $? "conditional \"TONES_STATIC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_CODEC_L16_TRUE}" && test -z "${BUILD_CODEC_L16_FALSE}"; then as_fn_error $? "conditional \"BUILD_CODEC_L16\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${L16_STATIC_TRUE}" && test -z "${L16_STATIC_FALSE}"; then as_fn_error $? "conditional \"L16_STATIC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_CODEC_G726_TRUE}" && test -z "${BUILD_CODEC_G726_FALSE}"; then as_fn_error $? "conditional \"BUILD_CODEC_G726\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${G726_STATIC_TRUE}" && test -z "${G726_STATIC_FALSE}"; then as_fn_error $? "conditional \"G726_STATIC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_CODEC_G722_TRUE}" && test -z "${BUILD_CODEC_G722_FALSE}"; then as_fn_error $? "conditional \"BUILD_CODEC_G722\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${G722_STATIC_TRUE}" && test -z "${G722_STATIC_FALSE}"; then as_fn_error $? "conditional \"G722_STATIC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${AMRNB_TRUE}" && test -z "${AMRNB_FALSE}"; then as_fn_error $? "conditional \"AMRNB\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${AMRWB_TRUE}" && test -z "${AMRWB_FALSE}"; then as_fn_error $? "conditional \"AMRWB\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_CODEC_OPUS_TRUE}" && test -z "${BUILD_CODEC_OPUS_FALSE}"; then as_fn_error $? "conditional \"BUILD_CODEC_OPUS\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${OPUS_STATIC_TRUE}" && test -z "${OPUS_STATIC_FALSE}"; then as_fn_error $? "conditional \"OPUS_STATIC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_SIPXUNIT_TRUE}" && test -z "${BUILD_SIPXUNIT_FALSE}"; then as_fn_error $? "conditional \"BUILD_SIPXUNIT\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_SIPXPORTUNIT_TRUE}" && test -z "${BUILD_SIPXPORTUNIT_FALSE}"; then as_fn_error $? "conditional \"BUILD_SIPXPORTUNIT\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${SPEEX_CONTRIB_TRUE}" && test -z "${SPEEX_CONTRIB_FALSE}"; then as_fn_error $? "conditional \"SPEEX_CONTRIB\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${DISABLE_STREAM_PLAYER_TRUE}" && test -z "${DISABLE_STREAM_PLAYER_FALSE}"; then as_fn_error $? "conditional \"DISABLE_STREAM_PLAYER\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILDTLS_TRUE}" && test -z "${BUILDTLS_FALSE}"; then as_fn_error $? "conditional \"BUILDTLS\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${ENABLE_LOCAL_AUDIO_TRUE}" && test -z "${ENABLE_LOCAL_AUDIO_FALSE}"; then as_fn_error $? "conditional \"ENABLE_LOCAL_AUDIO\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${DOC_TRUE}" && test -z "${DOC_FALSE}"; then as_fn_error $? "conditional \"DOC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${USE_BLDNO_TRUE}" && test -z "${USE_BLDNO_FALSE}"; then as_fn_error $? "conditional \"USE_BLDNO\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${SIPVIEWER_TRUE}" && test -z "${SIPVIEWER_FALSE}"; then as_fn_error $? "conditional \"SIPVIEWER\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${USE_BLDNO_TRUE}" && test -z "${USE_BLDNO_FALSE}"; then as_fn_error $? "conditional \"USE_BLDNO\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILDVE_TRUE}" && test -z "${BUILDVE_FALSE}"; then as_fn_error $? "conditional \"BUILDVE\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILDCE_TRUE}" && test -z "${BUILDCE_FALSE}"; then as_fn_error $? "conditional \"BUILDCE\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILDEZPHONE_TRUE}" && test -z "${BUILDEZPHONE_FALSE}"; then as_fn_error $? "conditional \"BUILDEZPHONE\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi : "${CONFIG_STATUS=./config.status}" ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 $as_echo "$as_me: creating $CONFIG_STATUS" >&6;} as_write_fail=0 cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. # Compiler output produced by configure, useful for debugging # configure, is in config.log if it exists. debug=false ac_cs_recheck=false ac_cs_silent=false SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" exec 6>&1 ## ----------------------------------- ## ## Main body of $CONFIG_STATUS script. ## ## ----------------------------------- ## _ASEOF test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Save the log message, to keep $0 and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" This file was extended by sipXtapi $as_me 3.3.0~test17, which was generated by GNU Autoconf 2.69. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS CONFIG_LINKS = $CONFIG_LINKS CONFIG_COMMANDS = $CONFIG_COMMANDS $ $0 $@ on `(hostname || uname -n) 2>/dev/null | sed 1q` " _ACEOF case $ac_config_files in *" "*) set x $ac_config_files; shift; ac_config_files=$*;; esac case $ac_config_headers in *" "*) set x $ac_config_headers; shift; ac_config_headers=$*;; esac cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" config_headers="$ac_config_headers" config_commands="$ac_config_commands" _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ \`$as_me' instantiates files and other configuration actions from templates according to the current configuration. Unless the files and actions are specified as TAGs, all are instantiated by default. Usage: $0 [OPTION]... [TAG]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit --config print configuration, then exit -q, --quiet, --silent do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions --file=FILE[:TEMPLATE] instantiate the configuration file FILE --header=FILE[:TEMPLATE] instantiate the configuration header FILE Configuration files: $config_files Configuration headers: $config_headers Configuration commands: $config_commands Report bugs to ." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ sipXtapi config.status 3.3.0~test17 configured by $0, generated by GNU Autoconf 2.69, with options \\"\$ac_cs_config\\" Copyright (C) 2012 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' INSTALL='$INSTALL' MKDIR_P='$MKDIR_P' AWK='$AWK' test -n "\$AWK" || AWK=awk _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do case $1 in --*=?*) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` ac_shift=: ;; --*=) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg= ac_shift=: ;; *) ac_option=$1 ac_optarg=$2 ac_shift=shift ;; esac case $ac_option in # Handling of the options. -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) $as_echo "$ac_cs_version"; exit ;; --config | --confi | --conf | --con | --co | --c ) $as_echo "$ac_cs_config"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; '') as_fn_error $? "missing file argument" ;; esac as_fn_append CONFIG_FILES " '$ac_optarg'" ac_need_defaults=false;; --header | --heade | --head | --hea ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; esac as_fn_append CONFIG_HEADERS " '$ac_optarg'" ac_need_defaults=false;; --he | --h) # Conflict between --help and --header as_fn_error $? "ambiguous option: \`$1' Try \`$0 --help' for more information.";; --help | --hel | -h ) $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. -*) as_fn_error $? "unrecognized option: \`$1' Try \`$0 --help' for more information." ;; *) as_fn_append ac_config_targets " $1" ac_need_defaults=false ;; esac shift done ac_configure_extra_args= if $ac_cs_silent; then exec 6>/dev/null ac_configure_extra_args="$ac_configure_extra_args --silent" fi _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion shift \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 CONFIG_SHELL='$SHELL' export CONFIG_SHELL exec "\$@" fi _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX $as_echo "$ac_log" } >&5 _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # # INIT-COMMANDS # AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir" # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH sed_quote_subst='$sed_quote_subst' double_quote_subst='$double_quote_subst' delay_variable_subst='$delay_variable_subst' macro_version='`$ECHO "$macro_version" | $SED "$delay_single_quote_subst"`' macro_revision='`$ECHO "$macro_revision" | $SED "$delay_single_quote_subst"`' enable_shared='`$ECHO "$enable_shared" | $SED "$delay_single_quote_subst"`' enable_static='`$ECHO "$enable_static" | $SED "$delay_single_quote_subst"`' pic_mode='`$ECHO "$pic_mode" | $SED "$delay_single_quote_subst"`' enable_fast_install='`$ECHO "$enable_fast_install" | $SED "$delay_single_quote_subst"`' SHELL='`$ECHO "$SHELL" | $SED "$delay_single_quote_subst"`' ECHO='`$ECHO "$ECHO" | $SED "$delay_single_quote_subst"`' PATH_SEPARATOR='`$ECHO "$PATH_SEPARATOR" | $SED "$delay_single_quote_subst"`' host_alias='`$ECHO "$host_alias" | $SED "$delay_single_quote_subst"`' host='`$ECHO "$host" | $SED "$delay_single_quote_subst"`' host_os='`$ECHO "$host_os" | $SED "$delay_single_quote_subst"`' build_alias='`$ECHO "$build_alias" | $SED "$delay_single_quote_subst"`' build='`$ECHO "$build" | $SED "$delay_single_quote_subst"`' build_os='`$ECHO "$build_os" | $SED "$delay_single_quote_subst"`' SED='`$ECHO "$SED" | $SED "$delay_single_quote_subst"`' Xsed='`$ECHO "$Xsed" | $SED "$delay_single_quote_subst"`' GREP='`$ECHO "$GREP" | $SED "$delay_single_quote_subst"`' EGREP='`$ECHO "$EGREP" | $SED "$delay_single_quote_subst"`' FGREP='`$ECHO "$FGREP" | $SED "$delay_single_quote_subst"`' LD='`$ECHO "$LD" | $SED "$delay_single_quote_subst"`' NM='`$ECHO "$NM" | $SED "$delay_single_quote_subst"`' LN_S='`$ECHO "$LN_S" | $SED "$delay_single_quote_subst"`' max_cmd_len='`$ECHO "$max_cmd_len" | $SED "$delay_single_quote_subst"`' ac_objext='`$ECHO "$ac_objext" | $SED "$delay_single_quote_subst"`' exeext='`$ECHO "$exeext" | $SED "$delay_single_quote_subst"`' lt_unset='`$ECHO "$lt_unset" | $SED "$delay_single_quote_subst"`' lt_SP2NL='`$ECHO "$lt_SP2NL" | $SED "$delay_single_quote_subst"`' lt_NL2SP='`$ECHO "$lt_NL2SP" | $SED "$delay_single_quote_subst"`' lt_cv_to_host_file_cmd='`$ECHO "$lt_cv_to_host_file_cmd" | $SED "$delay_single_quote_subst"`' lt_cv_to_tool_file_cmd='`$ECHO "$lt_cv_to_tool_file_cmd" | $SED "$delay_single_quote_subst"`' reload_flag='`$ECHO "$reload_flag" | $SED "$delay_single_quote_subst"`' reload_cmds='`$ECHO "$reload_cmds" | $SED "$delay_single_quote_subst"`' OBJDUMP='`$ECHO "$OBJDUMP" | $SED "$delay_single_quote_subst"`' deplibs_check_method='`$ECHO "$deplibs_check_method" | $SED "$delay_single_quote_subst"`' file_magic_cmd='`$ECHO "$file_magic_cmd" | $SED "$delay_single_quote_subst"`' file_magic_glob='`$ECHO "$file_magic_glob" | $SED "$delay_single_quote_subst"`' want_nocaseglob='`$ECHO "$want_nocaseglob" | $SED "$delay_single_quote_subst"`' DLLTOOL='`$ECHO "$DLLTOOL" | $SED "$delay_single_quote_subst"`' sharedlib_from_linklib_cmd='`$ECHO "$sharedlib_from_linklib_cmd" | $SED "$delay_single_quote_subst"`' AR='`$ECHO "$AR" | $SED "$delay_single_quote_subst"`' AR_FLAGS='`$ECHO "$AR_FLAGS" | $SED "$delay_single_quote_subst"`' archiver_list_spec='`$ECHO "$archiver_list_spec" | $SED "$delay_single_quote_subst"`' STRIP='`$ECHO "$STRIP" | $SED "$delay_single_quote_subst"`' RANLIB='`$ECHO "$RANLIB" | $SED "$delay_single_quote_subst"`' old_postinstall_cmds='`$ECHO "$old_postinstall_cmds" | $SED "$delay_single_quote_subst"`' old_postuninstall_cmds='`$ECHO "$old_postuninstall_cmds" | $SED "$delay_single_quote_subst"`' old_archive_cmds='`$ECHO "$old_archive_cmds" | $SED "$delay_single_quote_subst"`' lock_old_archive_extraction='`$ECHO "$lock_old_archive_extraction" | $SED "$delay_single_quote_subst"`' CC='`$ECHO "$CC" | $SED "$delay_single_quote_subst"`' CFLAGS='`$ECHO "$CFLAGS" | $SED "$delay_single_quote_subst"`' compiler='`$ECHO "$compiler" | $SED "$delay_single_quote_subst"`' GCC='`$ECHO "$GCC" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_pipe='`$ECHO "$lt_cv_sys_global_symbol_pipe" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_cdecl='`$ECHO "$lt_cv_sys_global_symbol_to_cdecl" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_c_name_address='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_c_name_address_lib_prefix='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address_lib_prefix" | $SED "$delay_single_quote_subst"`' nm_file_list_spec='`$ECHO "$nm_file_list_spec" | $SED "$delay_single_quote_subst"`' lt_sysroot='`$ECHO "$lt_sysroot" | $SED "$delay_single_quote_subst"`' objdir='`$ECHO "$objdir" | $SED "$delay_single_quote_subst"`' MAGIC_CMD='`$ECHO "$MAGIC_CMD" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_no_builtin_flag='`$ECHO "$lt_prog_compiler_no_builtin_flag" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_pic='`$ECHO "$lt_prog_compiler_pic" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_wl='`$ECHO "$lt_prog_compiler_wl" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_static='`$ECHO "$lt_prog_compiler_static" | $SED "$delay_single_quote_subst"`' lt_cv_prog_compiler_c_o='`$ECHO "$lt_cv_prog_compiler_c_o" | $SED "$delay_single_quote_subst"`' need_locks='`$ECHO "$need_locks" | $SED "$delay_single_quote_subst"`' MANIFEST_TOOL='`$ECHO "$MANIFEST_TOOL" | $SED "$delay_single_quote_subst"`' DSYMUTIL='`$ECHO "$DSYMUTIL" | $SED "$delay_single_quote_subst"`' NMEDIT='`$ECHO "$NMEDIT" | $SED "$delay_single_quote_subst"`' LIPO='`$ECHO "$LIPO" | $SED "$delay_single_quote_subst"`' OTOOL='`$ECHO "$OTOOL" | $SED "$delay_single_quote_subst"`' OTOOL64='`$ECHO "$OTOOL64" | $SED "$delay_single_quote_subst"`' libext='`$ECHO "$libext" | $SED "$delay_single_quote_subst"`' shrext_cmds='`$ECHO "$shrext_cmds" | $SED "$delay_single_quote_subst"`' extract_expsyms_cmds='`$ECHO "$extract_expsyms_cmds" | $SED "$delay_single_quote_subst"`' archive_cmds_need_lc='`$ECHO "$archive_cmds_need_lc" | $SED "$delay_single_quote_subst"`' enable_shared_with_static_runtimes='`$ECHO "$enable_shared_with_static_runtimes" | $SED "$delay_single_quote_subst"`' export_dynamic_flag_spec='`$ECHO "$export_dynamic_flag_spec" | $SED "$delay_single_quote_subst"`' whole_archive_flag_spec='`$ECHO "$whole_archive_flag_spec" | $SED "$delay_single_quote_subst"`' compiler_needs_object='`$ECHO "$compiler_needs_object" | $SED "$delay_single_quote_subst"`' old_archive_from_new_cmds='`$ECHO "$old_archive_from_new_cmds" | $SED "$delay_single_quote_subst"`' old_archive_from_expsyms_cmds='`$ECHO "$old_archive_from_expsyms_cmds" | $SED "$delay_single_quote_subst"`' archive_cmds='`$ECHO "$archive_cmds" | $SED "$delay_single_quote_subst"`' archive_expsym_cmds='`$ECHO "$archive_expsym_cmds" | $SED "$delay_single_quote_subst"`' module_cmds='`$ECHO "$module_cmds" | $SED "$delay_single_quote_subst"`' module_expsym_cmds='`$ECHO "$module_expsym_cmds" | $SED "$delay_single_quote_subst"`' with_gnu_ld='`$ECHO "$with_gnu_ld" | $SED "$delay_single_quote_subst"`' allow_undefined_flag='`$ECHO "$allow_undefined_flag" | $SED "$delay_single_quote_subst"`' no_undefined_flag='`$ECHO "$no_undefined_flag" | $SED "$delay_single_quote_subst"`' hardcode_libdir_flag_spec='`$ECHO "$hardcode_libdir_flag_spec" | $SED "$delay_single_quote_subst"`' hardcode_libdir_separator='`$ECHO "$hardcode_libdir_separator" | $SED "$delay_single_quote_subst"`' hardcode_direct='`$ECHO "$hardcode_direct" | $SED "$delay_single_quote_subst"`' hardcode_direct_absolute='`$ECHO "$hardcode_direct_absolute" | $SED "$delay_single_quote_subst"`' hardcode_minus_L='`$ECHO "$hardcode_minus_L" | $SED "$delay_single_quote_subst"`' hardcode_shlibpath_var='`$ECHO "$hardcode_shlibpath_var" | $SED "$delay_single_quote_subst"`' hardcode_automatic='`$ECHO "$hardcode_automatic" | $SED "$delay_single_quote_subst"`' inherit_rpath='`$ECHO "$inherit_rpath" | $SED "$delay_single_quote_subst"`' link_all_deplibs='`$ECHO "$link_all_deplibs" | $SED "$delay_single_quote_subst"`' always_export_symbols='`$ECHO "$always_export_symbols" | $SED "$delay_single_quote_subst"`' export_symbols_cmds='`$ECHO "$export_symbols_cmds" | $SED "$delay_single_quote_subst"`' exclude_expsyms='`$ECHO "$exclude_expsyms" | $SED "$delay_single_quote_subst"`' include_expsyms='`$ECHO "$include_expsyms" | $SED "$delay_single_quote_subst"`' prelink_cmds='`$ECHO "$prelink_cmds" | $SED "$delay_single_quote_subst"`' postlink_cmds='`$ECHO "$postlink_cmds" | $SED "$delay_single_quote_subst"`' file_list_spec='`$ECHO "$file_list_spec" | $SED "$delay_single_quote_subst"`' variables_saved_for_relink='`$ECHO "$variables_saved_for_relink" | $SED "$delay_single_quote_subst"`' need_lib_prefix='`$ECHO "$need_lib_prefix" | $SED "$delay_single_quote_subst"`' need_version='`$ECHO "$need_version" | $SED "$delay_single_quote_subst"`' version_type='`$ECHO "$version_type" | $SED "$delay_single_quote_subst"`' runpath_var='`$ECHO "$runpath_var" | $SED "$delay_single_quote_subst"`' shlibpath_var='`$ECHO "$shlibpath_var" | $SED "$delay_single_quote_subst"`' shlibpath_overrides_runpath='`$ECHO "$shlibpath_overrides_runpath" | $SED "$delay_single_quote_subst"`' libname_spec='`$ECHO "$libname_spec" | $SED "$delay_single_quote_subst"`' library_names_spec='`$ECHO "$library_names_spec" | $SED "$delay_single_quote_subst"`' soname_spec='`$ECHO "$soname_spec" | $SED "$delay_single_quote_subst"`' install_override_mode='`$ECHO "$install_override_mode" | $SED "$delay_single_quote_subst"`' postinstall_cmds='`$ECHO "$postinstall_cmds" | $SED "$delay_single_quote_subst"`' postuninstall_cmds='`$ECHO "$postuninstall_cmds" | $SED "$delay_single_quote_subst"`' finish_cmds='`$ECHO "$finish_cmds" | $SED "$delay_single_quote_subst"`' finish_eval='`$ECHO "$finish_eval" | $SED "$delay_single_quote_subst"`' hardcode_into_libs='`$ECHO "$hardcode_into_libs" | $SED "$delay_single_quote_subst"`' sys_lib_search_path_spec='`$ECHO "$sys_lib_search_path_spec" | $SED "$delay_single_quote_subst"`' sys_lib_dlsearch_path_spec='`$ECHO "$sys_lib_dlsearch_path_spec" | $SED "$delay_single_quote_subst"`' hardcode_action='`$ECHO "$hardcode_action" | $SED "$delay_single_quote_subst"`' enable_dlopen='`$ECHO "$enable_dlopen" | $SED "$delay_single_quote_subst"`' enable_dlopen_self='`$ECHO "$enable_dlopen_self" | $SED "$delay_single_quote_subst"`' enable_dlopen_self_static='`$ECHO "$enable_dlopen_self_static" | $SED "$delay_single_quote_subst"`' old_striplib='`$ECHO "$old_striplib" | $SED "$delay_single_quote_subst"`' striplib='`$ECHO "$striplib" | $SED "$delay_single_quote_subst"`' compiler_lib_search_dirs='`$ECHO "$compiler_lib_search_dirs" | $SED "$delay_single_quote_subst"`' predep_objects='`$ECHO "$predep_objects" | $SED "$delay_single_quote_subst"`' postdep_objects='`$ECHO "$postdep_objects" | $SED "$delay_single_quote_subst"`' predeps='`$ECHO "$predeps" | $SED "$delay_single_quote_subst"`' postdeps='`$ECHO "$postdeps" | $SED "$delay_single_quote_subst"`' compiler_lib_search_path='`$ECHO "$compiler_lib_search_path" | $SED "$delay_single_quote_subst"`' LD_CXX='`$ECHO "$LD_CXX" | $SED "$delay_single_quote_subst"`' reload_flag_CXX='`$ECHO "$reload_flag_CXX" | $SED "$delay_single_quote_subst"`' reload_cmds_CXX='`$ECHO "$reload_cmds_CXX" | $SED "$delay_single_quote_subst"`' old_archive_cmds_CXX='`$ECHO "$old_archive_cmds_CXX" | $SED "$delay_single_quote_subst"`' compiler_CXX='`$ECHO "$compiler_CXX" | $SED "$delay_single_quote_subst"`' GCC_CXX='`$ECHO "$GCC_CXX" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_no_builtin_flag_CXX='`$ECHO "$lt_prog_compiler_no_builtin_flag_CXX" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_pic_CXX='`$ECHO "$lt_prog_compiler_pic_CXX" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_wl_CXX='`$ECHO "$lt_prog_compiler_wl_CXX" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_static_CXX='`$ECHO "$lt_prog_compiler_static_CXX" | $SED "$delay_single_quote_subst"`' lt_cv_prog_compiler_c_o_CXX='`$ECHO "$lt_cv_prog_compiler_c_o_CXX" | $SED "$delay_single_quote_subst"`' archive_cmds_need_lc_CXX='`$ECHO "$archive_cmds_need_lc_CXX" | $SED "$delay_single_quote_subst"`' enable_shared_with_static_runtimes_CXX='`$ECHO "$enable_shared_with_static_runtimes_CXX" | $SED "$delay_single_quote_subst"`' export_dynamic_flag_spec_CXX='`$ECHO "$export_dynamic_flag_spec_CXX" | $SED "$delay_single_quote_subst"`' whole_archive_flag_spec_CXX='`$ECHO "$whole_archive_flag_spec_CXX" | $SED "$delay_single_quote_subst"`' compiler_needs_object_CXX='`$ECHO "$compiler_needs_object_CXX" | $SED "$delay_single_quote_subst"`' old_archive_from_new_cmds_CXX='`$ECHO "$old_archive_from_new_cmds_CXX" | $SED "$delay_single_quote_subst"`' old_archive_from_expsyms_cmds_CXX='`$ECHO "$old_archive_from_expsyms_cmds_CXX" | $SED "$delay_single_quote_subst"`' archive_cmds_CXX='`$ECHO "$archive_cmds_CXX" | $SED "$delay_single_quote_subst"`' archive_expsym_cmds_CXX='`$ECHO "$archive_expsym_cmds_CXX" | $SED "$delay_single_quote_subst"`' module_cmds_CXX='`$ECHO "$module_cmds_CXX" | $SED "$delay_single_quote_subst"`' module_expsym_cmds_CXX='`$ECHO "$module_expsym_cmds_CXX" | $SED "$delay_single_quote_subst"`' with_gnu_ld_CXX='`$ECHO "$with_gnu_ld_CXX" | $SED "$delay_single_quote_subst"`' allow_undefined_flag_CXX='`$ECHO "$allow_undefined_flag_CXX" | $SED "$delay_single_quote_subst"`' no_undefined_flag_CXX='`$ECHO "$no_undefined_flag_CXX" | $SED "$delay_single_quote_subst"`' hardcode_libdir_flag_spec_CXX='`$ECHO "$hardcode_libdir_flag_spec_CXX" | $SED "$delay_single_quote_subst"`' hardcode_libdir_separator_CXX='`$ECHO "$hardcode_libdir_separator_CXX" | $SED "$delay_single_quote_subst"`' hardcode_direct_CXX='`$ECHO "$hardcode_direct_CXX" | $SED "$delay_single_quote_subst"`' hardcode_direct_absolute_CXX='`$ECHO "$hardcode_direct_absolute_CXX" | $SED "$delay_single_quote_subst"`' hardcode_minus_L_CXX='`$ECHO "$hardcode_minus_L_CXX" | $SED "$delay_single_quote_subst"`' hardcode_shlibpath_var_CXX='`$ECHO "$hardcode_shlibpath_var_CXX" | $SED "$delay_single_quote_subst"`' hardcode_automatic_CXX='`$ECHO "$hardcode_automatic_CXX" | $SED "$delay_single_quote_subst"`' inherit_rpath_CXX='`$ECHO "$inherit_rpath_CXX" | $SED "$delay_single_quote_subst"`' link_all_deplibs_CXX='`$ECHO "$link_all_deplibs_CXX" | $SED "$delay_single_quote_subst"`' always_export_symbols_CXX='`$ECHO "$always_export_symbols_CXX" | $SED "$delay_single_quote_subst"`' export_symbols_cmds_CXX='`$ECHO "$export_symbols_cmds_CXX" | $SED "$delay_single_quote_subst"`' exclude_expsyms_CXX='`$ECHO "$exclude_expsyms_CXX" | $SED "$delay_single_quote_subst"`' include_expsyms_CXX='`$ECHO "$include_expsyms_CXX" | $SED "$delay_single_quote_subst"`' prelink_cmds_CXX='`$ECHO "$prelink_cmds_CXX" | $SED "$delay_single_quote_subst"`' postlink_cmds_CXX='`$ECHO "$postlink_cmds_CXX" | $SED "$delay_single_quote_subst"`' file_list_spec_CXX='`$ECHO "$file_list_spec_CXX" | $SED "$delay_single_quote_subst"`' hardcode_action_CXX='`$ECHO "$hardcode_action_CXX" | $SED "$delay_single_quote_subst"`' compiler_lib_search_dirs_CXX='`$ECHO "$compiler_lib_search_dirs_CXX" | $SED "$delay_single_quote_subst"`' predep_objects_CXX='`$ECHO "$predep_objects_CXX" | $SED "$delay_single_quote_subst"`' postdep_objects_CXX='`$ECHO "$postdep_objects_CXX" | $SED "$delay_single_quote_subst"`' predeps_CXX='`$ECHO "$predeps_CXX" | $SED "$delay_single_quote_subst"`' postdeps_CXX='`$ECHO "$postdeps_CXX" | $SED "$delay_single_quote_subst"`' compiler_lib_search_path_CXX='`$ECHO "$compiler_lib_search_path_CXX" | $SED "$delay_single_quote_subst"`' LTCC='$LTCC' LTCFLAGS='$LTCFLAGS' compiler='$compiler_DEFAULT' # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } # Quote evaled strings. for var in SHELL \ ECHO \ PATH_SEPARATOR \ SED \ GREP \ EGREP \ FGREP \ LD \ NM \ LN_S \ lt_SP2NL \ lt_NL2SP \ reload_flag \ OBJDUMP \ deplibs_check_method \ file_magic_cmd \ file_magic_glob \ want_nocaseglob \ DLLTOOL \ sharedlib_from_linklib_cmd \ AR \ AR_FLAGS \ archiver_list_spec \ STRIP \ RANLIB \ CC \ CFLAGS \ compiler \ lt_cv_sys_global_symbol_pipe \ lt_cv_sys_global_symbol_to_cdecl \ lt_cv_sys_global_symbol_to_c_name_address \ lt_cv_sys_global_symbol_to_c_name_address_lib_prefix \ nm_file_list_spec \ lt_prog_compiler_no_builtin_flag \ lt_prog_compiler_pic \ lt_prog_compiler_wl \ lt_prog_compiler_static \ lt_cv_prog_compiler_c_o \ need_locks \ MANIFEST_TOOL \ DSYMUTIL \ NMEDIT \ LIPO \ OTOOL \ OTOOL64 \ shrext_cmds \ export_dynamic_flag_spec \ whole_archive_flag_spec \ compiler_needs_object \ with_gnu_ld \ allow_undefined_flag \ no_undefined_flag \ hardcode_libdir_flag_spec \ hardcode_libdir_separator \ exclude_expsyms \ include_expsyms \ file_list_spec \ variables_saved_for_relink \ libname_spec \ library_names_spec \ soname_spec \ install_override_mode \ finish_eval \ old_striplib \ striplib \ compiler_lib_search_dirs \ predep_objects \ postdep_objects \ predeps \ postdeps \ compiler_lib_search_path \ LD_CXX \ reload_flag_CXX \ compiler_CXX \ lt_prog_compiler_no_builtin_flag_CXX \ lt_prog_compiler_pic_CXX \ lt_prog_compiler_wl_CXX \ lt_prog_compiler_static_CXX \ lt_cv_prog_compiler_c_o_CXX \ export_dynamic_flag_spec_CXX \ whole_archive_flag_spec_CXX \ compiler_needs_object_CXX \ with_gnu_ld_CXX \ allow_undefined_flag_CXX \ no_undefined_flag_CXX \ hardcode_libdir_flag_spec_CXX \ hardcode_libdir_separator_CXX \ exclude_expsyms_CXX \ include_expsyms_CXX \ file_list_spec_CXX \ compiler_lib_search_dirs_CXX \ predep_objects_CXX \ postdep_objects_CXX \ predeps_CXX \ postdeps_CXX \ compiler_lib_search_path_CXX; do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[\\\\\\\`\\"\\\$]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done # Double-quote double-evaled strings. for var in reload_cmds \ old_postinstall_cmds \ old_postuninstall_cmds \ old_archive_cmds \ extract_expsyms_cmds \ old_archive_from_new_cmds \ old_archive_from_expsyms_cmds \ archive_cmds \ archive_expsym_cmds \ module_cmds \ module_expsym_cmds \ export_symbols_cmds \ prelink_cmds \ postlink_cmds \ postinstall_cmds \ postuninstall_cmds \ finish_cmds \ sys_lib_search_path_spec \ sys_lib_dlsearch_path_spec \ reload_cmds_CXX \ old_archive_cmds_CXX \ old_archive_from_new_cmds_CXX \ old_archive_from_expsyms_cmds_CXX \ archive_cmds_CXX \ archive_expsym_cmds_CXX \ module_cmds_CXX \ module_expsym_cmds_CXX \ export_symbols_cmds_CXX \ prelink_cmds_CXX \ postlink_cmds_CXX; do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[\\\\\\\`\\"\\\$]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done ac_aux_dir='$ac_aux_dir' xsi_shell='$xsi_shell' lt_shell_append='$lt_shell_append' # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes INIT. if test -n "\${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi PACKAGE='$PACKAGE' VERSION='$VERSION' TIMESTAMP='$TIMESTAMP' RM='$RM' ofile='$ofile' _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets do case $ac_config_target in "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;; "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;; "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; "sipxtapi.spec") CONFIG_FILES="$CONFIG_FILES sipxtapi.spec" ;; "bin/Makefile") CONFIG_FILES="$CONFIG_FILES bin/Makefile" ;; "sipXcallLib/Makefile") CONFIG_FILES="$CONFIG_FILES sipXcallLib/Makefile" ;; "sipXcallLib/doc/Makefile") CONFIG_FILES="$CONFIG_FILES sipXcallLib/doc/Makefile" ;; "sipXcallLib/examples/Makefile") CONFIG_FILES="$CONFIG_FILES sipXcallLib/examples/Makefile" ;; "sipXcallLib/examples/sipXezPhone/Makefile") CONFIG_FILES="$CONFIG_FILES sipXcallLib/examples/sipXezPhone/Makefile" ;; "sipXcallLib/include/Makefile") CONFIG_FILES="$CONFIG_FILES sipXcallLib/include/Makefile" ;; "sipXcallLib/src/Makefile") CONFIG_FILES="$CONFIG_FILES sipXcallLib/src/Makefile" ;; "sipXcallLib/src/test/Makefile") CONFIG_FILES="$CONFIG_FILES sipXcallLib/src/test/Makefile" ;; "sipXcallLib/src/test/tapi/Makefile") CONFIG_FILES="$CONFIG_FILES sipXcallLib/src/test/tapi/Makefile" ;; "sipXmediaAdapterLib/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaAdapterLib/Makefile" ;; "sipXmediaAdapterLib/interface/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaAdapterLib/interface/Makefile" ;; "sipXmediaAdapterLib/sipXmediaMediaProcessing/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaAdapterLib/sipXmediaMediaProcessing/Makefile" ;; "sipXmediaAdapterLib/sipXmediaMediaProcessing/src/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaAdapterLib/sipXmediaMediaProcessing/src/Makefile" ;; "sipXmediaAdapterLib/sipXmediaMediaProcessing/src/test/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaAdapterLib/sipXmediaMediaProcessing/src/test/Makefile" ;; "sipXmediaAdapterLib/sipXmediaMediaProcessing/include/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaAdapterLib/sipXmediaMediaProcessing/include/Makefile" ;; "sipXmediaAdapterLib/examples/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaAdapterLib/examples/Makefile" ;; "sipXmediaAdapterLib/doc/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaAdapterLib/doc/Makefile" ;; "sipXmediaLib/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/Makefile" ;; "sipXmediaLib/include/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/include/Makefile" ;; "sipXmediaLib/src/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/src/Makefile" ;; "sipXmediaLib/src/mp/codecs/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/src/mp/codecs/Makefile" ;; "sipXmediaLib/src/mp/codecs/plggsm/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/src/mp/codecs/plggsm/Makefile" ;; "sipXmediaLib/src/mp/codecs/plgpcmapcmu/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/src/mp/codecs/plgpcmapcmu/Makefile" ;; "sipXmediaLib/src/mp/codecs/plgtones/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/src/mp/codecs/plgtones/Makefile" ;; "sipXmediaLib/src/mp/codecs/plgl16/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/src/mp/codecs/plgl16/Makefile" ;; "sipXmediaLib/src/mp/codecs/plgspeex/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/src/mp/codecs/plgspeex/Makefile" ;; "sipXmediaLib/src/mp/codecs/plgilbc/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/src/mp/codecs/plgilbc/Makefile" ;; "sipXmediaLib/src/mp/codecs/plgg726/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/src/mp/codecs/plgg726/Makefile" ;; "sipXmediaLib/src/mp/codecs/plgg722/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/src/mp/codecs/plgg722/Makefile" ;; "sipXmediaLib/src/mp/codecs/plgamr/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/src/mp/codecs/plgamr/Makefile" ;; "sipXmediaLib/src/mp/codecs/plgamrwb/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/src/mp/codecs/plgamrwb/Makefile" ;; "sipXmediaLib/src/mp/codecs/plgopus/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/src/mp/codecs/plgopus/Makefile" ;; "sipXmediaLib/src/test/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/src/test/Makefile" ;; "sipXmediaLib/doc/Makefile") CONFIG_FILES="$CONFIG_FILES sipXmediaLib/doc/Makefile" ;; "sipXportLib/Makefile") CONFIG_FILES="$CONFIG_FILES sipXportLib/Makefile" ;; "sipXportLib/include/Makefile") CONFIG_FILES="$CONFIG_FILES sipXportLib/include/Makefile" ;; "sipXportLib/src/Makefile") CONFIG_FILES="$CONFIG_FILES sipXportLib/src/Makefile" ;; "sipXportLib/src/test/Makefile") CONFIG_FILES="$CONFIG_FILES sipXportLib/src/test/Makefile" ;; "sipXportLib/src/test/sipxunit/Makefile") CONFIG_FILES="$CONFIG_FILES sipXportLib/src/test/sipxunit/Makefile" ;; "sipXportLib/src/test/sipxportunit/Makefile") CONFIG_FILES="$CONFIG_FILES sipXportLib/src/test/sipxportunit/Makefile" ;; "sipXportLib/src/test/testplugin/Makefile") CONFIG_FILES="$CONFIG_FILES sipXportLib/src/test/testplugin/Makefile" ;; "sipXportLib/syslogviewer/Makefile") CONFIG_FILES="$CONFIG_FILES sipXportLib/syslogviewer/Makefile" ;; "sipXportLib/doc/Makefile") CONFIG_FILES="$CONFIG_FILES sipXportLib/doc/Makefile" ;; "sipXsdpLib/Makefile") CONFIG_FILES="$CONFIG_FILES sipXsdpLib/Makefile" ;; "sipXsdpLib/include/Makefile") CONFIG_FILES="$CONFIG_FILES sipXsdpLib/include/Makefile" ;; "sipXsdpLib/src/Makefile") CONFIG_FILES="$CONFIG_FILES sipXsdpLib/src/Makefile" ;; "sipXsdpLib/src/test/Makefile") CONFIG_FILES="$CONFIG_FILES sipXsdpLib/src/test/Makefile" ;; "sipXsdpLib/doc/Makefile") CONFIG_FILES="$CONFIG_FILES sipXsdpLib/doc/Makefile" ;; "sipXtackLib/Makefile") CONFIG_FILES="$CONFIG_FILES sipXtackLib/Makefile" ;; "sipXtackLib/include/Makefile") CONFIG_FILES="$CONFIG_FILES sipXtackLib/include/Makefile" ;; "sipXtackLib/src/Makefile") CONFIG_FILES="$CONFIG_FILES sipXtackLib/src/Makefile" ;; "sipXtackLib/meta/Makefile") CONFIG_FILES="$CONFIG_FILES sipXtackLib/meta/Makefile" ;; "sipXtackLib/src/test/Makefile") CONFIG_FILES="$CONFIG_FILES sipXtackLib/src/test/Makefile" ;; "sipXtackLib/examples/Makefile") CONFIG_FILES="$CONFIG_FILES sipXtackLib/examples/Makefile" ;; "sipXtackLib/examples/im/Makefile") CONFIG_FILES="$CONFIG_FILES sipXtackLib/examples/im/Makefile" ;; "sipXtackLib/examples/xmlrpc/Makefile") CONFIG_FILES="$CONFIG_FILES sipXtackLib/examples/xmlrpc/Makefile" ;; "sipXtackLib/syslog2siptrace/Makefile") CONFIG_FILES="$CONFIG_FILES sipXtackLib/syslog2siptrace/Makefile" ;; "sipXtackLib/siplog2siptrace/Makefile") CONFIG_FILES="$CONFIG_FILES sipXtackLib/siplog2siptrace/Makefile" ;; "sipXtackLib/sipviewer/Makefile") CONFIG_FILES="$CONFIG_FILES sipXtackLib/sipviewer/Makefile" ;; "sipXtackLib/siptest/Makefile") CONFIG_FILES="$CONFIG_FILES sipXtackLib/siptest/Makefile" ;; "sipXtackLib/siptest/src/Makefile") CONFIG_FILES="$CONFIG_FILES sipXtackLib/siptest/src/Makefile" ;; "sipXtackLib/siptest/include/Makefile") CONFIG_FILES="$CONFIG_FILES sipXtackLib/siptest/include/Makefile" ;; "sipXtackLib/siptest/src/siptest/Makefile") CONFIG_FILES="$CONFIG_FILES sipXtackLib/siptest/src/siptest/Makefile" ;; "sipXtackLib/doc/Makefile") CONFIG_FILES="$CONFIG_FILES sipXtackLib/doc/Makefile" ;; *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; esac done # If the user did not use the arguments to specify the items to instantiate, # then the envvar interface is used. Set only those that are not. # We use the long form for the default assignment because of an extremely # bizarre bug on SunOS 4.1.3. if $ac_need_defaults; then test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands fi # Have a temporary directory for convenience. Make it in the build tree # simply because there is no reason against having it here, and in addition, # creating and moving files from /tmp can sometimes cause problems. # Hook for its removal unless debugging. # Note that there is a small window in which the directory will not be cleaned: # after its creation but before its name has been assigned to `$tmp'. $debug || { tmp= ac_tmp= trap 'exit_status=$? : "${ac_tmp:=$tmp}" { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status ' 0 trap 'as_fn_exit 1' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. { tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && test -d "$tmp" } || { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 ac_tmp=$tmp # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. # This happens for instance with `./config.status config.h'. if test -n "$CONFIG_FILES"; then ac_cr=`echo X | tr X '\015'` # On cygwin, bash can eat \r inside `` if the user requested igncr. # But we know of no other shell where ac_cr would be empty at this # point, so we can use a bashism as a fallback. if test "x$ac_cr" = x; then eval ac_cr=\$\'\\r\' fi ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then ac_cs_awk_cr='\\r' else ac_cs_awk_cr=$ac_cr fi echo 'BEGIN {' >"$ac_tmp/subs1.awk" && _ACEOF { echo "cat >conf$$subs.awk <<_ACEOF" && echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && echo "_ACEOF" } >conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do . ./conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done rm -f conf$$subs.sh cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && _ACEOF sed -n ' h s/^/S["/; s/!.*/"]=/ p g s/^[^!]*!// :repl t repl s/'"$ac_delim"'$// t delim :nl h s/\(.\{148\}\)..*/\1/ t more1 s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ p n b repl :more1 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t nl :delim h s/\(.\{148\}\)..*/\1/ t more2 s/["\\]/\\&/g; s/^/"/; s/$/"/ p b :more2 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t delim ' >$CONFIG_STATUS || ac_write_fail=1 rm -f conf$$subs.awk cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACAWK cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && for (key in S) S_is_set[key] = 1 FS = "" } { line = $ 0 nfields = split(line, field, "@") substed = 0 len = length(field[1]) for (i = 2; i < nfields; i++) { key = field[i] keylen = length(key) if (S_is_set[key]) { value = S[key] line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) len += length(value) + length(field[++i]) substed = 1 } else len += 1 + keylen } print line } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" else cat fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 _ACEOF # VPATH may cause trouble with some makes, so we remove sole $(srcdir), # ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty # (actually we leave an empty line to preserve line numbers). if test "x$srcdir" = x.; then ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ h s/// s/^/:/ s/[ ]*$/:/ s/:\$(srcdir):/:/g s/:\${srcdir}:/:/g s/:@srcdir@:/:/g s/^:*// s/:*$// x s/\(=[ ]*\).*/\1/ G s/\n// s/^[^=]*=[ ]*$// }' fi cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" # Set up the scripts for CONFIG_HEADERS section. # No need to generate them if there are no CONFIG_HEADERS. # This happens for instance with `./config.status Makefile'. if test -n "$CONFIG_HEADERS"; then cat >"$ac_tmp/defines.awk" <<\_ACAWK || BEGIN { _ACEOF # Transform confdefs.h into an awk script `defines.awk', embedded as # here-document in config.status, that substitutes the proper values into # config.h.in to produce config.h. # Create a delimiter string that does not exist in confdefs.h, to ease # handling of long lines. ac_delim='%!_!# ' for ac_last_try in false false :; do ac_tt=`sed -n "/$ac_delim/p" confdefs.h` if test -z "$ac_tt"; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done # For the awk script, D is an array of macro values keyed by name, # likewise P contains macro parameters if any. Preserve backslash # newline sequences. ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* sed -n ' s/.\{148\}/&'"$ac_delim"'/g t rset :rset s/^[ ]*#[ ]*define[ ][ ]*/ / t def d :def s/\\$// t bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3"/p s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p d :bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3\\\\\\n"\\/p t cont s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p t cont d :cont n s/.\{148\}/&'"$ac_delim"'/g t clear :clear s/\\$// t bsnlc s/["\\]/\\&/g; s/^/"/; s/$/"/p d :bsnlc s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p b cont ' >$CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 for (key in D) D_is_set[key] = 1 FS = "" } /^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { line = \$ 0 split(line, arg, " ") if (arg[1] == "#") { defundef = arg[2] mac1 = arg[3] } else { defundef = substr(arg[1], 2) mac1 = arg[2] } split(mac1, mac2, "(") #) macro = mac2[1] prefix = substr(line, 1, index(line, defundef) - 1) if (D_is_set[macro]) { # Preserve the white space surrounding the "#". print prefix "define", macro P[macro] D[macro] next } else { # Replace #undef with comments. This is necessary, for example, # in the case of _POSIX_SOURCE, which is predefined and required # on some systems where configure will not decide to define it. if (defundef == "undef") { print "/*", prefix defundef, macro, "*/" next } } } { print } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 fi # test -n "$CONFIG_HEADERS" eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS :C $CONFIG_COMMANDS" shift for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac ac_save_IFS=$IFS IFS=: set x $ac_tag IFS=$ac_save_IFS shift ac_file=$1 shift case $ac_mode in :L) ac_source=$1;; :[FH]) ac_file_inputs= for ac_f do case $ac_f in -) ac_f="$ac_tmp/stdin";; *) # Look for the file first in the build tree, then in the source tree # (if the path is not absolute). The absolute path cannot be DOS-style, # because $ac_f cannot contain `:'. test -f "$ac_f" || case $ac_f in [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; esac case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac as_fn_append ac_file_inputs " '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ configure_input='Generated from '` $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 $as_echo "$as_me: creating $ac_file" >&6;} fi # Neutralize special characters interpreted by sed in replacement strings. case $configure_input in #( *\&* | *\|* | *\\* ) ac_sed_conf_input=`$as_echo "$configure_input" | sed 's/[\\\\&|]/\\\\&/g'`;; #( *) ac_sed_conf_input=$configure_input;; esac case $ac_tag in *:-:* | *:-) cat >"$ac_tmp/stdin" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac ac_dir=`$as_dirname -- "$ac_file" || $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix case $ac_mode in :F) # # CONFIG_FILE # case $INSTALL in [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; esac ac_MKDIR_P=$MKDIR_P case $MKDIR_P in [\\/$]* | ?:[\\/]* ) ;; */*) ac_MKDIR_P=$ac_top_build_prefix$MKDIR_P ;; esac _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= ac_sed_dataroot=' /datarootdir/ { p q } /@datadir@/p /@docdir@/p /@infodir@/p /@localedir@/p /@mandir@/p' case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 $as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_sed_extra="$ac_vpsub $extrasub _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t s&@builddir@&$ac_builddir&;t t s&@abs_builddir@&$ac_abs_builddir&;t t s&@abs_top_builddir@&$ac_abs_top_builddir&;t t s&@INSTALL@&$ac_INSTALL&;t t s&@MKDIR_P@&$ac_MKDIR_P&;t t $ac_datarootdir_hack " eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ "$ac_tmp/out"`; test -z "$ac_out"; } && { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&5 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&2;} rm -f "$ac_tmp/stdin" case $ac_file in -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; esac \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; :H) # # CONFIG_HEADER # if test x"$ac_file" != x-; then { $as_echo "/* $configure_input */" \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" } >"$ac_tmp/config.h" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 $as_echo "$as_me: $ac_file is unchanged" >&6;} else rm -f "$ac_file" mv "$ac_tmp/config.h" "$ac_file" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 fi else $as_echo "/* $configure_input */" \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ || as_fn_error $? "could not create -" "$LINENO" 5 fi # Compute "$ac_file"'s index in $config_headers. _am_arg="$ac_file" _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done echo "timestamp for $_am_arg" >`$as_dirname -- "$_am_arg" || $as_expr X"$_am_arg" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$_am_arg" : 'X\(//\)[^/]' \| \ X"$_am_arg" : 'X\(//\)$' \| \ X"$_am_arg" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$_am_arg" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'`/stamp-h$_am_stamp_count ;; :C) { $as_echo "$as_me:${as_lineno-$LINENO}: executing $ac_file commands" >&5 $as_echo "$as_me: executing $ac_file commands" >&6;} ;; esac case $ac_file$ac_mode in "depfiles":C) test x"$AMDEP_TRUE" != x"" || { # Autoconf 2.62 quotes --file arguments for eval, but not when files # are listed without --file. Let's play safe and only enable the eval # if we detect the quoting. case $CONFIG_FILES in *\'*) eval set x "$CONFIG_FILES" ;; *) set x $CONFIG_FILES ;; esac shift for mf do # Strip MF so we end up with the name of the file. mf=`echo "$mf" | sed -e 's/:.*$//'` # Check whether this is an Automake generated Makefile or not. # We used to match only the files named `Makefile.in', but # some people rename them; so instead we look at the file content. # Grep'ing the first line is not enough: some people post-process # each Makefile.in and add a new line on top of each file to say so. # Grep'ing the whole file is not good either: AIX grep has a line # limit of 2048, but all sed's we know have understand at least 4000. if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then dirpart=`$as_dirname -- "$mf" || $as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$mf" : 'X\(//\)[^/]' \| \ X"$mf" : 'X\(//\)$' \| \ X"$mf" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$mf" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` else continue fi # Extract the definition of DEPDIR, am__include, and am__quote # from the Makefile without running `make'. DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` test -z "$DEPDIR" && continue am__include=`sed -n 's/^am__include = //p' < "$mf"` test -z "am__include" && continue am__quote=`sed -n 's/^am__quote = //p' < "$mf"` # When using ansi2knr, U may be empty or an underscore; expand it U=`sed -n 's/^U = //p' < "$mf"` # Find all dependency output files, they are included files with # $(DEPDIR) in their names. We invoke sed twice because it is the # simplest approach to changing $(DEPDIR) to its actual value in the # expansion. for file in `sed -n " s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do # Make sure the directory exists. test -f "$dirpart/$file" && continue fdir=`$as_dirname -- "$file" || $as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$file" : 'X\(//\)[^/]' \| \ X"$file" : 'X\(//\)$' \| \ X"$file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir=$dirpart/$fdir; as_fn_mkdir_p # echo "creating $dirpart/$file" echo '# dummy' > "$dirpart/$file" done done } ;; "libtool":C) # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes. if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi cfgfile="${ofile}T" trap "$RM \"$cfgfile\"; exit 1" 1 2 15 $RM "$cfgfile" cat <<_LT_EOF >> "$cfgfile" #! $SHELL # `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services. # Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION # Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: # NOTE: Changes made to this file will be lost: look at ltmain.sh. # # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, # 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is part of GNU Libtool. # # GNU Libtool is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, or # obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # The names of the tagged configurations supported by this script. available_tags="CXX " # ### BEGIN LIBTOOL CONFIG # Which release of libtool.m4 was used? macro_version=$macro_version macro_revision=$macro_revision # Whether or not to build shared libraries. build_libtool_libs=$enable_shared # Whether or not to build static libraries. build_old_libs=$enable_static # What type of objects to build. pic_mode=$pic_mode # Whether or not to optimize for fast installation. fast_install=$enable_fast_install # Shell to use when invoking shell scripts. SHELL=$lt_SHELL # An echo program that protects backslashes. ECHO=$lt_ECHO # The PATH separator for the build system. PATH_SEPARATOR=$lt_PATH_SEPARATOR # The host system. host_alias=$host_alias host=$host host_os=$host_os # The build system. build_alias=$build_alias build=$build build_os=$build_os # A sed program that does not truncate output. SED=$lt_SED # Sed that helps us avoid accidentally triggering echo(1) options like -n. Xsed="\$SED -e 1s/^X//" # A grep program that handles long lines. GREP=$lt_GREP # An ERE matcher. EGREP=$lt_EGREP # A literal string matcher. FGREP=$lt_FGREP # A BSD- or MS-compatible name lister. NM=$lt_NM # Whether we need soft or hard links. LN_S=$lt_LN_S # What is the maximum length of a command? max_cmd_len=$max_cmd_len # Object file suffix (normally "o"). objext=$ac_objext # Executable file suffix (normally ""). exeext=$exeext # whether the shell understands "unset". lt_unset=$lt_unset # turn spaces into newlines. SP2NL=$lt_lt_SP2NL # turn newlines into spaces. NL2SP=$lt_lt_NL2SP # convert \$build file names to \$host format. to_host_file_cmd=$lt_cv_to_host_file_cmd # convert \$build files to toolchain format. to_tool_file_cmd=$lt_cv_to_tool_file_cmd # An object symbol dumper. OBJDUMP=$lt_OBJDUMP # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method # Command to use when deplibs_check_method = "file_magic". file_magic_cmd=$lt_file_magic_cmd # How to find potential files when deplibs_check_method = "file_magic". file_magic_glob=$lt_file_magic_glob # Find potential files using nocaseglob when deplibs_check_method = "file_magic". want_nocaseglob=$lt_want_nocaseglob # DLL creation program. DLLTOOL=$lt_DLLTOOL # Command to associate shared and link libraries. sharedlib_from_linklib_cmd=$lt_sharedlib_from_linklib_cmd # The archiver. AR=$lt_AR # Flags to create an archive. AR_FLAGS=$lt_AR_FLAGS # How to feed a file listing to the archiver. archiver_list_spec=$lt_archiver_list_spec # A symbol stripping program. STRIP=$lt_STRIP # Commands used to install an old-style archive. RANLIB=$lt_RANLIB old_postinstall_cmds=$lt_old_postinstall_cmds old_postuninstall_cmds=$lt_old_postuninstall_cmds # Whether to use a lock for old archive extraction. lock_old_archive_extraction=$lock_old_archive_extraction # A C compiler. LTCC=$lt_CC # LTCC compiler flags. LTCFLAGS=$lt_CFLAGS # Take the output of nm and produce a listing of raw symbols and C names. global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe # Transform the output of nm in a proper C declaration. global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl # Transform the output of nm in a C name address pair. global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address # Transform the output of nm in a C name address pair when lib prefix is needed. global_symbol_to_c_name_address_lib_prefix=$lt_lt_cv_sys_global_symbol_to_c_name_address_lib_prefix # Specify filename containing input files for \$NM. nm_file_list_spec=$lt_nm_file_list_spec # The root where to search for dependent libraries,and in which our libraries should be installed. lt_sysroot=$lt_sysroot # The name of the directory that contains temporary libtool files. objdir=$objdir # Used to examine libraries when file_magic_cmd begins with "file". MAGIC_CMD=$MAGIC_CMD # Must we lock files when doing compilation? need_locks=$lt_need_locks # Manifest tool. MANIFEST_TOOL=$lt_MANIFEST_TOOL # Tool to manipulate archived DWARF debug symbol files on Mac OS X. DSYMUTIL=$lt_DSYMUTIL # Tool to change global to local symbols on Mac OS X. NMEDIT=$lt_NMEDIT # Tool to manipulate fat objects and archives on Mac OS X. LIPO=$lt_LIPO # ldd/readelf like tool for Mach-O binaries on Mac OS X. OTOOL=$lt_OTOOL # ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4. OTOOL64=$lt_OTOOL64 # Old archive suffix (normally "a"). libext=$libext # Shared library suffix (normally ".so"). shrext_cmds=$lt_shrext_cmds # The commands to extract the exported symbol list from a shared archive. extract_expsyms_cmds=$lt_extract_expsyms_cmds # Variables whose values should be saved in libtool wrapper scripts and # restored at link time. variables_saved_for_relink=$lt_variables_saved_for_relink # Do we need the "lib" prefix for modules? need_lib_prefix=$need_lib_prefix # Do we need a version for libraries? need_version=$need_version # Library versioning type. version_type=$version_type # Shared library runtime path variable. runpath_var=$runpath_var # Shared library path variable. shlibpath_var=$shlibpath_var # Is shlibpath searched before the hard-coded library search path? shlibpath_overrides_runpath=$shlibpath_overrides_runpath # Format of library name prefix. libname_spec=$lt_libname_spec # List of archive names. First name is the real one, the rest are links. # The last name is the one that the linker finds with -lNAME library_names_spec=$lt_library_names_spec # The coded name of the library, if different from the real name. soname_spec=$lt_soname_spec # Permission mode override for installation of shared libraries. install_override_mode=$lt_install_override_mode # Command to use after installation of a shared archive. postinstall_cmds=$lt_postinstall_cmds # Command to use after uninstallation of a shared archive. postuninstall_cmds=$lt_postuninstall_cmds # Commands used to finish a libtool library installation in a directory. finish_cmds=$lt_finish_cmds # As "finish_cmds", except a single script fragment to be evaled but # not shown. finish_eval=$lt_finish_eval # Whether we should hardcode library paths into libraries. hardcode_into_libs=$hardcode_into_libs # Compile-time system search path for libraries. sys_lib_search_path_spec=$lt_sys_lib_search_path_spec # Run-time system search path for libraries. sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec # Whether dlopen is supported. dlopen_support=$enable_dlopen # Whether dlopen of programs is supported. dlopen_self=$enable_dlopen_self # Whether dlopen of statically linked programs is supported. dlopen_self_static=$enable_dlopen_self_static # Commands to strip libraries. old_striplib=$lt_old_striplib striplib=$lt_striplib # The linker used to build libraries. LD=$lt_LD # How to create reloadable object files. reload_flag=$lt_reload_flag reload_cmds=$lt_reload_cmds # Commands used to build an old-style archive. old_archive_cmds=$lt_old_archive_cmds # A language specific compiler. CC=$lt_compiler # Is the compiler the GNU compiler? with_gcc=$GCC # Compiler flag to turn off builtin functions. no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag # Additional compiler flags for building library objects. pic_flag=$lt_lt_prog_compiler_pic # How to pass a linker flag through the compiler. wl=$lt_lt_prog_compiler_wl # Compiler flag to prevent dynamic linking. link_static_flag=$lt_lt_prog_compiler_static # Does compiler simultaneously support -c and -o options? compiler_c_o=$lt_lt_cv_prog_compiler_c_o # Whether or not to add -lc for building shared libraries. build_libtool_need_lc=$archive_cmds_need_lc # Whether or not to disallow shared libs when runtime libs are static. allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes # Compiler flag to allow reflexive dlopens. export_dynamic_flag_spec=$lt_export_dynamic_flag_spec # Compiler flag to generate shared objects directly from archives. whole_archive_flag_spec=$lt_whole_archive_flag_spec # Whether the compiler copes with passing no objects directly. compiler_needs_object=$lt_compiler_needs_object # Create an old-style archive from a shared archive. old_archive_from_new_cmds=$lt_old_archive_from_new_cmds # Create a temporary old-style archive to link instead of a shared archive. old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds # Commands used to build a shared archive. archive_cmds=$lt_archive_cmds archive_expsym_cmds=$lt_archive_expsym_cmds # Commands used to build a loadable module if different from building # a shared archive. module_cmds=$lt_module_cmds module_expsym_cmds=$lt_module_expsym_cmds # Whether we are building with GNU ld or not. with_gnu_ld=$lt_with_gnu_ld # Flag that allows shared libraries with undefined symbols to be built. allow_undefined_flag=$lt_allow_undefined_flag # Flag that enforces no undefined symbols. no_undefined_flag=$lt_no_undefined_flag # Flag to hardcode \$libdir into a binary during linking. # This must work even if \$libdir does not exist hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec # Whether we need a single "-rpath" flag with a separated argument. hardcode_libdir_separator=$lt_hardcode_libdir_separator # Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes # DIR into the resulting binary. hardcode_direct=$hardcode_direct # Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes # DIR into the resulting binary and the resulting library dependency is # "absolute",i.e impossible to change by setting \${shlibpath_var} if the # library is relocated. hardcode_direct_absolute=$hardcode_direct_absolute # Set to "yes" if using the -LDIR flag during linking hardcodes DIR # into the resulting binary. hardcode_minus_L=$hardcode_minus_L # Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR # into the resulting binary. hardcode_shlibpath_var=$hardcode_shlibpath_var # Set to "yes" if building a shared library automatically hardcodes DIR # into the library and all subsequent libraries and executables linked # against it. hardcode_automatic=$hardcode_automatic # Set to yes if linker adds runtime paths of dependent libraries # to runtime path list. inherit_rpath=$inherit_rpath # Whether libtool must link a program against all its dependency libraries. link_all_deplibs=$link_all_deplibs # Set to "yes" if exported symbols are required. always_export_symbols=$always_export_symbols # The commands to list exported symbols. export_symbols_cmds=$lt_export_symbols_cmds # Symbols that should not be listed in the preloaded symbols. exclude_expsyms=$lt_exclude_expsyms # Symbols that must always be exported. include_expsyms=$lt_include_expsyms # Commands necessary for linking programs (against libraries) with templates. prelink_cmds=$lt_prelink_cmds # Commands necessary for finishing linking programs. postlink_cmds=$lt_postlink_cmds # Specify filename containing input files. file_list_spec=$lt_file_list_spec # How to hardcode a shared library path into an executable. hardcode_action=$hardcode_action # The directories searched by this compiler when creating a shared library. compiler_lib_search_dirs=$lt_compiler_lib_search_dirs # Dependencies to place before and after the objects being linked to # create a shared library. predep_objects=$lt_predep_objects postdep_objects=$lt_postdep_objects predeps=$lt_predeps postdeps=$lt_postdeps # The library search path used internally by the compiler when linking # a shared library. compiler_lib_search_path=$lt_compiler_lib_search_path # ### END LIBTOOL CONFIG _LT_EOF case $host_os in aix3*) cat <<\_LT_EOF >> "$cfgfile" # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi _LT_EOF ;; esac ltmain="$ac_aux_dir/ltmain.sh" # We use sed instead of cat because bash on DJGPP gets confused if # if finds mixed CR/LF and LF-only lines. Since sed operates in # text mode, it properly converts lines to CR/LF. This bash problem # is reportedly fixed, but why not run on old versions too? sed '$q' "$ltmain" >> "$cfgfile" \ || (rm -f "$cfgfile"; exit 1) if test x"$xsi_shell" = xyes; then sed -e '/^func_dirname ()$/,/^} # func_dirname /c\ func_dirname ()\ {\ \ case ${1} in\ \ */*) func_dirname_result="${1%/*}${2}" ;;\ \ * ) func_dirname_result="${3}" ;;\ \ esac\ } # Extended-shell func_dirname implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_basename ()$/,/^} # func_basename /c\ func_basename ()\ {\ \ func_basename_result="${1##*/}"\ } # Extended-shell func_basename implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_dirname_and_basename ()$/,/^} # func_dirname_and_basename /c\ func_dirname_and_basename ()\ {\ \ case ${1} in\ \ */*) func_dirname_result="${1%/*}${2}" ;;\ \ * ) func_dirname_result="${3}" ;;\ \ esac\ \ func_basename_result="${1##*/}"\ } # Extended-shell func_dirname_and_basename implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_stripname ()$/,/^} # func_stripname /c\ func_stripname ()\ {\ \ # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\ \ # positional parameters, so assign one to ordinary parameter first.\ \ func_stripname_result=${3}\ \ func_stripname_result=${func_stripname_result#"${1}"}\ \ func_stripname_result=${func_stripname_result%"${2}"}\ } # Extended-shell func_stripname implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_split_long_opt ()$/,/^} # func_split_long_opt /c\ func_split_long_opt ()\ {\ \ func_split_long_opt_name=${1%%=*}\ \ func_split_long_opt_arg=${1#*=}\ } # Extended-shell func_split_long_opt implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_split_short_opt ()$/,/^} # func_split_short_opt /c\ func_split_short_opt ()\ {\ \ func_split_short_opt_arg=${1#??}\ \ func_split_short_opt_name=${1%"$func_split_short_opt_arg"}\ } # Extended-shell func_split_short_opt implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_lo2o ()$/,/^} # func_lo2o /c\ func_lo2o ()\ {\ \ case ${1} in\ \ *.lo) func_lo2o_result=${1%.lo}.${objext} ;;\ \ *) func_lo2o_result=${1} ;;\ \ esac\ } # Extended-shell func_lo2o implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_xform ()$/,/^} # func_xform /c\ func_xform ()\ {\ func_xform_result=${1%.*}.lo\ } # Extended-shell func_xform implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_arith ()$/,/^} # func_arith /c\ func_arith ()\ {\ func_arith_result=$(( $* ))\ } # Extended-shell func_arith implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_len ()$/,/^} # func_len /c\ func_len ()\ {\ func_len_result=${#1}\ } # Extended-shell func_len implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: fi if test x"$lt_shell_append" = xyes; then sed -e '/^func_append ()$/,/^} # func_append /c\ func_append ()\ {\ eval "${1}+=\\${2}"\ } # Extended-shell func_append implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_append_quoted ()$/,/^} # func_append_quoted /c\ func_append_quoted ()\ {\ \ func_quote_for_eval "${2}"\ \ eval "${1}+=\\\\ \\$func_quote_for_eval_result"\ } # Extended-shell func_append_quoted implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: # Save a `func_append' function call where possible by direct use of '+=' sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: else # Save a `func_append' function call even when '+=' is not available sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: fi if test x"$_lt_function_replace_fail" = x":"; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Unable to substitute extended shell functions in $ofile" >&5 $as_echo "$as_me: WARNING: Unable to substitute extended shell functions in $ofile" >&2;} fi mv -f "$cfgfile" "$ofile" || (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") chmod +x "$ofile" cat <<_LT_EOF >> "$ofile" # ### BEGIN LIBTOOL TAG CONFIG: CXX # The linker used to build libraries. LD=$lt_LD_CXX # How to create reloadable object files. reload_flag=$lt_reload_flag_CXX reload_cmds=$lt_reload_cmds_CXX # Commands used to build an old-style archive. old_archive_cmds=$lt_old_archive_cmds_CXX # A language specific compiler. CC=$lt_compiler_CXX # Is the compiler the GNU compiler? with_gcc=$GCC_CXX # Compiler flag to turn off builtin functions. no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_CXX # Additional compiler flags for building library objects. pic_flag=$lt_lt_prog_compiler_pic_CXX # How to pass a linker flag through the compiler. wl=$lt_lt_prog_compiler_wl_CXX # Compiler flag to prevent dynamic linking. link_static_flag=$lt_lt_prog_compiler_static_CXX # Does compiler simultaneously support -c and -o options? compiler_c_o=$lt_lt_cv_prog_compiler_c_o_CXX # Whether or not to add -lc for building shared libraries. build_libtool_need_lc=$archive_cmds_need_lc_CXX # Whether or not to disallow shared libs when runtime libs are static. allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_CXX # Compiler flag to allow reflexive dlopens. export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_CXX # Compiler flag to generate shared objects directly from archives. whole_archive_flag_spec=$lt_whole_archive_flag_spec_CXX # Whether the compiler copes with passing no objects directly. compiler_needs_object=$lt_compiler_needs_object_CXX # Create an old-style archive from a shared archive. old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_CXX # Create a temporary old-style archive to link instead of a shared archive. old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_CXX # Commands used to build a shared archive. archive_cmds=$lt_archive_cmds_CXX archive_expsym_cmds=$lt_archive_expsym_cmds_CXX # Commands used to build a loadable module if different from building # a shared archive. module_cmds=$lt_module_cmds_CXX module_expsym_cmds=$lt_module_expsym_cmds_CXX # Whether we are building with GNU ld or not. with_gnu_ld=$lt_with_gnu_ld_CXX # Flag that allows shared libraries with undefined symbols to be built. allow_undefined_flag=$lt_allow_undefined_flag_CXX # Flag that enforces no undefined symbols. no_undefined_flag=$lt_no_undefined_flag_CXX # Flag to hardcode \$libdir into a binary during linking. # This must work even if \$libdir does not exist hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_CXX # Whether we need a single "-rpath" flag with a separated argument. hardcode_libdir_separator=$lt_hardcode_libdir_separator_CXX # Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes # DIR into the resulting binary. hardcode_direct=$hardcode_direct_CXX # Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes # DIR into the resulting binary and the resulting library dependency is # "absolute",i.e impossible to change by setting \${shlibpath_var} if the # library is relocated. hardcode_direct_absolute=$hardcode_direct_absolute_CXX # Set to "yes" if using the -LDIR flag during linking hardcodes DIR # into the resulting binary. hardcode_minus_L=$hardcode_minus_L_CXX # Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR # into the resulting binary. hardcode_shlibpath_var=$hardcode_shlibpath_var_CXX # Set to "yes" if building a shared library automatically hardcodes DIR # into the library and all subsequent libraries and executables linked # against it. hardcode_automatic=$hardcode_automatic_CXX # Set to yes if linker adds runtime paths of dependent libraries # to runtime path list. inherit_rpath=$inherit_rpath_CXX # Whether libtool must link a program against all its dependency libraries. link_all_deplibs=$link_all_deplibs_CXX # Set to "yes" if exported symbols are required. always_export_symbols=$always_export_symbols_CXX # The commands to list exported symbols. export_symbols_cmds=$lt_export_symbols_cmds_CXX # Symbols that should not be listed in the preloaded symbols. exclude_expsyms=$lt_exclude_expsyms_CXX # Symbols that must always be exported. include_expsyms=$lt_include_expsyms_CXX # Commands necessary for linking programs (against libraries) with templates. prelink_cmds=$lt_prelink_cmds_CXX # Commands necessary for finishing linking programs. postlink_cmds=$lt_postlink_cmds_CXX # Specify filename containing input files. file_list_spec=$lt_file_list_spec_CXX # How to hardcode a shared library path into an executable. hardcode_action=$hardcode_action_CXX # The directories searched by this compiler when creating a shared library. compiler_lib_search_dirs=$lt_compiler_lib_search_dirs_CXX # Dependencies to place before and after the objects being linked to # create a shared library. predep_objects=$lt_predep_objects_CXX postdep_objects=$lt_postdep_objects_CXX predeps=$lt_predeps_CXX postdeps=$lt_postdeps_CXX # The library search path used internally by the compiler when linking # a shared library. compiler_lib_search_path=$lt_compiler_lib_search_path_CXX # ### END LIBTOOL TAG CONFIG: CXX _LT_EOF ;; esac done # for ac_tag as_fn_exit 0 _ACEOF ac_clean_files=$ac_clean_files_save test $ac_write_fail = 0 || as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. # Unfortunately, on DOS this fails, as config.log is still kept open # by configure, so config.status won't be able to write to it; its # output is simply discarded. So we exec the FD to /dev/null, # effectively closing config.log, so it can be properly (re)opened and # appended to by config.status. When coming back to configure, we # need to make the FD available again. if test "$no_create" != yes; then ac_cs_success=: ac_config_status_args= test "$silent" = yes && ac_config_status_args="$ac_config_status_args --quiet" exec 5>/dev/null $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. $ac_cs_success || as_fn_exit 1 fi # # CONFIG_SUBDIRS section. # if test "$no_recursion" != yes; then # Remove --cache-file, --srcdir, and --disable-option-checking arguments # so they do not pile up. ac_sub_configure_args= ac_prev= eval "set x $ac_configure_args" shift for ac_arg do if test -n "$ac_prev"; then ac_prev= continue fi case $ac_arg in -cache-file | --cache-file | --cache-fil | --cache-fi \ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) ac_prev=cache_file ;; -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* \ | --c=*) ;; --config-cache | -C) ;; -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) ac_prev=srcdir ;; -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) ;; -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) ac_prev=prefix ;; -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) ;; --disable-option-checking) ;; *) case $ac_arg in *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac as_fn_append ac_sub_configure_args " '$ac_arg'" ;; esac done # Always prepend --prefix to ensure using the same prefix # in subdir configurations. ac_arg="--prefix=$prefix" case $ac_arg in *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac ac_sub_configure_args="'$ac_arg' $ac_sub_configure_args" # Pass --silent if test "$silent" = yes; then ac_sub_configure_args="--silent $ac_sub_configure_args" fi # Always prepend --disable-option-checking to silence warnings, since # different subdirs can have different --enable and --with options. ac_sub_configure_args="--disable-option-checking $ac_sub_configure_args" ac_popdir=`pwd` for ac_dir in : $subdirs; do test "x$ac_dir" = x: && continue # Do not complain, so a configure script can configure whichever # parts of a large source tree are present. test -d "$srcdir/$ac_dir" || continue ac_msg="=== configuring in $ac_dir (`pwd`/$ac_dir)" $as_echo "$as_me:${as_lineno-$LINENO}: $ac_msg" >&5 $as_echo "$ac_msg" >&6 as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix cd "$ac_dir" # Check for guested configure; otherwise get Cygnus style configure. if test -f "$ac_srcdir/configure.gnu"; then ac_sub_configure=$ac_srcdir/configure.gnu elif test -f "$ac_srcdir/configure"; then ac_sub_configure=$ac_srcdir/configure elif test -f "$ac_srcdir/configure.in"; then # This should be Cygnus configure. ac_sub_configure=$ac_aux_dir/configure else { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: no configuration information is in $ac_dir" >&5 $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2;} ac_sub_configure= fi # The recursion is here. if test -n "$ac_sub_configure"; then # Make the cache file name correct relative to the subdirectory. case $cache_file in [\\/]* | ?:[\\/]* ) ac_sub_cache_file=$cache_file ;; *) # Relative name. ac_sub_cache_file=$ac_top_build_prefix$cache_file ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: running $SHELL $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_srcdir" >&5 $as_echo "$as_me: running $SHELL $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_srcdir" >&6;} # The eval makes quoting arguments work. eval "\$SHELL \"\$ac_sub_configure\" $ac_sub_configure_args \ --cache-file=\"\$ac_sub_cache_file\" --srcdir=\"\$ac_srcdir\"" || as_fn_error $? "$ac_sub_configure failed for $ac_dir" "$LINENO" 5 fi cd "$ac_popdir" done fi if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi sipxtapi-3.3.0~test17/AUTHORS0000644000175000017500000000000012205613305016431 0ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/COPYING0000644000175000017500000006277412205613305016446 0ustar00danieldaniel00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. sipXtapi Copyright (C) 2004-2006, Pingtel Corp. Copyright (C) 2004-2009, SIPfoundry Inc. Copyright (C) 2006-2013, SIPez LLC Copyright (C) 2013, Daniel Pocock http://danielpocock.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA sipxtapi-3.3.0~test17/ChangeLog0000644000175000017500000000000012205613305017133 0ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/INSTALL0000644000175000017500000003660012321250507016431 0ustar00danieldaniel00000000000000Installation Instructions ************************* Copyright (C) 1994-1996, 1999-2002, 2004-2011 Free Software Foundation, Inc. Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without warranty of any kind. Basic Installation ================== Briefly, the shell commands `./configure; make; make install' should configure, build, and install this package. The following more-detailed instructions are generic; see the `README' file for instructions specific to this package. Some packages provide this `INSTALL' file but do not implement all of the features documented below. The lack of an optional feature in a given package is not necessarily a bug. More recommendations for GNU packages can be found in *note Makefile Conventions: (standards)Makefile Conventions. The `configure' shell script attempts to guess correct values for various system-dependent variables used during compilation. It uses those values to create a `Makefile' in each directory of the package. It may also create one or more `.h' files containing system-dependent definitions. Finally, it creates a shell script `config.status' that you can run in the future to recreate the current configuration, and a file `config.log' containing compiler output (useful mainly for debugging `configure'). It can also use an optional file (typically called `config.cache' and enabled with `--cache-file=config.cache' or simply `-C') that saves the results of its tests to speed up reconfiguring. Caching is disabled by default to prevent problems with accidental use of stale cache files. If you need to do unusual things to compile the package, please try to figure out how `configure' could check whether to do them, and mail diffs or instructions to the address given in the `README' so they can be considered for the next release. If you are using the cache, and at some point `config.cache' contains results you don't want to keep, you may remove or edit it. The file `configure.ac' (or `configure.in') is used to create `configure' by a program called `autoconf'. You need `configure.ac' if you want to change it or regenerate `configure' using a newer version of `autoconf'. The simplest way to compile this package is: 1. `cd' to the directory containing the package's source code and type `./configure' to configure the package for your system. Running `configure' might take a while. While running, it prints some messages telling which features it is checking for. 2. Type `make' to compile the package. 3. Optionally, type `make check' to run any self-tests that come with the package, generally using the just-built uninstalled binaries. 4. Type `make install' to install the programs and any data files and documentation. When installing into a prefix owned by root, it is recommended that the package be configured and built as a regular user, and only the `make install' phase executed with root privileges. 5. Optionally, type `make installcheck' to repeat any self-tests, but this time using the binaries in their final installed location. This target does not install anything. Running this target as a regular user, particularly if the prior `make install' required root privileges, verifies that the installation completed correctly. 6. You can remove the program binaries and object files from the source code directory by typing `make clean'. To also remove the files that `configure' created (so you can compile the package for a different kind of computer), type `make distclean'. There is also a `make maintainer-clean' target, but that is intended mainly for the package's developers. If you use it, you may have to get all sorts of other programs in order to regenerate files that came with the distribution. 7. Often, you can also type `make uninstall' to remove the installed files again. In practice, not all packages have tested that uninstallation works correctly, even though it is required by the GNU Coding Standards. 8. Some packages, particularly those that use Automake, provide `make distcheck', which can by used by developers to test that all other targets like `make install' and `make uninstall' work correctly. This target is generally not run by end users. Compilers and Options ===================== Some systems require unusual options for compilation or linking that the `configure' script does not know about. Run `./configure --help' for details on some of the pertinent environment variables. You can give `configure' initial values for configuration parameters by setting variables in the command line or in the environment. Here is an example: ./configure CC=c99 CFLAGS=-g LIBS=-lposix *Note Defining Variables::, for more details. Compiling For Multiple Architectures ==================================== You can compile the package for more than one kind of computer at the same time, by placing the object files for each architecture in their own directory. To do this, you can use GNU `make'. `cd' to the directory where you want the object files and executables to go and run the `configure' script. `configure' automatically checks for the source code in the directory that `configure' is in and in `..'. This is known as a "VPATH" build. With a non-GNU `make', it is safer to compile the package for one architecture at a time in the source code directory. After you have installed the package for one architecture, use `make distclean' before reconfiguring for another architecture. On MacOS X 10.5 and later systems, you can create libraries and executables that work on multiple system types--known as "fat" or "universal" binaries--by specifying multiple `-arch' options to the compiler but only a single `-arch' option to the preprocessor. Like this: ./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ CPP="gcc -E" CXXCPP="g++ -E" This is not guaranteed to produce working output in all cases, you may have to build one architecture at a time and combine the results using the `lipo' tool if you have problems. Installation Names ================== By default, `make install' installs the package's commands under `/usr/local/bin', include files under `/usr/local/include', etc. You can specify an installation prefix other than `/usr/local' by giving `configure' the option `--prefix=PREFIX', where PREFIX must be an absolute file name. You can specify separate installation prefixes for architecture-specific files and architecture-independent files. If you pass the option `--exec-prefix=PREFIX' to `configure', the package uses PREFIX as the prefix for installing programs and libraries. Documentation and other data files still use the regular prefix. In addition, if you use an unusual directory layout you can give options like `--bindir=DIR' to specify different values for particular kinds of files. Run `configure --help' for a list of the directories you can set and what kinds of files go in them. In general, the default for these options is expressed in terms of `${prefix}', so that specifying just `--prefix' will affect all of the other directory specifications that were not explicitly provided. The most portable way to affect installation locations is to pass the correct locations to `configure'; however, many packages provide one or both of the following shortcuts of passing variable assignments to the `make install' command line to change installation locations without having to reconfigure or recompile. The first method involves providing an override variable for each affected directory. For example, `make install prefix=/alternate/directory' will choose an alternate location for all directory configuration variables that were expressed in terms of `${prefix}'. Any directories that were specified during `configure', but not in terms of `${prefix}', must each be overridden at install time for the entire installation to be relocated. The approach of makefile variable overrides for each directory variable is required by the GNU Coding Standards, and ideally causes no recompilation. However, some platforms have known limitations with the semantics of shared libraries that end up requiring recompilation when using this method, particularly noticeable in packages that use GNU Libtool. The second method involves providing the `DESTDIR' variable. For example, `make install DESTDIR=/alternate/directory' will prepend `/alternate/directory' before all installation names. The approach of `DESTDIR' overrides is not required by the GNU Coding Standards, and does not work on platforms that have drive letters. On the other hand, it does better at avoiding recompilation issues, and works well even when some directory options were not specified in terms of `${prefix}' at `configure' time. Optional Features ================= If the package supports it, you can cause programs to be installed with an extra prefix or suffix on their names by giving `configure' the option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. Some packages pay attention to `--enable-FEATURE' options to `configure', where FEATURE indicates an optional part of the package. They may also pay attention to `--with-PACKAGE' options, where PACKAGE is something like `gnu-as' or `x' (for the X Window System). The `README' should mention any `--enable-' and `--with-' options that the package recognizes. For packages that use the X Window System, `configure' can usually find the X include and library files automatically, but if it doesn't, you can use the `configure' options `--x-includes=DIR' and `--x-libraries=DIR' to specify their locations. Some packages offer the ability to configure how verbose the execution of `make' will be. For these packages, running `./configure --enable-silent-rules' sets the default to minimal output, which can be overridden with `make V=1'; while running `./configure --disable-silent-rules' sets the default to verbose, which can be overridden with `make V=0'. Particular systems ================== On HP-UX, the default C compiler is not ANSI C compatible. If GNU CC is not installed, it is recommended to use the following options in order to use an ANSI C compiler: ./configure CC="cc -Ae -D_XOPEN_SOURCE=500" and if that doesn't work, install pre-built binaries of GCC for HP-UX. HP-UX `make' updates targets which have the same time stamps as their prerequisites, which makes it generally unusable when shipped generated files such as `configure' are involved. Use GNU `make' instead. On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot parse its `' header file. The option `-nodtk' can be used as a workaround. If GNU CC is not installed, it is therefore recommended to try ./configure CC="cc" and if that doesn't work, try ./configure CC="cc -nodtk" On Solaris, don't put `/usr/ucb' early in your `PATH'. This directory contains several dysfunctional programs; working variants of these programs are available in `/usr/bin'. So, if you need `/usr/ucb' in your `PATH', put it _after_ `/usr/bin'. On Haiku, software installed for all users goes in `/boot/common', not `/usr/local'. It is recommended to use the following options: ./configure --prefix=/boot/common Specifying the System Type ========================== There may be some features `configure' cannot figure out automatically, but needs to determine by the type of machine the package will run on. Usually, assuming the package is built to be run on the _same_ architectures, `configure' can figure that out, but if it prints a message saying it cannot guess the machine type, give it the `--build=TYPE' option. TYPE can either be a short name for the system type, such as `sun4', or a canonical name which has the form: CPU-COMPANY-SYSTEM where SYSTEM can have one of these forms: OS KERNEL-OS See the file `config.sub' for the possible values of each field. If `config.sub' isn't included in this package, then this package doesn't need to know the machine type. If you are _building_ compiler tools for cross-compiling, you should use the option `--target=TYPE' to select the type of system they will produce code for. If you want to _use_ a cross compiler, that generates code for a platform different from the build platform, you should specify the "host" platform (i.e., that on which the generated programs will eventually be run) with `--host=TYPE'. Sharing Defaults ================ If you want to set default values for `configure' scripts to share, you can create a site shell script called `config.site' that gives default values for variables like `CC', `cache_file', and `prefix'. `configure' looks for `PREFIX/share/config.site' if it exists, then `PREFIX/etc/config.site' if it exists. Or, you can set the `CONFIG_SITE' environment variable to the location of the site script. A warning: not all `configure' scripts look for a site script. Defining Variables ================== Variables not defined in a site shell script can be set in the environment passed to `configure'. However, some packages may run configure again during the build, and the customized values of these variables may be lost. In order to avoid this problem, you should set them in the `configure' command line, using `VAR=value'. For example: ./configure CC=/usr/local2/bin/gcc causes the specified `gcc' to be used as the C compiler (unless it is overridden in the site shell script). Unfortunately, this technique does not work for `CONFIG_SHELL' due to an Autoconf bug. Until the bug is fixed you can use this workaround: CONFIG_SHELL=/bin/bash /bin/bash ./configure CONFIG_SHELL=/bin/bash `configure' Invocation ====================== `configure' recognizes the following options to control how it operates. `--help' `-h' Print a summary of all of the options to `configure', and exit. `--help=short' `--help=recursive' Print a summary of the options unique to this package's `configure', and exit. The `short' variant lists options used only in the top level, while the `recursive' variant lists options also present in any nested packages. `--version' `-V' Print the version of Autoconf used to generate the `configure' script, and exit. `--cache-file=FILE' Enable the cache: use and save the results of the tests in FILE, traditionally `config.cache'. FILE defaults to `/dev/null' to disable caching. `--config-cache' `-C' Alias for `--cache-file=config.cache'. `--quiet' `--silent' `-q' Do not print messages saying which checks are being made. To suppress all normal output, redirect it to `/dev/null' (any error messages will still be shown). `--srcdir=DIR' Look for the package's source code in directory DIR. Usually `configure' can determine that directory automatically. `--prefix=DIR' Use DIR as the installation prefix. *note Installation Names:: for more details, including other options available for fine-tuning the installation locations. `--no-create' `-n' Run the configure checks, but stop before creating any output files. `configure' also accepts some other, not widely useful, options. Run `configure --help' for more details. sipxtapi-3.3.0~test17/NEWS0000644000175000017500000000000012205613305016060 0ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipxtapi.spec0000644000175000017500000000466512321445017020125 0ustar00danieldaniel00000000000000Name: sipxtapi Version: 3.3.0~test17 Release: 4 Summary: SIP stack, RTP media framework and codecs License: LGPLv2 Url: http://www.sipxtapi.org Source: http://www.sipxtapi.org/files/pub/sipX/%{name}-%{version}.tar.gz BuildRequires: libtool automake autoconf BuildRequires: cppunit-devel BuildRequires: doxygen BuildRequires: gsm-devel BuildRequires: openssl-devel >= 0.9.8 BuildRequires: pcre-devel BuildRequires: spandsp-devel BuildRequires: xerces-c-devel %description sipXtapi is a framework that makes it easy to construct SIP user agents, including soft-phones and telephony servers. %package devel Requires: %{name}%{?_isa} = %{version}-%{release} Summary: Development files for %{name} %description devel The %{name}-devel package contains libraries and header files for developing applications that use %{name}. %package doc Summary: API documentation for %{name} %description doc sipXtapi is a framework that makes it easy to construct SIP user agents, including softphones and telephony servers. This package provides developer documentation about the API. %prep %setup -q %build %configure --enable-topology-graph --disable-codec-ilbc --disable-codec-g726 --enable-codec-g722 --enable-codec-gsm --disable-static sed -i 's|^hardcode_libdir_flag_spec=.*|hardcode_libdir_flag_spec=""|g' libtool sed -i 's|^runpath_var=LD_RUN_PATH|runpath_var=DIE_RPATH_DIE|g' libtool make %{?_smp_mflags} # sipXtapi provides unit tests but they are not currently invoked # automatically as they demand network access and other local resources # that have to be manually configured #%check %install make DESTDIR=%{buildroot} install rm -f %{buildroot}%{_libdir}/lib*.a rm -f %{buildroot}%{_libdir}/lib*.la rm -rf %{buildroot}%{_bindir} %post -p /sbin/ldconfig %postun -p /sbin/ldconfig %files %defattr(-, root, root, -) %doc COPYING %{_libdir}/lib*.so.* %{_libdir}/sipxtapi/ %files devel %defattr(-, root, root, -) %doc COPYING %{_includedir}/sipxtapi/ %{_libdir}/lib*.so %{_datarootdir}/sipxtapi/ %files doc %defattr(-, root, root, -) %doc %{_docdir}/%{name}/* %changelog * Wed Aug 7 2013 Daniel Pocock - 3.3.0~test17-4 - Tweak documentation packaging * Wed Aug 7 2013 Daniel Pocock - 3.3.0~test17-3 - Various spec file improvements * Wed Aug 7 2013 Daniel Pocock - 3.3.0~test17-2 - Various spec file improvements * Mon May 6 2013 Daniel Pocock - 3.3.0~test17-1 - Initial build sipxtapi-3.3.0~test17/bin/0000755000175000017500000000000012321445023016142 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/bin/Makefile.am0000644000175000017500000000110712205613305020176 0ustar00danieldaniel00000000000000include $(top_srcdir)/config/sipXcommon.am.inc bin_SCRIPTS = \ @PACKAGE@-config $(top_builddir)/BUILDSTAMP: ${MAKE} -C $(top_builddir) BUILDSTAMP @PACKAGE@-config: $(top_srcdir)/config/sipX-config.in $(top_builddir)/BUILDSTAMP BuildStamp="$(shell cat $(top_builddir)/BUILDSTAMP)" \ ; ${LocalizeSipXconfig} -e "s/@SIPX_BUILDSTAMP\@/$${BuildStamp}/" \ $(top_srcdir)/config/sipX-config.in \ > @PACKAGE@-config chmod +x @PACKAGE@-config DISTCLEANFILES = \ @PACKAGE@-config \ $(top_srcdir)/config/@PACKAGE@-buildstamp.cpp \ $(top_srcdir)/config/@PACKAGE@-buildstamp.h sipxtapi-3.3.0~test17/bin/Makefile.in0000644000175000017500000004647012321444775020237 0ustar00danieldaniel00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # -*-makefile-*- VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ $(top_srcdir)/config/sipXcommon.am.inc subdir = bin ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/general.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/sipXlib.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(bindir)" SCRIPTS = $(bin_SCRIPTS) SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMRNB_INCLUDE = @AMRNB_INCLUDE@ AMRNB_LIB_ROOT = @AMRNB_LIB_ROOT@ AMRWB_INCLUDE = @AMRWB_INCLUDE@ AMRWB_LIB_ROOT = @AMRWB_LIB_ROOT@ AMRWB_TARGET = @AMRWB_TARGET@ AMR_TARGET = @AMR_TARGET@ AMTAR = @AMTAR@ ANT = @ANT@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CARBON_LIBS = @CARBON_LIBS@ CA_LIBS = @CA_LIBS@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPUNIT_CFLAGS = @CPPUNIT_CFLAGS@ CPPUNIT_CONFIG = @CPPUNIT_CONFIG@ CPPUNIT_LIBS = @CPPUNIT_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPS_PCRE_CFLAGS = @DEPS_PCRE_CFLAGS@ DEPS_PCRE_LIBS = @DEPS_PCRE_LIBS@ DLLTOOL = @DLLTOOL@ DOT = @DOT@ DOXYGEN = @DOXYGEN@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DYNEXT = @DYNEXT@ EAGC_LDFLAGS = @EAGC_LDFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EJBE_LDFLAGS = @EJBE_LDFLAGS@ EPLC_LDFLAGS = @EPLC_LDFLAGS@ EVAD_LDFLAGS = @EVAD_LDFLAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ G722_TARGET = @G722_TARGET@ G726_TARGET = @G726_TARGET@ GIPSINC = @GIPSINC@ GIPS_CE_OBJS = @GIPS_CE_OBJS@ GIPS_CPPFLAGS = @GIPS_CPPFLAGS@ GIPS_NEQ_OBJS = @GIPS_NEQ_OBJS@ GIPS_VE_OBJS = @GIPS_VE_OBJS@ GREP = @GREP@ GSM_CFLAGS = @GSM_CFLAGS@ GSM_CXXFLAGS = @GSM_CXXFLAGS@ GSM_LDFLAGS = @GSM_LDFLAGS@ GSM_LIBS = @GSM_LIBS@ GSM_TARGET = @GSM_TARGET@ ILBC_INCLUDE = @ILBC_INCLUDE@ ILBC_LIB_ROOT = @ILBC_LIB_ROOT@ ILBC_LIB_TARGET = @ILBC_LIB_TARGET@ ILBC_TARGET = @ILBC_TARGET@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTERFACE_FLAGS = @INTERFACE_FLAGS@ JAVA = @JAVA@ JAVAC_DEBUG = @JAVAC_DEBUG@ JAVAC_OPTIMIZED = @JAVAC_OPTIMIZED@ JAVA_HOME = @JAVA_HOME@ L16_TARGET = @L16_TARGET@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NAMED_PROGRAM = @NAMED_PROGRAM@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPUS_CFLAGS = @OPUS_CFLAGS@ OPUS_LIBS = @OPUS_LIBS@ OPUS_TARGET = @OPUS_TARGET@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PCMAPCMU_TARGET = @PCMAPCMU_TARGET@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ RTL_CXXFLAGS = @RTL_CXXFLAGS@ RTL_LDFLAGS = @RTL_LDFLAGS@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SIPXMEDIA_CE_LIBS = @SIPXMEDIA_CE_LIBS@ SIPXMEDIA_VE_LIBS = @SIPXMEDIA_VE_LIBS@ SIPXMEDIA_VE_STATIC_LIBS = @SIPXMEDIA_VE_STATIC_LIBS@ SIPXPBXUSER = @SIPXPBXUSER@ SIPXPHONECONF = @SIPXPHONECONF@ SIPXPHONEDATA = @SIPXPHONEDATA@ SIPXPHONELIB = @SIPXPHONELIB@ SIPX_BACKUPDIR = @SIPX_BACKUPDIR@ SIPX_BINDIR = @SIPX_BINDIR@ SIPX_CONFDIR = @SIPX_CONFDIR@ SIPX_CONFIGPHONEDIR = @SIPX_CONFIGPHONEDIR@ SIPX_DATADIR = @SIPX_DATADIR@ SIPX_DBDIR = @SIPX_DBDIR@ SIPX_DOCDIR = @SIPX_DOCDIR@ SIPX_INCDIR = @SIPX_INCDIR@ SIPX_LIBDIR = @SIPX_LIBDIR@ SIPX_LOGDIR = @SIPX_LOGDIR@ SIPX_PARKMUSICDIR = @SIPX_PARKMUSICDIR@ SIPX_RUNDIR = @SIPX_RUNDIR@ SIPX_SCHEMADIR = @SIPX_SCHEMADIR@ SIPX_TMPDIR = @SIPX_TMPDIR@ SIPX_UNIT_TARGET = @SIPX_UNIT_TARGET@ SIPX_VXMLDATADIR = @SIPX_VXMLDATADIR@ SPANDSP_CFLAGS = @SPANDSP_CFLAGS@ SPANDSP_CXXFLAGS = @SPANDSP_CXXFLAGS@ SPANDSP_LDFLAGS = @SPANDSP_LDFLAGS@ SPANDSP_LIBS = @SPANDSP_LIBS@ SPEEXDSP_CFLAGS = @SPEEXDSP_CFLAGS@ SPEEXDSP_LIBS = @SPEEXDSP_LIBS@ SPEEXDSP_STATIC_LIB = @SPEEXDSP_STATIC_LIB@ SPEEX_CFLAGS = @SPEEX_CFLAGS@ SPEEX_LIBS = @SPEEX_LIBS@ SPEEX_ROOT = @SPEEX_ROOT@ SPEEX_STATIC_LIB = @SPEEX_STATIC_LIB@ SPEEX_TARGET = @SPEEX_TARGET@ SS_LDFLAGS = @SS_LDFLAGS@ STATIC_CODEC_LIBS = @STATIC_CODEC_LIBS@ STRIP = @STRIP@ TONES_TARGET = @TONES_TARGET@ VERSION = @VERSION@ VIDEO_DEFINE = @VIDEO_DEFINE@ WXWIDGETS_CFLAGS = @WXWIDGETS_CFLAGS@ WXWIDGETS_CONFIG = @WXWIDGETS_CONFIG@ WXWIDGETS_CXXFLAGS = @WXWIDGETS_CXXFLAGS@ WXWIDGETS_LIBS = @WXWIDGETS_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ codeclibdir = @codeclibdir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ enable_dot = @enable_dot@ enable_html_docs = @enable_html_docs@ enable_latex_docs = @enable_latex_docs@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ jar = @jar@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ sipx_abs_srcdir = @sipx_abs_srcdir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ wwwdir = @wwwdir@ ConfigureArgs = $(shell sed \ -e '/^ *\$$ .*\/configure/!d' \ -e 's/^ *\$$ .*\/configure *//' \ $(top_builddir)/config.log \ ) LocalizeSipXconfig = sed \ -e 's,@PACKAGE\@,@PACKAGE@,g' \ -e 's,@VERSION\@,@VERSION@,g' \ -e 's,@abs_builddir\@,@abs_builddir@,g' \ -e 's,@abs_srcdir\@,@abs_srcdir@,g' \ -e 's,@abs_top_srcdir\@,@abs_top_srcdir@,g' \ -e 's,@sipx_abs_srcdir\@,@sipx_abs_srcdir@,g' \ -e 's!@CONFIGURE_OPTIONS@!$(ConfigureArgs)!g' \ -e 's,@bindir\@,$(bindir),g' \ -e 's,@datadir\@,$(datadir),g' \ -e 's,@htmldir\@,@htmldir@,g' \ -e 's,@INSTALL\@,@INSTALL@,g' \ -e 's,@install_sh\@,@install_sh@,g' \ -e 's,@libdir\@,$(libdir),g' \ -e 's,@localstatedir\@,$(localstatedir),g' \ -e 's,@pkgdatadir\@,@pkgdatadir@,g' \ -e 's,@prefix\@,$(prefix),g' \ -e 's,@profiledir\@,@profiledir@,g' \ -e 's,@wwwdir\@,@wwwdir@,g' \ -e 's,@host\@,@host@,g' \ -e 's,@PERL\@,@PERL@,g' \ -e 's,@APACHE2_HTTPD\@,@APACHE2_HTTPD@,g' \ -e 's,@APACHE2_MOD\@,@APACHE2_MOD@,g' \ -e 's,@CLOVER_HOME\@,@CLOVER_HOME@,g' \ -e 's,@JAVAC_DEBUG\@,@JAVAC_DEBUG@,g' \ -e 's,@JAVAC_OPTIMIZED\@,@JAVAC_OPTIMIZED@,g' \ -e 's,@JAVA\@,@JAVA@,g' \ -e 's,@JAVA_HOME\@,@JAVA_HOME@,g' \ -e 's,@JBOSS_HOME\@,@JBOSS_HOME@,g' \ -e 's,@JBOSS_SERVER_CONF\@,@JBOSS_SERVER_CONF@,g' \ -e 's,@SIPFOUNDRY_ORG\@,@SIPFOUNDRY_ORG@,g' \ -e 's,@SIPXCONFIG_LIBDIR\@,@SIPXCONFIG_LIBDIR@,g' \ -e 's,@SIPXPBXUSER\@,@SIPXPBXUSER@,g' \ -e 's,@SIPX_BINDIR\@,@SIPX_BINDIR@,g' \ -e 's,@SIPX_CONFDIR\@,@SIPX_CONFDIR@,g' \ -e 's,@SIPX_CONFIGPHONEDIR\@,@SIPX_CONFIGPHONEDIR@,g' \ -e 's,@SIPX_BACKUPDIR\@,@SIPX_BACKUPDIR@,g' \ -e 's,@SIPX_DATADIR\@,@SIPX_DATADIR@,g' \ -e 's,@SIPX_DBDIR\@,@SIPX_DBDIR@,g' \ -e 's,@SIPX_DOCDIR\@,@SIPX_DOCDIR@,g' \ -e 's,@SIPX_LOGDIR\@,@SIPX_LOGDIR@,g' \ -e 's,@SIPX_RUNDIR\@,@SIPX_RUNDIR@,g' \ -e 's,@SIPX_TMPDIR\@,@SIPX_TMPDIR@,g' \ -e 's,@SIPX_INCDIR\@,@SIPX_INCDIR@,g' \ -e 's,@SIPX_LIBDIR\@,@SIPX_LIBDIR@,g' \ -e 's,@SIPX_SCHEMADIR\@,@SIPX_SCHEMADIR@,g' \ -e 's,@SIPX_VXMLDATADIR\@,@SIPX_VXMLDATADIR@,g' \ -e 's,@SIPX_PARKMUSICDIR\@,@SIPX_PARKMUSICDIR@,g' \ -e 's,@SPRING_HOME\@,@SPRING_HOME@,g' \ -e 's,@XPRESSA_BUILD_NUMBER\@,@XPRESSA_BUILD_NUMBER@,g' \ -e 's,@XPRESSA_BUILD_COMMENT\@,@XPRESSA_BUILD_COMMENT@,g' \ -e 's,@SIPXPHONELIB\@,@SIPXPHONELIB@,g' \ -e 's,@SIPXPHONEDATA\@,@SIPXPHONEDATA@,g' \ -e 's,@SIPXPHONECONF\@,@SIPXPHONECONF@,g' \ -e 's,@NAMED_PROGRAM\@,@NAMED_PROGRAM@,g' bin_SCRIPTS = \ @PACKAGE@-config DISTCLEANFILES = \ @PACKAGE@-config \ $(top_srcdir)/config/@PACKAGE@-buildstamp.cpp \ $(top_srcdir)/config/@PACKAGE@-buildstamp.h all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(top_srcdir)/config/sipXcommon.am.inc $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu bin/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu bin/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/config/sipXcommon.am.inc: $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-binSCRIPTS: $(bin_SCRIPTS) @$(NORMAL_INSTALL) @list='$(bin_SCRIPTS)'; test -n "$(bindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ if test -f "$$d$$p"; then echo "$$d$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n' \ -e 'h;s|.*|.|' \ -e 'p;x;s,.*/,,;$(transform)' | sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1; } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) { files[d] = files[d] " " $$1; \ if (++n[d] == $(am__install_max)) { \ print "f", d, files[d]; n[d] = 0; files[d] = "" } } \ else { print "f", d "/" $$4, $$1 } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_SCRIPT) $$files '$(DESTDIR)$(bindir)$$dir'"; \ $(INSTALL_SCRIPT) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ } \ ; done uninstall-binSCRIPTS: @$(NORMAL_UNINSTALL) @list='$(bin_SCRIPTS)'; test -n "$(bindir)" || exit 0; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 's,.*/,,;$(transform)'`; \ dir='$(DESTDIR)$(bindir)'; $(am__uninstall_files_from_dir) mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(SCRIPTS) installdirs: for dir in "$(DESTDIR)$(bindir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) -test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-binSCRIPTS install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-binSCRIPTS .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ distclean distclean-generic distclean-libtool distdir dvi \ dvi-am html html-am info info-am install install-am \ install-binSCRIPTS install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ uninstall uninstall-am uninstall-binSCRIPTS $(top_builddir)/BUILDSTAMP: ${MAKE} -C $(top_builddir) BUILDSTAMP @PACKAGE@-config: $(top_srcdir)/config/sipX-config.in $(top_builddir)/BUILDSTAMP BuildStamp="$(shell cat $(top_builddir)/BUILDSTAMP)" \ ; ${LocalizeSipXconfig} -e "s/@SIPX_BUILDSTAMP\@/$${BuildStamp}/" \ $(top_srcdir)/config/sipX-config.in \ > @PACKAGE@-config chmod +x @PACKAGE@-config # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: sipxtapi-3.3.0~test17/sipXportLib/0000755000175000017500000000000012321445025017653 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/config/0000755000175000017500000000000012321445023021116 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/config/sipX-config.in0000644000175000017500000000550512205613256023647 0ustar00danieldaniel00000000000000#! /bin/sh ## ## @PACKAGE@-config ## ## Copyright (C) 2004 SIPfoundry Inc. ## Licensed by SIPfoundry under the LGPL license. ## ## Copyright (C) 2004, 2005 Pingtel Corp. ## ## Action=PRINT Info="" prefix=@prefix@ exec_prefix=@exec_prefix@ includedir=@includedir@ libdir=@libdir@ while [ $# -ne 0 ] do case ${1} in --bin) Info="${Info} @SIPX_BINDIR@" ;; --include) Info="${Info} @SIPX_INCDIR@" ;; --lib) Info="${Info} @SIPX_LIBDIR@" ;; --host) Info="${Info} @host@" ;; --version) Info="${Info} @VERSION@" ;; --build) Info="${Info} @SIPX_BUILDSTAMP@" ;; --conf) Info="${Info} @SIPX_CONFDIR@" ;; --data) Info="${Info} @SIPX_DATADIR@" ;; --log) Info="${Info} @SIPX_LOGDIR@" ;; --run) Info="${Info} @SIPX_RUNDIR@" ;; --db) Info="${Info} @SIPX_DBDIR@" ;; --all) Action=ALL break ;; --configopts) Info="${Info} @CONFIGURE_OPTIONS@" ;; --help) Action=USAGE break ;; ## ## handle an unknown switch ## -*) echo "Unknown switch '${1}'" 1>&2 Action=USAGE ;; esac shift # always consume 1 done if [ "${Action}" = "PRINT" -a "${Info}" = "" ] then Action=USAGE fi case ${Action} in USAGE) cat <$(PACKAGE)-$(VERSION).tar.gz.md5 # RPM Spec file sipxportlib.spec : sipxportlib.spec.in $(LocalizeSipXconfig) $(srcdir)/sipxportlib.spec.in > sipxportlib.spec # 'rpmbuild -ta' searches root of tarball for first *.spec file to build # RPM from #dist-hook: sipxportlib.spec # cp sipxportlib.spec $(distdir) sipxtapi-3.3.0~test17/sipXportLib/Makefile.in0000644000175000017500000006075712321445000021730 0ustar00danieldaniel00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # -*-makefile-*- VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ DIST_COMMON = README $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ $(top_srcdir)/config/sipXcommon.am.inc \ $(top_srcdir)/config/sipXprojtop.mak ChangeLog INSTALL NEWS \ TODO subdir = sipXportLib ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/general.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/sipXlib.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ html-recursive info-recursive install-data-recursive \ install-dvi-recursive install-exec-recursive \ install-html-recursive install-info-recursive \ install-pdf-recursive install-ps-recursive install-recursive \ installcheck-recursive installdirs-recursive pdf-recursive \ ps-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ distdir ETAGS = etags CTAGS = ctags DIST_SUBDIRS = . src include syslogviewer doc DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMRNB_INCLUDE = @AMRNB_INCLUDE@ AMRNB_LIB_ROOT = @AMRNB_LIB_ROOT@ AMRWB_INCLUDE = @AMRWB_INCLUDE@ AMRWB_LIB_ROOT = @AMRWB_LIB_ROOT@ AMRWB_TARGET = @AMRWB_TARGET@ AMR_TARGET = @AMR_TARGET@ AMTAR = @AMTAR@ ANT = @ANT@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CARBON_LIBS = @CARBON_LIBS@ CA_LIBS = @CA_LIBS@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPUNIT_CFLAGS = @CPPUNIT_CFLAGS@ CPPUNIT_CONFIG = @CPPUNIT_CONFIG@ CPPUNIT_LIBS = @CPPUNIT_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPS_PCRE_CFLAGS = @DEPS_PCRE_CFLAGS@ DEPS_PCRE_LIBS = @DEPS_PCRE_LIBS@ DLLTOOL = @DLLTOOL@ DOT = @DOT@ DOXYGEN = @DOXYGEN@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DYNEXT = @DYNEXT@ EAGC_LDFLAGS = @EAGC_LDFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EJBE_LDFLAGS = @EJBE_LDFLAGS@ EPLC_LDFLAGS = @EPLC_LDFLAGS@ EVAD_LDFLAGS = @EVAD_LDFLAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ G722_TARGET = @G722_TARGET@ G726_TARGET = @G726_TARGET@ GIPSINC = @GIPSINC@ GIPS_CE_OBJS = @GIPS_CE_OBJS@ GIPS_CPPFLAGS = @GIPS_CPPFLAGS@ GIPS_NEQ_OBJS = @GIPS_NEQ_OBJS@ GIPS_VE_OBJS = @GIPS_VE_OBJS@ GREP = @GREP@ GSM_CFLAGS = @GSM_CFLAGS@ GSM_CXXFLAGS = @GSM_CXXFLAGS@ GSM_LDFLAGS = @GSM_LDFLAGS@ GSM_LIBS = @GSM_LIBS@ GSM_TARGET = @GSM_TARGET@ ILBC_INCLUDE = @ILBC_INCLUDE@ ILBC_LIB_ROOT = @ILBC_LIB_ROOT@ ILBC_LIB_TARGET = @ILBC_LIB_TARGET@ ILBC_TARGET = @ILBC_TARGET@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTERFACE_FLAGS = @INTERFACE_FLAGS@ JAVA = @JAVA@ JAVAC_DEBUG = @JAVAC_DEBUG@ JAVAC_OPTIMIZED = @JAVAC_OPTIMIZED@ JAVA_HOME = @JAVA_HOME@ L16_TARGET = @L16_TARGET@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NAMED_PROGRAM = @NAMED_PROGRAM@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPUS_CFLAGS = @OPUS_CFLAGS@ OPUS_LIBS = @OPUS_LIBS@ OPUS_TARGET = @OPUS_TARGET@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PCMAPCMU_TARGET = @PCMAPCMU_TARGET@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ RTL_CXXFLAGS = @RTL_CXXFLAGS@ RTL_LDFLAGS = @RTL_LDFLAGS@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SIPXMEDIA_CE_LIBS = @SIPXMEDIA_CE_LIBS@ SIPXMEDIA_VE_LIBS = @SIPXMEDIA_VE_LIBS@ SIPXMEDIA_VE_STATIC_LIBS = @SIPXMEDIA_VE_STATIC_LIBS@ SIPXPBXUSER = @SIPXPBXUSER@ SIPXPHONECONF = @SIPXPHONECONF@ SIPXPHONEDATA = @SIPXPHONEDATA@ SIPXPHONELIB = @SIPXPHONELIB@ SIPX_BACKUPDIR = @SIPX_BACKUPDIR@ SIPX_BINDIR = @SIPX_BINDIR@ SIPX_CONFDIR = @SIPX_CONFDIR@ SIPX_CONFIGPHONEDIR = @SIPX_CONFIGPHONEDIR@ SIPX_DATADIR = @SIPX_DATADIR@ SIPX_DBDIR = @SIPX_DBDIR@ SIPX_DOCDIR = @SIPX_DOCDIR@ SIPX_INCDIR = @SIPX_INCDIR@ SIPX_LIBDIR = @SIPX_LIBDIR@ SIPX_LOGDIR = @SIPX_LOGDIR@ SIPX_PARKMUSICDIR = @SIPX_PARKMUSICDIR@ SIPX_RUNDIR = @SIPX_RUNDIR@ SIPX_SCHEMADIR = @SIPX_SCHEMADIR@ SIPX_TMPDIR = @SIPX_TMPDIR@ SIPX_UNIT_TARGET = @SIPX_UNIT_TARGET@ SIPX_VXMLDATADIR = @SIPX_VXMLDATADIR@ SPANDSP_CFLAGS = @SPANDSP_CFLAGS@ SPANDSP_CXXFLAGS = @SPANDSP_CXXFLAGS@ SPANDSP_LDFLAGS = @SPANDSP_LDFLAGS@ SPANDSP_LIBS = @SPANDSP_LIBS@ SPEEXDSP_CFLAGS = @SPEEXDSP_CFLAGS@ SPEEXDSP_LIBS = @SPEEXDSP_LIBS@ SPEEXDSP_STATIC_LIB = @SPEEXDSP_STATIC_LIB@ SPEEX_CFLAGS = @SPEEX_CFLAGS@ SPEEX_LIBS = @SPEEX_LIBS@ SPEEX_ROOT = @SPEEX_ROOT@ SPEEX_STATIC_LIB = @SPEEX_STATIC_LIB@ SPEEX_TARGET = @SPEEX_TARGET@ SS_LDFLAGS = @SS_LDFLAGS@ STATIC_CODEC_LIBS = @STATIC_CODEC_LIBS@ STRIP = @STRIP@ TONES_TARGET = @TONES_TARGET@ VERSION = @VERSION@ VIDEO_DEFINE = @VIDEO_DEFINE@ WXWIDGETS_CFLAGS = @WXWIDGETS_CFLAGS@ WXWIDGETS_CONFIG = @WXWIDGETS_CONFIG@ WXWIDGETS_CXXFLAGS = @WXWIDGETS_CXXFLAGS@ WXWIDGETS_LIBS = @WXWIDGETS_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ codeclibdir = @codeclibdir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ enable_dot = @enable_dot@ enable_html_docs = @enable_html_docs@ enable_latex_docs = @enable_latex_docs@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ jar = @jar@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ sipx_abs_srcdir = @sipx_abs_srcdir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ wwwdir = @wwwdir@ ConfigureArgs = $(shell sed \ -e '/^ *\$$ .*\/configure/!d' \ -e 's/^ *\$$ .*\/configure *//' \ $(top_builddir)/config.log \ ) LocalizeSipXconfig = sed \ -e 's,@PACKAGE\@,@PACKAGE@,g' \ -e 's,@VERSION\@,@VERSION@,g' \ -e 's,@abs_builddir\@,@abs_builddir@,g' \ -e 's,@abs_srcdir\@,@abs_srcdir@,g' \ -e 's,@abs_top_srcdir\@,@abs_top_srcdir@,g' \ -e 's,@sipx_abs_srcdir\@,@sipx_abs_srcdir@,g' \ -e 's!@CONFIGURE_OPTIONS@!$(ConfigureArgs)!g' \ -e 's,@bindir\@,$(bindir),g' \ -e 's,@datadir\@,$(datadir),g' \ -e 's,@htmldir\@,@htmldir@,g' \ -e 's,@INSTALL\@,@INSTALL@,g' \ -e 's,@install_sh\@,@install_sh@,g' \ -e 's,@libdir\@,$(libdir),g' \ -e 's,@localstatedir\@,$(localstatedir),g' \ -e 's,@pkgdatadir\@,@pkgdatadir@,g' \ -e 's,@prefix\@,$(prefix),g' \ -e 's,@profiledir\@,@profiledir@,g' \ -e 's,@wwwdir\@,@wwwdir@,g' \ -e 's,@host\@,@host@,g' \ -e 's,@PERL\@,@PERL@,g' \ -e 's,@APACHE2_HTTPD\@,@APACHE2_HTTPD@,g' \ -e 's,@APACHE2_MOD\@,@APACHE2_MOD@,g' \ -e 's,@CLOVER_HOME\@,@CLOVER_HOME@,g' \ -e 's,@JAVAC_DEBUG\@,@JAVAC_DEBUG@,g' \ -e 's,@JAVAC_OPTIMIZED\@,@JAVAC_OPTIMIZED@,g' \ -e 's,@JAVA\@,@JAVA@,g' \ -e 's,@JAVA_HOME\@,@JAVA_HOME@,g' \ -e 's,@JBOSS_HOME\@,@JBOSS_HOME@,g' \ -e 's,@JBOSS_SERVER_CONF\@,@JBOSS_SERVER_CONF@,g' \ -e 's,@SIPFOUNDRY_ORG\@,@SIPFOUNDRY_ORG@,g' \ -e 's,@SIPXCONFIG_LIBDIR\@,@SIPXCONFIG_LIBDIR@,g' \ -e 's,@SIPXPBXUSER\@,@SIPXPBXUSER@,g' \ -e 's,@SIPX_BINDIR\@,@SIPX_BINDIR@,g' \ -e 's,@SIPX_CONFDIR\@,@SIPX_CONFDIR@,g' \ -e 's,@SIPX_CONFIGPHONEDIR\@,@SIPX_CONFIGPHONEDIR@,g' \ -e 's,@SIPX_BACKUPDIR\@,@SIPX_BACKUPDIR@,g' \ -e 's,@SIPX_DATADIR\@,@SIPX_DATADIR@,g' \ -e 's,@SIPX_DBDIR\@,@SIPX_DBDIR@,g' \ -e 's,@SIPX_DOCDIR\@,@SIPX_DOCDIR@,g' \ -e 's,@SIPX_LOGDIR\@,@SIPX_LOGDIR@,g' \ -e 's,@SIPX_RUNDIR\@,@SIPX_RUNDIR@,g' \ -e 's,@SIPX_TMPDIR\@,@SIPX_TMPDIR@,g' \ -e 's,@SIPX_INCDIR\@,@SIPX_INCDIR@,g' \ -e 's,@SIPX_LIBDIR\@,@SIPX_LIBDIR@,g' \ -e 's,@SIPX_SCHEMADIR\@,@SIPX_SCHEMADIR@,g' \ -e 's,@SIPX_VXMLDATADIR\@,@SIPX_VXMLDATADIR@,g' \ -e 's,@SIPX_PARKMUSICDIR\@,@SIPX_PARKMUSICDIR@,g' \ -e 's,@SPRING_HOME\@,@SPRING_HOME@,g' \ -e 's,@XPRESSA_BUILD_NUMBER\@,@XPRESSA_BUILD_NUMBER@,g' \ -e 's,@XPRESSA_BUILD_COMMENT\@,@XPRESSA_BUILD_COMMENT@,g' \ -e 's,@SIPXPHONELIB\@,@SIPXPHONELIB@,g' \ -e 's,@SIPXPHONEDATA\@,@SIPXPHONEDATA@,g' \ -e 's,@SIPXPHONECONF\@,@SIPXPHONECONF@,g' \ -e 's,@NAMED_PROGRAM\@,@NAMED_PROGRAM@,g' EXTRA_DIST = \ config/sipX-config.in \ config/sipX-buildstamp.cpp.in \ config/sipX-buildstamp.h.in \ config/sipXprojtop.mak \ config/sipXcommon.am.inc \ CONTRIBUTORS unconditional_SUBDIRS = . src include syslogviewer # # If Doxygen is enabled # @DOC_TRUE@doc_SUBDIRS = doc # bin is not really needed now that we have a top-level build system #unconditional_SUBDIRS += bin SUBDIRS = $(unconditional_SUBDIRS) $(doc_SUBDIRS) RELEASE = 2 # Where rpmbuild will do its work. RPMBUILD_TOPDIR = $(shell rpm --eval '%{_topdir}') @USE_BLDNO_FALSE@BUILDPARM = --define="buildno $(RELEASE)" # Get the revision number @USE_BLDNO_TRUE@BUILDPARM = --define="buildno 0.$(shell cat $(srcdir)/SVN-VERSION)" all: all-recursive .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(top_srcdir)/config/sipXcommon.am.inc $(top_srcdir)/config/sipXprojtop.mak $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu sipXportLib/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu sipXportLib/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/config/sipXcommon.am.inc $(top_srcdir)/config/sipXprojtop.mak: $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run `make' without going through this Makefile. # To change the values of `make' variables: instead of editing Makefiles, # (1) if the variable is set in `config.status', edit `config.status' # (which will cause the Makefiles to be regenerated when you run `make'); # (2) otherwise, pass the desired values on the `make' command line. $(RECURSIVE_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ list='$(SUBDIRS)'; for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" $(RECURSIVE_CLEAN_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ rev=''; for subdir in $$list; do \ if test "$$subdir" = "."; then :; else \ rev="$$subdir $$rev"; \ fi; \ done; \ rev="$$rev ."; \ target=`echo $@ | sed s/-recursive//`; \ for subdir in $$rev; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done && test -z "$$fail" tags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ done ctags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ done ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \ install-am install-strip tags-recursive .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ all all-am check check-am clean clean-generic clean-libtool \ ctags ctags-recursive distclean distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-recursive \ uninstall uninstall-am # automake doesn't like this inside the conditional .PHONY : doc @DOC_TRUE@doc : @DOC_TRUE@ cd doc && $(MAKE) $(AM_MAKEFLAGS) all .PHONY : rpm rpm : dist rpmbuild -ta $(BUILDPARM) $(PACKAGE)-$(VERSION).tar.gz mv -f $(RPMBUILD_TOPDIR)/SRPMS/$(PACKAGE)-$(VERSION)-*.rpm . mv -f $(RPMBUILD_TOPDIR)/RPMS/*/$(PACKAGE)*-$(VERSION)-*.rpm . md5sum $(PACKAGE)-$(VERSION).tar.gz >$(PACKAGE)-$(VERSION).tar.gz.md5 # RPM Spec file sipxportlib.spec : sipxportlib.spec.in $(LocalizeSipXconfig) $(srcdir)/sipxportlib.spec.in > sipxportlib.spec # 'rpmbuild -ta' searches root of tarball for first *.spec file to build # RPM from #dist-hook: sipxportlib.spec # cp sipxportlib.spec $(distdir) # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: sipxtapi-3.3.0~test17/sipXportLib/ChangeLog0000644000175000017500000000427512205613256021441 0ustar00danieldaniel00000000000000The most current information on the status of any release is in the SIPfoundry Issue Tracker at: http://track.sipfoundry.org/browse?XPL Release Notes - sipXportLib - Version 2.6.2 ** Bug * Change locking strategy for UtlContainer and UtlIterator classes Remove the UtlIterator::remove method See comments in UtlContainer.h for locking rules * [XPB-143] Added _FILE_OFFSET_BITS=64 flag ** New Feature * [XPB-162] Add --version option for sipx-config ** Other Changes * [XMR-18] Temporarily reduce the logging level of "Message queue increased to 1600 msgs" to INFO. * Add libtool version-info Release Notes - sipXportLib - Version 2.6.1 ** Bug * [XPL-36] - check for correctly build openssl libs * [XPL-54] - Incorrect directory name in general.m4 * [XPL-60] - Windows project file cannot be converted by VS .NET 2003/7.1 * [XPL-69] - SIPX_HOME not compatible with multiple-rooted install ** New Feature * [XPL-72] - need a way to locate installed components ** Task * [XPL-71] - spec files use URLs for source and shouldn't ** Improvement * [XPL-55] - ./configure options to allow PCRE include and lib dirs to be in different places Release Notes - sipXpbx - Version 2.5.2 ** Bug * [XPB-2] - Clean up generation/installation of SSL Certificates * [XPB-7] - Failed unittest * [XPB-11] - Watchdog trying to start apache from the wrong location * [XPB-12] - Error while starting apache2 * [XPB-13] - watchdog stop doesn't work * [XPB-15] - Clean up startup/shutdown * [XPB-16] - Major memory leak in watchdog (e.g. 642MB after 1hr) ** Improvement * [XPB-8] - Clean up code to remove all warnings. Release Notes - sipXportLib - Version 2.5.1 ** Bug * [XPL-1] - Dependency with rwToolsppLib * [XPL-10] - checking for rwToolsppLib includes... configure: error: not found * [XPL-11] - Need to update the tarballs now that this project builds * [XPL-13] - UtlContainer should inherit from UtlContainable * [XPL-14] - needs verify that we are using automake version 1.8 or better * [XPL-17] - Need to implement a UtlSortedListIterator sipxtapi-3.3.0~test17/sipXportLib/INSTALL0000644000175000017500000003706012205613256020716 0ustar00danieldaniel00000000000000============================================================ S Y S T E M R E Q U I R E M E N T S ============================================================ Required Software ================= PCRE - Perl Compatible Regular Expression Library http://www.pcre.org/ sipX has been tested with version 4.5. Cppunit 1.10.2 - Unitesting framework for C++ http://cppunit.sourceforge.net/ OpenSSL 0.9.7.c - Security Library http://www.openssl.org *Autoconf 2.59c & Automake 1.6 (not positive on automake prereq -- latest tested with 1.9.6) - GNU build tool chain http://www.gnu.org/directory/GNU/ *ONLY if building from subversion 2.59c is required, as this is when C99 integer type checking was added. *pkgconfig 0.20 - for use with Autoconf http://pkgconfig.freedesktop.org/ *ONLY if building from subversion libtool 1.5.24 http://www.gnu.org/software/libtool/ On RedHat Enterprise 3 "up2date libtool libtool-libs" Optional but highly recommended if you will be coding: ====================================================== Doxygen - Source Code Documentation System http://www.doxygen.org tested with 1.3.5 On RedHat Enterprise 3 "up2date doxygen" Optional Codec Sources ====================== AMR Narrowband library - libamrnb v7.0.0.0 Under windows: Download http://www.3gpp.org/ftp/Specs/archive/26_series/26.104/26104-700.zip Expand amrnb sources to sipXmediaLib/contrib/libamrnb Build using sipX supplied project file sipXmediaLib/contrib/libamrnb/libamrnb.dsp Under OSes using GNU autoconf, this will be automatically done via configure/makefile process. Included autoconf files checked in come from: http://www.penguin.cz/~utx/amr AMR Wideband library - libamrwb v7.0.0.2 Under windows: Download http://www.3gpp.org/ftp/Specs/archive/26_series/26.204/26204-700.zip Expand amrwb sources to sipXmediaLib/contrib/libamrwb Build using sipX supplied project file sipXmediaLib/contrib/libamrwb/libamrwb.dsp Under OSes using GNU autoconf, this will be automatically done via configure/makefile process. Included autoconf files checked in come from: http://www.penguin.cz/~utx/amr SpanDSP library - spandsp 0.0.3 Download http://www.soft-switch.org/downloads/spandsp/ Expand to sipXmediaLib/contrib/libspandsp Build using sipX supplied project file sipXmediaLib/contrib/libspandsp/libspandsp.dsp Prerequisite installation on Fedora Core 4 ------------------------------------------ yum should get every thing you need: yum install cppunit cppunit-devel autoconf automake pkgconfig pcre-devel openssl openssl-devel libtool doxygen subversion gcc-c++ PCRE Installation Instructions ============================== Red Hat Linux ------------- The pcre-3.9-10 and pcre-devel-3.9-10 RPMs from the Red Hat 9 distribution will work. Windows ------- PRCE is a perl-compatible regular-expression library for C/C++. GnuWin32 (gnuwin32.sourceforge.net) maintains Win32 binaries: http://gnuwin32.sourceforge.net/packages/pcre.htm You will need to install both the binaries and the developer files. Mac OS X -------- See the section below on "Mac OS X Development System Setup" for setting up a system to compile and build sipX projects. sipXportLib, sipXtackLib, sipXmediaLib and sipXcallLib (and sipXtapi) are known to build on OS X 10.3 If you follow the instructions in the section below on: "Mac OS X Development System Setup", you can skip all the other special instructions in this file as fink will install all of the dependencies for you. Special Software Installation Instructions ============================================= For OpenSSL, run the follow commands when installing ./config threads shared -D_REENTRANT make make install WARNING: Libraries are not installing into /usr/local/lib, recommended workaround for this is to edit this file /etc/ld.so.conf and add this line /usr/local/ssl/lib then run this command > ldconfig Alternatively, you can do this: sh, bash: export LD_LIBRARY_PATH=/usr/local/ssl/lib csh, tcsh: setenv LD_LIBRARY_PATH /usr/local/ssl/lib ============================================================ I N S T A L L A T I O N ============================================================ Unix : Building From Subversion =============================== If you've obtained source from subversion, you must do this first, then continue on with "Unix : Building from Source Code" or "Windows: Building from Source Code" autoreconf --install --force Unix : Building from Source Code ================================ ./configure make make check make install Windows: Building from Source Code ================================== Aftering installing pcre, update your MSVC6 environment by selecting "Options" from the "Tools" menu, select the "Directories" tab and then adding the following (assuming installation into C:\Program Files\GnuWin32): C:\Program Files\GnuWin32\include Next, select the "libraries" path and add the following: C:\Program Files\GnuWin32\lib WinCE (EVC4): Building from Source Code ======================================= Make sure you have the following installed: Microsoft eMbedded C++ 4.2 (eVC4) (this is a free download) eVC4 Service Pack 4 * hotfix to fix "Datatype Misalignment" first chance exception when running things that use sipXmediaLib. Knowledge Base article: KB909973 Fix: http://www.microsoft.com/downloads/details.aspx?FamilyID=a22ef691-f4f1-4d95-b1f7-8fb283e274d7 After compiling or installing STLport, cppunit, and pcre, update your EVC4 environment. * Open up EVC4 * go to Tools->Options...->Directories * Select the platform you want to build * Select "Include files" * Add path to STLport include directory. * Add path to PCRE include directory. * Add path to CPPUnit include directory. * Move these new entries to top (included before all others), with STLport first. * Select "Library Files" * Add path to STLport library. * Add path to PCRE library. * Add path to CPPUnit library. * Move these new entries to the top (linked before all others), with STLport first. * Click "Ok". * Open project sipXportLib.vcp * Choose your target. Currently emulator and ARMV4I have project settings set properly. * Build. ================================================================================ Generic installation instructions from FSF included for convienence: -------------------------------------------------------------------- Copyright 1994, 1995, 1996, 1999, 2000, 2001, 2002 Free Software Foundation, Inc. This file is free documentation; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. Basic Installation ================== These are generic installation instructions. The `configure' shell script attempts to guess correct values for various system-dependent variables used during compilation. It uses those values to create a `Makefile' in each directory of the package. It may also create one or more `.h' files containing system-dependent definitions. Finally, it creates a shell script `config.status' that you can run in the future to recreate the current configuration, and a file `config.log' containing compiler output (useful mainly for debugging `configure'). It can also use an optional file (typically called `config.cache' and enabled with `--cache-file=config.cache' or simply `-C') that saves the results of its tests to speed up reconfiguring. (Caching is disabled by default to prevent problems with accidental use of stale cache files.) If you need to do unusual things to compile the package, please try to figure out how `configure' could check whether to do them, and mail diffs or instructions to the address given in the `README' so they can be considered for the next release. If you are using the cache, and at some point `config.cache' contains results you don't want to keep, you may remove or edit it. The file `configure.ac' (or `configure.in') is used to create `configure' by a program called `autoconf'. You only need `configure.ac' if you want to change it or regenerate `configure' using a newer version of `autoconf'. The simplest way to compile this package is: 1. `cd' to the directory containing the package's source code and type `./configure' to configure the package for your system. If you're using `csh' on an old version of System V, you might need to type `sh ./configure' instead to prevent `csh' from trying to execute `configure' itself. Running `configure' takes awhile. While running, it prints some messages telling which features it is checking for. 2. Type `make' to compile the package. 3. Optionally, type `make check' to run any self-tests that come with the package. 4. Type `make install' to install the programs and any data files and documentation. 5. You can remove the program binaries and object files from the source code directory by typing `make clean'. To also remove the files that `configure' created (so you can compile the package for a different kind of computer), type `make distclean'. There is also a `make maintainer-clean' target, but that is intended mainly for the package's developers. If you use it, you may have to get all sorts of other programs in order to regenerate files that came with the distribution. Compilers and Options ===================== Some systems require unusual options for compilation or linking that the `configure' script does not know about. Run `./configure --help' for details on some of the pertinent environment variables. You can give `configure' initial values for configuration parameters by setting variables in the command line or in the environment. Here is an example: ./configure CC=c89 CFLAGS=-O2 LIBS=-lposix *Note Defining Variables::, for more details. Compiling For Multiple Architectures ==================================== You can compile the package for more than one kind of computer at the same time, by placing the object files for each architecture in their own directory. To do this, you must use a version of `make' that supports the `VPATH' variable, such as GNU `make'. `cd' to the directory where you want the object files and executables to go and run the `configure' script. `configure' automatically checks for the source code in the directory that `configure' is in and in `..'. If you have to use a `make' that does not support the `VPATH' variable, you have to compile the package for one architecture at a time in the source code directory. After you have installed the package for one architecture, use `make distclean' before reconfiguring for another architecture. Installation Names ================== By default, `make install' will install the package's files in `/usr/local/bin', `/usr/local/man', etc. You can specify an installation prefix other than `/usr/local' by giving `configure' the option `--prefix=PATH'. You can specify separate installation prefixes for architecture-specific files and architecture-independent files. If you give `configure' the option `--exec-prefix=PATH', the package will use PATH as the prefix for installing programs and libraries. Documentation and other data files will still use the regular prefix. In addition, if you use an unusual directory layout you can give options like `--bindir=PATH' to specify different values for particular kinds of files. Run `configure --help' for a list of the directories you can set and what kinds of files go in them. If the package supports it, you can cause programs to be installed with an extra prefix or suffix on their names by giving `configure' the option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. Optional Features ================= Some packages pay attention to `--enable-FEATURE' options to `configure', where FEATURE indicates an optional part of the package. They may also pay attention to `--with-PACKAGE' options, where PACKAGE is something like `gnu-as' or `x' (for the X Window System). The `README' should mention any `--enable-' and `--with-' options that the package recognizes. For packages that use the X Window System, `configure' can usually find the X include and library files automatically, but if it doesn't, you can use the `configure' options `--x-includes=DIR' and `--x-libraries=DIR' to specify their locations. Specifying the System Type ========================== There may be some features `configure' cannot figure out automatically, but needs to determine by the type of machine the package will run on. Usually, assuming the package is built to be run on the _same_ architectures, `configure' can figure that out, but if it prints a message saying it cannot guess the machine type, give it the `--build=TYPE' option. TYPE can either be a short name for the system type, such as `sun4', or a canonical name which has the form: CPU-COMPANY-SYSTEM where SYSTEM can have one of these forms: OS KERNEL-OS See the file `config.sub' for the possible values of each field. If `config.sub' isn't included in this package, then this package doesn't need to know the machine type. If you are _building_ compiler tools for cross-compiling, you should use the `--target=TYPE' option to select the type of system they will produce code for. If you want to _use_ a cross compiler, that generates code for a platform different from the build platform, you should specify the "host" platform (i.e., that on which the generated programs will eventually be run) with `--host=TYPE'. Sharing Defaults ================ If you want to set default values for `configure' scripts to share, you can create a site shell script called `config.site' that gives default values for variables like `CC', `cache_file', and `prefix'. `configure' looks for `PREFIX/share/config.site' if it exists, then `PREFIX/etc/config.site' if it exists. Or, you can set the `CONFIG_SITE' environment variable to the location of the site script. A warning: not all `configure' scripts look for a site script. Defining Variables ================== Variables not defined in a site shell script can be set in the environment passed to `configure'. However, some packages may run configure again during the build, and the customized values of these variables may be lost. In order to avoid this problem, you should set them in the `configure' command line, using `VAR=value'. For example: ./configure CC=/usr/local2/bin/gcc will cause the specified gcc to be used as the C compiler (unless it is overridden in the site shell script). `configure' Invocation ====================== `configure' recognizes the following options to control how it operates. `--help' `-h' Print a summary of the options to `configure', and exit. `--version' `-V' Print the version of Autoconf used to generate the `configure' script, and exit. `--cache-file=FILE' Enable the cache: use and save the results of the tests in FILE, traditionally `config.cache'. FILE defaults to `/dev/null' to disable caching. `--config-cache' `-C' Alias for `--cache-file=config.cache'. `--quiet' `--silent' `-q' Do not print messages saying which checks are being made. To suppress all normal output, redirect it to `/dev/null' (any error messages will still be shown). `--srcdir=DIR' Look for the package's source code in directory DIR. Usually `configure' can determine that directory automatically. `configure' also accepts some other, not widely useful, options. Run `configure --help' for more details. sipxtapi-3.3.0~test17/sipXportLib/NEWS0000644000175000017500000000000012205613256020344 0ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/TODO0000644000175000017500000000015012205613256020343 0ustar00danieldaniel00000000000000 See the sipXportLib issue tracker at SIPfoundry: http://track.sipfoundry.org/browse/XPL sipxtapi-3.3.0~test17/sipXportLib/CONTRIBUTORS0000644000175000017500000000037212205613256021541 0ustar00danieldaniel00000000000000 On March 24th, 2004, Pingtel Corp. contributed this source code to SIPfoundry, Inc. While we are only crediting authors and contributors who wish to be named, we would like to thank everyone from the Pingtel team who helped to build this. sipxtapi-3.3.0~test17/sipXportLib/src/0000755000175000017500000000000012321445024020441 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/src/hmac-sha1/0000755000175000017500000000000012321445024022203 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/src/hmac-sha1/hmac-sha1.c0000644000175000017500000000304412205613256024117 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include "sha1.h" void hmac_sha1(const char* pBlob, size_t nBlob, const char* pKey, size_t nKey, char* digest) { SHA1Context context ; char cTempKey[20] ; char iPad[64] ; char oPad[64] ; int i ; // If the key length is larger then 64 bytes, replace with hash of the key if (nKey > 64) { SHA1Reset(&context) ; SHA1Input(&context, pKey, nKey) ; memset(cTempKey, 0, sizeof(cTempKey)) ; SHA1Result(&context, cTempKey) ; pKey = cTempKey ; nKey = 20 ; } // Initialize opad and ipad memset(iPad, 0, 64) ; memset(oPad, 0, 64) ; if (pKey) { memcpy(iPad, pKey, nKey) ; memcpy(oPad, pKey, nKey) ; } for (i=0; i<64; i++) { iPad[i] ^= 0x36 ; oPad[i] ^= 0x5c ; } // Step one using iPad SHA1Reset(&context) ; SHA1Input(&context, iPad, 64) ; SHA1Input(&context, pBlob, nBlob) ; SHA1Result(&context, digest) ; // Step two using oPad SHA1Reset(&context) ; SHA1Input(&context, oPad, 64) ; SHA1Input(&context, digest, 20) ; SHA1Result(&context, digest) ; } sipxtapi-3.3.0~test17/sipXportLib/src/hmac-sha1/sha1.c0000644000175000017500000002721612205613256023220 0ustar00danieldaniel00000000000000/* * sha1.c (Obtained from rfc3471) * * Copyright (c) The Internet Society (2001). All Rights Reserved. * * This document and translations of it may be copied and furnished to others, * and derivative works that comment on or otherwise explain it or assist in * its implementation may be prepared, copied, published and distributed, in * whole or in part, without restriction of any kind, provided that the above * copyright notice and this paragraph are included on all such copies and * derivative works. However, this document itself may not be modified in any * way, such as by removing the copyright notice or references to the Internet * Society or other Internet organizations, except as needed for the purpose * of developing Internet standards in which case the procedures for copyrights * defined in the Internet Standards process must be followed, or as required * to translate it into languages other than English. * * The limited permissions granted above are perpetual and will not be revoked * by the Internet Society or its successors or assigns. * * This document and the information contained herein is provided on an * "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK * FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT * INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR * FITNESS FOR A PARTICULAR PURPOSE. * * Description: * This file implements the Secure Hashing Algorithm 1 as * defined in FIPS PUB 180-1 published April 17, 1995. * * The SHA-1, produces a 160-bit message digest for a given * data stream. It should take about 2**n steps to find a * message with the same digest as a given message and * 2**(n/2) to find any two messages with the same digest, * when n is the digest size in bits. Therefore, this * algorithm can serve as a means of providing a * "fingerprint" for a message. * * Portability Issues: * SHA-1 is defined in terms of 32-bit "words". This code * uses (included via "sha1.h" to define 32 and 8 * bit unsigned integer types. If your C compiler does not * support 32 bit unsigned integers, this code is not * appropriate. * * Caveats: * SHA-1 is designed to work with messages less than 2^64 bits * long. Although SHA-1 allows a message digest to be generated * for messages of any number of bits less than 2^64, this * implementation only works with messages with a length that is * a multiple of the size of an 8-bit character. * */ #include "sha1.h" /* * Define the SHA1 circular left shift macro */ #define SHA1CircularShift(bits,word) \ (((word) << (bits)) | ((word) >> (32-(bits)))) /* Local Function Prototyptes */ void SHA1PadMessage(SHA1Context *); void SHA1ProcessMessageBlock(SHA1Context *); /* * SHA1Reset * * Description: * This function will initialize the SHA1Context in preparation * for computing a new SHA1 message digest. * * Parameters: * context: [in/out] * The context to reset. * * Returns: * sha Error Code. * */ int SHA1Reset(SHA1Context *context) { if (!context) { return shaNull; } context->Length_Low = 0; context->Length_High = 0; context->Message_Block_Index = 0; context->Intermediate_Hash[0] = 0x67452301; context->Intermediate_Hash[1] = 0xEFCDAB89; context->Intermediate_Hash[2] = 0x98BADCFE; context->Intermediate_Hash[3] = 0x10325476; context->Intermediate_Hash[4] = 0xC3D2E1F0; context->Computed = 0; context->Corrupted = 0; return shaSuccess; } /* * SHA1Result * * Description: * This function will return the 160-bit message digest into the * Message_Digest array provided by the caller. * NOTE: The first octet of hash is stored in the 0th element, * the last octet of hash in the 19th element. * * Parameters: * context: [in/out] * The context to use to calculate the SHA-1 hash. * Message_Digest: [out] * Where the digest is returned. * * Returns: * sha Error Code. * */ int SHA1Result( SHA1Context *context, uint8_t Message_Digest[SHA1HashSize]) { int i; if (!context || !Message_Digest) { return shaNull; } if (context->Corrupted) { return context->Corrupted; } if (!context->Computed) { SHA1PadMessage(context); for(i=0; i<64; ++i) { /* message may be sensitive, clear it out */ context->Message_Block[i] = 0; } context->Length_Low = 0; /* and clear length */ context->Length_High = 0; context->Computed = 1; } for(i = 0; i < SHA1HashSize; ++i) { Message_Digest[i] = (unsigned char)((context->Intermediate_Hash[i>>2] >> 8 * ( 3 - ( i & 0x03 ) )) & 0xFF) ; } return shaSuccess; } /* * SHA1Input * * Description: * This function accepts an array of octets as the next portion * of the message. * * Parameters: * context: [in/out] * The SHA context to update * message_array: [in] * An array of characters representing the next portion of * the message. * length: [in] * The length of the message in message_array * * Returns: * sha Error Code. * */ int SHA1Input( SHA1Context *context, const uint8_t *message_array, unsigned length) { if (!length) { return shaSuccess; } if (!context || !message_array) { return shaNull; } if (context->Computed) { context->Corrupted = shaStateError; return shaStateError; } if (context->Corrupted) { return context->Corrupted; } while(length-- && !context->Corrupted) { context->Message_Block[context->Message_Block_Index++] = (*message_array & 0xFF); context->Length_Low += 8; if (context->Length_Low == 0) { context->Length_High++; if (context->Length_High == 0) { /* Message is too long */ context->Corrupted = 1; } } if (context->Message_Block_Index == 64) { SHA1ProcessMessageBlock(context); } message_array++; } return shaSuccess; } /* * SHA1ProcessMessageBlock * * Description: * This function will process the next 512 bits of the message * stored in the Message_Block array. * * Parameters: * None. * * Returns: * Nothing. * * Comments: * Many of the variable names in this code, especially the * single character names, were used because those were the * names used in the publication. * * */ void SHA1ProcessMessageBlock(SHA1Context *context) { const uint32_t K[] = { /* Constants defined in SHA-1 */ 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 }; int t; /* Loop counter */ uint32_t temp; /* Temporary word value */ uint32_t W[80]; /* Word sequence */ uint32_t A, B, C, D, E; /* Word buffers */ /* * Initialize the first 16 words in the array W */ for(t = 0; t < 16; t++) { W[t] = context->Message_Block[t * 4] << 24; W[t] |= context->Message_Block[t * 4 + 1] << 16; W[t] |= context->Message_Block[t * 4 + 2] << 8; W[t] |= context->Message_Block[t * 4 + 3]; } for(t = 16; t < 80; t++) { W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]); } A = context->Intermediate_Hash[0]; B = context->Intermediate_Hash[1]; C = context->Intermediate_Hash[2]; D = context->Intermediate_Hash[3]; E = context->Intermediate_Hash[4]; for(t = 0; t < 20; t++) { temp = SHA1CircularShift(5,A) + ((B & C) | ((~B) & D)) + E + W[t] + K[0]; E = D; D = C; C = SHA1CircularShift(30,B); B = A; A = temp; } for(t = 20; t < 40; t++) { temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]; E = D; D = C; C = SHA1CircularShift(30,B); B = A; A = temp; } for(t = 40; t < 60; t++) { temp = SHA1CircularShift(5,A) + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]; E = D; D = C; C = SHA1CircularShift(30,B); B = A; A = temp; } for(t = 60; t < 80; t++) { temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3]; E = D; D = C; C = SHA1CircularShift(30,B); B = A; A = temp; } context->Intermediate_Hash[0] += A; context->Intermediate_Hash[1] += B; context->Intermediate_Hash[2] += C; context->Intermediate_Hash[3] += D; context->Intermediate_Hash[4] += E; context->Message_Block_Index = 0; } /* * SHA1PadMessage * * Description: * According to the standard, the message must be padded to an even * 512 bits. The first padding bit must be a '1'. The last 64 * bits represent the length of the original message. All bits in * between should be 0. This function will pad the message * according to those rules by filling the Message_Block array * accordingly. It will also call the ProcessMessageBlock function * provided appropriately. When it returns, it can be assumed that * the message digest has been computed. * * Parameters: * context: [in/out] * The context to pad * ProcessMessageBlock: [in] * The appropriate SHA*ProcessMessageBlock function * Returns: * Nothing. * */ void SHA1PadMessage(SHA1Context *context) { /* * Check to see if the current message block is too small to hold * the initial padding bits and length. If so, we will pad the * block, process it, and then continue padding into a second * block. */ if (context->Message_Block_Index > 55) { context->Message_Block[context->Message_Block_Index++] = 0x80; while(context->Message_Block_Index < 64) { context->Message_Block[context->Message_Block_Index++] = 0; } SHA1ProcessMessageBlock(context); while(context->Message_Block_Index < 56) { context->Message_Block[context->Message_Block_Index++] = 0; } } else { context->Message_Block[context->Message_Block_Index++] = 0x80; while(context->Message_Block_Index < 56) { context->Message_Block[context->Message_Block_Index++] = 0; } } /* * Store the message length as the last 8 octets */ context->Message_Block[56] = (unsigned char)((context->Length_High >> 24) & 0xFF); context->Message_Block[57] = (unsigned char)((context->Length_High >> 16) & 0xFF); context->Message_Block[58] = (unsigned char)((context->Length_High >> 8) & 0xFF); context->Message_Block[59] = (unsigned char)((context->Length_High) & 0xFF); context->Message_Block[60] = (unsigned char)((context->Length_Low >> 24) & 0xFF); context->Message_Block[61] = (unsigned char)((context->Length_Low >> 16) & 0xFF); context->Message_Block[62] = (unsigned char)((context->Length_Low >> 8) & 0xFF); context->Message_Block[63] = (unsigned char)((context->Length_Low) & 0xFF); SHA1ProcessMessageBlock(context); } sipxtapi-3.3.0~test17/sipXportLib/src/hmac-sha1/sha1.h0000644000175000017500000000670012205613256023220 0ustar00danieldaniel00000000000000/* * sha1.h (Obtained from rfc3471) * * Copyright (c) The Internet Society (2001). All Rights Reserved. * * This document and translations of it may be copied and furnished to others, * and derivative works that comment on or otherwise explain it or assist in * its implementation may be prepared, copied, published and distributed, in * whole or in part, without restriction of any kind, provided that the above * copyright notice and this paragraph are included on all such copies and * derivative works. However, this document itself may not be modified in any * way, such as by removing the copyright notice or references to the Internet * Society or other Internet organizations, except as needed for the purpose * of developing Internet standards in which case the procedures for copyrights * defined in the Internet Standards process must be followed, or as required * to translate it into languages other than English. * * The limited permissions granted above are perpetual and will not be revoked * by the Internet Society or its successors or assigns. * * This document and the information contained herein is provided on an * "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK * FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT * INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR * FITNESS FOR A PARTICULAR PURPOSE. * * Description: * This is the header file for code which implements the Secure * Hashing Algorithm 1 as defined in FIPS PUB 180-1 published * April 17, 1995. * * Many of the variable names in this code, especially the * single character names, were used because those were the names * used in the publication. * * Please read the file sha1.c for more information. */ #ifndef _SHA1_H_ #define _SHA1_H_ /* * If you do not have the ISO standard stdint.h header file, then you * must typdef the following: * name meaning * uint32_t unsigned 32 bit integer * uint8_t unsigned 8 bit integer (i.e., unsigned char) * int_least16_t integer of >= 16 bits * */ #ifdef WIN32 typedef unsigned __int32 uint32_t ; typedef unsigned char uint8_t ; typedef signed __int16 int_least16_t ; #else #include #endif #ifndef _SHA_enum_ #define _SHA_enum_ enum { shaSuccess = 0, shaNull, /* Null pointer parameter */ shaInputTooLong, /* input data too long */ shaStateError /* called Input after Result */ }; #endif #define SHA1HashSize 20 /* * This structure will hold context information for the SHA-1 * hashing operation */ typedef struct SHA1Context { uint32_t Intermediate_Hash[SHA1HashSize/4]; /* Message Digest */ uint32_t Length_Low; /* Message length in bits */ uint32_t Length_High; /* Message length in bits */ /* Index into message block array */ int_least16_t Message_Block_Index; uint8_t Message_Block[64]; /* 512-bit message blocks */ int Computed; /* Is the digest computed? */ int Corrupted; /* Is the message digest corrupted? */ } SHA1Context; /* * Function Prototypes */ int SHA1Reset( SHA1Context *); int SHA1Input( SHA1Context *, const uint8_t *, unsigned int); int SHA1Result( SHA1Context *, uint8_t Message_Digest[SHA1HashSize]); #endif sipxtapi-3.3.0~test17/sipXportLib/src/os/0000755000175000017500000000000012321445024021062 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/0000755000175000017500000000000012321445024022221 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/clock_gettime.c0000644000175000017500000000161012205613256025201 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include /* This function comes from librt.so. We would prefer not to need that library * but the RTCP code uses clock_gettime(). Rather than rewrite that code, we * just implement clock_gettime() using gettimeofday(). */ #ifdef __APPLE__ /* we don't even have the typedef on OS X */ typedef int clockid_t; #endif int clock_gettime(clockid_t clock_id, struct timespec * tp) { struct timeval tv; if(gettimeofday(&tv, NULL)) return -1; tp->tv_sec = tv.tv_sec; tp->tv_nsec = tv.tv_usec * 1000; return 0; } sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/host_address.c0000644000175000017500000000632212205613256025057 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// /* This file contains routines to inspect the routing table, discern the default * route, and look up the IP address of the network interface that corresponds * to this route. This allows software to bind to that address reliably, rather * than having to look up the hostname, which resolves to 127.0.0.1 on many * Linux distributions. */ /* This code will only work on Linux. */ #ifdef __linux__ /* [ */ #include #include #include #include #include #include #include #include #include #include #include "os/linux/host_address.h" static void get_default(char * if_name, int length) { if(length <= 999) { FILE * routes = fopen("/proc/net/route", "r"); if(routes) { char line[256]; /* read header line */ fgets(line, 256, routes); /* prefetch read loop */ fgets(line, 256, routes); while(!feof(routes)) { unsigned int address; char query[9]; sprintf(query, "%%%ds %%x", length); sscanf(line, query, if_name, &address); if(!address) break; fgets(line, 256, routes); } if(feof(routes)) if_name[0] = 0; fclose(routes); } } else if_name[0] = 0; } static unsigned int get_address(char * if_name) { struct ifconf if_list; struct ifreq interfaces[16]; int i, s = socket(AF_INET, SOCK_DGRAM, 0); if_list.ifc_len = 16 * sizeof(struct ifreq); if_list.ifc_req = interfaces; ioctl(s, SIOCGIFCONF, &if_list); close(s); for(i = 0; i != if_list.ifc_len / sizeof(struct ifreq); i++) { char * name = interfaces[i].ifr_ifrn.ifrn_name; unsigned int address = ((struct sockaddr_in *)&interfaces[i].ifr_ifru.ifru_addr)->sin_addr.s_addr; if(if_name && !strcmp(name, if_name)) return address; /* if we couldn't get a default route, accept the first non-local address */ if(!if_name && address != 0x0100007F) return address; } /* return 127.0.0.1 */ return 0x0100007F; } static void get_hwaddr(char * if_name, char * address, int length) { unsigned char * hwaddr; struct ifreq interface; int s = socket(AF_INET, SOCK_DGRAM, 0); strcpy(interface.ifr_name, if_name); ioctl(s, SIOCGIFHWADDR, &interface); close(s); hwaddr = interface.ifr_hwaddr.sa_data; snprintf(address, length, "%02X:%02X:%02X:%02X:%02X:%02X", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3], hwaddr[4], hwaddr[5]); } unsigned int getExternalHostAddressLinux(void) { char if_name[16]; get_default(if_name, 16); return get_address(if_name[0] ? if_name : NULL); } void getEthernetHWAddrLinux(char * address, int length) { char if_name[16]; get_default(if_name, 16); get_hwaddr(if_name, address, length); } #endif /* __linux__ ] */ sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/AdapterInfo.cpp0000644000175000017500000001234612205613256025134 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #include #include #include #include #include #include #include #include #include // APPLICATION INCLUDES #include #include /** * Get the addresses associated with all of the IP interfaces. * * The core work is done by the SIOCGIFCONF ioctl, documented in the * netdevice(7) manual page, with additional hints in ioctl(2), ip(7) and inet(3). */ bool getAllLocalHostIps(const HostAdapterAddress* localHostAddresses[], int &numAddresses) { numAddresses = 0; UtlBoolean rc; // Allocate array of struct ifreq's. struct ifreq ifreq_array[MAX_IP_ADDRESSES]; // Allocate struct ifconf. struct ifconf ifconf_structure; // Point ifconf to ifreq's. ifconf_structure.ifc_len = sizeof (ifreq_array); ifconf_structure.ifc_req = ifreq_array; // Open an arbitrary network socket on which to perform the ioctl. int sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "getAllLocalHostIps unable to open socket, errno = %d", errno); rc = FALSE; } else { // Perform the SIOCGIFCONF ioctl to get the interface addresses. int ret = ioctl(sock, SIOCGIFCONF, (void*) &ifconf_structure); //printf("RES=%d\n", ret); if (ret < 0) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "getAllLocalHostIps error performing SIOCGIFCONF, errno = %d", errno); rc = FALSE; } else { rc = TRUE; // Get the number of returned addresses from ifc_len. numAddresses = ifconf_structure.ifc_len / sizeof (struct ifreq); //printf("adrs=%d (%d)\n", numAddresses, MAX_IP_ADDRESSES); int j = 0; #ifdef __APPLE__ # define max(a,b) ((a) > (b) ? (a) : (b)) char *ptr; for (ptr = (char*)ifreq_array; ptr < (char*)ifreq_array + ifconf_structure.ifc_len; ) { struct ifreq* ifr = (struct ifreq*)ptr; int len = max(sizeof(struct sockaddr), ifr->ifr_addr.sa_len); ptr += sizeof(ifr->ifr_name) + len; if (ifr->ifr_addr.sa_family != AF_INET) continue; #else // Iterate through the returned addresses. for (int i = 0; i < numAddresses; i++) { if (ifreq_array[i].ifr_addr.sa_family != AF_INET) continue; struct ifreq* ifr = &ifreq_array[i]; #endif // Get transient pointer to address in text format. char* s = inet_ntoa(((struct sockaddr_in&) (ifr->ifr_addr)).sin_addr); //printf("D = %s\n", s); // Ignore the loopback address, because opening ports on the // loopback interface interferes with STUN operation. UtlString address(s); if (address.compareTo("127.0.0.1") != 0 && address.compareTo("0.0.0.0") != 0) { // Put the interface name and address into a HostAdapterAddress. localHostAddresses[j] = new HostAdapterAddress(ifr->ifr_name, s); /* OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "getAllLocalHostIps entry %d, interface '%s', address '%s'", j, ifreq_array[i].ifr_name, s); */ //printf("lha[%d] = %s\n", j, ifr->ifr_name); j++; } } numAddresses = j; } close(sock); } //printf ("rc=%d (%d)\n", rc, numAddresses); return rc; } bool getContactAdapterName(UtlString &adapterName, const UtlString &ipAddress, bool unusedHere) { bool found = false; // Explicitly check for loopback adapter, because getAllLocalHostIps never // name it. if (ipAddress == "127.0.0.1") { found = true; // TODO:: It is not always true. You may set any name to loopback // adapter, afaik. So we may want to do real search here. adapterName = "lo"; return found; } else { int numAddresses = 0; const HostAdapterAddress* adapterAddresses[MAX_IP_ADDRESSES]; getAllLocalHostIps(adapterAddresses, numAddresses); // Return empty string if nothing will be found adapterName.remove(0); for (int i = 0; i < numAddresses; i++) { if (ipAddress.compareTo(adapterAddresses[i]->mAddress.data()) == 0) { adapterName = adapterAddresses[i]->mAdapter; /* OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "getContactAdapterName found name %s for ip %s", szAdapter, szIp); */ found = true; } delete adapterAddresses[i]; } } return found; } sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/OsBSemLinux.cpp0000644000175000017500000000767512205613256025121 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/linux/OsBSemLinux.h" #include "os/linux/OsUtilLinux.h" #include "os/linux/pt_csem.h" #include "os/OsSysLog.h" #include "os/OsTask.h" #ifdef OS_SYNC_DEBUG # include "os/OsDateTime.h" #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsBSemLinux::OsBSemLinux(const int queueOptions, const int initState) { int res; mOptions = queueOptions; res = pt_sem_init(&mSemImp, 1, initState); assert(res == POSIX_OK); #ifdef OS_SYNC_DEBUG int me = pthread_self(); mSyncCrumbs.dropCrumb(me, crumbCreated); if (EMPTY == initState) { mSyncCrumbs.dropCrumb(me, crumbAcquired); } #endif } // Destructor OsBSemLinux::~OsBSemLinux() { int res; res = pt_sem_destroy(&mSemImp); if (res != POSIX_OK) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsBSemLinux::~OsBSemLinux pt_sem_destroy returned %d in task %u", res, (unsigned int)pthread_self() ); } # ifdef OS_SYNC_DEBUG mSyncCrumbs.dropCrumb(pthread_self(), crumbDeleted); # endif } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ // Block the task until the semaphore is acquired or the timeout expires OsStatus OsBSemLinux::acquire(const OsTime& rTimeout) { OsStatus retVal; struct timespec timeout; # ifdef OS_SYNC_DEBUG OsTime waitingSince; OsDateTime::getCurTime(waitingSince); # endif if(rTimeout.isInfinite()) { retVal = (pt_sem_wait(&mSemImp) == POSIX_OK) ? OS_SUCCESS : OS_BUSY; } else if(rTimeout.isNoWait()) { retVal = (pt_sem_trywait(&mSemImp) == POSIX_OK) ? OS_SUCCESS : OS_BUSY; } else { OsUtilLinux::cvtOsTimeToTimespec(rTimeout, &timeout); retVal = (pt_sem_timedwait(&mSemImp, &timeout) == POSIX_OK) ? OS_SUCCESS : OS_WAIT_TIMEOUT; } #ifdef OS_SYNC_DEBUG if (OS_SUCCESS == retVal) { mSyncCrumbs.dropCrumb(pthread_self(), crumbAcquired); /* use the waitingSince to keep the compiler from optimizing it away */ if ( 0 == waitingSince.cvtToMsecs() )// should never be true { retVal = OS_SUCCESS; } } #endif return retVal; } // Conditionally acquire the semaphore (i.e., don't block) // Return OS_BUSY if the semaphore is held by some other task OsStatus OsBSemLinux::tryAcquire(void) { OsStatus retVal; retVal = (pt_sem_trywait(&mSemImp) == POSIX_OK) ? OS_SUCCESS : OS_BUSY; #ifdef OS_SYNC_DEBUG if (retVal == OS_SUCCESS) { mSyncCrumbs.dropCrumb(pthread_self(), crumbAcquired); } #endif return retVal; } // Release the semaphore OsStatus OsBSemLinux::release(void) { OsStatus retVal; #ifdef OS_SYNC_DEBUG // change these while still holding the lock... mSyncCrumbs.dropCrumb(pthread_self(), crumbReleased); #endif retVal = (pt_sem_post(&mSemImp) == POSIX_OK) ? OS_SUCCESS : OS_ALREADY_SIGNALED; return retVal; } /* ============================ INQUIRY =================================== */ // Print semaphore information to the console void OsBSemLinux::OsBSemShow(void) { // don't need this } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/OsCSemLinux.cpp0000644000175000017500000000776612205613256025123 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include // APPLICATION INCLUDES #include "os/OsSysLog.h" #include "os/linux/OsCSemLinux.h" #include "os/linux/OsUtilLinux.h" #include "os/linux/pt_csem.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor setting the initial and max semaphore values to maxCount OsCSemLinux::OsCSemLinux(const int queueOptions, const int maxCount) : OsCSemBase(queueOptions, maxCount, maxCount) { int res; init(); res = pt_sem_init(&mSemImp, maxCount, maxCount); assert(res == POSIX_OK); # ifdef OS_SYNC_DEBUG int me = pthread_self(); mSyncCrumbs.dropCrumb(me, crumbCreated); # endif } // Constructor allowing different initial and maximum semaphore values OsCSemLinux::OsCSemLinux(const int queueOptions, const int maxCount, const int initCount) : OsCSemBase(queueOptions, maxCount,initCount) { int res; init(); res = pt_sem_init(&mSemImp, maxCount, initCount); assert(res == POSIX_OK); # ifdef OS_SYNC_DEBUG int me = pthread_self(); mSyncCrumbs.dropCrumb(me, crumbCreated); # endif } // Destructor OsCSemLinux::~OsCSemLinux() { int res; res = pt_sem_destroy(&mSemImp); # ifdef OS_SYNC_DEBUG mSyncCrumbs.dropCrumb(pthread_self(), crumbDeleted); # endif } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ // Block the task until the semaphore is acquired or the timeout expires OsStatus OsCSemLinux::acquire(const OsTime& rTimeout) { struct timespec timeout; OsStatus res; if (rTimeout.isInfinite()) res = (pt_sem_wait(&mSemImp) == POSIX_OK) ? OS_SUCCESS : OS_BUSY; else if (rTimeout.isNoWait()) res = (pt_sem_trywait(&mSemImp) == POSIX_OK) ? OS_SUCCESS : OS_BUSY; else { OsUtilLinux::cvtOsTimeToTimespec(rTimeout, &timeout); res = (pt_sem_timedwait(&mSemImp, &timeout) == POSIX_OK) ? OS_SUCCESS : OS_WAIT_TIMEOUT; } #ifdef OS_CSEM_DEBUG if (res == OS_SUCCESS) { updateAcquireStats(); } #endif #ifdef OS_SYNC_DEBUG if (res == OS_SUCCESS) { mSyncCrumbs.dropCrumb(pthread_self(), crumbAcquired); } #endif return res; } // Conditionally acquire the semaphore (i.e., don't block) // Return OS_BUSY if the semaphore is held by some other task OsStatus OsCSemLinux::tryAcquire(void) { OsStatus res; res = (pt_sem_trywait(&mSemImp) == POSIX_OK) ? OS_SUCCESS : OS_BUSY; #ifdef OS_CSEM_DEBUG if (res == OS_SUCCESS) { updateAcquireStats(); } #endif #ifdef OS_SYNC_DEBUG if (res == OS_SUCCESS) { mSyncCrumbs.dropCrumb(pthread_self(), crumbAcquired); } #endif return res; } /* // Returns the current value of the semaphone int OsCSemLinux::getValue(void) { return pt_sem_getvalue(&mSemImp); } */ // Release the semaphore OsStatus OsCSemLinux::release(void) { OsStatus res; #ifdef OS_SYNC_DEBUG mSyncCrumbs.dropCrumb(pthread_self(), crumbReleased); #endif res = (pt_sem_post(&mSemImp) == POSIX_OK) ? OS_SUCCESS : OS_BUSY; #ifdef OS_CSEM_DEBUG if (res == OS_SUCCESS) { updateReleaseStats(); } #endif return res; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ // Common initialization shared by all (non-copy) constructors void OsCSemLinux::init(void) { } sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/OsDateTimeLinux.cpp0000644000175000017500000001767712205613256025772 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #include #include #ifdef __APPLE__ #include #endif // APPLICATION INCLUDES #include "os/OsTime.h" #include "os/linux/OsLinuxDefs.h" #include "os/linux/OsDateTimeLinux.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const int MICROSECS_PER_SEC = 1000000; #ifndef __APPLE__ static double sSecondsSinceBoot = -1; // First call to get seconds since boot and store the number here. static double sSecondsFirstCall = 0; // Store the seconds since Epoch at first call to get seconds since boot // and just call time() to calculate the seconds since boot, rather than // to read the /proc/ everytime. #endif // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Default constructor OsDateTimeLinux::OsDateTimeLinux() : OsDateTimeBase() { // no further work required // all of the work is done by the parent constructor } // Constructor OsDateTimeLinux::OsDateTimeLinux(const unsigned short year, const unsigned char month, const unsigned char day, const unsigned char hour, const unsigned char minute, const unsigned char second, const unsigned int microsecond) : OsDateTimeBase(year, month, day, hour, minute, second, microsecond) { // no further work required // all of the work is done by the parent constructor } // Copy constructor OsDateTimeLinux::OsDateTimeLinux(const OsDateTimeLinux& rOsDateTimeLinux) : OsDateTimeBase((const OsDateTimeBase&) rOsDateTimeLinux) { // no further work required // all of the work is done by the parent copy constructor } /// Convert an OsTime to an OsDateTime OsDateTimeLinux::OsDateTimeLinux(const OsTime& toTime) { struct tm dateTime; time_t seconds = toTime.seconds(); gmtime_r(&seconds, &dateTime); mYear = 1900 + dateTime.tm_year; mMonth = (unsigned char) dateTime.tm_mon; mDay = (unsigned char) dateTime.tm_mday; mHour = (unsigned char) dateTime.tm_hour; mMinute = (unsigned char) dateTime.tm_min; mSecond = (unsigned char) dateTime.tm_sec; mMicrosecond = toTime.usecs(); } // Destructor OsDateTimeLinux::~OsDateTimeLinux() { // no work required } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsDateTimeLinux& OsDateTimeLinux::operator=(const OsDateTimeLinux& rhs) { if (this == &rhs) // handle the assignment to self case return *this; OsDateTimeBase::operator=((const OsDateTimeBase&) rhs); // no further work required // all of the "heavy lifting" is done by the parent assignment operator return *this; } // Set the system time -- this is a no-op under Linux for now. void OsDateTimeLinux::setTime(struct timespec gmt, int tzOffsetSecs, DstRule dstRule) { // no-op for now } // Set the system timezone -- this is a no-op under Linux for now. void OsDateTimeLinux::setTimeZone(int tzOffsetSecs, DstRule dstRule) { // no-op for now } /* ============================ ACCESSORS ================================= */ // Convert the OsDateTimeBase value to an OsTime value // The OsTime value is relative to when the system was booted. OsStatus OsDateTimeLinux::cvtToTimeSinceBoot(OsTime& rTime) const { unsigned long curTimeAsSecsSinceBoot; time_t curTimeAsTimeT; struct tm thisTime; long thisTimeAsSecsSinceBoot; time_t thisTimeAsTimeT; // convert "this" OsDateTime to a time_t representation thisTime.tm_year = mYear - 1900; thisTime.tm_mon = mMonth; thisTime.tm_mday = mDay; thisTime.tm_hour = mHour; thisTime.tm_min = mMinute; thisTime.tm_sec = mSecond; thisTimeAsTimeT = mktime(&thisTime); assert(thisTimeAsTimeT >= 0); // get the current time as a time_t curTimeAsTimeT = time(NULL); assert(curTimeAsTimeT >= 0); // get the current time as seconds since boot curTimeAsSecsSinceBoot = (unsigned long)secondsSinceBoot(); // convert "this" time to seconds since boot thisTimeAsSecsSinceBoot = (thisTimeAsTimeT - curTimeAsTimeT) + curTimeAsSecsSinceBoot; OsTime deltaOsTime(thisTimeAsSecsSinceBoot, 0); rTime = deltaOsTime; return OS_SUCCESS; } // Return the current time as an OsTime value void OsDateTimeLinux::getCurTime(OsTime& rTime) { struct timeval theTime; gettimeofday( &theTime, NULL ); OsTime curTime(theTime.tv_sec, theTime.tv_usec); rTime = curTime; } // Return the current time as an OsDateTime value void OsDateTimeLinux::getCurTime(OsDateTimeLinux& rDateTime) { struct timeval theTime; gettimeofday( &theTime, NULL ); struct tm curDateTime; gmtime_r(&theTime.tv_sec, &curDateTime); rDateTime.mYear = 1900 + curDateTime.tm_year; rDateTime.mMonth = (unsigned char) curDateTime.tm_mon; rDateTime.mDay = (unsigned char) curDateTime.tm_mday; rDateTime.mHour = (unsigned char) curDateTime.tm_hour; rDateTime.mMinute = (unsigned char) curDateTime.tm_min; rDateTime.mSecond = (unsigned char) curDateTime.tm_sec; rDateTime.mMicrosecond = theTime.tv_usec; } // Return the current time as an OsTime value // The OsTime value is relative to when the system was booted. void OsDateTimeLinux::getCurTimeSinceBoot(OsTime& rTime) { double seconds; unsigned long secs; unsigned long usecs; seconds = secondsSinceBoot(); secs = (int)seconds; usecs = (int)((seconds - secs) * MICROSECS_PER_SEC); OsTime timeSinceBoot(secs, usecs); rTime = timeSinceBoot; } // Current time as the number of seconds since midnight (0 hour) 01/01/1970 unsigned long OsDateTimeLinux::getSecsSinceEpoch(void) { return time(NULL); } // Get the number of seconds since boot using /proc/uptime or sysctl() double OsDateTimeLinux::secondsSinceBoot(void) { #ifndef __APPLE__ double seconds = 0; // default to 0 if we can't open the file OsTime curTime(time(NULL), 0); if (sSecondsSinceBoot >= 0) seconds = curTime.seconds() - sSecondsFirstCall + sSecondsSinceBoot; else { // This is somewhat of a cheezy hack but there doesn't seem to be a // system call to do it. It will work on all Linux systems with the // /proc filesystem enabled, which is just about every one of them. FILE * proc; sSecondsFirstCall = curTime.seconds(); proc = fopen("/proc/uptime","r"); if(proc != NULL) { fscanf(proc,"%lf",&seconds); fclose(proc); } sSecondsSinceBoot = seconds; } return seconds; #else /* __APPLE__ */ // On OS X, we can use sysctl() to get the uptime struct timeval boot, now; int r, request[2] = {CTL_KERN, KERN_BOOTTIME}; size_t result_len = sizeof(boot); r = sysctl(request, 2, &boot, &result_len, NULL, 0); /* this should never happen, but make sure anyway */ assert(r >= 0); gettimeofday(&now, NULL); now.tv_sec -= boot.tv_sec; if (now.tv_usec < boot.tv_usec) now.tv_sec--; return now.tv_sec; #endif } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/OsDirLinux.cpp0000644000175000017500000000653412205613256025002 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #include #include #include #include // APPLICATION INCLUDES #include "os/OsFS.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsDirLinux::OsDirLinux(const char* pathname) : OsDirBase(pathname) { } OsDirLinux::OsDirLinux(const OsPathLinux& pathname) : OsDirBase(pathname.data()) { } // Copy constructor OsDirLinux::OsDirLinux(const OsDirLinux& rOsDirLinux) : OsDirBase(rOsDirLinux.mDirName.data()) { } // Destructor OsDirLinux::~OsDirLinux() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsDirLinux& OsDirLinux::operator=(const OsDirLinux& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } OsStatus OsDirLinux::create(int permissions) const { OsStatus ret = OS_INVALID; OsPathBase path; if (mDirName.getNativePath(path) == OS_SUCCESS) { int err = mkdir((const char *)path.data(),permissions); if (err != -1) { ret = OS_SUCCESS; } } return ret; } OsStatus OsDirLinux::rename(const char* name) { OsStatus ret = OS_INVALID; OsPathBase path; if (mDirName.getNativePath(path) == OS_SUCCESS) { int err = ::rename(path.data(),name); if (err != -1) { ret = OS_SUCCESS; //make this object point to new path mDirName = name; } } return ret; } /* ============================ ACCESSORS ================================= */ OsStatus OsDirLinux::getFileInfo(OsFileInfoBase& fileinfo) const { OsStatus ret = OS_INVALID; struct stat stats; if (stat((char *)mDirName.data(),&stats) == 0) { ret = OS_SUCCESS; if (stats.st_mode & S_IFDIR) fileinfo.mbIsDirectory = TRUE; else fileinfo.mbIsDirectory = FALSE; if (stats.st_mode & S_IWUSR) fileinfo.mbIsReadOnly = FALSE; else fileinfo.mbIsReadOnly = TRUE; OsTime createTime(stats.st_ctime,0); fileinfo.mCreateTime = createTime; OsTime modifiedTime(stats.st_mtime,0); fileinfo.mModifiedTime = modifiedTime; fileinfo.mSize = stats.st_size; } return ret; } /* ============================ INQUIRY =================================== */ UtlBoolean OsDirLinux::exists() { UtlBoolean stat = FALSE; OsFileInfoLinux info; OsStatus retval = getFileInfo(info); if (retval == OS_SUCCESS) stat = TRUE; return stat; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/OsFileInfoLinux.cpp0000644000175000017500000000320012205613256025742 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/linux/OsFileInfoLinux.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsFileInfoLinux::OsFileInfoLinux() { } // Copy constructor OsFileInfoLinux::OsFileInfoLinux(const OsFileInfoLinux& rOsFileInfo) { } // Destructor OsFileInfoLinux::~OsFileInfoLinux() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsFileInfoLinux& OsFileInfoLinux::operator=(const OsFileInfoLinux& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ UtlBoolean OsFileInfoLinux::isReadOnly() const { UtlBoolean retval = TRUE; return retval; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/OsFileIteratorLinux.cpp0000644000175000017500000000646212205613256026655 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/linux/OsFileIteratorLinux.h" #include "os/OsFileIteratorBase.h" #include "os/linux/OsPathLinux.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsFileIteratorLinux::OsFileIteratorLinux(const OsPathLinux& pathname) : OsFileIteratorBase(pathname), mSearchHandle(NULL) { } // Destructor OsFileIteratorLinux::~OsFileIteratorLinux() { if (mSearchHandle) { closedir(mSearchHandle); mSearchHandle = NULL; } } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ OsFileIteratorLinux::OsFileIteratorLinux() : mSearchHandle(NULL) { } OsStatus OsFileIteratorLinux::getFirstEntryName(UtlString &name, OsFileType &type) { OsStatus retstat = OS_FILE_NOT_FOUND; name = ""; mFullSearchSpec.strip(UtlString::trailing, '/'); if (mFullSearchSpec == "") { mFullSearchSpec = "."; } if(mSearchHandle) closedir(mSearchHandle); mSearchHandle = opendir((char*) mFullSearchSpec.data()); if (mSearchHandle) { struct dirent* uriDirEntry = NULL; if ((uriDirEntry = readdir(mSearchHandle)) != NULL) { name = uriDirEntry->d_name; retstat = OS_SUCCESS; UtlString fullName = mUserSpecifiedPath; fullName += name; struct stat dirEntryStat; stat((char*)fullName.data(), &dirEntryStat); if(dirEntryStat.st_mode & S_IFDIR) type = DIRECTORIES; else type = FILES; } } else { retstat = OS_FILE_NOT_FOUND; } return retstat; } OsStatus OsFileIteratorLinux::getNextEntryName(UtlString &name, OsFileType &type) { OsStatus retstat = OS_FILE_NOT_FOUND; name = ""; if (mSearchHandle) { struct dirent* uriDirEntry = NULL; if ((uriDirEntry = readdir(mSearchHandle)) != NULL) { retstat = OS_SUCCESS; name = uriDirEntry->d_name; UtlString fullName = mUserSpecifiedPath; fullName += name; struct stat dirEntryStat; stat((char*)fullName.data(), &dirEntryStat); if(dirEntryStat.st_mode & S_IFDIR) { type = DIRECTORIES; } else { type = FILES; } } } return retstat; } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/OsFileLinux.cpp0000644000175000017500000001031012205613256025126 0ustar00danieldaniel00000000000000// // Copyright (C) 2005, 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004, 2005 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #include #include #include #include // APPLICATION INCLUDES #include "os/OsFS.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const unsigned long CopyBufLen = 32768; //needed this so vxworks macros will find OK for the stdio funcs #ifdef _VXWORKS #ifndef OK#include #define OK 0 #endif /* OK */ #endif /* _VXWORKS */ // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsFileLinux::OsFileLinux(const OsPathBase& filename) : OsFileBase(filename) { } // Copy constructor OsFileLinux::OsFileLinux(const OsFileLinux& rOsFileLinux) : OsFileBase(rOsFileLinux) { OsPathLinux path; rOsFileLinux.getFileName(path); mFilename = path; mOsFileHandle = rOsFileLinux.mOsFileHandle; } // Destructor OsFileLinux::~OsFileLinux() { if (mOsFileHandle) close(); //call our close } /* ============================ MANIPULATORS ============================== */ OsStatus OsFileLinux::filelock(const bool wait) { OsStatus retval = OS_FAILED; struct flock f; if (mOsFileHandle) { f.l_type = F_WRLCK; f.l_start = 0; f.l_whence = SEEK_SET; f.l_len = 0; f.l_pid = getpid(); int fd = fileno(mOsFileHandle); if (fcntl(fd, wait ? F_SETLKW : F_SETLK, &f) != -1); retval = OS_SUCCESS; } return retval; } OsStatus OsFileLinux::fileunlock() { OsStatus retval = OS_FAILED; struct flock f; if (mOsFileHandle) { f.l_type = F_UNLCK; f.l_start = 0; f.l_whence = SEEK_SET; f.l_len = 0; f.l_pid = getpid(); int fd = fileno(mOsFileHandle); if (fcntl(fd, F_SETLK, &f) != -1) retval = OS_SUCCESS; } else retval = OS_SUCCESS; return retval; } OsStatus OsFileLinux::setLength(unsigned long newLength) { OsStatus stat = OS_SUCCESS; return stat; } OsStatus OsFileLinux::setReadOnly(UtlBoolean bState) { OsStatus stat = OS_INVALID; int mode = S_IREAD; if (!bState) mode |= S_IWRITE; if (chmod(mFilename,mode) != -1) stat = OS_SUCCESS; return stat; } OsStatus OsFileLinux::touch() { OsStatus stat = OS_INVALID; if (exists() == OS_SUCCESS) { if (utime(mFilename,NULL) == 0) stat = OS_SUCCESS; } else { stat = open(CREATE); close(); } return stat; } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ UtlBoolean OsFileLinux::isReadonly() const { OsFileInfoLinux info; getFileInfo(info); return info.mbIsReadOnly; } OsStatus OsFileLinux::getFileInfo(OsFileInfoBase& fileinfo) const { OsStatus ret = OS_INVALID; struct stat stats; if (stat(mFilename,&stats) == 0) { ret = OS_SUCCESS; fileinfo.mbIsReadOnly = (stats.st_mode & S_IWUSR) == 0; OsTime createTime(stats.st_ctime,0); fileinfo.mCreateTime = createTime; OsTime modifiedTime(stats.st_mtime, 0); fileinfo.mModifiedTime = modifiedTime; fileinfo.mSize = stats.st_size; } return ret; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ // Assignment operator OsFileLinux& OsFileLinux::operator=(const OsFileLinux& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/OsMutexLinux.cpp0000644000175000017500000000660412205613256025364 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include //#include #include "utl/UtlRscTrace.h" // APPLICATION INCLUDES #include "os/linux/OsMutexLinux.h" #include "os/linux/OsUtilLinux.h" #include "os/linux/pt_mutex.h" #include "os/OsTask.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor allowing the user to specify options OsMutexLinux::OsMutexLinux(const unsigned options) { int res; res = pt_mutex_init(&mMutexImp); assert(res == POSIX_OK); # ifdef OS_SYNC_DEBUG mSyncCrumbs.dropCrumb(pthread_self(), crumbCreated); # endif } // Destructor OsMutexLinux::~OsMutexLinux() { int res; res = pt_mutex_destroy(&mMutexImp); if(res != POSIX_OK) { osPrintf("**** ERROR: OsMutex at %p could not be destroyed in thread %ld! ****\n", this, pthread_self()); } # ifdef OS_SYNC_DEBUG mSyncCrumbs.dropCrumb(pthread_self(), crumbDeleted); # endif } /* ============================ MANIPULATORS ============================== */ // Block the task until the mutex is acquired or the timeout expires OsStatus OsMutexLinux::acquire(const OsTime& rTimeout) { struct timespec timeout; OsStatus status; if(rTimeout.isInfinite()) { status = (pt_mutex_lock(&mMutexImp) == POSIX_OK) ? OS_SUCCESS : OS_BUSY; } else if(rTimeout.isNoWait()) { status = (pt_mutex_trylock(&mMutexImp) == POSIX_OK) ? OS_SUCCESS : OS_BUSY; } else { OsUtilLinux::cvtOsTimeToTimespec(rTimeout, &timeout); status = (pt_mutex_timedlock(&mMutexImp, &timeout) == POSIX_OK) ? OS_SUCCESS : OS_WAIT_TIMEOUT; } #ifdef OS_SYNC_DEBUG if (status == OS_SUCCESS) { mSyncCrumbs.dropCrumb(pthread_self(), crumbAcquired); } #endif return status; } // Conditionally acquire the mutex (i.e., don't block) // Return OS_BUSY if the lock is held by some other task OsStatus OsMutexLinux::tryAcquire(void) { OsStatus status = (pt_mutex_trylock(&mMutexImp) == POSIX_OK) ? OS_SUCCESS : OS_BUSY; #ifdef OS_SYNC_DEBUG if (status == OS_SUCCESS) { mSyncCrumbs.dropCrumb(pthread_self(), crumbAcquired); } #endif return status; } // Release the mutex OsStatus OsMutexLinux::release(void) { #ifdef OS_SYNC_DEBUG // change these while still holding the lock... mSyncCrumbs.dropCrumb(pthread_self(), crumbReleased); #endif return (pt_mutex_unlock(&mMutexImp) == POSIX_OK) ? OS_SUCCESS : OS_BUSY; } /* ============================ ACCESSORS ================================= */ // Print mutex information to the console void OsMutexLinux::OsMutexShow(void) { osPrintf("OsMutex object %p\n", (void*) this); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/OsPathLinux.cpp0000644000175000017500000000337712205613256025162 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsFS.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsPathLinux::OsPathLinux() { } // Make one from a char string OsPathLinux::OsPathLinux(const char *pathname) : OsPathBase(pathname) { } // Make one from a UtlStringchar string OsPathLinux::OsPathLinux(const UtlString &pathname) : OsPathBase(pathname) { } // Copy constructor OsPathLinux::OsPathLinux(const OsPathLinux& rOsPath) { *this = rOsPath.data(); } // Destructor OsPathLinux::~OsPathLinux() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsPathLinux& OsPathLinux::operator=(const OsPathLinux& rhs) { if (this == &rhs) // handle the assignment to self case return *this; UtlString::operator=(rhs.data()); return *this; } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/OsProcessIteratorLinux.cpp0000644000175000017500000001117312205613256027407 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include // APPLICATION INCLUDES #include "os/OsFS.h" #include "os/linux/OsProcessIteratorLinux.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsProcessIteratorLinux::OsProcessIteratorLinux() : hProcessSnapshot(0) { OsPath procDir = "/proc"; mpFileIterator = new OsFileIterator(procDir); } // Destructor OsProcessIteratorLinux::~OsProcessIteratorLinux() { if (mpFileIterator) delete mpFileIterator; } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ OsStatus OsProcessIteratorLinux::findFirst(OsProcess &rProcess) { OsStatus retval = OS_FAILED; OsPath procName; OsStatus status = mpFileIterator->findFirst(procName,"^[0-9]+$",OsFileIterator::DIRECTORIES); if (status == OS_SUCCESS) { //this next line will fill in the needed members of the rProcess object if (readProcFile(procName,rProcess) == OS_SUCCESS) { retval = OS_SUCCESS; } else { osPrintf("ERROR: Couldn't read %s file!\n",procName.data()); } } else { osPrintf("No Files found in ProcIterator::findfirst\n"); } return retval; } OsStatus OsProcessIteratorLinux::findNext(OsProcess &rProcess) { OsStatus retval = OS_FAILED; OsPath procName; if (mpFileIterator) { OsStatus status = mpFileIterator->findNext(procName); if (status != OS_FILE_NOT_FOUND) { //this next line will fill in the needed members of the rProcess object if (readProcFile(procName,rProcess) == OS_SUCCESS) retval = OS_SUCCESS; else osPrintf("ERROR: Couldn't read %s file!\n",procName.data()); } } return retval; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ //reads the status file in the /proc/nnnn directory OsStatus OsProcessIteratorLinux::readProcFile(OsPath &procDirname, OsProcess & rProcess) { OsStatus retval = OS_FAILED; OsPath fullProcName = "/proc/"; fullProcName += procDirname; fullProcName += "/status"; OsFileLinux procFile(fullProcName); if (procFile.open(OsFile::READ_ONLY) == OS_SUCCESS) { long len = 5000; //since the length is always 0 for these files, lets try to read 5k char *buffer = new char[len+1]; if (buffer) { unsigned long bytesRead; procFile.read((void *)buffer,(unsigned long)len,bytesRead); if (bytesRead) { procFile.close(); //null-terminate the string buffer[bytesRead] = 0; //now parse the info we need char *ptr = strtok(buffer,"\n"); while(ptr) { if (memcmp(ptr,"Name:",5) == 0) { ptr +=5; while (*ptr == ' ' || *ptr == 0x09) ptr++; rProcess.mProcessName = ptr; rProcess.mProcessName.strip(UtlString::both, ' '); } else if (memcmp(ptr,"Pid:",4) == 0) { rProcess.mPID = atoi(ptr+4); } else if (memcmp(ptr,"PPid:",5) == 0) { rProcess.mParentPID = atoi(ptr+5); } ptr = strtok(NULL,"\n"); } //say we are successful retval = OS_SUCCESS; } else osPrintf("Couldn't read bytes in readProcFile\n"); delete [] buffer; } procFile.close(); } return retval; } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/OsProcessLinux.cpp0000644000175000017500000002327512205613256025703 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #include #include #include #include #include #include #include // APPLICATION INCLUDES #include "os/OsProcess.h" #include "os/OsTask.h" #include "os/linux/OsProcessLinux.h" #include "os/linux/OsUtilLinux.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ OsProcessLinux::OsProcessLinux() { } // Destructor OsProcessLinux::~OsProcessLinux() { } /* ============================ MANIPULATORS ============================== */ OsStatus OsProcessLinux::setIORedirect(OsPath &rStdInputFilename, OsPath &rStdOutputFilename, OsPath &rStdErrorFilename) { OsStatus retval = OS_FAILED; if (rStdInputFilename.length()) mStdInputFilename = rStdInputFilename; else mStdInputFilename = ""; if (rStdOutputFilename.length()) mStdOutputFilename = rStdOutputFilename; else mStdInputFilename = ""; if (rStdErrorFilename.length()) mStdErrorFilename = rStdErrorFilename; else mStdInputFilename = ""; return retval; } OsStatus OsProcessLinux::setPriority(int prio) { OsStatus retval = OS_FAILED; if (setpriority(PRIO_PROCESS,mPID,prio) == 0) { retval = OS_SUCCESS; } return retval; } //waits for a process to complete before returning //or exits when WaitInSecs has completed int OsProcessLinux::wait(int WaitInSecs) { UtlBoolean bStillRunning = TRUE; int secs_waited = 0; int status = 1; int ExitCode = -1; if (WaitInSecs < 0) WaitInSecs = 0; if (mPID > 0) { while (bStillRunning && secs_waited <= WaitInSecs) { if (waitpid(mPID,&status,WNOHANG|WUNTRACED) != mPID) { bStillRunning = TRUE; OsTask::delay(1000); if (WaitInSecs > 0) secs_waited++; } else { bStillRunning = FALSE; ExitCode = WEXITSTATUS(status); } } } else ExitCode = -1; return ExitCode; } OsStatus OsProcessLinux::kill() { OsStatus retval = OS_FAILED; if (::kill(mPID, SIGTERM) == 0) { int trycount = 0; OsSysLog::add(FAC_PROCESS, PRI_INFO,"Attempting kill on %s\n",mProcessName.data()); while (isRunning() && trycount++ < 3) { OsTask::delay(1000); ::kill(mPID, SIGTERM); } //bust a cap in it's.... trycount = 0; while (isRunning() && trycount++ < 30) { ::kill(mPID, SIGKILL); OsTask::delay(1000); } if (isRunning()) { OsSysLog::add(FAC_PROCESS, PRI_INFO,"KILL FAILED on %s\n",mProcessName.data()); retval = OS_FAILED; //not good. the thing just won't go away } else { retval = OS_SUCCESS; //hurray! it's gone OsSysLog::add(FAC_PROCESS, PRI_INFO,"SUCCESSFUL KILL on %s\n",mProcessName.data()); } } //this is the only way "so far" that I have found for killing the parent and //all the children /* if (isRunning()) { char killString[80]; sprintf(killString,"ps -ef | grep \"%d\" | awk '{ print $2}' | xargs kill 2>&1>/dev/null",mPID); system(killString); if (!isRunning()) retval = OS_SUCCESS; }*/ return retval; } OsStatus OsProcessLinux::launch(UtlString &rAppName, UtlString parameters[], OsPath &startupDir, OsProcessPriorityClass prioClass, UtlBoolean bExeclusive) { OsStatus retval = OS_FAILED; OsUtilLinux::signal(SIGCHLD, cleanZombieProcess); //build one string out of the array passed in int parameterCount = -1; while (!parameters[++parameterCount].isNull()); const char ** parms = new const char * [parameterCount + 2]; parms[0] = rAppName.data(); for(int i = 0; i < parameterCount; i++) parms[i + 1] = parameters[i].data(); parms[parameterCount + 1] = NULL; //now fork into two processes int forkReturnVal = fork(); switch (forkReturnVal) { case -1 : retval = OS_FAILED; break; case 0 : // this is the child process so we need to exec the new // process now it's time to redirect the output, input, and // error streams // Note: we must use _exit() rather than exit() here. // This has to do with the interactions between C++, the OS // abstraction layer, and the way threads are implemented on // Linux. if (mStdInputFilename.length()) { if (!freopen(mStdInputFilename.data(),"r",stdin)) { osPrintf("Could not redirect stdInput in OsProcess!"); _exit(1); } } if (mStdOutputFilename.length()) { if (!freopen(mStdOutputFilename.data(),"w",stdout)) { osPrintf("Could not redirect stdOutput in OsProcess!"); _exit(1); } } if (mStdErrorFilename.length()) { if (!freopen(mStdErrorFilename.data(),"w",stderr)) { osPrintf("Could not redirect stdError in OsProcess!"); _exit(1); } } //now apply the env variables the user may have set ApplyEnv(); //osPrintf("About to launch: %s %s\n", rAppName.data(), cmdLine.data()); //set the current dir for this process OsFileSystem::change(startupDir); //3...2...1... Blastoff! execvp(rAppName.data(), (char **) parms); //and it never reaches here hopefully osPrintf("Failed to execute '%s'!\n", rAppName.data()); _exit(1); default : // this is the parent process mPID = forkReturnVal; mParentPID = getpid(); retval = OS_SUCCESS; break; } delete[] parms; return retval; } /* ============================ ACCESSORS ================================= */ OsStatus OsProcessLinux::getByPID(PID pid, OsProcess &rProcess) { OsStatus retval = OS_FAILED; OsProcess process; OsProcessIterator pi; char buf[20]; sprintf(buf,"%d",pid); OsPath pidStr = buf; OsStatus findRetVal = pi.readProcFile(pidStr,process); if (findRetVal == OS_SUCCESS) { rProcess.mParentPID = process.mParentPID; rProcess.mPID = process.mPID; rProcess.mProcessName = process.mProcessName; retval = OS_SUCCESS; } return retval; } OsStatus OsProcessLinux::getInfo(OsProcessInfo &rProcessInfo) { OsStatus retval = OS_FAILED; OsProcess process; OsProcessIterator pi; OsStatus findRetVal = getByPID(mPID,process); if(findRetVal == OS_SUCCESS) { rProcessInfo.parentProcessID = process.mParentPID; rProcessInfo.name = process.mProcessName; rProcessInfo.commandline = ""; //TODO rProcessInfo.prioClass = 0; //TODO retval = OS_SUCCESS; } return retval; } OsStatus OsProcessLinux::getUpTime(OsTime &rUpTime) { OsStatus retval = OS_FAILED; return retval; } OsStatus OsProcessLinux::getPriorityClass(OsProcessPriorityClass &rPrioClass) { OsStatus retval = OS_FAILED; return retval; } OsStatus OsProcessLinux::getMinPriority(int &rMinPrio) { OsStatus retval = OS_FAILED; return retval; } OsStatus OsProcessLinux::getMaxPriority(int &rMaxPrio) { OsStatus retval = OS_FAILED; return retval; } OsStatus OsProcessLinux::getPriority(int &rPrio) { OsStatus retval = OS_FAILED; errno = 0; rPrio = getpriority(PRIO_PROCESS,mPID); if (errno == 0) { retval = OS_SUCCESS; } return retval; } int OsProcessLinux::getCurrentPID() { return getpid(); } /* ============================ INQUIRY =================================== */ UtlBoolean OsProcessLinux::isRunning() const { UtlBoolean retval = FALSE; OsProcess rProcess; if ( getByPID(mPID,rProcess) == OS_SUCCESS) retval = TRUE; return retval; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ void OsProcessLinux::cleanZombieProcess(int signal) { while(waitpid(-1, NULL, WNOHANG) > 0); } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/OsRWMutexLinux.cpp0000644000175000017500000000331712205613256025633 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include // APPLICATION INCLUDES #include "os/linux/OsRWMutexLinux.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /* ============================ CREATORS ================================== */ OsRWMutexLinux::OsRWMutexLinux(const int queueOptions) { int res; res = pthread_rwlock_init(&mLockImp, NULL); assert(res == POSIX_OK); } OsRWMutexLinux::~OsRWMutexLinux() { int res; res = pthread_rwlock_destroy(&mLockImp); assert(res == POSIX_OK); } /* ============================ MANIPULATORS ============================== */ OsStatus OsRWMutexLinux::acquireRead() { return pthread_rwlock_rdlock(&mLockImp) == POSIX_OK ? OS_SUCCESS : OS_BUSY; } OsStatus OsRWMutexLinux::acquireWrite() { return pthread_rwlock_wrlock(&mLockImp) == POSIX_OK ? OS_SUCCESS : OS_BUSY; } OsStatus OsRWMutexLinux::tryAcquireRead() { return pthread_rwlock_tryrdlock(&mLockImp) == POSIX_OK ? OS_SUCCESS : OS_BUSY; } OsStatus OsRWMutexLinux::tryAcquireWrite() { return pthread_rwlock_trywrlock(&mLockImp) == POSIX_OK ? OS_SUCCESS : OS_BUSY; } OsStatus OsRWMutexLinux::releaseRead() { return pthread_rwlock_unlock(&mLockImp) == POSIX_OK ? OS_SUCCESS : OS_BUSY; } OsStatus OsRWMutexLinux::releaseWrite() { return pthread_rwlock_unlock(&mLockImp) == POSIX_OK ? OS_SUCCESS : OS_BUSY; } sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/OsSharedLibMgrLinux.cpp0000644000175000017500000001425412205613256026565 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #include // APPLICATION INCLUDES #include "os/OsSysLog.h" #include "os/linux/OsSharedLibMgrLinux.h" #include "utl/UtlString.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // Private container class for collectable handles to shared libs class OsSharedLibHandleLinux : public UtlString { public: OsSharedLibHandleLinux(const char* libName, void* libHandle); void* mLibHandle; }; OsSharedLibHandleLinux::OsSharedLibHandleLinux(const char* libName, void* libHandle) : UtlString(libName ? libName : "") { mLibHandle = libHandle; } // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsSharedLibMgrLinux::OsSharedLibMgrLinux() { } // Copy constructor OsSharedLibMgrLinux::OsSharedLibMgrLinux(const OsSharedLibMgrLinux& rOsSharedLibMgrLinux) { } // Destructor OsSharedLibMgrLinux::~OsSharedLibMgrLinux() { } /* ============================ MANIPULATORS ============================== */ //: Loads the given shared library //!param: libName - name of library, may include absolute or relative path OsStatus OsSharedLibMgrLinux::loadSharedLib(const char* libName) { OsStatus status = OS_INVALID; // Check if we aready have a handle for this lib UtlString collectableName(libName ? libName : ""); sLock.acquire(); OsSharedLibHandleLinux* collectableLibHandle = (OsSharedLibHandleLinux*) mLibraryHandles.find(&collectableName); sLock.release(); // We do not already have a handle for this lib if(!collectableLibHandle) { // Load the shared library void* libHandle = dlopen(libName, RTLD_NOW | RTLD_GLOBAL); if (!libHandle) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "Failed to load shared library: %s error: %s", libName, dlerror()); status = OS_NOT_FOUND; } else { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "Loaded shared lib \"%s\" handle: %p", libName ? libName : "(null)", libHandle); OsSharedLibHandleLinux* collectableHandle = new OsSharedLibHandleLinux(libName, libHandle); sLock.acquire(); mLibraryHandles.insert(collectableHandle); sLock.release(); status = OS_SUCCESS; } } else { status = OS_SUCCESS; } return(status); } //: Gets the address of a symbol in the shared lib //!param: (in) libName - name of library, may include absolute or relative path //!param: (in) symbolName - name of the variable or function exported in the shared lib //!param: (out) symbolAddress - the address of the function or variable OsStatus OsSharedLibMgrLinux::getSharedLibSymbol(const char* libName, const char* symbolName, void*& symbolAddress) { OsStatus status = OS_INVALID; UtlString collectableName(libName ? libName : ""); sLock.acquire(); OsSharedLibHandleLinux* collectableLibHandle = (OsSharedLibHandleLinux*) mLibraryHandles.find(&collectableName); if(!collectableLibHandle) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSharedLibMgrLinux::getSharedLibSymbol library: \"%s\" not loaded yet, attempting to load", collectableName.data()); sLock.release(); loadSharedLib(libName); sLock.acquire(); collectableLibHandle = (OsSharedLibHandleLinux*) mLibraryHandles.find(&collectableName); } if(collectableLibHandle) { // Get a named symbol from the shared library symbolAddress = dlsym(collectableLibHandle->mLibHandle, symbolName); if (!symbolAddress) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "Failed to find symbol: %s in shared lib: %s error: %s", symbolName, libName ? libName : "(null)", dlerror()); status = OS_NOT_FOUND; } else { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "Found symbol: %s in shared lib: %s", symbolName, libName ? libName : "(null)"); status = OS_SUCCESS; } } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "Could not find or create handle for shared library: \'%s\'", libName ? libName : "(null)"); } sLock.release(); return(status); } OsStatus OsSharedLibMgrLinux::unloadSharedLib(const char* libName) { OsStatus status = OS_INVALID; UtlString collectableName(libName ? libName : ""); sLock.acquire(); OsSharedLibHandleLinux* collectableLibHandle = (OsSharedLibHandleLinux*) mLibraryHandles.find(&collectableName); if(!collectableLibHandle) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSharedLibMgrLinux::unloadSharedLib library: \"%s\" not loaded yet, nothing to do", collectableName.data()); sLock.release(); return status; } if (dlclose(collectableLibHandle->mLibHandle) != 0) { status = OS_FAILED; } else { collectableLibHandle = (OsSharedLibHandleLinux*) mLibraryHandles.remove(&collectableName); status = OS_SUCCESS; } sLock.release(); return(status); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/OsTaskLinux.cpp0000644000175000017500000006552212205617431025167 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #include #include #include #include #ifdef ANDROID // [ # include // for setpriority() #endif // !ANDROID ] /* Make sure we get MCL_CURRENT and MCL_FUTURE (for mlockall) on OS X 10.3 */ #define _P1003_1B_VISIBLE #include #undef _P1003_1B_VISIBLE // Include to access gettid() syscall for debug purposes #include // APPLICATION INCLUDES #include "os/OsExcept.h" #include "os/OsLock.h" #include "os/OsUtil.h" #include "os/linux/OsLinuxDefs.h" #include "os/linux/OsTaskLinux.h" #include "os/linux/OsUtilLinux.h" // DEFINES #ifdef ANDROID // [ // Bionic does not provide some functions, which we don't really need. # define pthread_cancel(x) assert("There's no pthread_cancel T_T\n") # define pthread_setcanceltype(a,b) # define mlockall(a) POSIX_OK #endif // ANDROID ] // EXTERNAL FUNCTIONS #ifndef ANDROID // [ static inline int gettid() {return syscall(SYS_gettid);} #endif // !ANDROID ] // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsTaskLinux::OsTaskLinux(const UtlString& name, void* pArg, const int priority, const int options, const int stackSize) : OsTaskBase(name, pArg, priority, options, stackSize), mTaskId(0), mDeleteGuard(OsRWMutex::Q_PRIORITY), mSuspendCnt(0), mOptions(options), mPriority(priority), mStackSize(stackSize) { pthread_mutex_init(&mStartupSyncMutex, NULL); pthread_cond_init(&mTaskInitializedEvent, NULL); pthread_cond_init(&mTaskStartedEvent, NULL); } // Destructor OsTaskLinux::~OsTaskLinux() { waitUntilShutDown(); doLinuxTerminateTask(FALSE); } // Delete the task even if the task is protected from deletion. // After calling this method, the user will still need to delete the // corresponding OsTask object to reclaim its storage. OsStatus OsTaskLinux::deleteForce(void) { OsLock lock(mDataGuard); doLinuxTerminateTask(TRUE); return OS_SUCCESS; } /* ============================ MANIPULATORS ============================== */ // Restart the task. // The task is first terminated, and then reinitialized with the same // name, priority, options, stack size, original entry point, and // parameters it had when it was terminated. // Return TRUE if the restart of the task is successful. UtlBoolean OsTaskLinux::restart(void) { OsLock lock(mDataGuard); doLinuxTerminateTask(FALSE); return doLinuxCreateTask(getName()); } // Resume the task. // This routine resumes the task. The task suspension is cleared, and // the task operates in the remaining state. OsStatus OsTaskLinux::resume(void) { OsLock lock(mDataGuard); if (!isStarted()) return OS_TASK_NOT_STARTED; if (mSuspendCnt < 1) // we're already running return OS_SUCCESS; if (--mSuspendCnt == 0) // predecrement to perform the test afterward pthread_kill(mTaskId, SIGCONT); return OS_SUCCESS; } // Spawn a new task and invoke its run() method. // Return TRUE if the spawning of the new task is successful. // Return FALSE if the task spawn fails or if the task has already // been started. UtlBoolean OsTaskLinux::start(void) { OsLock lock(mDataGuard); if (isStarted()) return FALSE; return doLinuxCreateTask(getName()); } // Suspend the task. // This routine suspends the task. Suspension is additive: thus, tasks // can be delayed and suspended, or pended and suspended. Suspended, // delayed tasks whose delays expire remain suspended. Likewise, // suspended, pended tasks that unblock remain suspended only. OsStatus OsTaskLinux::suspend(void) { OsLock lock(mDataGuard); if (!isStarted()) return OS_TASK_NOT_STARTED; if (mSuspendCnt++ == 0) // postincrement to perform the test beforehand pthread_kill(mTaskId, SIGSTOP); return OS_SUCCESS; } // Set the errno status for the task. OsStatus OsTaskLinux::setErrno(int errno) { if (!isStarted()) return OS_TASK_NOT_STARTED; return OS_SUCCESS; } // Set the execution options for the task // The only option that can be changed after a task has been created // is whether to allow breakpoint debugging. OsStatus OsTaskLinux::setOptions(int options) { return OS_NOT_YET_IMPLEMENTED; } // Set the priority of the task. // Priorities range from 0, the highest priority, to 255, the lowest priority. OsStatus OsTaskLinux::setPriority(int priority) { int linuxRes; int policy; struct sched_param param; OsLock lock(mDataGuard); if (!isStarted()) { mPriority = priority; // save mPriority for later use return OS_TASK_NOT_STARTED; } #ifdef ANDROID // [ int nice = OsUtilLinux::cvtOsPrioToLinuxPrio(priority); int res = setpriority(PRIO_PROCESS, 0, nice); OsSysLog::add(FAC_KERNEL, PRI_INFO, "OsTaskLinux::setPriority(%d): setpriority(%d) for thread %s returned %d", priority, nice, getName().data(), res); linuxRes = POSIX_OK; int rtPrio = OsUtilLinux::cvtOsPrioToLinuxRtPrio(priority); if (rtPrio > OsTaskLinux::RT_NO) { pthread_getschedparam(mTaskId, &policy, ¶m); param.sched_priority = rtPrio; linuxRes = pthread_setschedparam(mTaskId, SCHED_FIFO, ¶m); if (linuxRes == POSIX_OK) { OsSysLog::add(FAC_KERNEL, PRI_INFO, "OsTaskLinux::setPriority: setting RT priority %d for \"%s\"", rtPrio, mName.data()); } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsTaskLinux::setPriority: failed to set RT priority %d for task \"%s\"", rtPrio, mName.data()); } } #else // ANDROID ][ pthread_getschedparam(mTaskId, &policy, ¶m); param.sched_priority = OsUtilLinux::cvtOsPrioToLinuxPrio(priority); linuxRes = pthread_setschedparam(mTaskId, policy, ¶m); #endif // !ANDROID ] if (linuxRes == POSIX_OK) { mPriority = priority; return OS_SUCCESS; } return OS_INVALID_PRIORITY; } // Add a task variable to the task. // This routine adds a specified variable pVar (4-byte memory // location) to its task's context. After calling this routine, the // variable is private to the task. The task can access and modify // the variable, but the modifications are not visible to other tasks, // and other tasks' modifications to that variable do not affect the // value seen by the task. This is accomplished by saving and restoring // the variable's value each time a task switch occurs to or from the // calling task. OsStatus OsTaskLinux::varAdd(int* pVar) { if (!isStarted()) return OS_TASK_NOT_STARTED; return OS_NOT_YET_IMPLEMENTED; } // Remove a task variable from the task. // This routine removes a specified task variable, pVar, from its // task's context. The private value of that variable is lost. OsStatus OsTaskLinux::varDelete(int* pVar) { if (!isStarted()) return OS_TASK_NOT_STARTED; return OS_NOT_YET_IMPLEMENTED; } // Set the value of a private task variable. // This routine sets the private value of the task variable for a // specified task. The specified task is usually not the calling task, // which can set its private value by directly modifying the variable. // This routine is provided primarily for debugging purposes. OsStatus OsTaskLinux::varSet(int* pVar, int value) { if (!isStarted()) return OS_TASK_NOT_STARTED; return OS_NOT_YET_IMPLEMENTED; } // Delay a task from executing for the specified number of milliseconds. // This routine causes the calling task to relinquish the CPU for the // duration specified. This is commonly referred to as manual // rescheduling, but it is also useful when waiting for some external // condition that does not have an interrupt associated with it. OsStatus OsTaskLinux::delay(const int milliSecs) { #if defined(__APPLE__) || defined(ANDROID) struct timespec ts; ts.tv_nsec = (milliSecs % 1000) * 1000000; ts.tv_sec = milliSecs / 1000; // WARNING: This version of delay() is signal-unsafe. // An unmasked signal during sleep may cause to wake the thread. nanosleep(&ts, NULL); #else const clockid_t clock = CLOCK_REALTIME; struct timespec ts; int ret; assert(milliSecs >= 0); // negative delays don't make sense ret = clock_gettime(clock, &ts); if (ret != 0) return OS_FAILED; ts.tv_nsec += (milliSecs % 1000) * 1000000; ts.tv_sec += milliSecs / 1000; while (ts.tv_nsec > 1000000000) { ts.tv_nsec -= 1000000000; ts.tv_sec ++; } do { ret = clock_nanosleep(clock, TIMER_ABSTIME, &ts, NULL); if (ret != 0 && ret != EAGAIN && ret != EINTR && ret != ENOENT) { return OS_FAILED; } } while (ret != 0); #endif return OS_SUCCESS; } // Make the calling task safe from deletion. // This routine protects the calling task from deletion. Tasks that // attempt to delete a protected task will block until the task is // made unsafe, using unsafe(). When a task becomes unsafe, the // deleter will be unblocked and allowed to delete the task. // The safe() primitive utilizes a count to keep track of // nested calls for task protection. When nesting occurs, // the task becomes unsafe only after the outermost unsafe() // is executed. OsStatus OsTaskLinux::safe(void) { OsTask* pTask; OsStatus res; pTask = getCurrentTask(); res = pTask->mDeleteGuard.acquireRead(); assert(res == OS_SUCCESS); return res; } // Make the calling task unsafe from deletion. // This routine removes the calling task's protection from deletion. // Tasks that attempt to delete a protected task will block until the // task is unsafe. When a task becomes unsafe, the deleter will be // unblocked and allowed to delete the task. // The unsafe() primitive utilizes a count to keep track of nested // calls for task protection. When nesting occurs, the task becomes // unsafe only after the outermost unsafe() is executed. OsStatus OsTaskLinux::unsafe(void) { OsTask* pTask; OsStatus res; pTask = getCurrentTask(); res = pTask->mDeleteGuard.releaseRead(); assert(res == OS_SUCCESS); return res; } // Yield the CPU if a task of equal or higher priority is ready to run. void OsTaskLinux::yield(void) { delay(0); } /* ============================ ACCESSORS ================================= */ // Return a pointer to the OsTask object for the currently executing task // Return NULL if none exists. OsTaskLinux* OsTaskLinux::getCurrentTask(void) { return OsTaskLinux::getTaskById(pthread_self()); } // Convert a taskId into a UtlString void OsTaskLinux::getIdString_d(UtlString &dest, OsTaskId_t tid) { dest.appendFormat("%ld", tid); } // Convert a taskId into a UtlString void OsTaskLinux::getIdString_x(UtlString &dest, OsTaskId_t tid) { dest.appendFormat("%lx", tid); } // Convert a taskId into a UtlString void OsTaskLinux::getIdString_X(UtlString &dest, OsTaskId_t tid) { dest.appendFormat("%lX", tid); } // Return an Id of the currently executing task OsStatus OsTaskLinux::getCurrentTaskId(OsTaskId_t &rid) { rid = pthread_self(); return OS_SUCCESS; } // Return a pointer to the OsTask object corresponding to the named task // Return NULL if there is no task object with that name. OsTaskLinux* OsTaskLinux::getTaskByName(const UtlString& taskName) { OsStatus res; intptr_t val; res = OsUtil::lookupKeyValue(TASK_PREFIX, taskName, &val); assert(res == OS_SUCCESS || res == OS_NOT_FOUND); if (res == OS_SUCCESS) { assert(val != 0); return ((OsTaskLinux*) val); } else return NULL; } // Return a pointer to the OsTask object corresponding to taskId // Return NULL is there is no task object with that id. OsTaskLinux* OsTaskLinux::getTaskById(const pthread_t taskId) { UtlString idString; OsStatus res; intptr_t val; getIdString_d(idString, taskId); // convert the id to a string res = OsUtil::lookupKeyValue(TASKID_PREFIX, idString, &val); assert(res == OS_SUCCESS || res == OS_NOT_FOUND); if (res == OS_SUCCESS) { assert(val != 0); return ((OsTaskLinux*) val); } else return NULL; } // Get the errno status for the task // We do have per-thread errno's under Linux, but there's no way to // get them except from the thread itself. We could use a message to // the thread to report back its errno, but then we'd have to wait // for it to run and get the message. Solution: don't bother. OsStatus OsTaskLinux::getErrno(int& rErrno) { if (!isStarted()) return OS_TASK_NOT_STARTED; rErrno = 0; // no error return OS_SUCCESS; } // Return the execution options for the task int OsTaskLinux::getOptions(void) { return mOptions; } // Return the priority of the task OsStatus OsTaskLinux::getPriority(int& rPriority) { // int linuxRes; // int policy; // struct sched_param param; if (!isStarted()) return OS_TASK_NOT_STARTED; // linuxRes = pthread_getschedparam(mTaskId, &policy, ¶m); // assert(linuxRes == POSIX_OK); // rPriority = OsUtilLinux::cvtLinuxPrioToOsPrio(param.sched_priority); rPriority = mPriority; return OS_SUCCESS; } // Get the value of a task variable. // This routine returns the private value of a task variable for its // task. The task is usually not the calling task, which can get its // private value by directly accessing the variable. This routine is // provided primarily for debugging purposes. OsStatus OsTaskLinux::varGet(void) { if (!isStarted()) return OS_TASK_NOT_STARTED; return OS_NOT_YET_IMPLEMENTED; } /* ============================ INQUIRY =================================== */ // Get the task ID for this task OsStatus OsTaskLinux::id(OsTaskId_t &rId) { OsStatus retVal = OS_SUCCESS; //if started, return the taskId, otherwise return -1 if (isStarted()) rId = mTaskId; else { retVal = OS_TASK_NOT_STARTED; rId = -1; } return retVal; } // Check if the task is suspended. // Return TRUE is the task is suspended, otherwise FALSE. UtlBoolean OsTaskLinux::isSuspended(void) { OsLock lock(mDataGuard); if (!isStarted()) return FALSE; return mSuspendCnt > 0; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ // Do the real work associated with creating a new Linux task UtlBoolean OsTaskLinux::doLinuxCreateTask(const char* pTaskName) { int linuxRes; UtlString idString; pthread_attr_t attributes; timeval threadStartTime; timespec threadStartTimeout; // construct thread attribute linuxRes = pthread_attr_init(&attributes); if (linuxRes != POSIX_OK) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "doLinuxCreateTask: pthread_attr_init failed (%d) ", linuxRes); } // Set desired stack size. size_t stacksize = 0; linuxRes = pthread_attr_getstacksize(&attributes, &stacksize); if (linuxRes != POSIX_OK) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsTaskLinux:doLinuxCreateTask pthread_attr_getstacksize error, returned %d", linuxRes); } else { if (mStackSize < PTHREAD_STACK_MIN) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTaskLinux:doLinuxCreateTask %s increasing stack size from %d to allowed minimium %d", pTaskName, mStackSize, PTHREAD_STACK_MIN); mStackSize = PTHREAD_STACK_MIN; } OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTaskLinux:doLinuxCreateTask %s default stack size: %d setting to: %d", pTaskName, (int)stacksize, mStackSize); linuxRes = pthread_attr_setstacksize(&attributes, mStackSize); if (linuxRes != POSIX_OK) OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsTaskLinux:doLinuxCreateTask pthread_attr_setstacksize error, returned %d", linuxRes); } // Create threads detached linuxRes = pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED); if (linuxRes != POSIX_OK) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsTaskLinux:doLinuxCreateTask pthread_attr_setdetachstate error, returned %d", linuxRes); } // Create threads with given RT policy and given priority linuxRes = pthread_attr_setschedpolicy(&attributes, SCHED_FIFO); if (linuxRes != POSIX_OK) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsTaskLinux:doLinuxCreateTask pthread_attr_setschedpolicy error, returned %d", linuxRes); } { struct sched_param param; param.sched_priority = OsUtilLinux::cvtOsPrioToLinuxRtPrio(mPriority); linuxRes = pthread_attr_setschedparam(&attributes, ¶m); if (linuxRes != POSIX_OK) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsTaskLinux:doLinuxCreateTask pthread_attr_setschedparam error, returned %d", linuxRes); } } // Lock startup synchronization mutex. It will be used in conjunction with // mTaskInitializedEvent and mTaskStartedEvent conditional variables. pthread_mutex_lock(&mStartupSyncMutex); linuxRes = pthread_create(&mTaskId, &attributes, taskEntry, (void *)this); pthread_attr_destroy(&attributes); if (linuxRes != POSIX_OK) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsTaskLinux:doLinuxCreateTask " "pthread_create failed, returned %d in %s (%p)", linuxRes, mName.data(), this); // Unlock startup synchronization mutex. We do not need it more. pthread_mutex_unlock(&mStartupSyncMutex); return FALSE; } // Get current time and prepare thread startup timeout value. // Note that we need an absolute time. gettimeofday(&threadStartTime, NULL); threadStartTimeout.tv_sec = threadStartTime.tv_sec + OS_TASK_THREAD_STARTUP_TIMEOUT; // Timeval uses micro-seconds, while timespec uses nano-seconds. threadStartTimeout.tv_nsec = threadStartTime.tv_usec * 1000; // Wait for thread to startup. int pt_res = pthread_cond_timedwait(&mTaskStartedEvent, &mStartupSyncMutex, &threadStartTimeout); // If it will not startup in OS_TASK_THREAD_STARTUP_TIMEOUT seconds then // something gone terribly wrong. if (pt_res == ETIMEDOUT) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsTaskLinux:doLinuxCreateTask " "thread %s did not started up in %d seconds. Give up on it.", mName.data(), OS_TASK_THREAD_STARTUP_TIMEOUT); // Unlock startup synchronization mutex. We do not need it more. pthread_mutex_unlock(&mStartupSyncMutex); return FALSE; } // Enter the thread id into the global name database so that given the // thread id we will be able to find the corresponding OsTask object getIdString_d(idString, mTaskId); // convert the id to a string OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTaskLinux::doLinuxCreateTask, task ID: %ld/'%s'/0x%lX", mTaskId, idString.data(), mTaskId); OsUtil::insertKeyValue(TASKID_PREFIX, idString, (intptr_t) this); mState = STARTED; // Startup initialization finished. Signal this to started thread, so // it could go on. pthread_cond_signal(&mTaskInitializedEvent); // Unlock startup synchronization mutex. Synchronization finished. pthread_mutex_unlock(&mStartupSyncMutex); return TRUE; } // Do the real work associated with terminating a Linux task void OsTaskLinux::doLinuxTerminateTask(UtlBoolean doForce) { OsStatus res; pthread_t savedTaskId; OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTaskLinux::doLinuxTerminateTask, deleting task thread: %x," " force = %d", (int)mTaskId, doForce); // if there is no low-level task, or entry in the name database, just return if ((mState != UNINITIALIZED) && ((int)mTaskId != 0)) { // DEBUGGING HACK: Suspend requester if target is suspended $$$ while (isSuspended()) { suspend(); } if (!doForce) { // We are being well behaved and will wait until the task is no longer // safe from deletes. A task is made safe from deletes by acquiring // a read lock on its mDeleteGuard. In order to delete a task, the // application must acquire a write lock. This will only happen after // all of the read lock holders have released their locks. res = mDeleteGuard.acquireWrite(); assert(res == OS_SUCCESS); } savedTaskId = mTaskId; // taskUnregister sets mTaskId to zero; taskUnregister(); // Send the thread the actual cancellation request. if (mState == STARTED) { requestShutdown(); /* maybe replace this with a call to waitUntilShutDown() ? */ for(int i = 0; i < 10 && isShuttingDown(); i++) { delay(100); } } if (mState == SHUTTING_DOWN) { if (savedTaskId != 0) { pthread_cancel(savedTaskId); } } if (!doForce) { res = mDeleteGuard.releaseWrite(); // release the write lock assert(res == OS_SUCCESS); } } mState = UNINITIALIZED; } extern "C" {int setLinuxTaskStartSuspended(int susp);} extern "C" {int setVTSusp(int susp);} int linuxTaskStartSuspended = 0; int setLinuxTaskStartSuspended(int susp) { int save = linuxTaskStartSuspended; linuxTaskStartSuspended = susp; return save; } int setVTSusp(int susp) { return setLinuxTaskStartSuspended(susp); } // Function that serves as the starting address for a Linux thread void * OsTaskLinux::taskEntry(void* arg) { OsStatus res; int linuxRes; OsTaskLinux* pTask; pthread_attr_t attributes; struct sched_param param; pTask = (OsTaskLinux*) arg; // If we ever receive a thread cancel request, it means that the OsTask // object is in the process of being destroyed. To avoid the situation // where a thread attempts to run after its containing OsTask object has // been freed, we set the thread up so that the cancel takes effect // immediately (as opposed to waiting until the next thread cancellation // point). pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); if (linuxTaskStartSuspended) { pthread_kill(pthread_self(), SIGSTOP); } // construct thread attribute linuxRes = pthread_attr_init(&attributes); if (linuxRes != 0) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsTaskLinux::taskEntry: pthread_attr_init failed (%d) ", linuxRes); } // Lock synchronization mutex. Begin synchronization of started thread with // doLinuxCreateTask() which created it. pthread_mutex_lock(&pTask->mStartupSyncMutex); // Thread started up. Signal this to doLinuxCreateTask(). pthread_cond_signal(&pTask->mTaskStartedEvent); // Wait until our init in doLinuxCreateTask() is finished. // // The actual thread is created and started with pthread_create(), then // doLinuxCreateTask() enters the thread in the name database and // sets mState=STARTED. However, if OsTaskLinux::taskEntry() runs before // this initialization completes, callers might think (among other things) // that the thread is not started. pthread_cond_wait(&pTask->mTaskInitializedEvent, &pTask->mStartupSyncMutex); // Unlock startup synchronization mutex. Synchronization finished. pthread_mutex_unlock(&pTask->mStartupSyncMutex); // Log Thread ID for debug purposes OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTaskLinux::taskEntry: Started task %s with lwp=%d, pid=%d", pTask->mName.data(), gettid(), getpid()); #ifdef ANDROID // [ pTask->setPriority(pTask->mPriority); #else // ANDROID ][ int linuxPriority = OsUtilLinux::cvtOsPrioToLinuxPrio(pTask->mPriority); if(linuxPriority != RT_NO) { #ifndef __APPLE__ // Use FIFO realtime scheduling param.sched_priority = linuxPriority; linuxRes = sched_setscheduler(0, SCHED_FIFO, ¶m); if (linuxRes == POSIX_OK) { OsSysLog::add(FAC_KERNEL, PRI_INFO, "OsTaskLinux::taskEntry: starting %s at RT linux priority: %d", pTask->mName.data(), linuxPriority); } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsTaskLinux::taskEntry: failed to set RT linux priority: %d for task: %s", linuxPriority, pTask->mName.data()); } #else linuxRes = ~POSIX_OK; OsSysLog::add(FAC_KERNEL, PRI_INFO, "OsTaskLinux not starting at RT priority under MacOs") ; #endif // keep all memory locked into physical mem, to guarantee realtime-behaviour if (linuxRes == POSIX_OK) { linuxRes = mlockall(MCL_CURRENT|MCL_FUTURE); if (linuxRes != POSIX_OK) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsTaskLinux::taskEntry: failed to lock memory for task: %s", pTask->mName.data()); } } } #endif // !ANDROID ] // Run the code the task is supposed to run, namely the run() // method of its class. // Mark the task as not safe to delete. res = pTask->mDeleteGuard.acquireRead(); assert(res == OS_SUCCESS); unsigned int returnCode = pTask->run(pTask->getArg()); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTaskLinux::taskEntry run method exited with return: %d for task: %s", returnCode, pTask->mName.data()); // After run returns be sure to mark the thread as shut down. pTask->ackShutdown(); // Then remove it from the OsNameDb. pTask->taskUnregister(); // Mark the task as now safe to delete. res = pTask->mDeleteGuard.releaseRead(); assert(res == OS_SUCCESS); return ((void *)returnCode); } void OsTaskLinux::taskUnregister(void) { OsStatus res; UtlString idString; if ( 0 != (int)mTaskId ) { // Remove the key from the internal task list, before terminating it getIdString_d(idString, mTaskId); // convert the id to a string res = OsUtil::deleteKeyValue(TASKID_PREFIX, idString); } else { res = OS_SUCCESS; } if (res != OS_SUCCESS) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsTaskLinux::doLinuxTerminateTask, failed to delete" " mTaskId = 0x%08x, key '%s', returns %d", (int) mTaskId, idString.data(), res); } mTaskId = 0; assert(res == OS_SUCCESS || res == OS_NOT_FOUND); } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/OsUtilLinux.cpp0000644000175000017500000001332712205613256025177 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #include #include // APPLICATION INCLUDES #include "os/linux/OsUtilLinux.h" #include "os/OsDateTime.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const int NSECS_PER_SEC = 1000000000; const int NSECS_PER_USEC = 1000; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ // Convert an abstraction layer task priority to a Linux task priority int OsUtilLinux::cvtOsPrioToLinuxPrio(const int osPrio) { #ifdef ANDROID // [ // Under Android we generally don't have privileges to work with RT // priorities, so we should do our best with usual nice values. // So we map our priorities to [-16; 16] range of nice values. We don't // want to use nice values below -16, because system multimedia I/O // threads (ClientRecordThread and AudioTrackThread) work at that priority // and we should be below that. // 0 => -16 // 128 => 0 // 255 => 16 // return (osPrio*32)/255 - 16; #else // ANDROID ][ return cvtOsPrioToLinuxRtPrio(osPrio); #endif // !ANDROID ] } // Convert a Linux task priority to an abstraction layer task priority int OsUtilLinux::cvtLinuxPrioToOsPrio(const int linuxPrio) { #ifdef ANDROID // [ // Under Android we generally don't have privileges to work with RT // priorities, so we should do our best with usual nice values. // So we map our priorities to [-16; 16] range of nice values. We don't // want to use nice values below -16, because system multimedia I/O // threads (ClientRecordThread and AudioTrackThread) work at that priority // and we should be below that. // -16 => 0 // 0 => 128 // 16 => 255 int priority = (linuxPrio*255-16)/32 + 128; // Bound to [0; 255] priority = sipx_min(255, sipx_max(0, priority)); return priority; #else // ANDROID ][ int osPrio; // The mapping flips the priorities upside down, and scales them. // // The OS abstraction layer allows task priorities to range from 0 // to 255, where zero is the highest priority and 255 is the lowest. // Linux priorities range from 1 to 99 (for realtime processes) and // 1 is the lowest while 99 is the highest. //osPrio = 255 - (linuxPrio - 1) * 255 / 98; switch(linuxPrio) { case OsTaskLinux::RT_HIGHEST: osPrio = 0; break; case OsTaskLinux::RT_HIGH: osPrio = 5; break; case OsTaskLinux::RT_NORMAL: osPrio = 10; break; case OsTaskLinux::RT_LOW: osPrio = 100; break; default: osPrio = 128; break; } assert(osPrio >= 0 && osPrio <= 255); return osPrio; #endif // !ANDROID ] } // Convert an abstraction layer task priority to a Linux RT task priority int OsUtilLinux::cvtOsPrioToLinuxRtPrio(const int osPrio) { int linuxPrio = 100; // set out of bounds to catch osPrio errors // The mapping flips the priorities upside down, and scales them. // // The OS abstraction layer allows task priorities to range from 0 // to 255, where zero is the highest priority and 255 is the lowest. // Linux priorities range from 1 to 99 (for realtime processes) and // 1 is the lowest while 99 is the highest. //linuxPrio = (255 - osPrio) * 98 / 255 + 1; if(osPrio == 0) { linuxPrio = OsTaskLinux::RT_HIGHEST; } else if(osPrio >= 1 && osPrio <= 5) { linuxPrio = OsTaskLinux::RT_HIGH; } else if(osPrio >= 6 && osPrio <=10) { linuxPrio = OsTaskLinux::RT_NORMAL; } else if(osPrio >= 11 && osPrio <=100) { linuxPrio = OsTaskLinux::RT_LOW; } else if(osPrio >= 101 && osPrio <= 255) { linuxPrio = OsTaskLinux::RT_NO; } assert(linuxPrio >= 0 && linuxPrio <= 99); return linuxPrio; } // Convert an OsTime class relative to the current time to a struct // timespec relative to epoch void OsUtilLinux::cvtOsTimeToTimespec(OsTime time1, struct timespec * time2) { struct timeval now; time2->tv_sec = time1.seconds(); time2->tv_nsec = time1.usecs() * NSECS_PER_USEC; gettimeofday(&now, NULL); time2->tv_sec += now.tv_sec; time2->tv_nsec += now.tv_usec * NSECS_PER_USEC; if(time2->tv_nsec >= NSECS_PER_SEC) { time2->tv_nsec -= NSECS_PER_SEC; time2->tv_sec++; } } /** * This is a replacement for signal() which registers a signal handler but sets * a flag causing system calls ( namely read() or getchar() ) not to bail out * upon recepit of that signal. We need this behavior, so we must call * sigaction() manually. */ sighandler_t OsUtilLinux::signal(int signum, sighandler_t handler) { struct sigaction action[2]; action[0].sa_handler = handler; sigemptyset(&action[0].sa_mask); action[0].sa_flags = 0; sigaction(signum, &action[0], &action[1]); return action[1].sa_handler; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/pt_csem.c0000644000175000017500000000747212205613256024036 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// /* The default LinuxThreads implementation does not have support for timing * out while waiting for a synchronization object. Since I've already ported * the rest of the OS dependent files to that interface, we can just drop in a * mostly-compatible replacement written in C (like pthreads itself) that uses * the pthread_cond_timedwait function and a mutex to build all the other * synchronization objects with timeout capabilities. */ /* This is the counting semaphore implementation. Binary semaphores are just * counting semaphores with a maximum count of 1. (Incidentally, pthreads * doesn't support maximum counts either, but as long as I'm building the * semaphores myself I may as well include that to make life easier.) */ #include #include #include #include "os/linux/pt_csem.h" #ifndef SIPX_USE_NATIVE_PTHREADS // [ int pt_sem_init(pt_sem_t *sem, unsigned int max, unsigned int count) { if(!max) return -1; sem->count=count; sem->max=max; return pthread_mutex_init(&sem->mutex,NULL) | pthread_cond_init(&sem->cond,NULL); } int pt_sem_wait(pt_sem_t *sem) { int retval = 0 ; pthread_mutex_lock(&sem->mutex); // wait for sem->count to be not zero, or error while(retval == 0 && !sem->count) { retval = pthread_cond_wait(&sem->cond,&sem->mutex); } switch ( retval ) { case 0: // retval is 0 and sem->count is not, the sem is ours sem->count--; break ; default: // all error cases assert(0) ; // something is amiss, drop core /*NOTREACHED */ errno = retval ; retval = -1 ; } pthread_mutex_unlock(&sem->mutex); return retval; } int pt_sem_timedwait(pt_sem_t *sem,const struct timespec *timeout) { pthread_mutex_lock(&sem->mutex); int retval = 0; // wait for sem->count to be not zero, or error while (0 == retval && !sem->count) { retval = pthread_cond_timedwait(&sem->cond,&sem->mutex,timeout); } switch ( retval ) { case 0: // retval is 0 and sem->count is not, the sem is ours sem->count--; break ; case ETIMEDOUT: // timedout waiting for count to be not zero errno=EAGAIN; retval = -1; break ; default: // all error cases assert(0) ; // something is amiss /*NOTREACHED */ errno = retval ; retval = -1 ; } pthread_mutex_unlock(&sem->mutex); return retval; } int pt_sem_trywait(pt_sem_t *sem) { pthread_mutex_lock(&sem->mutex); if(sem->count) { sem->count--; pthread_mutex_unlock(&sem->mutex); return 0; } errno=EAGAIN; pthread_mutex_unlock(&sem->mutex); return -1; } int pt_sem_post(pt_sem_t *sem) { pthread_mutex_lock(&sem->mutex); if(sem->countmax) { sem->count++; pthread_cond_broadcast(&sem->cond); pthread_mutex_unlock(&sem->mutex); return 0; } errno=ERANGE; pthread_mutex_unlock(&sem->mutex); return -1; } int pt_sem_getvalue(pt_sem_t *sem) { return sem->count; } int pt_sem_destroy(pt_sem_t *sem) { return pthread_mutex_destroy(&sem->mutex) | pthread_cond_destroy(&sem->cond); } #endif // SIPX_USE_NATIVE_PTHREADS ] sipxtapi-3.3.0~test17/sipXportLib/src/os/linux/pt_mutex.c0000644000175000017500000001156412205613256024246 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// /* The default LinuxThreads implementation does not have support for timing * out while waiting for a synchronization object. Since I've already ported * the rest of the OS dependent files to that interface, we can just drop in a * mostly-compatible replacement written in C (like pthreads itself) that uses * the pthread_cond_timedwait function and a mutex to build all the other * synchronization objects with timeout capabilities. */ /* This is the mutex implementation. */ #include #include #include #include "os/linux/pt_mutex.h" #ifndef SIPX_USE_NATIVE_PTHREADS // [ void dumpPtMutex(pt_mutex_t* mutex) { int* chunk = (int*) &mutex->mutex; int i = 0; for(i = 0; i < sizeof(pthread_mutex_t) / 4; i++) { printf("mutex[%d]: %d\n", i, chunk[i]); } } int pt_mutex_init(pt_mutex_t *mutex) { mutex->count=0; int ret = 0; ret = pthread_mutex_init(&mutex->mutex,NULL); assert(ret == 0); if(ret) { printf("pt_mutex_init pthread_mutex_init returned: %d\n", ret); } ret = pthread_cond_init(&mutex->cond,NULL); assert(ret ==0); if(ret) { printf("pt_mutex_init pthread_cond_init returned: %d\n", ret); } return 0; } int pt_mutex_lock(pt_mutex_t *mutex) { int retval = 0 ; pthread_mutex_lock(&mutex->mutex); if( mutex->count && mutex->thread==pthread_self()) { mutex->count++; } else { // wait for count to be 0, or error while(retval == 0 && mutex->count) { retval = pthread_cond_wait(&mutex->cond,&mutex->mutex); } switch ( retval ) { case 0: // retval and count are 0, we now own the mutex mutex->count=1; mutex->thread=pthread_self(); break; default: // all error cases assert(0) ; // something is amiss /*NOTREACHED*/ errno = retval; retval = -1; break; } } pthread_mutex_unlock(&mutex->mutex); return retval; } int pt_mutex_timedlock(pt_mutex_t *mutex,const struct timespec *timeout) { int retval = 0 ; pthread_mutex_lock(&mutex->mutex); if(mutex->count && mutex->thread==pthread_self()) // allow recursive locks { mutex->count++; } else { // wait for count to be 0, or error while(0 == retval && mutex->count) { retval = pthread_cond_timedwait(&mutex->cond,&mutex->mutex,timeout); } switch ( retval ) { case 0: // retval and count are 0, we now own the mutex mutex->count=1; mutex->thread=pthread_self(); break; case ETIMEDOUT: // timed out waiting for count to be 0 errno=EAGAIN; retval = -1; break; default: // all error cases assert(0) ; // if something is amiss, drop core please. /*NOTREACHED*/ errno = retval; retval = -1; break; } } pthread_mutex_unlock(&mutex->mutex); return retval; } int pt_mutex_trylock(pt_mutex_t *mutex) { int retval = 0; int pthreadRet = pthread_mutex_lock(&mutex->mutex); if(pthreadRet) { printf("pt_mutex_trylock pthread_mutex_lock returned: %d\n", pthreadRet); } if(!mutex->count) { mutex->count=1; mutex->thread=pthread_self(); } else if(mutex->thread==pthread_self()) { mutex->count++; } else { errno=EAGAIN; retval = -1; } pthread_mutex_unlock(&mutex->mutex); return retval; } int pt_mutex_unlock(pt_mutex_t *mutex) { pthread_mutex_lock(&mutex->mutex); if(mutex->count) { mutex->count--; if(!mutex->count) { pthread_cond_broadcast(&mutex->cond); } } pthread_mutex_unlock(&mutex->mutex); return 0; } int pt_mutex_destroy(pt_mutex_t *mutex) { if(mutex->count) { errno=EBUSY; return -1; } assert(0 == (pthread_mutex_destroy(&mutex->mutex) | pthread_cond_destroy(&mutex->cond))); return 0; } #endif // SIPX_USE_NATIVE_PTHREADS ] sipxtapi-3.3.0~test17/sipXportLib/src/os/shared/0000755000175000017500000000000012321445024022330 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/src/os/shared/OsMsgQShared.cpp0000644000175000017500000002726712205613256025357 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsLock.h" #include "os/shared/OsMsgQShared.h" #include "os/OsDateTime.h" #include "os/OsSysLog.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor // If the name is specified but is already in use, throw an exception OsMsgQShared::OsMsgQShared(const int maxMsgs, const int maxMsgLen, const int options, const UtlString& name) : OsMsgQBase(name) , mGuard(OsMutex::Q_PRIORITY + OsMutex::INVERSION_SAFE + OsMutex::DELETE_SAFE) , mEmpty(OsCSem::Q_PRIORITY, maxMsgs, maxMsgs) , mFull(OsCSem::Q_PRIORITY, maxMsgs, 0) , mDlist() #ifdef MSGQ_IS_VALID_CHECK , mOptions(options) , mHighCnt(0) #endif { mMaxMsgs = maxMsgs; #ifdef OS_MSGQ_REPORTING mIncrementLevel = mMaxMsgs / 20; if (mIncrementLevel < 1) mIncrementLevel = 1; mIncreaseLevel = mIncrementLevel; mDecreaseLevel = 0; #endif #ifdef MSGQ_IS_VALID_CHECK /* [ */ OsStatus ret = mGuard.acquire(); // start critical section assert(ret == OS_SUCCESS); mNumInsertEntry = 0; mNumInsertExitOk = 0; mNumInsertExitFail = 0; mNumRemoveEntry = 0; mNumRemoveExitOk = 0; mNumRemoveExitFail = 0; mLastSuccessTest = 0; ret = mGuard.release(); // exit critical section assert(ret == OS_SUCCESS); #endif /* MSGQ_IS_VALID_CHECK ] */ } // Destructor OsMsgQShared::~OsMsgQShared() { if (numMsgs()) flush(); // get rid of any messages in the queue } /* ============================ MANIPULATORS ============================== */ OsStatus OsMsgQShared::send(const OsMsg& rMsg, const OsTime& rTimeout) { return doSend(rMsg, rTimeout, FALSE, TRUE); } OsStatus OsMsgQShared::sendNoCopy(OsMsg *pMsg, const OsTime& rTimeout) { return doSend(*pMsg, rTimeout, FALSE, FALSE); } OsStatus OsMsgQShared::sendUrgent(const OsMsg& rMsg, const OsTime& rTimeout) { return doSend(rMsg, rTimeout, TRUE, TRUE); } OsStatus OsMsgQShared::sendFromISR(OsMsg& rMsg) { // set a flag in the msg to indicate if the message was sent // from an ISR rMsg.setSentFromISR(TRUE); return doSend(rMsg, OsTime::NO_WAIT_TIME, FALSE, FALSE); } // Remove a message from the head of the queue // Wait until either a message arrives or the timeout expires. // The receiver is responsible for freeing the received message. // Other than for messages sent from an ISR, the receiver is responsible // for freeing the received message. OsStatus OsMsgQShared::receive(OsMsg*& rpMsg, const OsTime& rTimeout) { return doReceive(rpMsg, rTimeout); } /* ============================ ACCESSORS ================================= */ // Return the number of messages in the queue int OsMsgQShared::numMsgs(void) { OsLock lock(mGuard); return(mDlist.entries()); } // Print information on the message queue to the console // Output enabled via a compile-time #ifdef #ifdef MSGQ_IS_VALID_CHECK void OsMsgQShared::show(void) { osPrintf("* OsMsgQShared: OsMsgQ=0x%p, options=%d, limitMsgs=%d, maxMsgs=%d, numMsgs=%d\n", (void *) this, mOptions, mMaxMsgs, mHighCnt, numMsgs()); osPrintf("* OsMsgQShared: mEmpty counting semaphore information\n"); mEmpty.OsCSemShow(); osPrintf("* OsMsgQShared: mFull counting semaphore information\n"); mFull.OsCSemShow(); } #endif /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ OsStatus OsMsgQShared::doSend(const OsMsg& rMsg, const OsTime& rTimeout, const UtlBoolean isUrgent, const UtlBoolean needCopy) { OsStatus ret; OsMsg* pMsg; const void* insResult; #ifdef MSGQ_IS_VALID_CHECK /* [ */ int msgCnt; ret = mGuard.acquire(); // start critical section assert(ret == OS_SUCCESS); testMessageQ(); mNumInsertEntry++; ret = mGuard.release(); // exit critical section assert(ret == OS_SUCCESS); #endif /* MSGQ_IS_VALID_CHECK ] */ if (mSendHookFunc != NULL) { if (mSendHookFunc(rMsg)) { // by returning TRUE, the mSendHookFunc indicates that it has handled // the message and there is no need to queue the message. #ifdef MSGQ_IS_VALID_CHECK /* [ */ OsStatus rc = mGuard.acquire(); // start critical section assert(rc == OS_SUCCESS); mNumInsertExitOk++; testMessageQ(); rc = mGuard.release(); // exit critical section assert(rc == OS_SUCCESS); #endif /* MSGQ_IS_VALID_CHECK ] */ return OS_SUCCESS; } } ret = mEmpty.acquire(rTimeout); // wait for there to be room in the queue if (ret != OS_SUCCESS) { // The caller should be responsible for logging this information /*OsSysLog::add(FAC_KERNEL, PRI_CRIT, "OsMsgQShared::doSend message send failed - no room, ret = %d", ret);*/ if (ret == OS_BUSY || ret == OS_WAIT_TIMEOUT) ret = OS_WAIT_TIMEOUT; // send timed out } else { if (!needCopy || rMsg.isMsgReusable()) { // If the message is sent from an ISR we cannot make a copy // (no allocation allowed), so in that case we just use the message. // If the message is marked as reusable, it's safe to use the // message without copying it. // Just go ahead and use the message without copying it. pMsg = (OsMsg*) &rMsg; } else { // we place a copy of the message on the queue // so that the caller is free to destroy the original pMsg = rMsg.createCopy(); } // start critical section ret = mGuard.acquire(); assert(ret == OS_SUCCESS); if (isUrgent) { // If the message is urgent, insert it at the queue head insResult = mDlist.insertAt(0, pMsg); } else { // If the message is not urgent, insert it at the queue tail insResult = mDlist.insert(pMsg); } #ifdef MSGQ_IS_VALID_CHECK msgCnt = mDlist.entries(); if (msgCnt > mHighCnt) { mHighCnt = msgCnt; } #endif if (insResult == NULL) { // queue insertion failed OsSysLog::add(FAC_KERNEL, PRI_CRIT, "OsMsgQShared::doSend message send failed - insert failed"); if (needCopy && !rMsg.isMsgReusable()) { // destroy the msg copy we made earlier delete pMsg; } assert(FALSE); ret = OS_UNSPECIFIED; } else { // signal receivers that a msg is available ret = mFull.release(); assert(ret == OS_SUCCESS); } #ifdef OS_MSGQ_REPORTING int curCount; UtlBoolean increasedLevel = FALSE; UtlBoolean decreasedLevel = FALSE; curCount = mDlist.entries(); if (curCount >= mIncreaseLevel) { increasedLevel = TRUE; while (curCount >= mIncreaseLevel) { mIncreaseLevel += mIncrementLevel; } mDecreaseLevel = mIncreaseLevel - (2 * mIncrementLevel); } if (curCount <= mDecreaseLevel) { decreasedLevel = TRUE; while (curCount <= mDecreaseLevel) { mDecreaseLevel = mDecreaseLevel - mIncrementLevel; } mIncreaseLevel = mDecreaseLevel + (2 * mIncrementLevel); } #endif OsStatus guardRet = mGuard.release(); // exit critical section assert(guardRet == OS_SUCCESS); #ifdef OS_MSGQ_REPORTING if (increasedLevel) { OsSysLogPriority pri = PRI_INFO; if (curCount == mMaxMsgs) pri = PRI_WARNING; OsSysLog::add(FAC_KERNEL, pri, "Message queue 0x%x increased to %d msgs (max=%d)\n", (int) this, curCount, mMaxMsgs); } else if (decreasedLevel) { OsSysLog::add(FAC_KERNEL, PRI_INFO, "Message queue 0x%x decreased to %d msgs (max=%d)\n", (int) this, curCount, mMaxMsgs); } #endif } #ifdef MSGQ_IS_VALID_CHECK /* [ */ OsStatus rc = mGuard.acquire(); // start critical section assert(rc == OS_SUCCESS); if (ret == OS_SUCCESS) mNumInsertExitOk++; else mNumInsertExitFail++; testMessageQ(); rc = mGuard.release(); // exit critical section assert(rc == OS_SUCCESS); #endif /* MSGQ_IS_VALID_CHECK ] */ return ret; } // Helper function for removing a message from the head of the queue OsStatus OsMsgQShared::doReceive(OsMsg*& rpMsg, const OsTime& rTimeout) { OsStatus ret; rpMsg = NULL; #ifdef MSGQ_IS_VALID_CHECK /* [ */ ret = mGuard.acquire(); // start critical section assert(ret == OS_SUCCESS); testMessageQ(); mNumRemoveEntry++; ret = mGuard.release(); // exit critical section assert(ret == OS_SUCCESS); #endif /* MSGQ_IS_VALID_CHECK ] */ ret = mFull.acquire(rTimeout); // wait for a message to be available if (ret != OS_SUCCESS) { if (ret == OS_BUSY || ret == OS_WAIT_TIMEOUT) ret = OS_WAIT_TIMEOUT; // receive timed out else { assert(FALSE); ret = OS_UNSPECIFIED; } } else { ret = mGuard.acquire(); // start critical section assert(ret == OS_SUCCESS); assert(numMsgs() > 0); rpMsg = (OsMsg*) mDlist.get(); // get the first message if (rpMsg == NULL) // was there a message? { assert(FALSE); ret = OS_UNSPECIFIED; } else { ret = mEmpty.release(); // the remove operation succeeded, signal assert(ret == OS_SUCCESS); // senders that there is an available // message slot. } (void)mGuard.release(); // exit critical section } #ifdef MSGQ_IS_VALID_CHECK /* [ */ OsStatus rc = mGuard.acquire(); // start critical section assert(rc == OS_SUCCESS); if (ret == OS_SUCCESS) mNumRemoveExitOk++; else mNumRemoveExitFail++; testMessageQ(); rc = mGuard.release(); // exit critical section assert(rc == OS_SUCCESS); #endif /* MSGQ_IS_VALID_CHECK ] */ return ret; } #if defined(MSGQ_IS_VALID_CHECK) && defined(OS_CSEM_DEBUG) /* [ */ // Test for message queue integrity void OsMsgQShared::testMessageQ() { if ( (mNumInsertEntry - mNumInsertExitOk - mNumInsertExitFail == 0) && (mNumRemoveEntry - mNumRemoveExitOk - mNumRemoveExitFail == 0)) { unsigned int numMsgs = mDlist.entries(); assert(numMsgs == mNumInsertExitOk - mNumRemoveExitOk); assert(mEmpty.getValue() == mMaxMsgs - numMsgs); assert(mFull.getValue() == numMsgs); mLastSuccessTest = 0; } else { mLastSuccessTest++; } } #endif /* defined(MSGQ_IS_VALID_CHECK) && defined(OS_CSEM_DEBUG) ] */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/shared/OsTimerMessage.cpp0000644000175000017500000000563012205613256025734 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/shared/OsTimerMessage.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructors OsTimerMessage::OsTimerMessage(OsTimer* pTimer, OsBSem* pSem) : OsMsg(OsMsg::OS_TIMER, ADD), mID(-1), mpTimer(pTimer), mpSynchSem(pSem) { } OsTimerMessage::OsTimerMessage(int ID, OsBSem* pSem) : OsMsg(OsMsg::OS_TIMER, REMOVE), mID(ID), mpTimer(NULL), mpSynchSem(pSem) { } OsTimerMessage::OsTimerMessage(OsBSem* pSem) : OsMsg(OsMsg::OS_TIMER, SHUTDOWN), mID(-1), mpTimer(NULL), mpSynchSem(pSem) { } // Copy constructor OsTimerMessage::OsTimerMessage(const OsTimerMessage& rOsTimerMessage) : OsMsg(rOsTimerMessage) { mID = rOsTimerMessage.mID; mpTimer = rOsTimerMessage.mpTimer; mpSynchSem = rOsTimerMessage.mpSynchSem; } // Create a copy of this msg object (which may be of a derived type) OsMsg* OsTimerMessage::createCopy(void) const { return new OsTimerMessage(*this); } // Destructor OsTimerMessage::~OsTimerMessage() { // no work required } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsTimerMessage& OsTimerMessage::operator=(const OsTimerMessage& rhs) { if (this == &rhs) // handle the assignment to self case return *this; OsMsg::operator=(rhs); // assign fields for parent class mID = rhs.mID; mpTimer = rhs.mpTimer; mpSynchSem = rhs.mpSynchSem; return *this; } /* ============================ ACCESSORS ================================= */ // Return the size of the message in bytes. // This is a virtual method so that it will return the accurate size for // the message object even if that object has been upcast to the type of // an ancestor class. int OsTimerMessage::getMsgSize(void) const { return sizeof(*this); } // Get the timer ID int OsTimerMessage::getTimerID(void) { return mID; } // Get the OsTimer OsTimer* OsTimerMessage::getTimer(void) { return mpTimer; } // Get the synchronization semaphore OsBSem* OsTimerMessage::getSynchSem(void) { return mpSynchSem; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/0000755000175000017500000000000012321445024021632 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/getWindowsDNSServers.cpp0000644000175000017500000004627012205613256026425 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifdef WIN32 // SYSTEM INCLUDES #define WIN32_LEAN_AND_MEAN #include #include #include #include // APPLICATION INCLUDES #include #include #include // DEFINES #define MAXNUM_DNS_ENTRIES 40 //used by getWindowsVersion #define WINDOWS_VERSION_ERROR 0 #define WINDOWS_VERSION_98 1 #define WINDOWS_VERSION_NT4 2 #define WINDOWS_VERSION_2000 3 // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS // GLOBALS static DWORD (WINAPI *GetNetworkParams)(PFIXED_INFO, PULONG); static DWORD (WINAPI *GetAdaptersInfo)( PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen ); static DWORD (WINAPI *GetPerAdapterInfo)( ULONG IfIndex, PIP_PER_ADAPTER_INFO pPerAdapterInfo, PULONG pOutBufLen ); static DWORD (WINAPI *GetAdapterIndex)( LPWSTR AdapterName, PULONG IfIndex ); static DWORD (WINAPI *GetInterfaceInfo)( PIP_INTERFACE_INFO pIfTable, PULONG dwOutBufLen ); static HMODULE hIpHelperModule = NULL; //retrieves the current windows version and returns //one of the WINDOWS_VERSION definitions. static int getWindowsVersion() { OSVERSIONINFO osInfo; int retVal = WINDOWS_VERSION_ERROR; //try to figure out what version of windows we are running osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (GetVersionEx(&osInfo)) { //check if it's the right version of windows if (osInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) { if (osInfo.dwMinorVersion > 0) //true if it is 98 retVal = WINDOWS_VERSION_98; } else if (osInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) { if (osInfo.dwMajorVersion == 4) { retVal = WINDOWS_VERSION_NT4; } else if (osInfo.dwMajorVersion > 4) { retVal = WINDOWS_VERSION_2000; } } } return retVal; } //loads the iphlpapi.dll and sets any func pointers we may need static HMODULE loadIPHelperAPI() { char caFullDLLPath[_MAX_PATH]; if (hIpHelperModule == NULL) { //first try loading it using the systems path hIpHelperModule = LoadLibrary("iphlpapi.dll"); if (!hIpHelperModule) { //if that fails, (it shouldn't), try using the GetSystemPath func GetSystemDirectory(caFullDLLPath,sizeof(caFullDLLPath)); strcat(caFullDLLPath,"\\iphlpapi.dll"); //try again hIpHelperModule = LoadLibrary(caFullDLLPath); } //ok, I give up...where the heck did they put the iphlpapi.dll??????? if (!hIpHelperModule) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "Cannot find iphlpapi.dll!\n"); } else { //now find IPHelper functions int windowsVersion = getWindowsVersion(); if (windowsVersion >= WINDOWS_VERSION_2000) { *(FARPROC*)&GetPerAdapterInfo = GetProcAddress(hIpHelperModule,"GetPerAdapterInfo"); if (GetPerAdapterInfo == NULL) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "Could not get the proc address to GetPerAdapterInfo!\n"); FreeLibrary(hIpHelperModule); hIpHelperModule = NULL; } } else { *(FARPROC*)&GetNetworkParams = GetProcAddress(hIpHelperModule,"GetNetworkParams"); if (GetNetworkParams == NULL) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "Could not get the proc address to GetNetworkParams!\n"); FreeLibrary(hIpHelperModule); hIpHelperModule = NULL; } } *(FARPROC*)&GetInterfaceInfo = GetProcAddress(hIpHelperModule,"GetInterfaceInfo"); if (GetInterfaceInfo == NULL) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "Could not get the proc address to GetInterfaceInfo!\n"); FreeLibrary(hIpHelperModule); hIpHelperModule = NULL; } *(FARPROC*)&GetAdapterIndex = GetProcAddress(hIpHelperModule,"GetAdapterIndex"); if (GetAdapterIndex == NULL) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "Could not get the proc address to GetAdapterIndex!\n"); FreeLibrary(hIpHelperModule); hIpHelperModule = NULL; } *(FARPROC*)&GetAdaptersInfo = GetProcAddress(hIpHelperModule,"GetAdaptersInfo"); if (GetAdaptersInfo == NULL) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "Could not get the proc address to GetAdaptersInfo!\n"); FreeLibrary(hIpHelperModule); hIpHelperModule = NULL; } } } return hIpHelperModule; } static int getIPHelperDNSEntries(char DNSServers[][MAXIPLEN], int max, const char* szLocalIp) { int ipHelperDNSServerCount = 0; int windowsVersion = getWindowsVersion(); if (windowsVersion != WINDOWS_VERSION_98 && windowsVersion < WINDOWS_VERSION_2000) { // iphlpapi.dll not supported return ipHelperDNSServerCount; } HMODULE hModule = loadIPHelperAPI(); if (!hModule) { // unabled to load iphlpapi.dll return ipHelperDNSServerCount; } if (windowsVersion >= WINDOWS_VERSION_2000 && GetAdaptersInfo && GetPerAdapterInfo) { // Get list of adapters and find the index of the one associated with szLocalIp long index = -1; unsigned long outBufLen = 0; DWORD dwResult = GetAdaptersInfo(NULL, &outBufLen); if (outBufLen) { PIP_ADAPTER_INFO pIpAdapterInfo = (PIP_ADAPTER_INFO)malloc(outBufLen); dwResult = GetAdaptersInfo(pIpAdapterInfo, &outBufLen); if (ERROR_SUCCESS == dwResult) { PIP_ADAPTER_INFO pNextInfoRecord = pIpAdapterInfo; while (pNextInfoRecord && index < 0) { PIP_ADDR_STRING pIpAddrString = &(pNextInfoRecord->IpAddressList); while (pIpAddrString) { if (strcmp (szLocalIp, pIpAddrString->IpAddress.String) == 0) { index = static_cast(pNextInfoRecord->Index); break; } pIpAddrString = pIpAddrString->Next; } pNextInfoRecord = pNextInfoRecord->Next; } } free(pIpAdapterInfo); } if (index >= 0) { // now that we have the index, we // can call GetPerAdapterInfo outBufLen = 0; GetPerAdapterInfo(index, NULL, &outBufLen); if (outBufLen) { IP_PER_ADAPTER_INFO* pPerAdapterInfo = (IP_PER_ADAPTER_INFO*) malloc(outBufLen); dwResult = GetPerAdapterInfo(index, pPerAdapterInfo, &outBufLen); if (ERROR_SUCCESS == dwResult) { IP_ADDR_STRING* pDns = &pPerAdapterInfo->DnsServerList; while (pDns && ipHelperDNSServerCount < max) { strcpy(DNSServers[ipHelperDNSServerCount++], pDns->IpAddress.String); pDns = pDns->Next; } } free(pPerAdapterInfo); } } } else if (GetNetworkParams) { // use GetNetworkParams //force size to 0 so the GetNetworkParams gets the correct size DWORD dwNetworkInfoSize = 0; DWORD retErr = GetNetworkParams( NULL, &dwNetworkInfoSize ); if( retErr == ERROR_BUFFER_OVERFLOW ) { // Allocate memory from sizing information PFIXED_INFO pNetworkInfo; if( ( pNetworkInfo = (PFIXED_INFO)GlobalAlloc( GPTR, dwNetworkInfoSize ) ) != NULL ) { // Get actual network params if( ( retErr = GetNetworkParams( pNetworkInfo, &dwNetworkInfoSize ) ) == 0 ) { //point to the server list PIP_ADDR_STRING pAddrStr = &(pNetworkInfo->DnsServerList); // first, add the 'current dns' if (pNetworkInfo && pNetworkInfo->CurrentDnsServer) { strcpy(DNSServers[ipHelperDNSServerCount++], pNetworkInfo->CurrentDnsServer->IpAddress.String); } //walk the list of IP addresses while( pAddrStr && ipHelperDNSServerCount < max ) { //copy one of the ip addresses strcpy(DNSServers[ipHelperDNSServerCount++],pAddrStr->IpAddress.String); pAddrStr = pAddrStr->Next; } //free the memory GlobalFree(pNetworkInfo); // handle to global memory object } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "DNS ERROR: GetNetworkParams failed with error %d\n", retErr ); GlobalFree(pNetworkInfo); // handle to global memory object } } } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "DNS ERROR: Memory allocation error\n" ); } } return ipHelperDNSServerCount; } static int getDNSEntriesFromRegistry(char regDNSServers[][MAXIPLEN], int max) { int retRegDNSServerCount = 0; const char *strParametersKey = "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters"; const char *strDhcpNameServerValue = "DhcpNameServer"; const char *strNameServerValue = "NameServer"; char *token; //used for parsing the ip addresses HKEY hKey; BYTE data[255]; DWORD cbData; DWORD dataType; char *ptr = NULL; //pointer to ip addresses when parsing DWORD err; err = RegOpenKeyEx( HKEY_LOCAL_MACHINE, // handle to open key strParametersKey, // subkey name 0, // reserved KEY_READ, // security access mask &hKey // handle to open key ); if (err == ERROR_SUCCESS) { cbData = sizeof(data); err = RegQueryValueEx( hKey, // handle to key strDhcpNameServerValue, // value name 0, // reserved &dataType, // type buffer data, // data buffer &cbData); // size of data buffer if (err != ERROR_SUCCESS) { //try a different value err = RegQueryValueEx( hKey, // handle to key strNameServerValue, // value name 0, // reserved &dataType, // type buffer data, // data buffer &cbData); // size of data buffer } if (err == ERROR_SUCCESS) { //we need to break it up on NT. It puts all the IP's on one line. //it may not be a space, which I set as default, ...lets check for a ',' if (strstr((char *)data,",")) token = ","; else token = " "; //find the first token ptr = strtok((char *)data,token); while (ptr != NULL && retRegDNSServerCount < max) { strncpy(regDNSServers[retRegDNSServerCount++],ptr,MAXIPLEN); //search for the next one ptr = strtok(NULL,token); } } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "Error reading values from registry in func: getDNSEntriesFromRegistry\n"); } RegCloseKey(hKey); } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "Error opening registry in func: getDNSEntriesFromRegistry\n"); } return retRegDNSServerCount; } extern "C" int getWindowsDNSServers(char DNSServers[][MAXIPLEN], int max, const char* szLocalIp) { int finalDNSServerCount = 0; //number of dns entries returned to user int ipHelperDNSServerCount = 0; //number of dns entries found through ipHelperAPI int regDNSServerCount = 0; //num entries found in registry char regDNSServers[MAXNUM_DNS_ENTRIES][MAXIPLEN]; //used to store registry DNS entries int i; // int j; //general purpose looping variables int swapPos = 0; //location to move the DNS entries that match the registry //retrieve the DNS entries from a MS provided DLL //This func will also load the dll if on win98 or NT 2000 ipHelperDNSServerCount = getIPHelperDNSEntries(DNSServers,max,szLocalIp); finalDNSServerCount = ipHelperDNSServerCount; //We always search the registry now... //Before we only did it for NT, but because //we want the most recently used entries at the top, we will consult //the registry and use the list retrieved and sort it. regDNSServerCount = getDNSEntriesFromRegistry(regDNSServers,max); // Because we now support multiple interfaces, we cannot use the following code: // (registry could contain DNS servers that are not associated with our // current interface) /* //now walk through the entries found through the registry //and make sure the registry entries are at the top //NOTE: We do this because windows seem to be hanging on to old entries. // This is causing really bad timeouts when doing a DNS search. // If you use the registry, we should be getting the newest entries // and moving those to the top of the DNS list if (ipHelperDNSServerCount && regDNSServerCount) { for (i = 0; i < ipHelperDNSServerCount;i++) { for (j = 0; j < regDNSServerCount;j++) { if (strcmp(DNSServers[i],regDNSServers[j]) == 0 && i != j) { char tmpdns[MAXIPLEN]; //save off the original strcpy(tmpdns,DNSServers[swapPos]); //copy the zero index entry to the that location strcpy(DNSServers[swapPos],DNSServers[i]); //copy the saved to the old location strcpy(DNSServers[i],tmpdns); swapPos++; } } } } */ //if we only found reg entries and no ipHelper entries , then we need to return those //to the user (The ones from the registry) if (regDNSServerCount && !ipHelperDNSServerCount) { finalDNSServerCount = regDNSServerCount; //copy to final list for (i = 0; i < finalDNSServerCount; i++) strcpy(DNSServers[i],regDNSServers[i]); } //return the number of DNS entries found return finalDNSServerCount; } bool getContactAdapterName(UtlString &adapterName, const UtlString &ipAddress, bool trueName) { bool rc = false; if (ipAddress == "127.0.0.1") { rc = true; adapterName = "loopback"; return rc; } else if (loadIPHelperAPI()) { unsigned long outBufLen = 0; DWORD dwResult = GetAdaptersInfo(NULL, &outBufLen); PIP_ADAPTER_INFO pIpAdapterInfo = (PIP_ADAPTER_INFO)malloc(outBufLen); dwResult = GetAdaptersInfo(pIpAdapterInfo, &outBufLen); if (ERROR_SUCCESS == dwResult) { rc = true; PIP_ADAPTER_INFO pNextInfoRecord = pIpAdapterInfo; unsigned int adapterId = 0; char szAdapterId[MAX_ADAPTER_NAME_LENGTH + 4]; bool bFound = false; while (pNextInfoRecord && !bFound) { sprintf(szAdapterId, "eth%u", adapterId); PIP_ADDR_STRING pNextAddress = &(pNextInfoRecord->IpAddressList); while (pNextAddress) { const char *szAddr = pNextAddress->IpAddress.String; // if the target matches this address or if the target is any if (ipAddress == szAddr || ipAddress == "0.0.0.0") { if (trueName) { adapterName = pNextInfoRecord->AdapterName; } else { adapterName = szAdapterId; } bFound = true; break; } pNextAddress = pNextAddress->Next; } adapterId++; pNextInfoRecord = pNextInfoRecord->Next; } } free((void*)pIpAdapterInfo); } return rc; } bool getAllLocalHostIps(const HostAdapterAddress* localHostAddresses[], int &numAddresses) { bool rc = false; if (loadIPHelperAPI()) { PIP_ADAPTER_INFO pIpAdapterInfo = (PIP_ADAPTER_INFO)malloc(sizeof(IP_ADAPTER_INFO) * MAX_IP_ADDRESSES); unsigned long outBufLen = sizeof(IP_ADAPTER_INFO) * MAX_IP_ADDRESSES; DWORD dwResult = GetAdaptersInfo(pIpAdapterInfo, &outBufLen); if (ERROR_SUCCESS == dwResult) { int maxAddresses = numAddresses; rc = true; numAddresses = 0; PIP_ADAPTER_INFO pNextInfoRecord = pIpAdapterInfo; unsigned int adapterId = 0; char szAdapterId[MAX_IP_ADDRESSES]; while (pNextInfoRecord && (numAddressesIpAddressList; while (pNextAddress && (numAddressesIpAddress.String; // ignore the loopback address if ( strncmp(szAddr, "127.0.0.1", 9) != 0 && strncmp(szAddr, "169.154", 7) != 0 && strncmp(szAddr, "0.", 2) != 0 ) { localHostAddresses[numAddresses] = new HostAdapterAddress(szAdapterId, szAddr); numAddresses++; } pNextAddress = pNextAddress->Next; } adapterId++; pNextInfoRecord = pNextInfoRecord->Next; } } free((void*)pIpAdapterInfo); } return rc; } #endif sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/OsBSemWnt.cpp0000644000175000017500000001113712205613256024167 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #ifndef WINCE # include #endif #include "utl/UtlRscTrace.h" // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlString.h" #include "os/OsDefs.h" #include "os/OsTask.h" #include "os/Wnt/OsBSemWnt.h" #include "os/Wnt/OsUtilWnt.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsBSemWnt::OsBSemWnt(const int queueOptions, const int initState) { mOptions = queueOptions; // Under Windows NT, we ignore the queueOptions argument // no security attributes // initial count is determined by the initState parameter // maximum count is 1 (since this is a binary semaphore) // no name for this semaphore object mSemImp = CreateSemaphore(NULL, initState, 1, NULL); #ifdef OS_SYNC_DEBUG mTaskId = (initState == EMPTY) ? GetCurrentThreadId() : 0; mLastId = 0; #endif } // Destructor OsBSemWnt::~OsBSemWnt() { UtlBoolean res; res = CloseHandle(mSemImp); mSemImp = NULL; mOptions = 0; assert(res == TRUE); // CloseHandle should always return TRUE } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ // Block the task until the semaphore is acquired or the timeout expires OsStatus OsBSemWnt::acquire(const OsTime& rTimeout) { OsStatus retVal; retVal = OsUtilWnt::synchObjAcquire(mSemImp, rTimeout); #ifdef OS_SYNC_DEBUG if (retVal == OS_SUCCESS) { mTaskId = GetCurrentThreadId(); } #endif return retVal; } // Conditionally acquire the semaphore (i.e., don't block) // Return OS_BUSY if the semaphore is held by some other task OsStatus OsBSemWnt::tryAcquire(void) { OsStatus retVal; retVal = OsUtilWnt::synchObjTryAcquire(mSemImp); #ifdef OS_SYNC_DEBUG if (retVal == OS_SUCCESS) { mTaskId = GetCurrentThreadId(); } #endif return retVal; } // Release the semaphore OsStatus OsBSemWnt::release(void) { OsStatus ret = OS_SUCCESS; if (mSemImp == NULL) { ret = OS_TASK_NOT_STARTED; } else { # ifdef OS_SYNC_DEBUG // make this change while holding the lock int previousLast = mLastId; mLastId = GetCurrentThreadId(); mTaskId = 0; # endif if (!ReleaseSemaphore(mSemImp, 1, // add one to the previous value NULL)) // don't return the old value { int lastErr; lastErr = GetLastError(); if (ERROR_TOO_MANY_POSTS == lastErr) { ret = OS_ALREADY_SIGNALED; } else { ret = OS_UNSPECIFIED; } #ifdef OS_SYNC_DEBUG // still holding it, so reset the status mTaskId = mLastId; mLastId = previousLast; #endif } } return ret; } /* ============================ INQUIRY =================================== */ // Print semaphore information to the console void OsBSemWnt::OsBSemShow(void) { char* pOptionStr; char* pSemState; char* pTaskName; #ifdef OS_SYNC_DEBUG UtlString taskName; OsTask* pTask; #endif switch (mOptions) { case Q_FIFO: pOptionStr = "Q_FIFO"; break; case Q_PRIORITY: pOptionStr = "Q_PRIORITY"; break; default: pOptionStr = "UNKNOWN"; break; } #ifdef OS_SYNC_DEBUG pSemState = (mTaskId == 0) ? "AVAILABLE" : "TAKEN"; if (mTaskId != 0) { pTask = OsTask::getTaskById(mTaskId); taskName = pTask->getName(); pTaskName = (char*) taskName.data(); } else { pTaskName = "N/A"; } #else pSemState = "UNKNOWN"; pTaskName = "UNKNOWN"; #endif osPrintf("OsBSem object 0x%08x, semOptions=%s, state=%s, heldBy=%s\n", (void *) this, pOptionStr, pSemState, pTaskName); #ifdef OS_SYNC_DEBUG taskName.remove(0); #endif } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/OsCSemWnt.cpp0000644000175000017500000000723012205613256024167 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include "utl/UtlRscTrace.h" // APPLICATION INCLUDES #include "os/Wnt/OsCSemWnt.h" #include "os/Wnt/OsUtilWnt.h" #ifdef OS_CSEM_DEBUG #include "os/OsLock.h" #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor setting the initial and max semaphore values to maxCount OsCSemWnt::OsCSemWnt(const int queueOptions, const int maxCount) : OsCSemBase(queueOptions, maxCount, maxCount) { init(); // Under Windows NT, we ignore the queueOptions argument mSemImp = CreateSemaphore(NULL, // no security attributes maxCount, // initial count is set to maxCount maxCount, // maximum count is set to maxCount NULL); // no name for this semaphore object } // Constructor allowing different initial and maximum semaphore values OsCSemWnt::OsCSemWnt(const int queueOptions, const int maxCount, const int initCount) : OsCSemBase(queueOptions, maxCount, initCount) { init(); // Under Windows NT, we ignore the queueOptions argument mSemImp = CreateSemaphore(NULL, // no security attributes initCount, // initial count is set to maxCount maxCount, // maximum count is set to maxCount NULL); // no name for this semaphore object } // Destructor OsCSemWnt::~OsCSemWnt() { UtlBoolean res; res = CloseHandle(mSemImp); assert(res == TRUE); // CloseHandle should always return TRUE } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ // Block the task until the semaphore is acquired or the timeout expires OsStatus OsCSemWnt::acquire(const OsTime& rTimeout) { OsStatus res = OsUtilWnt::synchObjAcquire(mSemImp, rTimeout); #ifdef OS_CSEM_DEBUG if (res == OS_SUCCESS) updateAcquireStats(); #endif return res; } // Conditionally acquire the semaphore (i.e., don't block) // Return OS_BUSY if the semaphore is held by some other task OsStatus OsCSemWnt::tryAcquire(void) { OsStatus res = OsUtilWnt::synchObjTryAcquire(mSemImp); #ifdef OS_CSEM_DEBUG if (res == OS_SUCCESS) updateAcquireStats(); #endif return res; } // Release the semaphore OsStatus OsCSemWnt::release(void) { long prevCount; OsStatus res; if (ReleaseSemaphore(mSemImp, 1, // add one to the previous value &prevCount)) // previous value res = OS_SUCCESS; else res = OS_BUSY; #ifdef OS_CSEM_DEBUG if (res == OS_SUCCESS) { updateReleaseStats(); } #endif //OS_CSEM_DEBUG return res; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ // Common initialization shared by all (non-copy) constructors void OsCSemWnt::init(void) { } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/OsDateTimeWnt.cpp0000644000175000017500000002537612205613256025047 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #define WIN32_LEAN_AND_MEAN #include #include #include #include #ifndef WINCE // [ // winmm.lib is required for OsDateTimeWnt::getCurTime() implementation // (for timeGetTime() and timeBeginPeriod() functions). # pragma comment(lib, "winmm.lib") #endif // WINCE ] // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/Wnt/OsDateTimeWnt.h" #include "os/OsTime.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const uint64_t WINDOWSTIME2UNIXTIME = UINT64_C(11644473600); const int MILLISECS_PER_SEC = 1000; const int MICROSECS_PER_MILLISEC = 1000; const int FILETIME_UNITS_PER_SEC = 10000000; // 100 nanosecs per sec const int FILETIME_UNITS_PER_USEC = 10; // 100 nanosecs per microsec // STATIC VARIABLE INITIALIZATIONS struct CriticalSectionWrapper { CRITICAL_SECTION CriticalSection; CriticalSectionWrapper() { InitializeCriticalSection(&CriticalSection); } ~CriticalSectionWrapper() { DeleteCriticalSection(&CriticalSection); } void Enter() { EnterCriticalSection(&CriticalSection); } void Leave() { LeaveCriticalSection(&CriticalSection); } }; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Default constructor OsDateTimeWnt::OsDateTimeWnt() : OsDateTimeBase() { // no further work required // all of the work is done by the parent constructor } // Constructor OsDateTimeWnt::OsDateTimeWnt(const unsigned short year, const unsigned char month, const unsigned char day, const unsigned char hour, const unsigned char minute, const unsigned char second, const unsigned int microsecond) : OsDateTimeBase(year, month, day, hour, minute, second, microsecond) { // no further work required // all of the work is done by the parent constructor } // Copy constructor OsDateTimeWnt::OsDateTimeWnt(const OsDateTimeWnt& rOsDateTimeWnt) : OsDateTimeBase((const OsDateTimeBase&) rOsDateTimeWnt) { // no further work required // all of the work is done by the parent copy constructor } /// Convert an OsTime to an OsDateTime OsDateTimeWnt::OsDateTimeWnt(const OsTime& toTime) { // first convert the OsTime to a Windows FILETIME int64_t winTime_64; winTime_64 = toTime.seconds(); winTime_64 += WINDOWSTIME2UNIXTIME; // adjust for epoch difference winTime_64 *= FILETIME_UNITS_PER_SEC; // scale to windows ticks winTime_64 += toTime.usecs() * FILETIME_UNITS_PER_USEC; FILETIME winTime; winTime.dwHighDateTime = (unsigned long)(winTime_64 >> 32); winTime.dwLowDateTime = (unsigned long)(winTime_64 & 0xFFFFFFFF); // then the FILETIME to a broken out SYSTEMTIME SYSTEMTIME sysTime; FileTimeToSystemTime(&winTime, &sysTime); // and last, SYSTEMTIME to OsDateTime mYear = sysTime.wYear; mMonth = sysTime.wMonth - 1; // windows is 1-based mDay = (unsigned char)sysTime.wDay; mHour = (unsigned char)sysTime.wHour; mMinute = (unsigned char)sysTime.wMinute; mSecond = (unsigned char)sysTime.wSecond; mMicrosecond = sysTime.wMilliseconds * MICROSECS_PER_MILLISEC; } // Destructor OsDateTimeWnt::~OsDateTimeWnt() { // no work required } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsDateTimeWnt& OsDateTimeWnt::operator=(const OsDateTimeWnt& rhs) { if (this == &rhs) // handle the assignment to self case return *this; OsDateTimeBase::operator=((const OsDateTimeBase&) rhs); // no further work required // all of the "heavy lifting" is done by the parent assignment operator return *this; } // Set the system time. For now, this is a no-op for Windows platforms. void OsDateTimeWnt::setTime(struct timespec gmt, int tzOffsetSecs, DstRule dstRule) { // no-op for now } // Set the system timezone. For now, this is a no-op for Windows platforms. void OsDateTimeWnt::setTimeZone(int tzOffsetSecs, DstRule dstRule) { // no-op for now } /* ============================ ACCESSORS ================================= */ // Convert the OsDateTimeBase value to an OsTime value // The OsTime value is relative to when the system was booted. OsStatus OsDateTimeWnt::cvtToTimeSinceBoot(OsTime& rTime) const { UtlBoolean ntRes; FILETIME bootFileTime; // boot time in various representations int64_t bootTime_i64; FILETIME thisFileTime; // this time in various representations SYSTEMTIME thisSysTime; int64_t thisTime_i64; int64_t deltaTime_i64; // (this time - boot time) in various int64_t deltaSecs_i64; // representations int64_t deltaUsecs_i64; // get the system boot time as a 64-bit integer recording the number of // 100-nanosecond intervals since January 1, 1601 GetSystemTimeAsFileTime(&bootFileTime); // get as FILETIME bootTime_i64 = (((int64_t)bootFileTime.dwHighDateTime) << 32) + bootFileTime.dwLowDateTime; // convert to int64_t // convert this OsDateTime object to a 64-bit integer thisSysTime.wYear = mYear; // represent as SYSTEMTIME thisSysTime.wMonth = mMonth+1; // because we subtracted previously(just like vxw) thisSysTime.wDay = mDay; thisSysTime.wHour = mHour; thisSysTime.wMinute = mMinute; thisSysTime.wSecond = mSecond; thisSysTime.wMilliseconds = mMicrosecond / 1000; // convert to FILETIME ntRes = SystemTimeToFileTime(&thisSysTime, &thisFileTime); assert(ntRes == TRUE); thisTime_i64 = (((int64_t)thisFileTime.dwHighDateTime) << 32) + thisFileTime.dwLowDateTime; // convert to int64_t // compute (thisFileTime - bootFileTime) and convert to an OsTime value deltaTime_i64 = thisTime_i64 - bootTime_i64; deltaSecs_i64 = (long) (deltaTime_i64 / FILETIME_UNITS_PER_SEC); deltaUsecs_i64 = (deltaTime_i64 % FILETIME_UNITS_PER_SEC) / FILETIME_UNITS_PER_USEC; assert((deltaSecs_i64 >> 32) == 0); assert((deltaUsecs_i64 >> 32) == 0); OsTime deltaOsTime((long) deltaSecs_i64, (long) deltaUsecs_i64); rTime = deltaOsTime; return OS_SUCCESS; } // Return the current time as an OsTime value void OsDateTimeWnt::getCurTime(OsTime& rTime) { static CriticalSectionWrapper criticalSection; // This function may be accessed from multiple threads, so we must // synchronize access to all these static variables. criticalSection.Enter(); typedef union { FILETIME ft; uint64_t int64; } g_FILETIME; static g_FILETIME sOsFileTime ; #if WINCE static bool sbInitialized = false ; static uint64_t sLastTicks = 0 ; static uint64_t sResetTime = 0 ; uint64_t ticks ; uint64_t freq ; QueryPerformanceCounter((LARGE_INTEGER*) &ticks) ; QueryPerformanceFrequency((LARGE_INTEGER*) &freq) ; if (!sbInitialized || sOsFileTime.int64 > sResetTime) { sbInitialized = true ; GetSystemTimeAsFileTime(&sOsFileTime.ft); sResetTime = -1 ; // sOsFileTime.int64 + (freq - 1) ; sLastTicks = ticks ; } else { uint64_t delta = ticks - sLastTicks ; sLastTicks = ticks ; sOsFileTime.int64 = sOsFileTime.int64 + (((uint64_t) 10000000) * (delta / freq)) + (((uint64_t) 10000000) * (delta % freq)) / freq ; SYSTEMTIME si ; FileTimeToSystemTime(&sOsFileTime.ft, &si) ; } #else static bool sbInitialized = false ; static DWORD sLastSystemMSecs = 0 ; DWORD systemMSecs = timeGetTime(); if (!sbInitialized) { sbInitialized = true ; // Set the precision of timings got from timeGetTime. timeBeginPeriod(1); // Resample time, since we changed the precision. systemMSecs = timeGetTime(); FILETIME sft; GetSystemTimeAsFileTime(&sft); // Store in a temp and copy over to prevent data type misalignment issues. sOsFileTime.ft = sft; sLastSystemMSecs = systemMSecs ; } else { DWORD delta = systemMSecs - sLastSystemMSecs ; sLastSystemMSecs = systemMSecs; // convert delta msec to 100ns units and advance system time sOsFileTime.int64 = sOsFileTime.int64 + 10000 * delta; SYSTEMTIME si ; FileTimeToSystemTime(&sOsFileTime.ft, &si) ; } #endif rTime = OsTime((long) ((sOsFileTime.int64 - WINDOWSTIME2UNIXTIME*10000000) / UINT64_C(10000000)), (long) ((sOsFileTime.int64 / UINT64_C(10)) % UINT64_C(1000000))); criticalSection.Leave(); } // Return the current time as an OsDateTime value void OsDateTimeWnt::getCurTime(OsDateTimeWnt& rDateTime) { SYSTEMTIME sysTime; GetSystemTime(&sysTime); rDateTime.mYear = sysTime.wYear; rDateTime.mMonth = (unsigned char) sysTime.wMonth-1; //month should start with 0 just like vxw rDateTime.mDay = (unsigned char) sysTime.wDay; rDateTime.mHour = (unsigned char) sysTime.wHour; rDateTime.mMinute = (unsigned char) sysTime.wMinute; rDateTime.mSecond = (unsigned char) sysTime.wSecond; rDateTime.mMicrosecond = sysTime.wMilliseconds * MICROSECS_PER_MILLISEC; } // Return the current time as an OsTime value // The OsTime value is relative to when the system was booted. void OsDateTimeWnt::getCurTimeSinceBoot(OsTime& rTime) { DWORD msecs; long secs; long usecs; static long start_msecs = GetTickCount(); msecs = GetTickCount()-start_msecs; secs = msecs / MILLISECS_PER_SEC; usecs = (msecs % MILLISECS_PER_SEC) * MICROSECS_PER_MILLISEC; OsTime timeSinceBoot(secs, usecs); rTime = timeSinceBoot; } // Current time as the number of seconds since midnight (0 hour) 01/01/1970 unsigned long OsDateTimeWnt::getSecsSinceEpoch(void) { return time(NULL); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/OsDirWnt.cpp0000644000175000017500000000671312205613256024063 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #ifdef WINCE # include #else # include # include # include #endif // APPLICATION INCLUDES #include "os/OsFS.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsDirWnt::OsDirWnt(const char* pathname) : OsDirBase(pathname) { } OsDirWnt::OsDirWnt(const OsPathWnt& pathname) : OsDirBase(pathname.data()) { } // Copy constructor OsDirWnt::OsDirWnt(const OsDirWnt& rOsDirWnt) : OsDirBase(rOsDirWnt.mDirName.data()) { } // Destructor OsDirWnt::~OsDirWnt() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsDirWnt& OsDirWnt::operator=(const OsDirWnt& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } OsStatus OsDirWnt::create() const { OsStatus ret = OS_INVALID; OsPathBase path; if (mDirName.getNativePath(path) == OS_SUCCESS) { int err = _mkdir((const char *)path.data()); if (err != -1) { ret = OS_SUCCESS; } } return ret; } OsStatus OsDirWnt::rename(const char* name) { OsStatus ret = OS_INVALID; OsPathBase path; if (mDirName.getNativePath(path) == OS_SUCCESS) { int err = ::rename(path.data(),name); if (err != -1) { ret = OS_SUCCESS; //make this object point to new path mDirName = name; } } return ret; } /* ============================ ACCESSORS ================================= */ OsStatus OsDirWnt::getFileInfo(OsFileInfoBase& fileinfo) const { OsStatus ret = OS_INVALID; WIN32_FILE_ATTRIBUTE_DATA w32data; BOOL bRes = GetFileAttributesEx(mDirName.data(), GetFileExInfoStandard, &w32data); if (bRes) { ret = OS_SUCCESS; fileinfo.mbIsDirectory = (w32data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? TRUE : FALSE; fileinfo.mbIsReadOnly = (w32data.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? TRUE : FALSE; fileinfo.mSize = ((ULONGLONG)w32data.nFileSizeHigh << 32) | w32data.nFileSizeLow; fileinfo.mCreateTime = OsFileWnt::fileTimeToOsTime(w32data.ftCreationTime); fileinfo.mModifiedTime = OsFileWnt::fileTimeToOsTime(w32data.ftLastWriteTime); } return ret; } /* ============================ INQUIRY =================================== */ UtlBoolean OsDirWnt::exists() { UtlBoolean stat = FALSE; OsFileInfoWnt info; OsStatus retval = getFileInfo(info); if (retval == OS_SUCCESS) stat = TRUE; return stat; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/OsFileInfoWnt.cpp0000644000175000017500000000314712205613256025036 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/wnt/OsFileInfoWnt.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsFileInfoWnt::OsFileInfoWnt() { } // Copy constructor OsFileInfoWnt::OsFileInfoWnt(const OsFileInfoWnt& rOsFileInfo) { } // Destructor OsFileInfoWnt::~OsFileInfoWnt() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsFileInfoWnt& OsFileInfoWnt::operator=(const OsFileInfoWnt& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ UtlBoolean OsFileInfoWnt::isReadOnly() const { UtlBoolean retval = TRUE; return retval; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/OsFileIteratorWnt.cpp0000644000175000017500000000534512205613256025736 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #ifndef WINCE # include #endif // APPLICATION INCLUDES #include "os/OsFS.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsFileIteratorWnt::OsFileIteratorWnt(const OsPathWnt& pathname) : OsFileIteratorBase(pathname) { } // Override this function for releasing mSearchHandle. void OsFileIteratorWnt::Release() { OsFileIteratorBase::Release(); if (mSearchHandle != INVALID_HANDLE) { _findclose(mSearchHandle); mSearchHandle = INVALID_HANDLE; } } // Destructor OsFileIteratorWnt::~OsFileIteratorWnt() { Release(); } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ OsFileIteratorWnt::OsFileIteratorWnt() { } OsStatus OsFileIteratorWnt::getFirstEntryName(UtlString &name, OsFileType &type) { OsStatus stat = OS_FILE_NOT_FOUND; name = ""; UtlString fullPath = mFullSearchSpec; fullPath += "*"; _finddata_t FileInfo; mSearchHandle = _findfirst(fullPath.data(),&FileInfo); if (mSearchHandle != -1) { name = FileInfo.name; stat = OS_SUCCESS; if (FileInfo.attrib & _A_SUBDIR) type = DIRECTORIES; else type = FILES; } else { stat = OS_FILE_NOT_FOUND; } return stat; } OsStatus OsFileIteratorWnt::getNextEntryName(UtlString &name, OsFileType &type) { OsStatus stat = OS_FILE_NOT_FOUND; name = ""; _finddata_t FileInfo; int retcode = _findnext(mSearchHandle,&FileInfo); if (retcode != -1) { stat = OS_SUCCESS; name = FileInfo.name; if (FileInfo.attrib & _A_SUBDIR) type = DIRECTORIES; else type = FILES; } return stat; } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/OsFileSystemWnt.cpp0000644000175000017500000000556612205613256025436 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsFS.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsFileSystemWnt::OsFileSystemWnt() { } // Copy constructor OsFileSystemWnt::OsFileSystemWnt(const OsFileSystemWnt& rOsFileSystem) { } // Destructor OsFileSystemWnt::~OsFileSystemWnt() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsFileSystemWnt& OsFileSystemWnt::operator=(const OsFileSystemWnt& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } //: Returns OS_SUCCESS if file copied ok. // see OsFile for more return codes OsStatus OsFileSystemWnt::copy(const OsPathWnt& source, const OsPathWnt& dest) { OsFileWnt sourcefile(source); return sourcefile.copy(dest); } //: Renames the directory or file specified by path // (no path may be specifed on 2nd parameter) OsStatus OsFileSystemWnt::rename(const OsPathWnt& source, const OsPathWnt& dest) { OsStatus stat = OS_SUCCESS; OsDirWnt dir(source); return dir.rename(dest); } //: Change the current working directory to the specified location OsStatus OsFileSystemWnt::change(const OsPathWnt& path) { OsStatus stat = OS_INVALID; if (chdir(path) != -1) stat = OS_SUCCESS; return stat; } //: Creates the specified directory // Fails if a file by the same name exist in the parent directory OsStatus OsFileSystemWnt::createDir(const OsPathWnt& path) { OsDirWnt dir(path); return dir.create(); } //: returns the current working directory for the process // OsStatus OsFileSystemWnt::getWorkingDirectory(OsPathWnt& path) { char buf[256]; OsStatus stat = OS_INVALID; if (getcwd(buf,256)) { stat = OS_SUCCESS; path=buf; } return stat; } /* ============================ ACCESSORS ================================= */ OsStatus OsFileSystemWnt::getFileInfo(OsPathWnt& filespec, OsFileInfoWnt& fileInfo) { OsDirWnt dir(filespec); return dir.getFileInfo(fileInfo); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/OsFileWnt.cpp0000644000175000017500000001032512205613256024216 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/Wnt/OsFileSystemWnt.h" #include "os/Wnt/OsFileWnt.h" #include "os/Wnt/OsPathWnt.h" #include "os/Wnt/OsFileInfoWnt.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const unsigned long CopyBufLen = 32768; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsFileWnt::OsFileWnt(const OsPathBase& filename) : OsFileBase(filename) { } // Copy constructor OsFileWnt::OsFileWnt(const OsFileWnt& rOsFileWnt) : OsFileBase(rOsFileWnt) { OsPathWnt path; rOsFileWnt.getFileName(path); mFilename = path; mOsFileHandle = rOsFileWnt.mOsFileHandle; } // Destructor OsFileWnt::~OsFileWnt() { if (mOsFileHandle) close(); //call our close } /* ============================ MANIPULATORS ============================== */ OsStatus OsFileWnt::setLength(unsigned long newLength) { OsStatus stat = OS_SUCCESS; return stat; } OsStatus OsFileWnt::fileunlock() { OsStatus retval = OS_SUCCESS; return retval; } OsStatus OsFileWnt::filelock(const bool wait) { OsStatus retval = OS_FAILED; return retval; } OsTime OsFileWnt::fileTimeToOsTime(FILETIME ft) { __int64 ll = (((__int64)ft.dwHighDateTime << 32) | ft.dwLowDateTime) - 116444736000000000; // See http://support.microsoft.com/?scid=kb%3Ben-us%3B167296&x=14&y=17 return OsTime((long)(ll / 10000000), (long)((ll / 10) % 1000000)); } OsStatus OsFileWnt::getFileInfo(OsFileInfoBase& fileinfo) const { OsStatus ret = OS_INVALID; WIN32_FILE_ATTRIBUTE_DATA w32data; BOOL bRes = GetFileAttributesEx(mFilename.data(), GetFileExInfoStandard, &w32data); if (bRes) { ret = OS_SUCCESS; fileinfo.mbIsReadOnly = (w32data.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? TRUE : FALSE; fileinfo.mSize = ((ULONGLONG)w32data.nFileSizeHigh << 32) | w32data.nFileSizeLow; fileinfo.mCreateTime = fileTimeToOsTime(w32data.ftCreationTime); fileinfo.mModifiedTime = fileTimeToOsTime(w32data.ftLastWriteTime); } return ret; } OsStatus OsFileWnt::touch() { OsStatus stat = OS_INVALID; if (exists() == OS_SUCCESS) { FILETIME ft; SYSTEMTIME st; BOOL fileTimeOk; // Grab the windows file handle for use in // windows file system calls. HANDLE fileHnd; fileHnd = CreateFile(mFilename, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); GetSystemTime(&st); // gets current time SystemTimeToFileTime(&st, &ft); // converts to file time format fileTimeOk = SetFileTime(fileHnd, // sets last-write time for file (LPFILETIME) NULL, (LPFILETIME) NULL, &ft); if (fileTimeOk) { stat = OS_SUCCESS; } } else { stat = open(CREATE); close(); } return stat; } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ UtlBoolean OsFileWnt::isReadonly() const { UtlBoolean retval = FALSE; OsFileInfoWnt info; getFileInfo(info); return info.mbIsReadOnly; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ // Assignment operator OsFileWnt& OsFileWnt::operator=(const OsFileWnt& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/OsMutexWnt.cpp0000644000175000017500000000441212205613256024441 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include "utl/UtlRscTrace.h" // APPLICATION INCLUDES #include "os/Wnt/OsMutexWnt.h" #include "os/Wnt/OsUtilWnt.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor allowing the user to specify options OsMutexWnt::OsMutexWnt(const unsigned options) { // Under Windows NT, we ignore the options argument to the constructor mMutexImp = CreateMutex(NULL, FALSE, NULL); } // Destructor OsMutexWnt::~OsMutexWnt() { UtlBoolean res; res = CloseHandle(mMutexImp); assert(res == TRUE); // CloseHandle should always return TRUE } /* ============================ MANIPULATORS ============================== */ // Block the task until the mutex is acquired or the timeout expires OsStatus OsMutexWnt::acquire(const OsTime& rTimeout) { return OsUtilWnt::synchObjAcquire(mMutexImp, rTimeout); } // Conditionally acquire the mutex (i.e., don't block) // Return OS_BUSY if the lock is held by some other task OsStatus OsMutexWnt::tryAcquire(void) { return OsUtilWnt::synchObjTryAcquire(mMutexImp); } // Release the semaphore OsStatus OsMutexWnt::release(void) { if (ReleaseMutex(mMutexImp)) return OS_SUCCESS; else return OS_UNSPECIFIED; } /* ============================ ACCESSORS ================================= */ // Print mutex information to the console void OsMutexWnt::OsMutexShow(void) { osPrintf("OsMutex object 0x%08x, no debug info available\n", (void*) this); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/OsPathWnt.cpp0000644000175000017500000000335412205613256024237 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsFS.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsPathWnt::OsPathWnt() { } // Make one from a char string OsPathWnt::OsPathWnt(const char *pathname) : OsPathBase(pathname) { } // Make one from a UtlStringchar string OsPathWnt::OsPathWnt(const UtlString &pathname) : OsPathBase(pathname) { } // Copy constructor OsPathWnt::OsPathWnt(const OsPathWnt& rOsPath) { *this = rOsPath.data(); } // Destructor OsPathWnt::~OsPathWnt() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsPathWnt& OsPathWnt::operator=(const OsPathWnt& rhs) { if (this == &rhs) // handle the assignment to self case return *this; OsPathBase::operator=(rhs.data()); return *this; } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/OsProcessIteratorWnt.cpp0000644000175000017500000000622012205613256026466 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #define WIN32_LEAN_AND_MEAN #include #include #include // APPLICATION INCLUDES #include "os/wnt/OsProcessIteratorWnt.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsProcessIteratorWnt::OsProcessIteratorWnt() : hProcessSnapshot(INVALID_HANDLE_VALUE) { } // Destructor OsProcessIteratorWnt::~OsProcessIteratorWnt() { if (hProcessSnapshot != (HANDLE)INVALID_HANDLE_VALUE) CloseHandle(hProcessSnapshot); } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ OsStatus OsProcessIteratorWnt::findFirst(OsProcess &rProcess) { OsStatus retval = OS_FAILED; if (hProcessSnapshot != INVALID_HANDLE_VALUE) { CloseHandle(hProcessSnapshot); } hProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); if (hProcessSnapshot != INVALID_HANDLE_VALUE) { PROCESSENTRY32 lppe; lppe.dwSize = sizeof(PROCESSENTRY32); //now actuall go find the process if (Process32First(hProcessSnapshot,&lppe)) { if (GetLastError() != ERROR_NO_MORE_FILES) { rProcess.mPID = lppe.th32ProcessID; rProcess.mParentPID = lppe.th32ParentProcessID; rProcess.mProcessName = lppe.szExeFile; retval = OS_SUCCESS; } else retval = OS_FAILED; } } return retval; } OsStatus OsProcessIteratorWnt::findNext(OsProcess &rProcess) { OsStatus retval = OS_FAILED; //hProcessSnapshot was retrieved with a call to findFirst above if (hProcessSnapshot != INVALID_HANDLE_VALUE) { PROCESSENTRY32 lppe; lppe.dwSize = sizeof(PROCESSENTRY32); //now actuall go find the process if (Process32Next(hProcessSnapshot,&lppe)) { if (GetLastError() != ERROR_NO_MORE_FILES) { rProcess.mPID = lppe.th32ProcessID; rProcess.mParentPID = lppe.th32ParentProcessID; rProcess.mProcessName = lppe.szExeFile; retval = OS_SUCCESS; } else retval = OS_FAILED; } } return retval; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/OsProcessWnt.cpp0000644000175000017500000004005712205613256024762 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #define WIN32_LEAN_AND_MEAN #include #ifndef WINCE # include #endif #ifdef WINCE # include #else # include # include #endif #include #ifndef WINCE # include #endif #include // APPLICATION INCLUDES #include "os/OsProcess.h" #include "os/wnt/OsProcessWnt.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ OsProcessWnt::OsProcessWnt() : mStdErrorHandle(0),mStdOutputHandle(0), mStdInputHandle(0), mhProcess(0), mhThread(0) { } // Destructor OsProcessWnt::~OsProcessWnt() { if (mStdErrorHandle != NULL && mStdErrorHandle != INVALID_HANDLE_VALUE) { CloseHandle(mStdErrorHandle); } if (mStdOutputHandle != NULL && mStdOutputHandle != INVALID_HANDLE_VALUE) { CloseHandle(mStdOutputHandle); } if (mStdInputHandle != NULL && mStdInputHandle != INVALID_HANDLE_VALUE) { CloseHandle(mStdInputHandle); } if (mhThread) { CloseHandle(mhThread); } if (mhProcess) { CloseHandle(mhProcess); } } /* ============================ MANIPULATORS ============================== */ OsStatus OsProcessWnt::setIORedirect(OsPath &rStdInputFilename, OsPath &rStdOutputFilename, OsPath &rStdErrorFilename) { OsStatus retval = OS_FAILED; UtlBoolean bOneFailed = FALSE; if (!rStdInputFilename.isNull()) { mStdInputHandle = CreateFile(rStdInputFilename.data(), GENERIC_READ, // access mode FILE_SHARE_READ, // share mode 0, // SD OPEN_EXISTING, // how to create FILE_ATTRIBUTE_NORMAL, // file attributes NULL); // handle to template file if (mStdInputHandle == INVALID_HANDLE_VALUE) { osPrintf("Could not open input file for Std Input for new process\n"); bOneFailed = TRUE; } else { mStdInputFilename = rStdInputFilename; } } if (!rStdErrorFilename.isNull()) { mStdErrorHandle = CreateFile(rStdErrorFilename.data(), GENERIC_WRITE, // access mode FILE_SHARE_READ, // share mode 0, // SD OPEN_ALWAYS, // how to create FILE_ATTRIBUTE_NORMAL, // file attributes NULL); // handle to template file if (mStdErrorHandle == INVALID_HANDLE_VALUE) { osPrintf("Could not open %s for Std Error on new process\n"); bOneFailed = TRUE; } else { mStdErrorFilename = rStdErrorFilename; } } if (!rStdOutputFilename.isNull()) { mStdOutputHandle = CreateFile(rStdOutputFilename.data(), GENERIC_WRITE, // access mode FILE_SHARE_READ, // share mode 0, // SD OPEN_ALWAYS, // how to create FILE_ATTRIBUTE_NORMAL, // file attributes NULL); // handle to template file if (mStdOutputHandle == INVALID_HANDLE_VALUE) { osPrintf("Could not open %s for Std Error on new process\n"); bOneFailed = TRUE; } else { mStdOutputFilename = rStdOutputFilename; } } if (!bOneFailed) retval = OS_SUCCESS; else { if (mStdErrorHandle != INVALID_HANDLE_VALUE) CloseHandle(mStdErrorHandle); if (mStdOutputHandle != INVALID_HANDLE_VALUE) CloseHandle(mStdOutputHandle); if (mStdInputHandle != INVALID_HANDLE_VALUE) CloseHandle(mStdInputHandle); } return retval; } OsStatus OsProcessWnt::setPriority(int prio) { OsStatus retval = OS_FAILED; return retval; } OsStatus OsProcessWnt::kill() { OsStatus retval = OS_FAILED; HANDLE hProcess = OpenProcess(PROCESS_TERMINATE,FALSE,mPID); if (hProcess) { if (TerminateProcess(hProcess,0)) retval = OS_SUCCESS; int trycount = 0; while (isRunning() && trycount++ < 30) { if (TerminateProcess(hProcess,0)) retval = OS_SUCCESS; } } CloseHandle(hProcess); return retval; } //waits for a process to complete before returning //or exits when WaitInSecs has completed int OsProcessWnt::wait(int WaitInSecs) { DWORD ExitCode = STILL_ACTIVE; int secs_waited = 0; if (WaitInSecs < 0) WaitInSecs = 0; if (mhProcess) { while (ExitCode == STILL_ACTIVE && secs_waited <= WaitInSecs) { if (GetExitCodeProcess(mhProcess, &ExitCode)) { } else osPrintf("Error getting exitcode for process %d\n",mPID); if (ExitCode == STILL_ACTIVE) { Sleep(1000); if (WaitInSecs > 0) secs_waited++; } } } else ExitCode = -1; return ExitCode; } OsStatus OsProcessWnt::launch(UtlString &rAppName, UtlString parameters[],OsPath &startupDir, OsProcessPriorityClass prioClass, UtlBoolean bExeclusive) { OsStatus retval = OS_FAILED; STARTUPINFO StartupInfo; PROCESS_INFORMATION ProcessInformation; UtlString cmdLine; if (startupDir.length() != 0) { cmdLine = startupDir + OsPath::separator; } else { startupDir = "."; } cmdLine += rAppName; /* int saved_stderr = dup(2); int saved_stdout = dup(1); int saved_stdin = dup(0); */ //build one string out of the array passed in int parameterCount = 0; while (!parameters[parameterCount].isNull()) { if(parameters[parameterCount].index(" ") != UTL_NOT_FOUND) parameters[parameterCount] = "\"" + parameters[parameterCount] + "\""; cmdLine.append(" "); cmdLine.append(parameters[parameterCount]); parameterCount++; } //clear out structure memset(&StartupInfo,'\0',sizeof(STARTUPINFO)); StartupInfo.cb = sizeof(STARTUPINFO); StartupInfo.lpReserved = NULL; StartupInfo.wShowWindow = SW_MINIMIZE|SW_HIDE; StartupInfo.lpDesktop = NULL; StartupInfo.lpTitle = NULL; StartupInfo.dwFlags |= STARTF_USESTDHANDLES; //now it's time to redirect the output,input and error streams if (mStdErrorFilename.length()) StartupInfo.hStdError = mStdErrorHandle; else StartupInfo.hStdError =GetStdHandle(STD_ERROR_HANDLE); if (mStdInputFilename.length()) StartupInfo.hStdInput = mStdInputHandle; else StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE); if (mStdOutputFilename.length()) StartupInfo.hStdOutput = mStdOutputHandle; else StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); //now apply the env variables the user may have set ApplyEnv(); //3...2...1... LAUNCH!!!! #ifdef WINCE int retcode = CreateProcess( NULL, // name of executable module (null because we want to execute all commands) // even things such as dir (char *)cmdLine.data(), // command line string NULL, NULL, //this originally was TRUE but the web browser was never coming back. FALSE, // handle inheritance flag // CREATE_NEW_CONSOLE, 0, // WinCE - must be zero or CREATE_SUSPENDED NULL, // WinCE - must be NULL NULL, // WinCE - must be NULL NULL, // WinCE - must be NULL &ProcessInformation ); #else int retcode = CreateProcess( NULL, // name of executable module (null because we want to execute all commands) // even things such as dir (char *)cmdLine.data(), // command line string NULL, NULL, //this originally was TRUE but the web browser was never coming back. FALSE, // handle inheritance flag // CREATE_NEW_CONSOLE, CREATE_NO_WINDOW | DETACHED_PROCESS, // creation flags NULL, // new environment block startupDir.data(), // startupdir &StartupInfo, &ProcessInformation ); #endif if (retcode != 0) { #ifndef WINCE //translate the incoming priority to Wnt values DWORD wntPrio = NORMAL_PRIORITY_CLASS; switch(prioClass) { case IdlePriorityClass: wntPrio = IDLE_PRIORITY_CLASS; break; case NormalPriorityClass: wntPrio = NORMAL_PRIORITY_CLASS; break; case HighPriorityClass: wntPrio = HIGH_PRIORITY_CLASS; break; case RealtimePriorityClass: wntPrio = REALTIME_PRIORITY_CLASS; break; default: osPrintf("**** Invalid process priority class specified!\n"); osPrintf("*** Defaulting to NormalPriorityClass *** \n"); break; } if (!SetPriorityClass(ProcessInformation.hProcess, wntPrio)) { osPrintf("*** Could not change the process priority on launch ***\n"); osPrintf("*** Priority will be the parents priority ! ***\n"); } if (bExeclusive) { //here is where we check if a process by the same name is already running } mPID = ProcessInformation.dwProcessId; mParentPID = getpid(); #else mPID = ProcessInformation.dwProcessId; mParentPID = NULL; #endif mhProcess = ProcessInformation.hProcess; mhThread = ProcessInformation.hThread; retval = OS_SUCCESS; } else { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); osPrintf("***** ERROR FROM LAUNCH: %s",(LPCTSTR)lpMsgBuf); // Free the buffer. LocalFree( lpMsgBuf ); } /* dup2(saved_stderr,2); dup2(saved_stdout,1); dup2(saved_stdin, 0); */ return retval; } /* ============================ ACCESSORS ================================= */ OsStatus OsProcessWnt::getByPID(PID pid, OsProcess &rProcess) { OsStatus retval = OS_FAILED; OsProcess process; OsProcessIterator pi; OsStatus findRetVal = pi.findFirst(process); while (findRetVal == OS_SUCCESS) { if (process.getPID() == pid) { rProcess.mParentPID = process.mParentPID; rProcess.mPID = process.mPID; rProcess.mProcessName = process.mProcessName; retval = OS_SUCCESS; break; } findRetVal = pi.findNext(process); } return retval; } OsStatus OsProcessWnt::getInfo(OsProcessInfo &rProcessInfo) { OsStatus retval = OS_FAILED; HANDLE hProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,mPID); if (hProcessSnapshot) { PROCESSENTRY32 pe; if (Process32First(hProcessSnapshot,&pe)) { rProcessInfo.parentProcessID = mParentPID; rProcessInfo.name = pe.szExeFile; rProcessInfo.commandline = mParameters; rProcessInfo.prioClass = pe.pcPriClassBase; retval = OS_SUCCESS; } CloseHandle(hProcessSnapshot); } return retval; } OsStatus OsProcessWnt::getUpTime(OsTime &rUpTime) { OsStatus retval = OS_FAILED; rUpTime = OsTime::OS_INFINITY; HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,mPID); #ifndef WINCE FILETIME creationTime; FILETIME exitTime; // process exit time FILETIME kernelTime; // process kernel-mode time FILETIME userTime; // process user-mode time if (GetProcessTimes(hProcess, &creationTime, &exitTime, &kernelTime, &userTime)) { retval = OS_SUCCESS; CloseHandle(hProcess); } #endif return retval; } OsStatus OsProcessWnt::getPriorityClass(OsProcessPriorityClass &rPrioClass) { OsStatus retval = OS_FAILED; #ifndef WINCE OsProcessInfo processInfo; if (getInfo(processInfo)) { switch(processInfo.prioClass) { case IDLE_PRIORITY_CLASS: break; case NORMAL_PRIORITY_CLASS: break; case HIGH_PRIORITY_CLASS: break; case REALTIME_PRIORITY_CLASS: break; } } #endif return retval; } OsStatus OsProcessWnt::getMinPriority(int &rMinPrio) { OsStatus retval = OS_FAILED; #ifndef WINCE OsProcessInfo processInfo; if (getInfo(processInfo)) { switch(processInfo.prioClass) { case IDLE_PRIORITY_CLASS: break; case NORMAL_PRIORITY_CLASS: break; case HIGH_PRIORITY_CLASS: break; case REALTIME_PRIORITY_CLASS: break; } } #endif return retval; } OsStatus OsProcessWnt::getMaxPriority(int &rMaxPrio) { OsStatus retval = OS_FAILED; return retval; } OsStatus OsProcessWnt::getPriority(int &rPrio) { OsStatus retval = OS_FAILED; return retval; } int OsProcessWnt::getCurrentPID() { #ifndef WINCE return _getpid(); #else return NULL; #endif } /* ============================ INQUIRY =================================== */ UtlBoolean OsProcessWnt::isRunning() const { UtlBoolean retval = FALSE; DWORD ExitCode = 0; HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION,TRUE,mPID); if (hProcess) { if (GetExitCodeProcess(hProcess,&ExitCode)) { if (ExitCode == STILL_ACTIVE) retval = TRUE; } CloseHandle(hProcess); } return retval; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/OsSharedLibMgrWnt.cpp0000644000175000017500000001531412205613256025645 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // Private container class for collectable handles to shared libs class OsSharedLibHandleWnt : public UtlString { public: OsSharedLibHandleWnt(const char* libName, HMODULE libHandle); HMODULE mLibHandle; }; OsSharedLibHandleWnt::OsSharedLibHandleWnt(const char* libName, HMODULE libHandle) : UtlString(libName ? libName : "") { mLibHandle = libHandle; } // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsSharedLibMgrWnt::OsSharedLibMgrWnt() { } // Copy constructor OsSharedLibMgrWnt::OsSharedLibMgrWnt(const OsSharedLibMgrWnt& rOsSharedLibMgrWnt) { } // Destructor OsSharedLibMgrWnt::~OsSharedLibMgrWnt() { } /* ============================ MANIPULATORS ============================== */ //: Loads the given shared library //!param: libName - name of library, may include absolute or relative path OsStatus OsSharedLibMgrWnt::loadSharedLib(const char* libName) { OsStatus status = OS_INVALID; // Check if we aready have a handle for this lib UtlString collectableName(libName ? libName : ""); sLock.acquire(); OsSharedLibHandleWnt* collectableLibHandle = (OsSharedLibHandleWnt*) mLibraryHandles.find(&collectableName); sLock.release(); // We do not already have a handle for this lib if(!collectableLibHandle) { // Prevent dialog from freezing the process unsigned int previousErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS); // Load the shared library HMODULE libHandle = NULL; if(libName) { libHandle = LoadLibraryEx(libName, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); } else { libHandle = GetModuleHandle(NULL); } if (!libHandle) { osPrintf("failed to shared lib load specified path\nTrying wider search path\n"); libHandle = LoadLibraryEx(libName, NULL, 0); } if (!libHandle) { int errorCode = GetLastError(); osPrintf("Failed to load shared library: %s error: %d\n", libName ? libName : "(null)", errorCode); status = OS_NOT_FOUND; } else { osPrintf("Loaded shared lib %s\n", libName ? libName : "(null)"); OsSharedLibHandleWnt* collectableHandle = new OsSharedLibHandleWnt(libName, libHandle); sLock.acquire(); mLibraryHandles.insert(collectableHandle); sLock.release(); status = OS_SUCCESS; } // Reset the error mode SetErrorMode(previousErrorMode); } else { status = OS_SUCCESS; } // Get a handle to the main program //libHandle = GetModuleHandle(NULL); //if(libHandle) //{ // osPrintf("got a handle to this\n"); //} return(status); } //: Gets the address of a symbol in the shared lib //!param: (in) libName - name of library, may include absolute or relative path //!param: (in) symbolName - name of the variable or function exported in the shared lib //!param: (out) symbolAddress - the address of the function or variable OsStatus OsSharedLibMgrWnt::getSharedLibSymbol(const char* libName, const char* symbolName, void*& symbolAddress) { OsStatus status = OS_INVALID; UtlString collectableName(libName ? libName : ""); sLock.acquire(); OsSharedLibHandleWnt* collectableLibHandle = (OsSharedLibHandleWnt*) mLibraryHandles.find(&collectableName); if(!collectableLibHandle) { sLock.release(); loadSharedLib(libName); sLock.acquire(); collectableLibHandle = (OsSharedLibHandleWnt*) mLibraryHandles.find(&collectableName); } if(collectableLibHandle) { // Get a named symbol from the shared library symbolAddress = GetProcAddress(collectableLibHandle->mLibHandle, symbolName); if (!symbolAddress) { int errorCode = GetLastError(); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "Failed to find symbol: %s in shared lib: %s error: %d", symbolName, libName ? libName : "(null)", errorCode); LPVOID lpMsgBuf; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorCode, 0, // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); osPrintf("%s\n", lpMsgBuf); LocalFree(lpMsgBuf); if(errorCode = 127) status = OS_NOT_FOUND; else status = OS_UNSPECIFIED; } else { osPrintf("Found symbol: %s in shared lib: %s\n", symbolName, libName ? libName : "(null)"); status = OS_SUCCESS; } } sLock.release(); return(status); } OsStatus OsSharedLibMgrWnt::unloadSharedLib(const char* libName) { OsStatus status = OS_INVALID; BOOL res; // Check if we already have a handle for this lib UtlString collectableName(libName ? libName : ""); sLock.acquire(); OsSharedLibHandleWnt* collectableLibHandle = (OsSharedLibHandleWnt*) mLibraryHandles.find(&collectableName); // We do not already have a handle for this lib if(!collectableLibHandle) { sLock.release(); return status; } res = FreeLibrary(collectableLibHandle->mLibHandle); if (res) { mLibraryHandles.remove(&collectableName); status = OS_SUCCESS; } else { status = OS_FAILED; } sLock.release(); return(status); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/OsTaskWnt.cpp0000644000175000017500000004435212205617431024247 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsExcept.h" #include "os/OsLock.h" #include "os/OsUtil.h" #include "os/OsDateTime.h" #include "os/Wnt/OsTaskWnt.h" #include "os/Wnt/OsUtilWnt.h" #ifndef WINCE # include #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // FORWARD DECLARATIONS static void SetThreadName(DWORD dwThreadID, LPCTSTR szThreadName); /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsTaskWnt::OsTaskWnt(const UtlString& name, void* pArg, const int priority, const int options, const int stackSize) : OsTaskBase(name, pArg, priority, options, stackSize), mDeleteGuard(OsRWMutex::Q_PRIORITY), mSuspendCnt(0), mThreadH(NULL), mThreadId(NULL), mOptions(options), mPriority(priority), mStackSize(stackSize) { // other than initialization, no work required } // Destructor OsTaskWnt::~OsTaskWnt() { waitUntilShutDown(); OsLock lock(mDataGuard); doWntTerminateTask(FALSE); } // Delete the task even if the task is protected from deletion. // After calling this method, the user will still need to delete the // corresponding OsTask object to reclaim its storage. OsStatus OsTaskWnt::deleteForce(void) { OsLock lock(mDataGuard); if (!isStarted()) return OS_TASK_NOT_STARTED; doWntTerminateTask(TRUE); return OS_SUCCESS; } /* ============================ MANIPULATORS ============================== */ // Restart the task. // The task is first terminated, and then reinitialized with the same // name, priority, options, stack size, original entry point, and // parameters it had when it was terminated. // Return TRUE if the restart of the task is successful. UtlBoolean OsTaskWnt::restart(void) { OsLock lock(mDataGuard); doWntTerminateTask(FALSE); return doWntCreateTask(); } // Resume the task. // This routine resumes the task. The task suspension is cleared, and // the task operates in the remaining state. OsStatus OsTaskWnt::resume(void) { BOOL ntResult; OsLock lock(mDataGuard); if (!isStarted()) return OS_TASK_NOT_STARTED; assert(mSuspendCnt > 0); ntResult = ResumeThread(mThreadH); if (ntResult >= 0) { mSuspendCnt--; return OS_SUCCESS; } else return OS_UNSPECIFIED; } // Spawn a new task and invoke its run() method. // Return TRUE if the spawning of the new task is successful. // Return FALSE if the task spawn fails or if the task has already // been started. UtlBoolean OsTaskWnt::start(void) { OsLock lock(mDataGuard); if (isStarted()) return FALSE; return doWntCreateTask(); ; } // Suspend the task. // This routine suspends the task. Suspension is additive: thus, tasks // can be delayed and suspended, or pended and suspended. Suspended, // delayed tasks whose delays expire remain suspended. Likewise, // suspended, pended tasks that unblock remain suspended only. OsStatus OsTaskWnt::suspend(void) { int ntResult; OsLock lock(mDataGuard); if (!isStarted()) return OS_TASK_NOT_STARTED; assert(mSuspendCnt >= 0); ntResult = SuspendThread(mThreadH); if (ntResult >= 0) { mSuspendCnt++; return OS_SUCCESS; } else return OS_UNSPECIFIED; } // Set the errno status for the task. // This call has no effect under Windows NT and, if the task has been // started, will always returns OS_SUCCESS OsStatus OsTaskWnt::setErrno(int errno) { if (!isStarted()) return OS_TASK_NOT_STARTED; return OS_SUCCESS; } // Set the execution options for the task // The only option that can be changed after a task has been created // is whether to allow breakpoint debugging. // This call has no effect under Windows NT and always returns OS_SUCCESS OsStatus OsTaskWnt::setOptions(int options) { return OS_SUCCESS; } // Set the priority of the task. // Priorities range from 0, the highest priority, to 255, the lowest priority. OsStatus OsTaskWnt::setPriority(int priority) { int wntPrio; OsLock lock(mDataGuard); if (!isStarted()) { mPriority = priority; // save mPriority for later use return OS_TASK_NOT_STARTED; } wntPrio = OsUtilWnt::cvtOsPrioToWntPrio(priority); if (SetThreadPriority(mThreadH, wntPrio)) { mPriority = priority; return OS_SUCCESS; } else return OS_UNSPECIFIED; } // Add a task variable to the task. // This routine adds a specified variable pVar (4-byte memory // location) to its task's context. After calling this routine, the // variable is private to the task. The task can access and modify // the variable, but the modifications are not visible to other tasks, // and other tasks' modifications to that variable do not affect the // value seen by the task. This is accomplished by saving and restoring // the variable's value each time a task switch occurs to or from the // calling task. OsStatus OsTaskWnt::varAdd(int* pVar) { if (!isStarted()) return OS_TASK_NOT_STARTED; return OS_NOT_YET_IMPLEMENTED; } // Remove a task variable from the task. // This routine removes a specified task variable, pVar, from its // task's context. The private value of that variable is lost. OsStatus OsTaskWnt::varDelete(int* pVar) { if (!isStarted()) return OS_TASK_NOT_STARTED; return OS_NOT_YET_IMPLEMENTED; } // Set the value of a private task variable. // This routine sets the private value of the task variable for a // specified task. The specified task is usually not the calling task, // which can set its private value by directly modifying the variable. // This routine is provided primarily for debugging purposes. OsStatus OsTaskWnt::varSet(int* pVar, int value) { if (!isStarted()) return OS_TASK_NOT_STARTED; return OS_NOT_YET_IMPLEMENTED; } // Delay a task from executing fpr the specified number of milliseconds. // This routine causes the calling task to relinquish the CPU for the // duration specified. This is commonly referred to as manual // rescheduling, but it is also useful when waiting for some external // condition that does not have an interrupt associated with it. OsStatus OsTaskWnt::delay(const int milliSecs) { Sleep(milliSecs); return OS_SUCCESS; } // Make the calling task safe from deletion. // This routine protects the calling task from deletion. Tasks that // attempt to delete a protected task will block until the task is // made unsafe, using unsafe(). When a task becomes unsafe, the // deleter will be unblocked and allowed to delete the task. // The safe() primitive utilizes a count to keep track of // nested calls for task protection. When nesting occurs, // the task becomes unsafe only after the outermost unsafe() // is executed. OsStatus OsTaskWnt::safe(void) { OsTask* pTask; OsStatus res; pTask = getCurrentTask(); res = pTask->mDeleteGuard.acquireRead(); assert(res == OS_SUCCESS); return res; } // Make the calling task unsafe from deletion. // This routine removes the calling task's protection from deletion. // Tasks that attempt to delete a protected task will block until the // task is unsafe. When a task becomes unsafe, the deleter will be // unblocked and allowed to delete the task. // The unsafe() primitive utilizes a count to keep track of nested // calls for task protection. When nesting occurs, the task becomes // unsafe only after the outermost unsafe() is executed. OsStatus OsTaskWnt::unsafe(void) { OsTask* pTask; OsStatus res; pTask = getCurrentTask(); res = pTask->mDeleteGuard.releaseRead(); assert(res == OS_SUCCESS); return res; } // Yield the CPU if a task of equal or higher priority is ready to run. void OsTaskWnt::yield(void) { delay(0); } /* ============================ ACCESSORS ================================= */ // Return a pointer to the OsTask object for the currently executing task // Return NULL if none exists. OsTaskWnt* OsTaskWnt::getCurrentTask(void) { DWORD threadId; threadId = GetCurrentThreadId(); return OsTaskWnt::getTaskById(threadId); } // I am adding this code at the same time as I add the same code to OsTaskLinux // It fixes a bug on 64-bit hosts (find the commented out calls to this, below). //*** BETTER: // Convert a taskId into a UtlString //*** BETTER: void OsTaskLinux::getIdString(UtlString &dest, DWORD tid) //*** BETTER: { //*** BETTER: dest.appendFormat("%ld", tid); //*** BETTER: } // Return the Id of the currently executing task OsStatus OsTaskWnt::getCurrentTaskId(int &rid) { rid = GetCurrentThreadId(); return OS_SUCCESS; } // Return a pointer to the OsTask object corresponding to the named task // Return NULL if there is no task object with that name. OsTaskWnt* OsTaskWnt::getTaskByName(const UtlString& taskName) { OsStatus res; intptr_t val; res = OsUtil::lookupKeyValue(TASK_PREFIX, taskName, &val); assert(res == OS_SUCCESS || res == OS_NOT_FOUND); if (res == OS_SUCCESS) { assert(val != 0); return ((OsTaskWnt*) val); } else return NULL; } // Return a pointer to the OsTask object corresponding to taskId // Return NULL is there is no task object with that id. OsTaskWnt* OsTaskWnt::getTaskById(const int taskId) { char idString[30]; //*** BETTER: UtlString idString; OsStatus res; intptr_t val; itoa((int) taskId, idString, 10); // convert the id to a string //*** BETTER: getIdString(idString, mThreadId); // convert the id to a string res = OsUtil::lookupKeyValue(TASKID_PREFIX, idString, &val); assert(res == OS_SUCCESS || res == OS_NOT_FOUND); if (res == OS_SUCCESS) { assert(val != 0); return ((OsTaskWnt*) val); } else return NULL; } // Get the errno status for the task // Under Windows NT, the rErrno value will always be 0. OsStatus OsTaskWnt::getErrno(int& rErrno) { rErrno = 0; if (!isStarted()) return OS_TASK_NOT_STARTED; return OS_SUCCESS; } // Return the execution options for the task int OsTaskWnt::getOptions(void) { return mOptions; } // Return the priority of the task OsStatus OsTaskWnt::getPriority(int& rPriority) { int wntPrio; if (!isStarted()) return OS_TASK_NOT_STARTED; wntPrio = GetThreadPriority(mThreadH); rPriority = OsUtilWnt::cvtWntPrioToOsPrio(wntPrio); return OS_SUCCESS; } // Get the value of a task variable. // This routine returns the private value of a task variable for its // task. The task is usually not the calling task, which can get its // private value by directly accessing the variable. This routine is // provided primarily for debugging purposes. OsStatus OsTaskWnt::varGet(void) { if (!isStarted()) return OS_TASK_NOT_STARTED; return OS_NOT_YET_IMPLEMENTED; } /* ============================ INQUIRY =================================== */ // Get the task ID for this task OsStatus OsTaskWnt::id(OsTaskId_t& rId) { OsStatus retVal = OS_SUCCESS; //if started, return the taskId, otherwise return -1 if (isStarted()) rId = mThreadId; else { retVal = OS_TASK_NOT_STARTED; rId = -1; } return retVal; } // Check if the task is suspended. // Return TRUE is the task is suspended, otherwise FALSE. UtlBoolean OsTaskWnt::isSuspended(void) { OsLock lock(mDataGuard); if (!isStarted()) return FALSE; return mSuspendCnt > 0; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ // Do the real work associated with creating a new WinNT task // The mDataGuard lock should be held upon entry into this method. UtlBoolean OsTaskWnt::doWntCreateTask(void) { // JEP - TODO - implement this... char idString[30]; //*** BETTER: UtlString idString; unsigned int threadId; // mThreadH = (void *)_beginthreadex( mThreadH = (void *)CreateThread( 0, // don't specify any thread attributes mStackSize, // stack size (in bytes) (LPTHREAD_START_ROUTINE) threadEntry, // starting address of the new thread (void*) this, // parameter value that will be passed // to the new thread CREATE_SUSPENDED, // suspend thread until priority is set (unsigned long *) &threadId); // thread identifier return value mSuspendCnt = 0; mThreadId = threadId; if (mThreadH != NULL) { // Enter the thread id into the global name database so that given the // thread id we will be able to find the corresponding OsTask object itoa((int) mThreadId, idString, 10); // convert the id to a string //*** BETTER: getIdString(idString, mThreadId); // convert the id to a string OsUtil::insertKeyValue(TASKID_PREFIX, idString, (intptr_t) this); mState = STARTED; // Unlike VxWorks, the priority is not an argument in the creation call, // so we have to set it explicitly ourselves. To that end, we start // the thread "suspended" and release it after setting its priority. setPriority(mPriority); ResumeThread(mThreadH); return TRUE; } else return FALSE; } // Do the real work associated with terminating a WinNT task // The mDataGuard lock should be held upon entry into this method. void OsTaskWnt::doWntTerminateTask(UtlBoolean force) { char idString[30]; //*** BETTER: UtlString idString; BOOL ntResult; OsStatus res; if (mState == UNINITIALIZED) return; // there is no low-level task, just return if (!force) { // We are being well behaved and will wait until the task is no longer // safe from deletes. A task is made safe from deletes by acquiring // a read lock on its mDeleteGuard. In order to delete a task, the // application must acquire a write lock. This will only happen after // all of the read lock holders have released their locks. res = mDeleteGuard.acquireWrite(); assert(res == OS_SUCCESS); } if (mThreadH != NULL) { // Remove the key from the internal task list, before terminating it itoa((int) mThreadId, idString, 10); // convert the id to a string //*** BETTER: getIdString(idString, mThreadId); // convert the id to a string res = OsUtil::deleteKeyValue(TASKID_PREFIX, idString); //before we go ahead and kill the thread, lets make sure it's still running DWORD ExitCode; // KLUDGE ALERT- we need to avoid calling // TerminateThread at all costs. // TerminateThread is VERY VERY dangerous. // Wait for 5 seconds, or until the thread exited // before calling TerminateThread. // attempt to wait for the thread to exit on its own for (int i = 0; i < 50; i++) { GetExitCodeThread( mThreadH,&ExitCode); if (ExitCode != STILL_ACTIVE) { break; } Sleep(100); } if (ExitCode == STILL_ACTIVE) TerminateThread(mThreadH, 0); // first get rid of the thread // ignore the return code since // it's possible the thread has // already terminated ntResult = CloseHandle(mThreadH); // next we close the handle assert(ntResult == TRUE); } mThreadH = 0; mThreadId = 0; mState = UNINITIALIZED; if (!force) { res = mDeleteGuard.releaseWrite(); // release the write lock assert(res == OS_SUCCESS); } } // Function that serves as the starting address for a Windows thread unsigned int __stdcall OsTaskWnt::threadEntry(LPVOID arg) { OsTaskWnt* pTask; pTask = (OsTaskWnt*) arg; // This is a trick for Visual Studio debugger only. SetThreadName(-1, pTask->mName.data()); // Windows uses a different random number generator each // thread. This means that you need to initialized the // random number generator seed in each thread as well // The following is an attempt to create a good seed // for this task. int eTimeInt = OsDateTime::getSecsSinceEpoch(); int taskId; pTask->id(taskId); // Get the lower 16 bits (most varying) of the time and task pointer int lower16Time = eTimeInt % (256 * 256); int lower16Thread = taskId % (256 * 256); // move the lower 16 bits (most varying) of the current time // to the upper 16 bits int lower16TaskPtr = ((intptr_t)pTask) << 16; int randSeed = lower16Time + lower16Thread + lower16TaskPtr; //osPrintf("OsTaskWnt::threadEntry time: %d id: %d task: %d randSeed: %u\n", // lower16Time, lower16Thread, lower16TaskPtr, (unsigned int)randSeed); srand(randSeed); //osPrintf("OsTaskWnt::threadEntry rand: %d threadId: %d epoch: %d ptr: %d\n", // rand(), taskId, eTimeInt, pTask); unsigned int returnCode = pTask->run(pTask->getArg()); // After run returns be sure to mark the thread as shut down pTask->ackShutdown(); return(returnCode); } /* ============================ FUNCTIONS ================================= */ #define MS_VC_EXCEPTION 0x406d1388 typedef struct tagTHREADNAME_INFO { DWORD dwType; // must be 0x1000 LPCSTR szName; // pointer to name (in same addr space) DWORD dwThreadID; // thread ID (-1 caller thread) DWORD dwFlags; // reserved for future use, most be zero } THREADNAME_INFO; /// This is a trick to show thread names in Visual Studio debugger. void SetThreadName(DWORD dwThreadID, LPCTSTR szThreadName) { #if defined(_DEBUG) && defined(_MSC_VER) // [ THREADNAME_INFO info; info.dwType = 0x1000; info.szName = szThreadName; info.dwThreadID = dwThreadID; info.dwFlags = 0; __try { RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(DWORD), (DWORD *)&info); } __except (EXCEPTION_CONTINUE_EXECUTION) { } #endif // _DEBUG && _MSC_VER ] } sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/OsTimerMessage.cpp0000644000175000017500000000054612205613256025237 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include "../src/os/shared/OsTimerMessage.cpp" sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/OsUtilWnt.cpp0000644000175000017500000001277312205613256024265 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/Wnt/OsUtilWnt.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const int MILLISECS_PER_SEC = 1000; const int MICROSECS_PER_MILLISEC = 1000; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ // (rschaaf) A note on manipulating synchronization objects: // For Windows NT, the code used to acquire synchronization objects is common // for binary semaphores, counting semaphores and mutexes. We capture this // common code here to avoid having to duplicate it for each of the // specialized synchronization objects. // // Ideally, I'd like to use inheritance to avoid code duplication in the // derived classes. However, in our object model the Windows NT-specific // classes for binary semaphore, counting semaphore and mutex do not have a // common Windows NT-specific base class. It therefore does not appear to be // possible to use single inheritance to achieve this goal and I am // deliberately avoiding the use (and attendant complications) of multiple // inheritance. // Block the task until the synch obj is acquired or the timeout expires OsStatus OsUtilWnt::synchObjAcquire(const HANDLE synchObj, const OsTime& rTimeout) { DWORD ntRes; DWORD msecsTimer; OsStatus res; if (rTimeout.isInfinite()) msecsTimer = INFINITE; else { assert(OsUtilWnt::isOsTimeValid(rTimeout)); msecsTimer = OsUtilWnt::cvtOsTimeToWntTime(rTimeout); } ntRes = WaitForSingleObject(synchObj, msecsTimer); switch (ntRes) { case 0: res = OS_SUCCESS; break; case WAIT_TIMEOUT: res = OS_WAIT_TIMEOUT; break; case WAIT_ABANDONED: res = OS_WAIT_ABANDONED; break; default: /* osPrintf( "OsUtilWnt::synchObjAcquire: WaitForSingleObject() returned %d,\n" " GetLastError() = %d" "\n\n", ntRes, GetLastError()); */ res = OS_UNSPECIFIED; break; } return res; } // Conditionally acquire the synch obj (i.e., don't block) // Return OS_BUSY if the synch object is held by some other task OsStatus OsUtilWnt::synchObjTryAcquire(const HANDLE synchObj) { OsStatus res; res = OsUtilWnt::synchObjAcquire(synchObj, OsTime::NO_WAIT_TIME); if (res == OS_WAIT_TIMEOUT) return OS_BUSY; else return res; } /* ============================ ACCESSORS ================================= */ // Convert an OsTime to the corresponding number of millisecs for WinNT DWORD OsUtilWnt::cvtOsTimeToWntTime(const OsTime& rTimer) { return (rTimer.seconds() * MILLISECS_PER_SEC) + (rTimer.usecs() / MICROSECS_PER_MILLISEC); } // Convert an abstraction layer task priority to a WinNT thread priority int OsUtilWnt::cvtOsPrioToWntPrio(const int osPrio) { // Map task priority values from the abstraction layer to Win NT as // follows: // 0 THREAD_PRIORITY_HIGHEST // 1 - 85 THREAD_PRIORITY_ABOVE_NORMAL // 86 - 170 THREAD_PRIORITY_NORMAL // 171 - 254 THREAD_PRIORITY_BELOW_NORMAL // 255 THREAD_PRIORITY_LOWEST assert(osPrio >= 0 && osPrio <= 255); if (osPrio == 0) return THREAD_PRIORITY_HIGHEST; else if (osPrio <= 85) return THREAD_PRIORITY_ABOVE_NORMAL; else if (osPrio <= 170) return THREAD_PRIORITY_NORMAL; else if (osPrio <= 254) return THREAD_PRIORITY_BELOW_NORMAL; else return THREAD_PRIORITY_LOWEST; } // Convert a WinNT thread priority to an abstraction layer task priority int OsUtilWnt::cvtWntPrioToOsPrio(const int wntPrio) { int osPrio; switch (wntPrio) { case THREAD_PRIORITY_HIGHEST: osPrio = 0; break; case THREAD_PRIORITY_ABOVE_NORMAL: osPrio = 43; // middle of range from 1 - 85 break; case THREAD_PRIORITY_NORMAL: osPrio = 128; // middle of range from 86 - 170 break; case THREAD_PRIORITY_BELOW_NORMAL: osPrio = 213; // middle of range from 171 - 254 break; case THREAD_PRIORITY_LOWEST: osPrio = 255; break; default: assert(FALSE); // should not happen osPrio = -1; break; } return osPrio; } /* ============================ INQUIRY =================================== */ // Verify that the OsTime is >= 0 and representable in msecs UtlBoolean OsUtilWnt::isOsTimeValid(const OsTime& rTimer) { int secs = rTimer.seconds(); // Assume that the size of an int is 4 bytes assert(sizeof(int) == 4); // Timeout values should be in the future if (secs < 0) return FALSE; // The following test is "<" rather than "<=" since the contribution of // the microseconds portion of rTimer could add another second. return (secs < (0x7FFFFFFF / MILLISECS_PER_SEC)); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/Wnt/WindowsAdapterInfo.cpp0000644000175000017500000003016112205613256026113 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifdef WIN32 #include #include "os/OsDefs.h" #define WIN32_LEAN_AND_MEAN #include #include "os/wnt/WindowsAdapterInfo.h" #include DWORD (WINAPI *GetAdaptersInfo)(PIP_ADAPTER_INFO, PULONG); DWORD (WINAPI *GetNetworkParams)(PFIXED_INFO, PULONG); AdapterInfoRec adapters[MAX_ADAPTERS]; //used to store all the adapters it finds int AdapterCount = 0; /////////////////////////////////////////// // // isIPHLPAvail // returns true if you can call functions in the windows iphlpapi // // // //returns: // true if win98, win2000, winnt (SP4 or above) // // ////////////////////////////////////////// BOOL isIPHLPAvail() { BOOL retval = FALSE; #ifdef WIN32 static BOOL iphlpapi_loaded = 0; //TRUE if already loaded HMODULE hModule = NULL; //handle to the iphlpapi.dll BOOL bIsWindows98 = FALSE; BOOL bIsWindowsNT = FALSE; BOOL bIsWindows2000 = FALSE; OSVERSIONINFO osInfo; char FullDLLPath[256]; LPVOID lpMsgBuf; //for returning error codes if (iphlpapi_loaded) //return true if we already loaded the dll. return TRUE; //try to figure out what version of windows we are running osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (!GetVersionEx(&osInfo)) { osPrintf("Could not retrieve OS version.\n"); exit(1); } //check if it's the right version of windows if (osInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) { if (osInfo.dwMinorVersion > 0) //true if it is 98 bIsWindows98 = TRUE; } else if (osInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) { if (osInfo.dwMajorVersion == 4) { bIsWindowsNT = TRUE; osPrintf("Running windows NT 4.0\n"); } else if (osInfo.dwMajorVersion > 4) { bIsWindows2000 = TRUE; osPrintf("Running windows 2000\n"); } else { osPrintf("Unknown version of windows."); return retval; } } // Get sizing information about network params if (bIsWindows2000 || bIsWindows98) { //first try loading it using the systems path hModule = LoadLibrary("iphlpapi.dll"); if (hModule == NULL) { //if that fails, (it shouldn't), try using the GetSystemPath func GetSystemDirectory(FullDLLPath,sizeof(FullDLLPath)); strcat(FullDLLPath,"\\iphlpapi.dll"); //try again hModule = LoadLibrary(FullDLLPath); //ok, I give up...where the heck did they put the iphlpapi.dll??????? if (hModule == NULL) { osPrintf("Could not load the DLL: iphlpaip.dll (check that it's in your path)\n"); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL); osPrintf("ERROR STRING: %s",(char *)lpMsgBuf); return retval; } } if (hModule) { //now assign the function pointers *(FARPROC*)&GetAdaptersInfo = GetProcAddress(hModule,"GetAdaptersInfo"); if (GetAdaptersInfo == NULL) { osPrintf("Could not get the proc address to GetAdaptersInfo!\n"); return FALSE; } //now find that function! *(FARPROC*)&GetNetworkParams = GetProcAddress(hModule,"GetNetworkParams"); if (GetNetworkParams == NULL) { osPrintf("Could not get the proc address to GetNetworkParams!\n"); return FALSE; } osPrintf("Success loading DLL: iphlpaip.dll\n"); retval = TRUE; iphlpapi_loaded = TRUE; //set flag so we know not to load it again } } #endif return retval; } /////////////////////////////////////////// // // gets the domain name // // returns: 0 on failure 1 on success // // ////////////////////////////////////////// int getWindowsDomainName(char *domain_name) { DWORD Err; DWORD NetworkInfoSize; PFIXED_INFO pNetworkInfo; int retval = 0; *domain_name = '\0'; if (isIPHLPAvail()) //inits iphlpapi and returns true if dll loaded { if (GetNetworkParams != NULL) { //force size to 0 so the GetNetworkParams gets the correct size NetworkInfoSize = 0; if( ( Err = GetNetworkParams( NULL, &NetworkInfoSize ) ) != 0 ) { if( Err != ERROR_BUFFER_OVERFLOW ) { printf( "GetNetworkParams sizing failed with error %d\n", Err ); return 0; } } // Allocate memory from sizing information if( ( pNetworkInfo = (PFIXED_INFO)GlobalAlloc( GPTR, NetworkInfoSize ) ) == NULL ) { printf( "Memory allocation error\n" ); return 0; } // Get actual network params if( ( Err = GetNetworkParams( pNetworkInfo, &NetworkInfoSize ) ) != 0 ) { printf( "GetNetworkParams failed with error %d\n", Err ); return 0; } strcpy(domain_name, pNetworkInfo->DomainName); //free the memory GlobalFree(pNetworkInfo); // handle to global memory object } } return retval; } /////////////////////////////////////////// // // lookupIpAddressByMacAddress // // // mac_address: the mac address for which you want the ipaddress for // //returns: // ipaddress is the address for the given mac address // // -1 is returned if adapters could not be found // 0 is returned on SUCCESS // ////////////////////////////////////////// int lookupIpAddressByMacAddress(char *mac_address, char *ipaddress) { int retval = -1; for (int loop = 0; loop < AdapterCount; loop++) { if (memicmp(adapters[loop].MacAddress,mac_address,strlen(mac_address)) == 0) { strcpy(ipaddress,adapters[loop].IpAddress); retval = 0; } } return retval; } /////////////////////////////////////////// // // getAdaptersInfo // // // iInterface: the interface for which you want the ipaddress for // pIpAddress: ip address returned. // // // returns 0 on failure or number of adapters available // 0 is returned if there are no adapters available. // ////////////////////////////////////////// int getAdaptersInfo() { char MacAddressStr[256]; //mac address converted to a string char MacOneByteStr[10]; //used to hold one byte of mac address int retval = 0; //return -1 if no adapters found if (isIPHLPAvail()) //inits iphlpapi and returns true if dll loaded { //just return count if we already did this before if (AdapterCount) return AdapterCount; IP_ADAPTER_INFO *pAdapterInfo; //points to buffer hold linked list adapter info DWORD dwSize = (sizeof(IP_ADAPTER_INFO) * MAX_ADAPTERS) + sizeof(DWORD); //size for lots of adapters char *buffer = new char[dwSize]; //allocate space for lots of adapters if (buffer) { pAdapterInfo = (IP_ADAPTER_INFO *)buffer; //point to buffer if (GetAdaptersInfo( pAdapterInfo, // buffer for mapping table &dwSize) == NO_ERROR) // sort the table { while (pAdapterInfo) { strcpy(adapters[AdapterCount].AdapterName, pAdapterInfo->Description); strcpy(adapters[AdapterCount].IpAddress, (const char *)pAdapterInfo->IpAddressList.IpAddress.String); //build mac address as a string *MacAddressStr = '\0'; for (unsigned int loop = 0; loop < pAdapterInfo->AddressLength; loop++) { if (strlen(MacAddressStr)) strcat(MacAddressStr,"-"); sprintf(MacOneByteStr,"%02X",pAdapterInfo->Address[loop]); strcat(MacAddressStr,MacOneByteStr); } strcpy((char *)adapters[AdapterCount].MacAddress, MacAddressStr); AdapterCount++; pAdapterInfo = pAdapterInfo->Next; } retval = AdapterCount; } delete [] buffer; } } return retval; } /* void main(int argc, char **argv) { int numInterfaces = getAdaptersInfo(); printf("Number of interfaces: %d\n\n",numInterfaces); for (int loop = 0; loop < numInterfaces; loop ++) { printf("adapter name : %s \n",adapters[loop].AdapterName); printf("IP address : %s \n",adapters[loop].IpAddress); printf("MAC address : %s \n",adapters[loop].MacAddress); } printf("\n\n"); char ipAddress[256]; for (int loop2 = 0; loop2 < AdapterCount;loop2++) { printf("Looking up mac address %s\n",adapters[loop2].MacAddress); if (lookupIpAddressByMacAddress((char *)adapters[loop2].MacAddress,ipAddress) == 0) printf("Found IP Address: %s \n",ipAddress); else printf("Could not find mac address!\n"); } } */ #endif //WIN32 sipxtapi-3.3.0~test17/sipXportLib/src/os/NatMsg.cpp0000644000175000017500000000447212205613256022773 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/NatMsg.h" NatMsg::NatMsg(int type, char* szBuffer, int nLength, IStunSocket* pSocket, UtlString receivedIp, int iReceivedPort) : OsMsg(NAT_MSG_TYPE, 0) { miType = type ; mBuffer = szBuffer ; // Shallow copy mLength = nLength ; mpSocket = pSocket ; mReceivedIp = receivedIp ; miReceivedPort = iReceivedPort ; mpContext = NULL ; } NatMsg::NatMsg(int type, void* pContext) : OsMsg(NAT_MSG_TYPE, 0) { miType = type ; mBuffer = NULL ; mLength = 0; mpSocket = NULL ; mReceivedIp.remove(0) ; miReceivedPort = 0 ; mpContext = pContext ; } NatMsg::NatMsg(const NatMsg& rNatMsg) : OsMsg(NAT_MSG_TYPE, 0) { miType = rNatMsg.miType ; mBuffer = rNatMsg.mBuffer ; mLength = rNatMsg.mLength ; mpSocket = rNatMsg.mpSocket ; mReceivedIp = rNatMsg.mReceivedIp ; miReceivedPort = rNatMsg.miReceivedPort ; mpContext = rNatMsg.mpContext ; } OsMsg* NatMsg::createCopy(void) const { return new NatMsg(*this); } NatMsg::~NatMsg() { } NatMsg& NatMsg::operator=(const NatMsg& rhs) { if (this != &rhs) // handle the assignment to self case { miType = rhs.miType ; mBuffer = rhs.mBuffer ; mLength = rhs.mLength ; mpSocket = rhs.mpSocket ; mReceivedIp = rhs.mReceivedIp ; miReceivedPort = rhs.miReceivedPort ; mpContext = rhs.mpContext ; } return *this ; } char* NatMsg::getBuffer() const { return mBuffer ; } int NatMsg::getLength() const { return mLength ; } IStunSocket* NatMsg::getSocket() const { return mpSocket ; } UtlString NatMsg::getReceivedIp() const { return mReceivedIp ; } int NatMsg::getReceivedPort() const { return miReceivedPort ; } int NatMsg::getType() const { return miType ; } void* NatMsg::getContext() const { return mpContext ; } sipxtapi-3.3.0~test17/sipXportLib/src/os/OsAssert.c0000644000175000017500000001403212205613256022776 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifdef _VXWORKS /* [ */ /* SYSTEM INCLUDES */ #include #include #include /* APPLICATION INCLUDES */ #include "os/OsAssert.h" #undef BUILDING_FOR_TORNADO_2_2 #if CPU == ARMSA110 /* Tornado 2.0 */ #undef BUILDING_FOR_TORNADO_2_2 #elif (CPU == ARMARCH4) || (CPU == STRONGARM) /* Tornado 2.0.1 */ #undef BUILDING_FOR_TORNADO_2_2 #elif (CPU == XSCALE) /* Tornado 2.2.0 */ #define BUILDING_FOR_TORNADO_2_2 #elif (CPU == MIPS32) /* Tornado 2.2.x */ #undef BUILDING_FOR_TORNADO_2_2 #else #error Unexpected CPU value #endif #undef BUILDING_FOR_TORNADO_2_2 /* EXTERNAL FUNCTIONS */ /* EXTERNAL VARIABLES */ /* CONSTANTS */ /* STATIC VARIABLE INITIALIZATIONS */ static volatile int actionOnAssert = OS_ASSERT_SUSPEND; /* FUNCTIONS */ /**************************************************************************** * This is an improved version of the corresponding VxWorks function. * Note: (rschaaf) 09/06/99 * This function is defined in the top-level directory of the * os library (.../src/os) rather than in the VxWorks specific * subdirectory (.../src/os/vxw) to make it easier to build a * version of the VxWorks kernel that uses the improved __assert() * function and optionally allows the Pinger application to be linked * in with the kernel. * * The somewhat complicated for doing this is described below. * * 1) Building the VxWorks kernel presently entails linking it with a * number of library files that are mostly specific to the Pinger * application. When the Pinger application is not being linked * with the kernel, these application-specific libraries are largely * ignored. The one exception is the definition of the __assert() * function. * 2) The os library is built in such a way that all of the * platform-specific definitions (e.g., for VxWorks, all of * src/os/vxw/?*.o) are combined into a single object module. * * If the __assert() function were defined in the VxWorks object * module, linking with the kernel would cause all of the other * definitions in that object module (and their unresolved references) * to also be pulled in. The unresolved references, in turn, would * cause more stuff from other application-specific libraries to be * included in the VxWorks kernel. * * We avoid this by defining the __assert() function in its own source * file in the .../src/os directory. It can therefore be included * independently of the other application-specific portions of the * VxWorks support for the OS abstraction layer. ***************************************************************************/ static int numberOfAsserts = 0; #ifdef BUILDING_FOR_TORNADO_2_2 /* [ */ static volatile int* dataAbort = (volatile int*) 0x09000000; static int lastAssertTask = 0; #endif /* BUILDING_FOR_TORNADO_2_2 ] */ int assertCount(void) {return numberOfAsserts;} void __takeAssertAction(int secondsToWait) { int Hz = sysClkRateGet(); if (OS_ASSERT_REBOOT == actionOnAssert) { while ((OS_ASSERT_REBOOT == actionOnAssert) && (secondsToWait-- > 0)) { taskDelay(Hz); /* wait one second */ } if (OS_ASSERT_REBOOT == actionOnAssert) { sysToMonitor(0); } } } void __assert(const char *msg) { /* The user can set the PHONESET_ASSERT_ACTION to RESTART or SUSPEND * the default (which is set in initConfigDb) is to restart */ taskLock(); numberOfAsserts++; #ifdef BUILDING_FOR_TORNADO_2_2 /* [ */ lastAssertTask = taskIdSelf(); #endif /* BUILDING_FOR_TORNADO_2_2 ] */ taskUnlock(); fdprintf(2, "\n\n(Task: '%s', TaskId: 0x%X)\n %s\n", taskName(0), taskIdSelf(), msg); __takeAssertAction(60); #ifdef BUILDING_FOR_TORNADO_2_2 /* [ */ { int iiii; iiii = *dataAbort; } #else /* BUILDING_FOR_TORNADO_2_2 ] [ */ taskSuspend(taskIdSelf()); #endif /* BUILDING_FOR_TORNADO_2_2 ] */ fdprintf(2, "\n *** RESUMING *** (Task: '%s', TaskId: 0x%X) %s\n" " Good Luck, you're probably gonna need it!!!!", taskName(0), taskIdSelf(), msg); } int OsAssert_SetFailureAction(int action) { int save = actionOnAssert; if (OS_ASSERT_ALWAYS_SUSPEND == actionOnAssert) return save; if ((OS_ASSERT_REBOOT == action) || (OS_ASSERT_SUSPEND == action) || (OS_ASSERT_ALWAYS_SUSPEND == action)) { actionOnAssert = action; } else { actionOnAssert = OS_ASSERT_SUSPEND; __assert( "\n\n ** WARNING: Invalid argument to OsAssert_SetFailureAction()\n"); } return save; } int NoAssertReboot() /* Console Commands */ { return OsAssert_SetFailureAction(OS_ASSERT_ALWAYS_SUSPEND); } int NAR() {return NoAssertReboot();} #ifdef BUILDING_FOR_TORNADO_2_2 /* [ */ int bumpAssertPC(int tid, int resume) { STATUS stat; REG_SET Regs; REG_SET* pRegs = &Regs; if (0 != (tid & 3)) { if (0 != lastAssertTask) { printf("most recently asserted task is 0x%X ('%s')\n", lastAssertTask, taskName(lastAssertTask)); } else { printf("no recently asserted task\n"); } return lastAssertTask; } if (0 == tid) tid = lastAssertTask; if (VX_OK == (stat = taskRegsGet(tid, pRegs))) { (int) (Regs.pc) = (int) (Regs.pc) + 4; stat = taskRegsSet(tid, pRegs); if (resume) { stat = taskResume(tid); if (lastAssertTask == tid) lastAssertTask = 0; } } else { printf("taskRegs(0x%0x, 0x%0x) returned %d!\n", tid, (int) pRegs, stat); } return stat; } int bAP(int tid, int resume) {return bumpAssertPC(tid, resume);} int bAPC(int tid, int resume) {return bumpAssertPC(tid, resume);} #endif /* BUILDING_FOR_TORNADO_2_2 ] */ #endif /* _VXWORKS ] */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsCallback.cpp0000644000175000017500000000337512205613256023601 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsCallback.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // Event notification method where a callback function is executed in the // Notifier's context when the corresponding event occurs. /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsCallback::OsCallback(const intptr_t userData, const OsCallbackFunc func) : mFunc(func), mUserData(userData) { // all work is done by the initializers, no other work required } // Destructor OsCallback::~OsCallback() { // no work required } /* ============================ MANIPULATORS ============================== */ // Signal the occurrence of the event by executing the callback function. // Always return OS_SUCCESS. OsStatus OsCallback::signal(const intptr_t eventData) { mFunc(mUserData, eventData); // execute the callback function return OS_SUCCESS; } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsConfigDb.cpp0000644000175000017500000007305712205613256023564 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #include #include #include // APPLICATION INCLUDES #include "os/OsConfigDb.h" #include "os/OsReadLock.h" #include "os/OsWriteLock.h" #include "os/OsStatus.h" #include "os/OsUtil.h" #include "os/OsFS.h" #include "os/OsSysLog.h" #include "os/OsConfigEncryption.h" #include "utl/UtlSortedListIterator.h" #include "utl/UtlSList.h" #include "utl/UtlSListIterator.h" #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define MAX_FILELINE_SIZE 1024 #define DB_LINE_FORMAT "%s : %s\r\n" // STATIC VARIABLE INITIALIZATIONS static OsConfigEncryption *gEncryption = NULL; const UtlContainableType DbEntry::TYPE = "DbEntry"; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Default Constructor OsConfigDb::OsConfigDb() : mRWMutex(OsRWMutex::Q_PRIORITY), mDb(), mCapitalizeName(FALSE) { } // Destructor OsConfigDb::~OsConfigDb() { OsWriteLock lock(mRWMutex); // take lock for writing mDb.destroyAll(); } /* ============================ MANIPULATORS ============================== */ OsStatus OsConfigDb::loadFromFile(const char *filename) { if (filename == NULL) { return OS_INVALID_ARGUMENT; } OsStatus retval = OS_UNSPECIFIED; OsWriteLock lock(mRWMutex); // take lock for writing while the database // is loaded setIdentityLabel(filename); OsConfigEncryption *encryption = getEncryption(); if (encryption != NULL && encryption->isNormallyEncrypted(this)) { retval = loadFromEncryptedFile(filename); } else { FILE *fp = fopen(filename,"rb"); if (fp) { retval = loadFromUnencryptedFile(fp); fclose(fp); } } return retval; } void OsConfigDb::dump() { for (unsigned int i = 0; i < mDb.entries(); i++) { DbEntry *e = (DbEntry *)mDb.at(i); osPrintf(DB_LINE_FORMAT, e->key.data(), e->value.data()); } } // Buffer CANNOT be encrypted OsStatus OsConfigDb::loadFromBuffer(const char *buff) { if (buff == NULL) return OS_INVALID_ARGUMENT; OsWriteLock lock(mRWMutex); // take lock for writing while the database // is loaded return loadFromUnencryptedBuffer(buff); } OsStatus OsConfigDb::loadFromFile(FILE* fp) { OsWriteLock lock(mRWMutex); // take lock for reading while the database // is stored // TODO: Support encrypted files loaded via FILE instance. Note however, this is // of little use because no file name is generally known and encryption/decryption // rules generally rely on this. If callers know the filename, try calling // loadFromFile with filename return loadFromUnencryptedFile(fp); } // Undo the previous hack # if defined(_VXWORKS) # undef OK # endif UtlBoolean OsConfigDb::parseLine(const char* fileLine, UtlBoolean capitalizeName, const char* fileLabel, UtlString& parameterName, UtlString& parameterValue) { UtlBoolean isParameter = FALSE; /* Format of a config line is: * whitespace name whitespace : whitespace value whitespace EOL */ const char* p = fileLine; // Scanning pointer. // Skip initial white space. while (*p != '\0' && isspace(*p)) { p++; } // If the first non-whitespace character is '#', this is a comment line. // Similarly, if it is NUL, this line is empty. // In either case, ignore this line. if (*p != '#' && *p != '\0') { // Save start of name. const char* name_start = p; // The name continues till EOL, whitespace, or colon. while (*p != '\0' && !isspace(*p) && *p != ':') { p++; } // Save length of name. ptrdiff_t name_len = p - name_start; // If the found name is null, do nothing. // (Probably due to an empty line.) if (name_len != 0) { // Skip whitespace. while (*p != '\0' && isspace(*p)) { p++; } // Skip colon, if any. // (There should be a colon, but if the line's format is bad, // it might not be there.) if (*p == ':') { p++; // Skip whitespace. while (*p != '\0' && isspace(*p)) { p++; } // Save start of value. const char* value_start = p; // Scan string back from the end skipping whitespace. p = fileLine + strlen(fileLine); while (p > value_start && isspace(p[-1])) { p--; } // Save length of value. ptrdiff_t value_len = p - value_start; // Construct UtlString's, which insertEntry(*, *) needs as arguments. UtlString name(name_start, name_len); UtlString value(value_start, value_len); if(!name.isNull() || !value.isNull()) { isParameter = TRUE; } // Capitalize the name if required. if (capitalizeName) { name.toUpper(); } parameterName = name; parameterValue = value; // Insert the entry. //insertEntry(name, value); } else { // The colon was not found. OsSysLog::add(FAC_KERNEL, PRI_CRIT, "Invalid config line format in file '%s', " "no colon found: '%s'", fileLabel, fileLine); } } else { // The colon was not found. OsSysLog::add(FAC_KERNEL, PRI_CRIT, "Invalid config line format in file '%s', " "name is missing: '%s'", fileLabel, fileLine); } } return(isParameter); } void OsConfigDb::setCapitalizeName(UtlBoolean capitalizeName) { mCapitalizeName = capitalizeName; } OsStatus OsConfigDb::updateFile(const char* filename) const { UtlString originalFileContents; long fileLength = OsFile::openAndRead(filename, originalFileContents); const char* unparsedBits = originalFileContents; int unparsedLength = originalFileContents.length(); // Loop through and try to preserve comments, space and order int lineStart = 0; int lineEnd = 0; UtlHashBag writtenNames; UtlString newFileContents; UtlString name; UtlString value; UtlString newValue; while(lineStart < unparsedLength) { lineEnd = UtlTokenizer::nextDelim(unparsedBits, lineStart, unparsedLength, "\n\r"); //printf("start: %d end: %d length: %d\n", lineStart, lineEnd, unparsedLength); UtlString oneLine(&unparsedBits[lineStart], lineEnd - lineStart); //printf("Line: <%s>\n", oneLine.data()); // If line contains a parameter if(parseLine(oneLine, mCapitalizeName, filename, name, value)) { //printf("name<%s> value<%s>\n", name.data(), value.data()); if(get(name, newValue) == OS_SUCCESS && !writtenNames.contains(&name)) { //printf("Wrote name<%s>\n", name.data()); // The parameter still exists in the configDb and we have not yet // written it out, write the potentially changed value newFileContents.appendFormat("%s : %s\n", name.data(), newValue.data()); // Save names/parameters written so that we can figure out what has not // been written out writtenNames.insert(new UtlString(name)); } // else the parameter was removed, do nothing } // The line was a comment or blank line, write it back out the same else { newFileContents.appendFormat("%s\n", oneLine.data()); } lineStart = lineEnd + 1; } int paramIndex; int paramCount = numEntries(); DbEntry* paramEntry; for (paramIndex = 0; paramIndex < paramCount; paramIndex++) { paramEntry = (DbEntry*) mDb.at(paramIndex); removeNewlineReturns(paramEntry->key); removeNewlineReturns(paramEntry->value); // We have not written the value yet if(!writtenNames.contains(&(paramEntry->key))) { newFileContents.appendFormat("%s : %s\n", paramEntry->key.data(), paramEntry->value.data()); writtenNames.insert(new UtlString(paramEntry->key)); } } fileLength = OsFile::openAndWrite(filename, newFileContents); writtenNames.destroyAll(); return(fileLength > 0 ? OS_SUCCESS : OS_INVALID_ARGUMENT); } OsStatus OsConfigDb::storeToFile(const char *filename) { if (filename == NULL) { return OS_INVALID_ARGUMENT; } OsStatus retval = OS_UNSPECIFIED; OsReadLock lock(mRWMutex); // take lock for writing while the database // is loaded setIdentityLabel(filename); OsConfigEncryption *encryption = getEncryption(); if (encryption != NULL && encryption->isWriteEncryptedEnabled() && encryption->isNormallyEncrypted(this)) { retval = storeToEncryptedFile(filename); } else { FILE *fp = fopen(filename,"wb"); if (!fp) { osPrintf("Could not open %s. errno = %d\n",filename,errno); return retval; } retval = storeToFile(fp); fclose(fp); } return retval; } // Remove the key/value pair associated with rKey. // Return OS_SUCCESS if the key was found in the database, return // OS_NOT_FOUND otherwise. OsStatus OsConfigDb::remove(const UtlString& rKey) { OsWriteLock lock(mRWMutex); DbEntry lookupPair(rKey); DbEntry* pEntryToRemove; size_t i = mDb.index(&lookupPair); if (i == UTL_NOT_FOUND) { return OS_NOT_FOUND; } else { pEntryToRemove = (DbEntry *)mDb.at(i); mDb.removeAt(i); delete pEntryToRemove; return OS_SUCCESS; } } // Remove all the key/value pairs starting with the designated prefix OsStatus OsConfigDb::removeByPrefix(const UtlString& rPrefix) { OsWriteLock lock(mRWMutex); DbEntry* pEntry ; UtlSortedListIterator itor(mDb) ; while ((pEntry = (DbEntry*) itor())) { if (pEntry->key.length() >= rPrefix.length()) { UtlString keyPrefix = pEntry->key ; keyPrefix.remove(rPrefix.length()) ; if (keyPrefix.compareTo(rPrefix, UtlString::ignoreCase) == 0) { remove(pEntry->key) ; } } } return OS_SUCCESS ; } // Insert the key/value pair into the config database. // If the database already contains an entry for this key, then replace it // with the new key/value pair. void OsConfigDb::set(const UtlString& rKey, const UtlString& rNewValue) { OsWriteLock lock(mRWMutex); if (rKey.length() > 0) { insertEntry(rKey, rNewValue); } } // Insert the key/value pair into the config database If the // database already contains an entry for this key, then set the // value for the existing entry to iNewValue. void OsConfigDb::set(const UtlString& rKey, const int iNewValue) { UtlString newValue ; // Convert to String char cTemp[64] ; sprintf(cTemp, "%d", iNewValue); // Set newValue = cTemp ; set(rKey, newValue) ; } /* ============================ ACCESSORS ================================= */ void OsConfigDb::setIdentityLabel(const char *idLabel) { if (idLabel != NULL) { mIdentityLabel = idLabel; //strncpy(mIdentityLabel, idLabel, sizeof(mIdentityLabel)); } else { mIdentityLabel.resize(0); } } // filename, url, etc that would help identity the source of this config // return NULL if no idenity was set const char *OsConfigDb::getIdentityLabel() const { return mIdentityLabel.data(); } // Encryption Rules for this instance. // SUBCLASS NOTE: no setter method, requires subclassing to override instance // only rules OsConfigEncryption *OsConfigDb::getEncryption() const { return getStaticEncryption(); } // Set encryption Rules for all instances void OsConfigDb::setStaticEncryption(OsConfigEncryption *encryption) { gEncryption = encryption; } // Get encryption Rules for all instances OsConfigEncryption *OsConfigDb::getStaticEncryption() { return gEncryption; } // Sets rValue to the value in the database associated with rKey. // If rKey is found in the database, returns OS_SUCCESS. Otherwise, // returns OS_NOT_FOUND and sets rValue to the empty string. OsStatus OsConfigDb::get(const UtlString& rKey, UtlString& rValue) const { OsReadLock lock(mRWMutex); DbEntry lookupPair(rKey); DbEntry* pEntry; size_t i = mDb.index(&lookupPair); if (i == UTL_NOT_FOUND) { rValue = ""; // entry not found return OS_NOT_FOUND; } else { pEntry = (DbEntry *)mDb.at(i); rValue = pEntry->value; } return OS_SUCCESS; } // Gets a db subset of name value pairs which have the given hashSubKey as // a prefix for the key OsStatus OsConfigDb::getSubHash(const UtlString& rHashSubKey, OsConfigDb& rSubDb) const { UtlSortedListIterator itor(const_cast(mDb)); DbEntry* entry; // Skip the initial entries in the list that do not match. while ((entry = static_cast (itor()))) { if (strncmp(entry->key.data(), rHashSubKey.data(), rHashSubKey.length()) >= 0) { break; } } // Process the entries in the list that do match. for (; entry && strncmp(entry->key.data(), rHashSubKey.data(), rHashSubKey.length()) == 0; entry = static_cast (itor())) { // Construct and add the entry to the subhash. // Make temporary UtlString, because that's what insertEntry demands // as an argument. UtlString key(&entry->key.data()[rHashSubKey.length()]); rSubDb.insertEntry(key, entry->value); } return OS_SUCCESS; } // Sets rValue to the value in the database associated with rKey. // If rKey is found in the database, returns OS_SUCCESS. Otherwise, // returns OS_NOT_FOUND and sets rValue to -1. OsStatus OsConfigDb::get(const UtlString& rKey, int& rValue) const { UtlString value; OsStatus returnStatus = get(rKey, value); if(returnStatus == OS_SUCCESS) { rValue = atoi(value.data()); } else { rValue = -1; } value.remove(0); return(returnStatus); } // Relative to rKey, return the key and value associated with // next (lexicographically ordered) key/value pair stored in the // database. If rKey is the empty string, key and value associated // with the first entry in the database will be returned. // Returns // OS_SUCCESS if there is a "next" entry // OS_NOT_FOUND if rKey is not found in the database and is not the // empty string // OS_NO_MORE_DATA if there is no "next" entry OsStatus OsConfigDb::getNext(const UtlString& rKey, UtlString& rNextKey, UtlString& rNextValue) const { OsReadLock lock(mRWMutex); UtlBoolean foundMatch; size_t nextIdx = 0; DbEntry lookupPair(rKey); DbEntry* pEntry; foundMatch = FALSE; if (rKey.compareTo("") == 0) { foundMatch = TRUE; // if the key is the empty string, then nextIdx = 0; // return the first entry in the database } else { size_t idx = mDb.index(&lookupPair); if (idx != UTL_NOT_FOUND) { foundMatch = TRUE; nextIdx = idx + 1; } } if (foundMatch && (((int)nextIdx) < numEntries())) { pEntry = (DbEntry *)mDb.at(nextIdx); rNextKey = pEntry->key; rNextValue = pEntry->value; return OS_SUCCESS; } rNextKey = ""; rNextValue = ""; if (!foundMatch) return OS_NOT_FOUND; else return OS_NO_MORE_DATA; } // Stores a list of strings to the configuration datadase using the // designated prefix as the base for the list items. void OsConfigDb::addList(const UtlString& rPrefix, UtlSList& rList) { OsWriteLock lock(mRWMutex); size_t iNumEntries ; UtlString key ; UtlString* pValue ; // First remove all items start with the specified prefix removeByPrefix(rPrefix) ; // Next add all of the new items iNumEntries = rList.entries() ; if (iNumEntries > 0) { key = rPrefix ; key.append(".COUNT") ; set(key, iNumEntries) ; UtlSListIterator itor(rList) ; int iCount = 1 ; char cTemp[64] ; while ((pValue = (UtlString*) itor())) { sprintf(cTemp, "%d", iCount++); key = rPrefix ; key.append(".") ; key.append(cTemp) ; set(key, *pValue) ; } } } // Loads a list of strings from the configuration datadase using the // designated prefix as the base for the list items. int OsConfigDb::loadList(const UtlString& rPrefix, UtlSList& rList) const { OsReadLock lock(mRWMutex); int iNumEntries ; int rc = 0 ; UtlString key ; UtlString value ; char cTemp[64] ; // Get number of items key = rPrefix ; key.append(".COUNT") ; if (get(key, iNumEntries) == OS_SUCCESS) { for (int i = 0; i < iNumEntries; i++) { sprintf(cTemp, "%d", i+1); key = rPrefix ; key.append(".") ; key.append(cTemp) ; if (get(key, value) == OS_SUCCESS) { rList.append(new UtlString(value)) ; rc++ ; } } } return rc ; } // Get a port number from the configuration database int OsConfigDb::getPort(const char* szKey) const { assert(szKey) ; UtlString value ; int port = PORT_NONE ; if (get(szKey, value) == OS_SUCCESS) { // If the value is null, leave port == PORT_NONE. if (value.length()) { if (value.compareTo("DEFAULT", UtlString::ignoreCase) == 0) { port = PORT_DEFAULT; } else if (value.compareTo("NONE", UtlString::ignoreCase) == 0) { port = PORT_NONE; } else { port = atoi(value.data()); if (!portIsValid(port)) { port = PORT_NONE; OsSysLog::add(FAC_KERNEL, PRI_CRIT, "Invalid port number value '%s' for config variable '%s' in file '%s'.", value.data(), szKey, mIdentityLabel.data()); } } } } return port ; } // Delete all entries from the configuration database void OsConfigDb::clear() { OsReadLock lock(mRWMutex); while (mDb.entries() > 0) { DbEntry *e = (DbEntry *)mDb.at(0); mDb.removeAt(0) ; delete e ; } } /* ============================ INQUIRY =================================== */ // Return TRUE if the database is empty, otherwise FALSE. UtlBoolean OsConfigDb::isEmpty(void) const { OsReadLock lock(mRWMutex); return (mDb.entries() == 0); } // Return the number of entries in the config database int OsConfigDb::numEntries(void) const { OsReadLock lock(mRWMutex); return mDb.entries(); } void OsConfigDb::storeToBuffer(char *buff) const { char *p = buff; int n = numEntries(); for (int i = 0; i < n; i++) { DbEntry *pEntry = (DbEntry *)mDb.at(i); removeChars(&pEntry->key, '\r'); removeChars(&pEntry->value, '\n'); sprintf(p, DB_LINE_FORMAT, (char *)pEntry->key.data(), (char *)pEntry->value.data()); p = buff + strlen(buff); } } // important that it be big enough, not so important it's exact int OsConfigDb::calculateBufferSize() const { int n = numEntries(); size_t size = n * strlen(DB_LINE_FORMAT); for (int i = 0; i < n; i++) { DbEntry *pEntry = (DbEntry *)mDb.at(i); size += pEntry->key.length() + pEntry->value.length(); } return size; } void OsConfigDb::removeChars(UtlString *s, char c) { size_t x = 0; while (x != UTL_NOT_FOUND) { x = s->first(c); if (x != UTL_NOT_FOUND) { s->remove(x, 1); } } } /* //////////////////////////// PROTECTED ///////////////////////////////// */ // write buffer to disk, replace existing file OsStatus OsConfigDb::storeBufferToFile(const char *filename, const char *buff, unsigned long buffLen) { OsStatus retval = OS_FAILED; if (buff != NULL && buffLen > 0) { UtlString filepath(filename); if (OsFileSystem::exists(filepath)) { OsFileSystem::remove(filepath); OsFile file(filepath); file.open(OsFile::CREATE); unsigned long writtenLen; file.write(buff, buffLen, writtenLen); file.close(); if (writtenLen == buffLen) { retval = OS_SUCCESS; } } } return retval; } OsStatus OsConfigDb::storeToEncryptedFile(const char *filename) { OsStatus retval = OS_SUCCESS; // store to buffer size_t buffLen = calculateBufferSize(); char *buff = new char[buffLen]; storeToBuffer(buff); buffLen = strlen(buff); OsEncryption e; retval = getEncryption()->encrypt(this, &e, buff, buffLen); if (retval == OS_SUCCESS) { retval = storeBufferToFile(filename, (const char *)e.getResults(), e.getResultsLen()); } return retval; } // Store the config database to a file OsStatus OsConfigDb::storeToFile(FILE* fp) { OsStatus retval = OS_SUCCESS; int i; int cnt; DbEntry* pEntry; // step through the database writing out one entry per line // each entry is of the form "%s: %s\n" cnt = numEntries(); for (i=0; i < cnt; i++) { pEntry = (DbEntry *)mDb.at(i); removeNewlineReturns(pEntry->key); removeNewlineReturns(pEntry->value); fprintf(fp, "%s : %s\r\n", (char*) pEntry->key.data(), (char*) pEntry->value.data()); } fflush(fp); // The following line probably should never have been here. // It was causing segfaults under Linux, and it should have // on VxWorks and Windows NT as well. //fclose(fp); return retval; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ void OsConfigDb::removeNewlineReturns(UtlString& stringData) { //remove any \n or \r at the ends of the lines size_t remove_char_loc = 0; while (remove_char_loc != UTL_NOT_FOUND) { remove_char_loc = stringData.first('\r'); if (remove_char_loc != UTL_NOT_FOUND) { stringData.remove(remove_char_loc,1); } } remove_char_loc = 0; while (remove_char_loc != UTL_NOT_FOUND) { remove_char_loc = stringData.first('\n'); if (remove_char_loc != UTL_NOT_FOUND) { stringData.remove(remove_char_loc,1); } } } OsStatus OsConfigDb::loadFromEncryptedFile(const char *file) { OsStatus retval = OS_UNSPECIFIED; if (file == NULL) { return retval; } OsFile osfile(file); retval = osfile.open(OsFile::READ_ONLY); if (retval == OS_SUCCESS) { unsigned long buffLen = 0; osfile.getLength(buffLen); char *buff = new char[buffLen + 1]; memset(buff, 0, buffLen + 1); unsigned long bytesRead; retval = osfile.read(buff, buffLen, bytesRead); if (bytesRead != buffLen || retval != OS_SUCCESS) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "Error reading config file or \ mismatch in expected size %s\n", getIdentityLabel()); retval = OS_FAILED; } else { retval = loadFromEncryptedBuffer(buff, buffLen); } delete [] buff; osfile.close(); } return retval; } // Load the configuration database from a file OsStatus OsConfigDb::loadFromUnencryptedFile(FILE* fp) { //int result; //char name[81]; //char value[81]; char fileLine[MAX_FILELINE_SIZE + 1]; OsStatus retval = OS_SUCCESS; // The following #define is needed in order for the feof() macro to work // properly under VxWorks # if defined(_VXWORKS) # define OK VX_OK # endif UtlString name; UtlString value; // step through the file reading one entry per line // each entry is of the form "%s: %s\n" while (!feof(fp)) { //result = fscanf(fp, "%80s : %80s", name, value); //if (result == 2) if(fgets(fileLine, MAX_FILELINE_SIZE, fp)) { if(parseLine(fileLine, mCapitalizeName, mIdentityLabel, name, value)) { insertEntry(name, value); } } else if(ferror(fp)) { perror("OsConfigDb::loadFromFile read error"); retval = OS_UNSPECIFIED; break; } } return retval; } OsStatus OsConfigDb::loadFromEncryptedBuffer(char *buf, int bufLen) { OsStatus retval = OS_SUCCESS; if (getEncryption()->isEncrypted(this, (const char *)buf, bufLen)) { OsEncryption e; getEncryption()->decrypt(this, &e, buf, bufLen); if (getEncryption()->isEncrypted(this, (const char *)e.getResults(), e.getResultsLen())) { // if decryption did not produce an unencrypted version // then probably bad password, or test for encryption is bad // to distinguish internal errors from bad password, use unauthorized retval = OS_UNAUTHORIZED; } else { // yes it's null terminated retval = loadFromUnencryptedBuffer((const char*)e.getResults()); } } else if (retval == OS_SUCCESS) { retval = loadFromUnencryptedBuffer((const char*)buf); } return retval; } OsStatus OsConfigDb::loadFromUnencryptedBuffer(const char *buf) { if (buf == NULL) return OS_INVALID_ARGUMENT; char configLine[MAX_FILELINE_SIZE + 1]; OsStatus retval = OS_SUCCESS; UtlString config = UtlString(buf); // The following #define is needed in order for the feof() macro to work // properly under VxWorks # if defined(_VXWORKS) # define OK VX_OK # endif // step through the file writing out one entry per line // each entry is of the form "%s: %s\n" size_t start = 0; size_t size ; size_t pos; UtlString name; UtlString value; while (1) { pos = config.first('\n'); if ((pos != UTL_NOT_FOUND) || (pos == UTL_NOT_FOUND && !config.isNull())) { if (pos == UTL_NOT_FOUND) { pos = config.length(); } // Do not allow lines greater than MAX_FILELINE_SIZE size = pos; if (size > MAX_FILELINE_SIZE) { #ifdef TEST osPrintf("Warning: max line length exceeded in config db file"); #endif //TEST size = MAX_FILELINE_SIZE; } strncpy(configLine, config.data(), size) ; configLine[size] = 0 ; start = pos + 1; size_t len = config.length(); if (len > start) config = config(start, len - start); else config = OsUtil::NULL_OS_STRING; if (strlen(configLine) == 0) continue; if(parseLine(configLine, mCapitalizeName, mIdentityLabel, name, value)) { insertEntry(name, value); } } else { break; // end of buffer reached. } } return retval; } // Helper method for inserting a key/value pair into the database. // The write lock for the database should be taken before calling this // method. If the database already contains an entry for this key, then // set the value for the existing entry to rNewValue. void OsConfigDb::insertEntry(const UtlString& rKey, const UtlString& rNewValue) { DbEntry tempEntry(rKey, rNewValue); DbEntry* pOldEntry; size_t i = mDb.index(&tempEntry); if (i != UTL_NOT_FOUND) { // we already have an entry with this key pOldEntry = (DbEntry *)mDb.at(i); // just change its value // osPrintf("OsConfigDb::iNVP(%X,%s) - FOUND %s replaces %s\n", // this, rKey.data(), pOldEntry->value.data(), rNewValue.data()); pOldEntry->value = rNewValue; } else { DbEntry* pNewEntry = new DbEntry(rKey, rNewValue); // osPrintf("OsConfigDb::iNVP(%X,%s) - ADDING (%s)\n", // this, rKey.data(), rNewValue.data()); mDb.insert(pNewEntry); } } //----------------DbEntry ------------------------ DbEntry::DbEntry(const UtlString &rKey, const UtlString &rValue) { key = rKey; value = rValue; } DbEntry::DbEntry(const UtlString &rKey) { key = rKey; } DbEntry::~DbEntry() { } int DbEntry::compareTo(const UtlContainable *b) const { return key.compareTo(((DbEntry *)b)->key); } unsigned int DbEntry::hash() const { return key.hash(); } const UtlContainableType DbEntry::getContainableType() const { return TYPE; } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsContact.cpp0000644000175000017500000000644212205613256023476 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include // APPLICATION INCLUDES #include "os/OsContact.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS UtlContainableType OsContact::TYPE = "OsContact" ; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor. OsContact::OsContact(UtlString address, int port, OsSocket::IpProtocolSocketType protocol, IpAddressType type) { mAddress = address; mPort = port; mProtocol = protocol; mType = type; } // Copy constructor OsContact::OsContact(const OsContact& ref) { this->mAddress = ref.mAddress; this->mPort = ref.mPort; this->mProtocol = ref.mProtocol; this->mType = ref.mType; } // Destructor OsContact::~OsContact() { } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ const int OsContact::getPort() const { return mPort; } const OsSocket::IpProtocolSocketType OsContact::getProtocol() const { return mProtocol; } const IpAddressType OsContact::getAddressType() const { return mType; } unsigned OsContact::hash() const { return mAddress.hash() + mPort + mProtocol + mType ; } UtlContainableType OsContact::getContainableType() const { return OsContact::TYPE ; } /* ============================ INQUIRY =================================== */ int OsContact::compareTo(UtlContainable const * inVal) const { int result ; const OsContact* pContact = static_cast(inVal); if (inVal->isInstanceOf(OsContact::TYPE) && pContact) { UtlString address; pContact->getAddress(address); result = mAddress.compareTo(address); if (0 == result) { result = compareInt(mPort, pContact->getPort()); } if (0 == result) { result = compareInt(mProtocol, pContact->getProtocol()); } if (0 == result) { result = compareInt((const int)mType, (const int)pContact->getAddressType()); } } else { result = INT_MAX ; } return result ; } UtlBoolean OsContact::isEqual(UtlContainable const * inVal) const { return (compareTo(inVal) == 0) ; } const void OsContact::getAddress(UtlString& address) const { address = mAddress; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ const int OsContact::compareInt(const int first, const int second) const { int ret; if (first == second) { ret = 0; } else if (first < second) { ret = -1; } else { ret = 1; } return ret; } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsContactList.cpp0000644000175000017500000000310712205613256024325 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsContactList.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const UtlContainableType OsContactList::TYPE = "OsContactList"; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsContactList::OsContactList() : UtlSList() { } /* ============================ MANIPULATORS ============================== */ /** * Get the ContainableType for the list as a contained object. */ UtlContainableType OsContactList::getContainableType() const { return OsContactList::TYPE; } void OsContactList::setPrimary(const OsContact& contact) { // first, remove the contact if it already exists remove(&contact); // insert the contact at the head of the list insertAt(0, (UtlContainable*)&contact); } const OsContact* OsContactList::getPrimary() { const OsContact* pContact = (OsContact*) at(0); return pContact; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsConnectionSocket.cpp0000644000175000017500000002364612205613256025360 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #if defined(_WIN32) # include #elif defined(_VXWORKS) # include # include # include # include #elif defined(__pingtel_on_posix__) # include # include # include # include # include #else #error Unsupported target platform. #endif // APPLICATION INCLUDES #include #include "os/OsUtil.h" #include "utl/UtlSList.h" #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsConnectionSocket::OsConnectionSocket(int connectedSocketDescriptor) { socketDescriptor = connectedSocketDescriptor; } OsConnectionSocket::OsConnectionSocket(const char* szLocalIp, int connectedSocketDescriptor) { socketDescriptor = connectedSocketDescriptor; mLocalIp = szLocalIp; } // Constructor OsConnectionSocket::OsConnectionSocket(int serverPort, const char* serverName, UtlBoolean blockingConnect, const char* localIp, const bool bConnect) { int error = 0; int connectReturn = 0; mLocalIp = localIp; OsSysLog::add(FAC_SIP, PRI_DEBUG, "OsConnectionSocket::_ attempt %s:%d %s" ,serverName, serverPort, blockingConnect ? "BLOCKING" : "NON-BLOCKING" ); socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; remoteHostPort = serverPort; if (!initialize(serverName, serverPort, blockingConnect)) { goto EXIT; } // Set the default destination address for the socket if (bConnect) { connectReturn = connect(); error = OsSocketGetERRNO(); } #if defined(_WIN32) if(error == WSAEWOULDBLOCK && !blockingConnect) { error = 0; connectReturn = 0; } #elif defined(_VXWORKS) if(error == EWOULDBLOCK && !blockingConnect) { error = 0; connectReturn = 0; } #elif defined(__pingtel_on_posix__) if(error == EINPROGRESS && !blockingConnect) { error = 0; connectReturn = 0; } #endif if(bConnect && connectReturn && error) { char* msgBuf; close(); msgBuf = strerror(error); OsSysLog::add(FAC_SIP, PRI_INFO, "OsConnectionSocket(%s:%d): call to connect() failed: %s\n" "connect call failed with error: %d %d\n", serverName, serverPort, msgBuf, error, connectReturn); #if 0 // Report exactly what the arguments to connect() were // to diagnose difficult errors. char buffer[100]; int i; unsigned char* p; for (i = 0, p = (unsigned char*) &serverSockAddr; i < sizeof(serverSockAddr); i++) { sprintf(buffer + 2 * i, "%02X", *p++); } OsSysLog::add(FAC_SIP, PRI_DEBUG, "OsConnectionSocket socketDescriptor = %d, " "serverSockAddr = %s", socketDescriptor, buffer); #endif } else { if (bConnect) { mIsConnected = TRUE; } } EXIT: return; } // Destructor OsConnectionSocket::~OsConnectionSocket() { remoteHostName = OsUtil::NULL_OS_STRING; close(); } bool OsConnectionSocket::initialize(const char* serverName, int serverPort, UtlBoolean blockingConnect) { int error = 0; bool bRet = false; UtlBoolean isIp; struct in_addr* serverAddr; struct hostent* server = NULL; UtlString temp_output_address; // Connect to a remote host if given if(! serverName || strlen(serverName) == 0) { #if defined(_VXWORKS) mLocalIp = "127.0.0.1"; serverName = "127.0.0.1"; #elif defined(__pingtel_on_posix__) || defined(WIN32) unsigned long address_val = OsSocket::getDefaultBindAddress(); if (address_val == htonl(INADDR_ANY)) serverName = "localhost"; else { struct in_addr in; # ifdef WIN32 // [ in.S_un.S_addr = address_val; # else // WIN32 ] in.s_addr = address_val; # endif // WIN32 ] serverName = inet_ntoa(in); } #else #error Unsupported target platform. #endif } if(serverName) { remoteHostName = serverName; } if(!socketInit()) { goto EXIT; } # if defined(_VXWORKS) char hostentBuf[512]; # endif // Create the socket socketDescriptor = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(socketDescriptor == OS_INVALID_SOCKET_DESCRIPTOR) { error = OsSocketGetERRNO(); socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; OsSysLog::add(FAC_SIP, PRI_ERR, "OsConnectionSocket::_ 'socket' failed: %x", error); goto EXIT; } if(!blockingConnect) { makeNonblocking(); } isIp = isIp4Address(serverName); if(!isIp) { # if defined(_WIN32) || defined(__pingtel_on_posix__) server = gethostbyname(serverName); # elif defined(_VXWORKS) server = resolvGetHostByName((char*) serverName, hostentBuf, sizeof(hostentBuf)); # else # error Unsupported target platform. # endif //_VXWORKS } if(!isIp && !server) { close(); OsSysLog::add(FAC_SIP, PRI_ERR, "DNS failed to look up host: '%s'\n", serverName); goto EXIT; } if (!isIp) { inet_ntoa_pt(*((in_addr*) (server->h_addr)),temp_output_address); serverAddr = (in_addr*) (server->h_addr); serverSockAddr.sin_family = server->h_addrtype; serverSockAddr.sin_port = htons(serverPort & 0xFFFF); serverSockAddr.sin_addr.s_addr = (serverAddr->s_addr); } else { serverSockAddr.sin_family = AF_INET; serverSockAddr.sin_port = htons(serverPort & 0xFFFF); serverSockAddr.sin_addr.s_addr = inet_addr(serverName); } bRet = true; EXIT: return bRet; } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsConnectionSocket& OsConnectionSocket::operator=(const OsConnectionSocket& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } int OsConnectionSocket::connect() { int connectReturn = 0; # if defined(_WIN32) || defined(__pingtel_on_posix__) connectReturn = ::connect(socketDescriptor, (const struct sockaddr*) &serverSockAddr, sizeof(serverSockAddr)); # elif defined(_VXWORKS) connectReturn = connect(socketDescriptor, (struct sockaddr*) &serverSockAddr, sizeof(serverSockAddr)); # else # error Unsupported target platform. # endif if (connectReturn == 0) { mIsConnected = true; } return connectReturn; } UtlBoolean OsConnectionSocket::reconnect() { OsSysLog::add(FAC_SIP, PRI_WARNING, " reconnect NOT implemented!\n"); return(FALSE); } // Because we have overrode one read method, we // must implement them all in OsConnectionSocket or // we end up hiding some of the methods. int OsConnectionSocket::read(char* buffer, int bufferLength) { // Use base class implementation int bytesRead = OsSocket::read(buffer, bufferLength); return(bytesRead); } int OsConnectionSocket::read(char* buffer, int bufferLength, UtlString* ipAddress, int* port) { // Override base class version as recvfrom does not // seem to return host info correctly for TCP // Use base class version without the remote host info int bytesRead = OsSocket::read(buffer, bufferLength); // Explicitly get the remote host info. getRemoteHostIp(ipAddress, port); return(bytesRead); } // Because we have overided one read method, we // must implement them all in OsConnectionSocket or // we end up hiding some of the methods. int OsConnectionSocket::read(char* buffer, int bufferLength, long waitMilliseconds) { // Use base class implementation int bytesRead = OsSocket::read(buffer, bufferLength, waitMilliseconds); return(bytesRead); } /* ============================ ACCESSORS ================================= */ OsSocket::IpProtocolSocketType OsConnectionSocket::getIpProtocol() const { return(TCP); } /* ============================ INQUIRY =================================== */ /// Is this connection encrypted using TLS/SSL? bool OsConnectionSocket::isEncrypted() const { return false; } /// Get any authenticated peer host names. bool OsConnectionSocket::peerIdentity( UtlSList* altNames ,UtlString* commonName ) const { /* * @returns * - true if the connection is TLS/SSL and the peer has presented * a certificate signed by a trusted certificate authority * - false if not */ if (altNames) { altNames->destroyAll(); } if (commonName) { commonName->remove(0); } return false; // an OsSSLServerSocket might return true... } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsCSemBase.cpp0000644000175000017500000000775412205613256023534 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include "utl/UtlRscTrace.h" #ifdef TEST #include "utl/UtlMemCheck.h" #endif //TEST // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsTask.h" #include "os/OsCSem.h" #ifdef OS_CSEM_DEBUG #include "os/OsLock.h" #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor allowing different initial and maximum semaphore values OsCSemBase::OsCSemBase(const int queueOptions, const int maxCount, const int initCount) #ifdef OS_CSEM_DEBUG : mGuard(OsBSem::Q_PRIORITY, OsBSem::FULL), mQueueOptions(queueOptions), mInitialCount(initCount), mMaxCount(maxCount), mCurCount(initCount), mHighCount(initCount), mLowCount(initCount), mNumAcquires(0), mNumReleases(0) #endif { } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ #ifdef OS_CSEM_DEBUG int OsCSemBase::getValue(void) { return mCurCount; } #endif // Print counting semaphore information to the console // Output enabled via a compile-time #ifdef #ifdef OS_CSEM_DEBUG void OsCSemBase::show(void) { OsLock lock(mGuard); osPrintf("OK: OsCSem: OsCSem=0x%08x, options=%d, initCnt=%d, maxCnt=%d\n", (void *) this, mQueueOptions, mInitialCount, mMaxCount); osPrintf("OK: OsCSem: curCnt=%d, acquires=%d, releases=%d, highCnt=%d, lowCnt=%d\n", mCurCount, mNumAcquires, mNumReleases, mHighCount, mLowCount); } #endif #ifdef OS_CSEM_DEBUG // Update the statistics associated with acquiring a counting semaphore. void OsCSemBase::updateAcquireStats(void) { OsLock lock(mGuard); mCurCount--; mNumAcquires++; if (mCurCount < mLowCount) mLowCount = mCurCount; if ((mCurCount < -1) || (mCurCount > mMaxCount)) { osPrintf("OsCSem::updateAcquireStats: OsCSem=0x%08x, mCurCount=%d, mMaxCount=%d\n", (void *) this, mCurCount, mMaxCount); osPrintf("OsCSem: OsCSem=0x%08x, options=%d, initCnt=%d, maxCnt=%d\n", (void *) this, mQueueOptions, mInitialCount, mMaxCount); osPrintf("OsCSem: curCnt=%d, acquires=%d, releases=%d, highCnt=%d, lowCnt=%d\n", mCurCount, mNumAcquires, mNumReleases, mHighCount, mLowCount); } else { #ifdef OS_CSEM_DEBUG_SHOWALL osPrintf("OK: OsCSem: OsCSem=0x%08x, mCurCnt=%d, maxCnt=%d\n", (void *) this, mCurCount, mMaxCount); #endif } } // Update the statistics associated with releasing a counting semaphore void OsCSemBase::updateReleaseStats(void) { OsLock lock(mGuard); mCurCount++; mNumReleases++; if (mCurCount > mHighCount) mHighCount = mCurCount; if ((mCurCount < 0) || (mCurCount > mMaxCount)) { osPrintf("OsCSem::updateReleaseStats: OsCSem=0x%08x, mCurCount=%d, mMaxCount=%d\n", (void *) this, mCurCount, mMaxCount); osPrintf("OsCSem: OsCSem=0x%08x, options=%d, initCnt=%d, maxCnt=%d\n", (void *) this, mQueueOptions, mInitialCount, mMaxCount); osPrintf("OsCSem: curCnt=%d, acquires=%d, releases=%d, highCnt=%d, lowCnt=%d\n", mCurCount, mNumAcquires, mNumReleases, mHighCount, mLowCount); } else { #ifdef OS_CSEM_DEBUG_SHOWALL osPrintf("OK: OsCSem: OsCSem=0x%08x, mCurCnt=%d, maxCnt=%d\n", (void *) this, mCurCount, mMaxCount); #endif } } #endif sipxtapi-3.3.0~test17/sipXportLib/src/os/OsDatagramSocket.cpp0000644000175000017500000004002012205613256024762 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #include #define OPTIONAL_CONST const #define OPTIONAL_VXW_CHARSTAR_CAST #define resolvGetHostByName(a, b, c) gethostbyname(a) #if defined(_WIN32) # include # include #elif defined(_VXWORKS) # undef resolvGetHostByName # include # include # include # include # undef OPTIONAL_CONST # define OPTIONAL_CONST # undef OPTIONAL_VXW_CHARSTAR_CAST # define OPTIONAL_VXW_CHARSTAR_CAST (char*) #elif defined(__pingtel_on_posix__) # include # include # include # include # include #else #error Unsupported target platform. #endif // APPLICATION INCLUDES #include "os/OsDatagramSocket.h" #include "os/OsSysLog.h" // DEFINES #define SOCKET_LEN_TYPE #ifdef __pingtel_on_posix__ #undef SOCKET_LEN_TYPE #define SOCKET_LEN_TYPE (socklen_t *) #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define MIN_REPORT_SECONDS 10 // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsDatagramSocket::OsDatagramSocket(int remoteHostPortNum, const char* remoteHost, int localHostPortNum, const char* localHost) : mNumTotalWriteErrors(0) , mNumRecentWriteErrors(0) , mSimulatedConnect(FALSE) // Simulated connection is off until // activated in doConnect. { int error = ctorCommonCode(); if (error != 0) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsDatagramSocket::OsDatagramSocket( %s:%d %s:%d) failed w/ errno %d)", remoteHost, remoteHostPortNum, localHost ? localHost : "NULL", localHostPortNum, error); goto EXIT; } // Bind to the socket bind(localHostPortNum, localHost); if (!isOk()) { goto EXIT; } // Kick off connection doConnect(remoteHostPortNum, remoteHost, mSimulatedConnect); EXIT: return; } // Bare-bones Constructor // Callers will need to call bind & doConnect on their own when this returns // (This allows for children to set socket options before the bind call) OsDatagramSocket::OsDatagramSocket() : mNumTotalWriteErrors(0) , mNumRecentWriteErrors(0) { int error = ctorCommonCode(); if (error != 0) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsDatagramSocket::OsDatagramSocket() failed w/ errno %d)", error); } } // Common code for both constructors // Returns 0 on success int OsDatagramSocket::ctorCommonCode() { socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; // Verify socket layer is initialized. if (!socketInit()) { return -1; } // Obtain time for throttling logging of write errors time(&mLastWriteErrorTime); // Initialize state settings mToSockaddrValid = FALSE; mpToSockaddr = (struct sockaddr_in*) malloc(sizeof(struct sockaddr_in)); assert(NULL != mpToSockaddr); memset(mpToSockaddr, 0, sizeof(struct sockaddr_in)); // Create the socket socketDescriptor = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (socketDescriptor == OS_INVALID_SOCKET_DESCRIPTOR) { int error = OsSocketGetERRNO(); close(); return error; } return 0; } // Destructor OsDatagramSocket::~OsDatagramSocket() { close(); free(mpToSockaddr); } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsDatagramSocket& OsDatagramSocket::operator=(const OsDatagramSocket& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } int OsDatagramSocket::bind(int localHostPortNum, const char* localHost) { int error = 0; localHostPort = localHostPortNum; if (localHost) { localHostName = localHost ; } struct sockaddr_in localAddr; memset(&localAddr, 0, sizeof(localAddr)); localAddr.sin_family = AF_INET; localAddr.sin_port = htons(localHostPort == PORT_DEFAULT ? 0 : localHostPort); #ifdef WIN32 localAddr.sin_addr.s_addr = htonl(INADDR_ANY); mLocalIp = localHost; #else // Should use host address (if specified in localHost) but for now use any if (!localHost) { localAddr.sin_addr.s_addr=OsSocket::getDefaultBindAddress(); // $$$ mLocalIp = inet_ntoa(localAddr.sin_addr); } else { struct in_addr ipAddr; ipAddr.s_addr = inet_addr (localHost); localAddr.sin_addr.s_addr= ipAddr.s_addr; mLocalIp = localHost; } #endif error = ::bind( socketDescriptor, (struct sockaddr*) &localAddr, sizeof(localAddr)); if(error == OS_INVALID_SOCKET_DESCRIPTOR) { error = OsSocketGetERRNO(); close(); OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsDatagramSocket::bind to %s:%d failed w/errno %d\n", mLocalIp.data(), localHostPortNum, error); } else { sockaddr_in addr ; int addrSize = sizeof(struct sockaddr_in); error = getsockname(socketDescriptor, (struct sockaddr*) &addr, SOCKET_LEN_TYPE& addrSize); localHostPort = htons(addr.sin_port); } return error; } UtlBoolean OsDatagramSocket::reconnect() { osPrintf("WARNING: reconnect NOT implemented!\n"); return(FALSE); } void OsDatagramSocket::doConnect(int remoteHostPortNum, const char* remoteHost, UtlBoolean simulateConnect) { struct hostent* server = NULL; mToSockaddrValid = FALSE; memset(mpToSockaddr, 0, sizeof(struct sockaddr_in)); remoteHostPort = remoteHostPortNum; // Store host name if(remoteHost) { remoteHostName = remoteHost ; getHostIpByName(remoteHostName, &mRemoteIpAddress); } else { remoteHostName.remove(0) ; } // Connect to a remote host if given if(portIsValid(remoteHostPort) && remoteHost && !simulateConnect) { #if defined(_WIN32) || defined(__pingtel_on_posix__) unsigned long ipAddr; ipAddr = inet_addr(remoteHost); if (ipAddr != INADDR_NONE) { server = gethostbyaddr((char * )&ipAddr,sizeof(ipAddr),AF_INET); } if ( server == NULL ) { server = gethostbyname(remoteHost); } #elif defined(_VXWORKS) char hostentBuf[512]; server = resolvGetHostByName((char*) remoteHost, hostentBuf, sizeof(hostentBuf)); #else # error Unsupported target platform. #endif //_VXWORKS if (server) { struct in_addr* serverAddr = (in_addr*) (server->h_addr); struct sockaddr_in serverSockAddr; serverSockAddr.sin_family = server->h_addrtype; serverSockAddr.sin_port = htons(remoteHostPort); serverSockAddr.sin_addr.s_addr = (serverAddr->s_addr); // Set the default destination address for the socket #if defined(_WIN32) || defined(__pingtel_on_posix__) if(connect(socketDescriptor, (const struct sockaddr*) &serverSockAddr, sizeof(serverSockAddr))) #elif defined(_VXWORKS) if(connect(socketDescriptor, (struct sockaddr*) &serverSockAddr, sizeof(serverSockAddr))) #else # error Unsupported target platform. #endif { int error = OsSocketGetERRNO(); close(); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsDatagramSocket::doConnect( %s:%d ) failed w/ errno %d)", remoteHost, remoteHostPortNum, error); } else { mIsConnected = TRUE; } } else { close(); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsDatagramSocket::doConnect( %s:%d ) failed host lookup)", remoteHost, remoteHostPortNum); goto EXIT; } } else if(portIsValid(remoteHostPort) && remoteHost && simulateConnect) { mIsConnected = TRUE; mSimulatedConnect = TRUE; } EXIT: ; } int OsDatagramSocket::write(const char* buffer, int bufferLength) { int returnCode; if(mSimulatedConnect) { returnCode = writeTo(buffer, bufferLength); } else { returnCode = OsSocket::write(buffer, bufferLength); } return(returnCode); } int OsDatagramSocket::write(const char* buffer, int bufferLength, const char* ipAddress, int port) { int bytesSent = 0; struct sockaddr_in toSockAddress; memset(&toSockAddress, 0, sizeof(toSockAddress)); toSockAddress.sin_family = AF_INET; toSockAddress.sin_port = htons(port); if(ipAddress == NULL || !strcmp(ipAddress, "0.0.0.0") || strlen(ipAddress) == 0 || (toSockAddress.sin_addr.s_addr = inet_addr(ipAddress)) == OS_INVALID_INET_ADDRESS) { osPrintf("OsDatagramSocket::write invalid IP address: \"%s\"\n", ipAddress); } else { // Why isn't this abstracted into OsSocket, as is done in ::write(2)? bytesSent = sendto(socketDescriptor, #ifdef _VXWORKS (char*) #endif buffer, bufferLength, 0, (struct sockaddr*) &toSockAddress, sizeof(struct sockaddr_in)); if(bytesSent != bufferLength) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsDatagramSocket::write(4) bytesSent = %d, " "bufferLength = %d, errno = %d", bytesSent, bufferLength, errno); time_t rightNow; (void) time(&rightNow); mNumRecentWriteErrors++; if (MIN_REPORT_SECONDS <= (rightNow - mLastWriteErrorTime)) { mNumTotalWriteErrors += mNumRecentWriteErrors; if (0 == mNumTotalWriteErrors) { mLastWriteErrorTime = rightNow; } osPrintf("OsDataGramSocket::write:\n" " In last %ld seconds: %d errors; total %d errors;" " last errno=%d\n", (rightNow - mLastWriteErrorTime), mNumRecentWriteErrors, mNumTotalWriteErrors, OsSocketGetERRNO()); mLastWriteErrorTime = rightNow; mNumRecentWriteErrors = 0; } } #ifdef TEST_PRINT else { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsDatagramSocket::write bytes: %d to address: %s port: %d", bytesSent, ipAddress, port); } #endif } return(bytesSent); } UtlBoolean OsDatagramSocket::getToSockaddr() { const char* ipAddress = mRemoteIpAddress.data(); if (!mToSockaddrValid) { mpToSockaddr->sin_family = AF_INET; mpToSockaddr->sin_port = htons(remoteHostPort); if (ipAddress == NULL || !strcmp(ipAddress, "0.0.0.0") || strlen(ipAddress) == 0 || (mpToSockaddr->sin_addr.s_addr = inet_addr(ipAddress)) == OS_INVALID_INET_ADDRESS) { /* osPrintf( "OsDatagramSocket::getToSockaddr: invalid IP address: \"%s\"\n", ipAddress); */ } else { mToSockaddrValid = TRUE; } } return mToSockaddrValid; } int OsDatagramSocket::writeTo(const char* buffer, int bufferLength) { int bytesSent = 0; if (getToSockaddr()) { bytesSent = sendto(socketDescriptor, #ifdef _VXWORKS (char*) #endif buffer, bufferLength, 0, (struct sockaddr*) mpToSockaddr, sizeof(struct sockaddr_in)); #ifdef TEST_PRINT UtlString address(inet_ntoa(mpToSockaddr->sin_addr)); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsDatagramSocket::writeTo bytes: %d to address: %s port: %d", bytesSent, address.data(), (int) ntohs(mpToSockaddr->sin_port)); #endif if(bytesSent != bufferLength) { time_t rightNow; (void) time(&rightNow); mNumRecentWriteErrors++; if (MIN_REPORT_SECONDS <= (rightNow - mLastWriteErrorTime)) { mNumTotalWriteErrors += mNumRecentWriteErrors; if (0 == mNumTotalWriteErrors) { mLastWriteErrorTime = rightNow; } osPrintf("OsDataGramSocket::write:\n" " In last %ld seconds: %d errors; total %d errors;" " last errno=%d\n", (rightNow - mLastWriteErrorTime), mNumRecentWriteErrors, mNumTotalWriteErrors, OsSocketGetERRNO()); mLastWriteErrorTime = rightNow; mNumRecentWriteErrors = 0; } } } return(bytesSent); } #ifdef WANT_GET_FROM_INFO /* [ */ #ifdef _VXWORKS /* [ */ static int getFromInfo = 0; extern "C" { extern int setFromInfo(int x);}; int setFromInfo(int getIt) { int save = getFromInfo; getFromInfo = getIt ? 1 : 0; return save; } #define GETFROMINFO getFromInfo #endif /* _VXWORKS ] */ #endif /* WANT_GET_FROM_INFO ] */ int OsDatagramSocket::read(char* buffer, int bufferLength) { int bytesRead; // If the remote end is not "connected" we cannot use recv if(mSimulatedConnect || !portIsValid(remoteHostPort) || remoteHostName.isNull()) { #ifdef GETFROMINFO /* [ */ if (GETFROMINFO) { int fromPort; UtlString fromAddress; bytesRead = OsSocket::read(buffer, bufferLength, &fromAddress, &fromPort); fromAddress.remove(0); } else #endif /* GETFROMINFO ] */ { bytesRead = OsSocket::read(buffer, bufferLength, (struct in_addr*) NULL, NULL); } } else { bytesRead = OsSocket::read(buffer, bufferLength); } return(bytesRead); } /* ============================ ACCESSORS ================================= */ OsSocket::IpProtocolSocketType OsDatagramSocket::getIpProtocol() const { return(UDP); } void OsDatagramSocket::getRemoteHostIp(struct in_addr* remoteHostAddress, int* remotePort) { #ifdef __pingtel_on_posix__ socklen_t len; #else int len; #endif struct sockaddr_in remoteAddr; const struct sockaddr_in* pAddr; if (mSimulatedConnect) { getToSockaddr(); pAddr = mpToSockaddr; } else { pAddr = &remoteAddr; len = sizeof(struct sockaddr_in); if (getpeername(socketDescriptor, (struct sockaddr *)pAddr, &len) != 0) { memset(&remoteAddr, 0, sizeof(struct sockaddr_in)); } } memcpy(remoteHostAddress, &(pAddr->sin_addr), sizeof(struct in_addr)); #ifdef TEST_PRINT { int p = ntohs(pAddr->sin_port); UtlString o; inet_ntoa_pt(*remoteHostAddress, o); osPrintf("getRemoteHostIP: Remote name: %s:%d\n" " (pAddr->sin_addr) = 0x%X, sizeof(struct in_addr) = %d\n", o.data(), p, (pAddr->sin_addr), sizeof(struct in_addr)); } #endif if (NULL != remotePort) { *remotePort = ntohs(pAddr->sin_port); } } // Return the external IP address for this socket. UtlBoolean OsDatagramSocket::getMappedIp(UtlString* ip, int* port) { return FALSE ; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsDateTime.cpp0000644000175000017500000004223012205613256023572 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #include #include #include #include // APPLICATION INCLUDES #include "os/OsDateTime.h" #include "os/OsTime.h" #include "utl/UtlString.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define BAD_DATE (time_t)0 static const int MICROSECS_PER_MILLISEC = 1000; // STATIC VARIABLE INITIALIZATIONS OsDateTimeBase::DstRule OsDateTimeBase::sDstRule = OsDateTimeBase::DST_NONE; int OsDateTimeBase::sDstYear = -1; int OsDateTimeBase::sTzOffsetSecs = 0; //:Represents a date and time. // Uses individual members for the month, day, year, hour, minute, second // second and microsecond. const char* OsDateTimeBase::spMonthStrings[12] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; const char* OsDateTimeBase::spDayStrings[7] = { "Sun","Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Default constructor OsDateTimeBase::OsDateTimeBase() : mMicrosecond(0), mYear(0), mMonth(0), mDay(0), mHour(0), mMinute(0), mSecond(0) { // no work required beyond what's been done by the initializers } // Constructor OsDateTimeBase::OsDateTimeBase(const unsigned short year, const unsigned char month, const unsigned char day, const unsigned char hour, const unsigned char minute, const unsigned char second, const unsigned int microsecond) : mMicrosecond(microsecond), mYear(year), mMonth(month), mDay(day), mHour(hour), mMinute(minute), mSecond(second) { // no work required beyond what's been done by the initializers } // Copy constructor OsDateTimeBase::OsDateTimeBase(const OsDateTimeBase& rOsDateTimeBase) { mYear = rOsDateTimeBase.mYear; mMonth = rOsDateTimeBase.mMonth; mDay = rOsDateTimeBase.mDay; mHour = rOsDateTimeBase.mHour; mMinute = rOsDateTimeBase.mMinute; mSecond = rOsDateTimeBase.mSecond; mMicrosecond = rOsDateTimeBase.mMicrosecond; } // Destructor OsDateTimeBase::~OsDateTimeBase() { // no work required } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsDateTimeBase& OsDateTimeBase::operator=(const OsDateTimeBase& rhs) { if (this == &rhs) // handle the assignment to self case return *this; mYear = rhs.mYear; mMonth = rhs.mMonth; mDay = rhs.mDay; mHour = rhs.mHour; mMinute = rhs.mMinute; mSecond = rhs.mSecond; mMicrosecond = rhs.mMicrosecond; return *this; } long OsDateTimeBase::tm2Epoch(const struct tm *t) { /* * tm2sec converts a GMT tm structure into the number of seconds since * 1st January 1970 UT. Note that we ignore tm_wday, tm_yday, and tm_dst. * * The return value is always a valid time_t value -- (time_t)0 is returned * if the input date is outside that capable of being represented by time(), * i.e., before Thu, 01 Jan 1970 00:00:00 for all systems and * beyond 2038 for 32bit systems. * * This routine is intended to be very fast, much faster than mktime(). */ int year; long days; const int dayoffset[12] = {306, 337, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275}; year = t->tm_year; if (year < 70 || ((sizeof(time_t) <= 4) && (year >= 138))) return BAD_DATE; /* shift new year to 1st March in order to make leap year calc easy */ if (t->tm_mon < 2) year--; /* Find number of days since 1st March 1900 (in the Gregorian calendar). */ days = year * 365 + year/4 - year/100 + (year/100 + 3)/4; days += dayoffset[t->tm_mon] + t->tm_mday - 1; days -= 25508; /* 1 jan 1970 is 25508 days since 1 mar 1900 */ days = ((days * 24 + t->tm_hour) * 60 + t->tm_min) * 60 + t->tm_sec; if (days < 0) return BAD_DATE; /* must have overflowed */ else return days; /* must be a valid time */ } long OsDateTimeBase::convertHttpDateToEpoch(const char *date) { /* * Parses an HTTP date in one of three standard forms: * * Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 * Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036 * Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format * * and returns the time_t number of seconds since 1 Jan 1970 GMT, or * 0 if this would be out of range or if the date is invalid. * * The restricted HTTP syntax is * * HTTP-date = rfc1123-date | rfc850-date | asctime-date * * rfc1123-date = wkday "," SP date1 SP time SP "GMT" * rfc850-date = weekday "," SP date2 SP time SP "GMT" * asctime-date = wkday SP date3 SP time SP 4DIGIT * * date1 = 2DIGIT SP month SP 4DIGIT * ; day month year (e.g., 02 Jun 1982) * date2 = 2DIGIT "-" month "-" 2DIGIT * ; day-month-year (e.g., 02-Jun-82) * date3 = month SP ( 2DIGIT | ( SP 1DIGIT )) * ; month day (e.g., Jun 2) * * time = 2DIGIT ":" 2DIGIT ":" 2DIGIT * ; 00:00:00 - 23:59:59 * * wkday = "Mon" | "Tue" | "Wed" * | "Thu" | "Fri" | "Sat" | "Sun" * * weekday = "Monday" | "Tuesday" | "Wednesday" * | "Thursday" | "Friday" | "Saturday" | "Sunday" * * month = "Jan" | "Feb" | "Mar" | "Apr" * | "May" | "Jun" | "Jul" | "Aug" * | "Sep" | "Oct" | "Nov" | "Dec" * * However, for the sake of robustness (and Netscapeness), we ignore the * weekday and anything after the time field (including the timezone). * * This routine is intended to be very fast; 10x faster than using sscanf. * * Originally from Andrew Daviel , 29 Jul 96 * but many changes since then. * */ struct tm ds; int mint, mon; const char *monstr, *timstr; const int months[12] = { ('J' << 16) | ( 'a' << 8) | 'n', ('F' << 16) | ( 'e' << 8) | 'b', ('M' << 16) | ( 'a' << 8) | 'r', ('A' << 16) | ( 'p' << 8) | 'r', ('M' << 16) | ( 'a' << 8) | 'y', ('J' << 16) | ( 'u' << 8) | 'n', ('J' << 16) | ( 'u' << 8) | 'l', ('A' << 16) | ( 'u' << 8) | 'g', ('S' << 16) | ( 'e' << 8) | 'p', ('O' << 16) | ( 'c' << 8) | 't', ('N' << 16) | ( 'o' << 8) | 'v', ('D' << 16) | ( 'e' << 8) | 'c'}; if (!date) return BAD_DATE; while (*date && isspace(*date)) /* Find first non-whitespace char */ ++date; if (*date == '\0') return BAD_DATE; if ((date = strchr(date,' ')) == NULL) /* Find space after weekday */ return BAD_DATE; ++date; /* Now pointing to first char after space, which should be */ /* start of the actual date information for all 3 formats. */ if (checkmask(date, "## @$$ #### ##:##:## *")) { /* RFC 1123 format */ ds.tm_year = ((date[7] - '0') * 10 + (date[8] - '0') - 19) * 100; if (ds.tm_year < 0) return BAD_DATE; ds.tm_year += ((date[9] - '0') * 10) + (date[10] - '0'); ds.tm_mday = ((date[0] - '0') * 10) + (date[1] - '0'); monstr = date + 3; timstr = date + 12; } else if (checkmask(date, "##-@$$-## ##:##:## *")) { /* RFC 850 format */ ds.tm_year = ((date[7] - '0') * 10) + (date[8] - '0'); if (ds.tm_year < 70) ds.tm_year += 100; ds.tm_mday = ((date[0] - '0') * 10) + (date[1] - '0'); monstr = date + 3; timstr = date + 10; } else if (checkmask(date, "@$$ ~# ##:##:## ####*")) { /* asctime format */ ds.tm_year = ((date[16] - '0') * 10 + (date[17] - '0') - 19) * 100; if (ds.tm_year < 0) return BAD_DATE; ds.tm_year += ((date[18] - '0') * 10) + (date[19] - '0'); if (date[4] == ' ') ds.tm_mday = 0; else ds.tm_mday = (date[4] - '0') * 10; ds.tm_mday += (date[5] - '0'); monstr = date; timstr = date + 7; } else return BAD_DATE; if (ds.tm_mday <= 0 || ds.tm_mday > 31) return BAD_DATE; ds.tm_hour = ((timstr[0] - '0') * 10) + (timstr[1] - '0'); ds.tm_min = ((timstr[3] - '0') * 10) + (timstr[4] - '0'); ds.tm_sec = ((timstr[6] - '0') * 10) + (timstr[7] - '0'); if ((ds.tm_hour > 23) || (ds.tm_min > 59) || (ds.tm_sec > 61)) return BAD_DATE; mint = (monstr[0] << 16) | (monstr[1] << 8) | monstr[2]; for (mon=0; mon < 12; mon++) if (mint == months[mon]) break; if (mon == 12) return BAD_DATE; if ((ds.tm_mday == 31) && (mon == 3 || mon == 5 || mon == 8 || mon == 10)) return BAD_DATE; /* February gets special check for leapyear */ if ((mon == 1) && ((ds.tm_mday > 29) || ((ds.tm_mday == 29) && ((ds.tm_year & 3) || (((ds.tm_year % 100) == 0) && (((ds.tm_year % 400) != 100))))))) return BAD_DATE; ds.tm_mon = mon; return tm2Epoch(&ds); } // Set the system time and retain the previous settings for // time zone offset and daylight savings rules void OsDateTimeBase::setTime(struct timespec gmt) { OsDateTime::setTime(gmt, sTzOffsetSecs, sDstRule); } // Set the time zone information void OsDateTimeBase::setTimeZone(int tzOffsetSecs, DstRule dstRule) { OsDateTime::setTimeZone(tzOffsetSecs, dstRule); } /* ============================ ACCESSORS ================================= */ void OsDateTimeBase::getDayOfWeek(int year, int month, int dayOfMonth, int& dayOfWeek) { // Note: this calculation was wonderfully documented on: // http://www.tondering.dk/claus/cal/node3.html#SECTION00350000000000000000 // A copy of this page is also in: // \\Pingpdc\Software\Info\technology\calendar-math\node3.html // Both VxWorks and Windows will set the mMonth to 0 based. // Windows used 1 based month (doh) and VxWorks uses 0 based month++; // osPrintf("getDayOfWeek (IN): year=%d, month=%d, dayofmonth=%d\n",year,month,dayOfMonth); int a = (14 - month)/12; int gy = year - a; int m = month + (12 * a) - 2; dayOfWeek = (dayOfMonth + gy + (gy/4) - (gy/100) + (gy/400) + (31 * m) / 12) % 7; // osPrintf("Month: %d day: %d, %d is on day of week: %d \n", // month, dayOfMonth, year, dayOfWeek); } void OsDateTimeBase::getDayOfWeek(int& dayOfWeek) { getDayOfWeek(mYear, mMonth, mDay, dayOfWeek); } // Convert the OsDateTimeBase value to an OsTime value. // The OsTime value is relative to midnight (0 hour) 01/01/70. OsStatus OsDateTimeBase::cvtToTimeSinceEpoch(OsTime& rTime) const { struct tm thisTime; time_t thisTimeAsTimeT; // convert "this" OsDateTime to a time_t representation thisTime.tm_year = mYear - 1900; thisTime.tm_mon = mMonth; thisTime.tm_mday = mDay; thisTime.tm_hour = mHour; thisTime.tm_min = mMinute; thisTime.tm_sec = mSecond; thisTime.tm_wday = 0; thisTime.tm_yday = 0; thisTime.tm_isdst = 0; thisTimeAsTimeT = tm2Epoch(&thisTime); assert(thisTimeAsTimeT >= 0); OsTime timeSinceEpoch(thisTimeAsTimeT, mMicrosecond); rTime = timeSinceEpoch; return OS_SUCCESS; } void OsDateTimeBase::getHttpTimeString(UtlString& dateString) { char dateBuffer[200]; // Need a day of the week function which takes year, month and day int dayOfTheWeek; getDayOfWeek(dayOfTheWeek); // Wed, 06 Mar 2002 05:51:44 GMT sprintf(dateBuffer, "%s, %.2d %s %d %.2d:%.2d:%.2d GMT", spDayStrings[dayOfTheWeek], mDay, spMonthStrings[mMonth], mYear, mHour, mMinute, mSecond); dateString = dateBuffer; } /// Set the dateString to the time as UTC time in a Postgres compatible format: /// 2002-08-26 19:21:32.000 void OsDateTimeBase::getSqlTimeStringZ(UtlString& dateString) { dateString.resize(24); sprintf(const_cast(dateString.data()), "%4d-%02d-%02d %02d:%02d:%02d.%03d", mYear, mMonth+1, mDay, mHour, mMinute, mSecond, mMicrosecond/MICROSECS_PER_MILLISEC ); } /// Set the dateString to the time as UTC time in the following format: /// 2002-08-26T19:21:32.000Z void OsDateTimeBase::getIsoTimeStringZ(UtlString& dateString) { dateString.resize(24); sprintf(const_cast(dateString.data()), "%4d-%02d-%02dT%02d:%02d:%02d.%03dZ", mYear, mMonth+1, mDay, mHour, mMinute, mSecond, mMicrosecond/MICROSECS_PER_MILLISEC ); } /// Set the dateString to the time as UTC time in the following format: /// 2002-08-26T19:21:32.000000Z void OsDateTimeBase::getIsoTimeStringZus(UtlString& dateString) { dateString.resize(27); sprintf(const_cast(dateString.data()), "%4d-%02d-%02dT%02d:%02d:%02d.%06dZ", mYear, mMonth+1, mDay, mHour, mMinute, mSecond, mMicrosecond ); } void OsDateTimeBase::getLocalTimeString(UtlString& dateString) { char dateBuffer[200]; char ampm[] = "AM"; time_t ltime; struct tm *today; #if !defined(_VXWORKS) && !defined(WINCE) && !defined(ANDROID) /* Set time zone from TZ environment variable. If TZ is not set, * the operating system is queried to obtain the default value * for the variable. */ tzset(); #endif /* _VXWORKS*/ /* Convert to time structure and adjust for PM if necessary. */ time( <ime ); today = localtime( <ime ); if( today->tm_hour >= 12 ) { strcpy( ampm, "PM" ); if (today->tm_hour > 12) today->tm_hour -= 12; } if( today->tm_hour == 0 ) /* Adjust if midnight hour. */ today->tm_hour = 12; char tz[4] = {" "}; #if !defined(_VXWORKS) && !defined(WINCE) UtlString timezone = tzname[0]; if (today->tm_isdst == 1) timezone = tzname[1]; int len = timezone.length(); if (len > 3) { size_t pos = timezone.index(" "); if (pos != UTL_NOT_FOUND) { tz[0] = timezone.data()[0]; tz[1] = timezone.data()[pos + 1]; if ((pos = timezone.index(" ", pos + 1)) != UTL_NOT_FOUND) { tz[2] = timezone.data()[pos + 1]; } } } else if (len > 0) { memcpy(tz, timezone.data(), 3); } #endif /* _VXWORKS */ tz[3] = 0; // Mon, 25-Sep-2002 05:51:44 EST sprintf(dateBuffer, "%s, %d-%s-%d %.2d:%.2d:%.2d %s %s", spDayStrings[today->tm_wday], today->tm_mday, spMonthStrings[today->tm_mon], (today->tm_year + 1900), today->tm_hour, today->tm_min, today->tm_sec, ampm, tz); dateString = dateBuffer; } // Return the current time as an OsTime value // Note that this method is overridden in both Linux and Windows with // methods that return time with microsecond resolution. So don't be // deceived by this code that getCurTime only returns time with second // resolution. void OsDateTimeBase::getCurTime(OsTime& rTime) { OsTime curTime(time(NULL), 0); rTime = curTime; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ int OsDateTimeBase::checkmask(const char *data, const char *mask) { /* * Compare a string to a mask * Mask characters (arbitrary maximum is 256 characters, just in case): * @ - uppercase letter * $ - lowercase letter * & - hex digit * # - digit * ~ - digit or space * * - swallow remaining characters * - exact match for any other character */ int i; char d; for (i = 0; i < 256; i++) { d = data[i]; switch (mask[i]) { case '\0': return (d == '\0'); case '*': return 1; case '@': if (!isupper(d)) return 0; break; case '$': if (!islower(d)) return 0; break; case '#': if (!isdigit(d)) return 0; break; case '&': if (!isxdigit(d)) return 0; break; case '~': if ((d != ' ') && !isdigit(d)) return 0; break; default: if (mask[i] != d) return 0; break; } } return 0; /* We only get here if mask is corrupted (exceeds 256) */ } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsDirBase.cpp0000644000175000017500000000522412205613256023411 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #if defined(__linux__) || defined(sun) || defined(_VXWORKS) #include #include #endif #ifdef WIN32 #ifndef WINCE #include #endif #endif #ifdef WINCE # include #else # include # include #endif // APPLICATION INCLUDES #include "os/OsFS.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // DEFINES #if defined(_WIN32) #define S_DIR _S_IFDIR #define S_READONLY S_IWRITE #elif defined(__pingtel_on_posix__) || defined(_VXWORKS) #define S_DIR S_IFDIR #define S_READONLY S_IWUSR #endif /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsDirBase::OsDirBase(const char* pathname) { mDirName = pathname; } OsDirBase::OsDirBase(const OsPathBase& pathname) { mDirName = pathname; } // Copy constructor OsDirBase::OsDirBase(const OsDirBase& rOsDirBase) { mDirName = rOsDirBase.mDirName; } // Destructor OsDirBase::~OsDirBase() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsDirBase& OsDirBase::operator=(const OsDirBase& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } OsStatus OsDirBase::create() const { return OS_INVALID; } OsStatus OsDirBase::remove(UtlBoolean bRecursive, UtlBoolean bForce) const { return OsFileSystem::remove(mDirName,bRecursive, bForce); } OsStatus OsDirBase::rename(const char* name) { return OS_INVALID; } /* ============================ ACCESSORS ================================= */ void OsDirBase::getPath(OsPathBase& rOsPath) const { rOsPath = mDirName; } /* ============================ INQUIRY =================================== */ UtlBoolean OsDirBase::exists() { return FALSE; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsEncryption.cpp0000644000175000017500000001677112205613256024243 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #include #include #ifdef __pingtel_on_posix__ #include #include #endif #ifdef HAVE_SSL #define WIN32_LEAN_AND_MEAN #include #include #include #include #include #include #include # ifdef WIN32 # pragma comment (lib, "libeay32.lib") # pragma comment (lib, "ssleay32.lib") # endif #endif #ifdef _VXWORKS #include #endif #ifdef TEST #include "utl/UtlMemCheck.h" #endif // APPLICATION INCLUDES #include "os/OsExcept.h" #include "os/OsNameDb.h" #include "os/OsEncryption.h" #include "os/OsSocket.h" #include "os/OsSysLog.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS static const char gSalt[] = { (unsigned char)0xc9, (unsigned char)0x36, (unsigned char)0x78, (unsigned char)0x99, (unsigned char)0x52, (unsigned char)0x3e, (unsigned char)0xea, (unsigned char)0xf2 }; // STATIC VARIABLE INITIALIZATIONS UtlBoolean OsEncryption::sIgnoreEncryption = FALSE; // Wrapper around encryption, currently OpenSSL, specifically DES w/MD5 // See: // http://www.catfive.org/cgi-bin/man2web?program=EVP_CipherInit§ion=3 // For OpenSLL API information /* //////////////////////////// PUBLIC //////////////////////////////////// */ OsEncryption::OsEncryption(void) { mSalt = (unsigned char *)gSalt; mSaltLen = sizeof(gSalt); memset(&mKey, 0, sizeof(mKey)); mKeyLen = 0; mData = NULL; mDataLen = 0; mResults = NULL; mResultsLen = 0; memset(&mHeader, 0, sizeof(mHeader)); mHeaderLen = 0; #if defined (OSENCRYPTION) mAlgorithm = NULL; memset(&mContext, 0, sizeof(mContext)); #endif } OsEncryption::~OsEncryption(void) { release(); // open encryption algorithms } void OsEncryption::setKey(const unsigned char* key, int keyLen) { if (key != NULL) { mKeyLen = (OE_MAX_KEY_LEN < keyLen ? OE_MAX_KEY_LEN : keyLen); memcpy(mKey, key, mKeyLen); } } void OsEncryption::setResultsHeader(const unsigned char* header, int headerLen) { mHeaderLen = (OE_MAX_RESULTS_HEADER_LEN < headerLen ? OE_MAX_RESULTS_HEADER_LEN : headerLen); memcpy(mHeader, header, mHeaderLen); } // Does not make a copy void OsEncryption::setDataPointer(unsigned char* data, int dataLen) { mData = data; mDataLen = dataLen; } int OsEncryption::getDataLen(void) { return mDataLen; } unsigned char *OsEncryption::getDataPointer(void) { return mData; } // Null terminiated incase this helps unsigned char *OsEncryption::getResults(void) { return mResults; } int OsEncryption::getResultsLen(void) { return mResultsLen; } OsStatus OsEncryption::decrypt(void) { return crypto(DECRYPT); } OsStatus OsEncryption::encrypt(void) { return crypto(ENCRYPT); } // Call this after you're done with encryption OsStatus OsEncryption::release(void) { OsStatus retval = OS_FAILED; #if defined(OSENCRYPTION) // TODO: Analyze performance v.s. memory gains to never release this if (mAlgorithm != NULL) { X509_ALGOR_free(mAlgorithm); mAlgorithm = NULL; } if (mResults != NULL) { OPENSSL_free(mResults); mResults = NULL; mResultsLen = 0; } retval = OS_SUCCESS; #endif return retval; } /* //////////////////////////// PRIVATE/PROTECTED //////////////////////////////////// */ OsStatus OsEncryption::init(Direction direction) { OsStatus retval = OS_FAILED; #if defined(OSENCRYPTION) release(); if (mKeyLen > 0 && mKey != NULL && mDataLen > 0 && mData != NULL) { ERR_clear_error(); SSLeay_add_all_algorithms(); mAlgorithm = PKCS5_pbe_set(NID_pbeWithMD5AndDES_CBC, PKCS5_DEFAULT_ITER, mSalt, mSaltLen); if (mAlgorithm != NULL) { EVP_CIPHER_CTX_init(&(mContext)); if (EVP_PBE_CipherInit(mAlgorithm->algorithm, (const char *)mKey, mKeyLen, mAlgorithm->parameter, &(mContext), (int)direction)) { int blockSize = EVP_CIPHER_CTX_block_size(&mContext); int allocLen = mDataLen + mHeaderLen + blockSize + 1; // plus 1 for null terminator on decrypt mResults = (unsigned char *)OPENSSL_malloc(allocLen); if (mResults == NULL) { OsSysLog::add(FAC_AUTH, PRI_ERR, "Could not allocate cryption buffer(size=%d)", allocLen); } else { retval = OS_SUCCESS; } } else { OsSysLog::add(FAC_AUTH, PRI_ERR, "Could not initialize cipher"); } } else { OsSysLog::add(FAC_AUTH, PRI_ERR, "Could not initialize cryption algorithm"); } } else { OsSysLog::add(FAC_AUTH, PRI_ERR, "No encryption key(%d) or data(%d) set.\n", mKeyLen, mDataLen); } #endif return retval; } OsStatus OsEncryption::crypto(Direction direction) { OsStatus retval = init(direction); #if defined(OSENCRYPTION) if (retval == OS_SUCCESS) { if (sIgnoreEncryption) { memcpy(mResults, mData, mDataLen); mResultsLen = mDataLen; } else { retval = OS_FAILED; unsigned char *in = mData; int inLen = mDataLen; unsigned char *out = mResults; int outLen = 0; if (mHeaderLen > 0) { if (direction == ENCRYPT) { // copy in header memcpy(out, mHeader, mHeaderLen); out += mHeaderLen; outLen += mHeaderLen; } else { // ignore header in += mHeaderLen; inLen -= mHeaderLen; } } int outLenPart1 = 0; if (EVP_CipherUpdate(&(mContext), out, &outLenPart1, in, inLen)) { out += outLenPart1; int outLenPart2 = 0; if (EVP_CipherFinal(&(mContext), out, &outLenPart2)) { outLen += outLenPart1 + outLenPart2; retval = OS_SUCCESS; mResults[outLen] = 0; mResultsLen = outLen; } } } } if (retval != OS_SUCCESS) { openSslError(); release(); } #endif return retval; } UtlBoolean OsEncryption::openSslError(void) { #if defined(OSENCRYPTION) unsigned long err = ERR_get_error(); if (err != 0) { ERR_load_crypto_strings(); ERR_load_ERR_strings(); char errbuff[256]; errbuff[0] = 0; ERR_error_string_n(err, errbuff, sizeof(errbuff)); osPrintf("OpenSLL ERROR:\n\tlib:%s\n\tfunction:%s\n\treason:%s\n", ERR_lib_error_string(err), ERR_func_error_string(err), ERR_reason_error_string(err)); ERR_free_strings(); return TRUE; } #endif return FALSE; } sipxtapi-3.3.0~test17/sipXportLib/src/os/OsEvent.cpp0000644000175000017500000001205112205613256023155 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsEvent.h" #include "os/OsLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // Events are used to synchronize a task with an ISR or between two tasks. // Events consist of event data (an integer) that is set when the event is // signaled and a state variable that indicates whether the event has been // signaled. When first initialized, an OsEvent is ready to be signaled. // However, once signaled, the OsEvent must be explicitly cleared before it // may be signaled again. An OsEvent is intended for use in synchronizing // one notifier (task or ISR) with one listener task. If an OsEvent object // is intended for use with more than one notifier or listener, then an // external mutex must be used to serialize access and avid race conditions. /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsEvent::OsEvent(const intptr_t userData) : mEventData(-1), mIsSignaled(FALSE), mSignalSem(OsBSem::Q_PRIORITY, OsBSem::EMPTY), mMutex(OsMutex::Q_FIFO), mUserData(userData) { // all work is done by the initializers, no other work required } // Destructor OsEvent::~OsEvent() { // Take lock here to prevent destroying member variables while signal() is // still running. OsLock lock(mMutex); } /* ============================ MANIPULATORS ============================== */ // Set the event data and signal the occurrence of the event. // Return OS_ALREADY_SIGNALED if the event has already been signaled // (and has not yet been cleared), otherwise return OS_SUCCESS. OsStatus OsEvent::signal(const intptr_t eventData) { OsStatus res; OsLock lock(mMutex); if (mIsSignaled) { return OS_ALREADY_SIGNALED; // error - has already been signaled } // (and not yet cleared) else { // Signal the event, making sure that the following conditions hold: // 1) if mIsSignaled == TRUE, then mEventData must be valid // 2) before releasing the signal semaphore, mIsSignaled must be TRUE mEventData = eventData; // set the event data mIsSignaled = TRUE; // set the isSignaled flag res = mSignalSem.release(); // post the signal indication event assert(res == OS_SUCCESS); return OS_SUCCESS; } } // Reset the event so that it may be signaled again. // Return OS_NOT_SIGNALED if the event has not been signaled (or has // already been cleared), otherwise return OS_SUCCESS. OsStatus OsEvent::reset(void) { OsStatus res; OsLock lock(mMutex); if (mIsSignaled) { // if the event has been signaled mEventData = -1; // set the event data to -1 and mIsSignaled = FALSE; // clear the isSignaled flag res = mSignalSem.tryAcquire(); // rearm the event by acquiring the // semaphore whose release is used // to signal this event assert(res == OS_SUCCESS || res == OS_BUSY); return OS_SUCCESS; } else { return OS_NOT_SIGNALED; // error - had not yet been signaled } } // Wait for the event to be signaled. // Return OS_BUSY if the timeout expired, otherwise return OS_SUCCESS. OsStatus OsEvent::wait(const OsTime& rTimeout) { return mSignalSem.acquire(rTimeout); } OsStatus OsEvent::setUserData(intptr_t userData) { mUserData = userData; return OS_SUCCESS; } /* ============================ ACCESSORS ================================= */ // Return the event data that was signaled by the notifier task. // Return OS_NOT_SIGNALED if the event has not been signaled (or has // already been cleared), otherwise return OS_SUCCESS. OsStatus OsEvent::getEventData(intptr_t& rEventData) { OsLock lock(mMutex); if (mIsSignaled) { rEventData = mEventData; return OS_SUCCESS; } else { return OS_NOT_SIGNALED; // error - had not yet been signaled } } // Return the user data specified when this object was constructed. // Always returns OS_SUCCESS. OsStatus OsEvent::getUserData(intptr_t& rUserData) const { rUserData = mUserData; return OS_SUCCESS; } /* ============================ INQUIRY =================================== */ // Return TRUE if the event has been signaled, otherwise FALSE. UtlBoolean OsEvent::isSignaled(void) { return mIsSignaled; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsEventMsg.cpp0000644000175000017500000000630112205613256023625 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsEventMsg.h" #include "os/OsQueuedEvent.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsEventMsg::OsEventMsg(const unsigned char subType, const OsQueuedEvent& rEvent, const intptr_t eventData, const OsTime& rTimestamp) : OsMsg(OsMsg::OS_EVENT, subType), mEventData(eventData), mTimestamp(rTimestamp) { OsStatus res; res = rEvent.getUserData(mUserData); assert(res == OS_SUCCESS); } // Copy constructor OsEventMsg::OsEventMsg(const OsEventMsg& rOsEventMsg) : OsMsg(rOsEventMsg) { mEventData = rOsEventMsg.mEventData; mUserData = rOsEventMsg.mUserData; mTimestamp = rOsEventMsg.mTimestamp; } // Create a copy of this msg object (which may be of a derived type) OsMsg* OsEventMsg::createCopy(void) const { return new OsEventMsg(*this); } // Destructor OsEventMsg::~OsEventMsg() { // no work required } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsEventMsg& OsEventMsg::operator=(const OsEventMsg& rhs) { if (this == &rhs) // handle the assignment to self case return *this; OsMsg::operator=(rhs); // assign fields for parent class mEventData = rhs.mEventData; mUserData = rhs.mUserData; mTimestamp = rhs.mTimestamp; return *this; } /* ============================ ACCESSORS ================================= */ // Return the size of the message in bytes. // This is a virtual method so that it will return the accurate size for // the message object even if that object has been upcast to the type of // an ancestor class. int OsEventMsg::getMsgSize(void) const { return sizeof(*this); } // Return the event data that was signaled by the notifier task. // Always returns OS_SUCCESS. OsStatus OsEventMsg::getEventData(intptr_t& rEventData) const { rEventData = mEventData; return OS_SUCCESS; } // Return the timestamp associated with this event. // Always returns OS_SUCCESS. OsStatus OsEventMsg::getTimestamp(OsTime& rTimestamp) const { rTimestamp = mTimestamp; return OS_SUCCESS; } // Return the user data specified when the OsQueuedEvent was constructed. // Always returns OS_SUCCESS. OsStatus OsEventMsg::getUserData(intptr_t& rUserData) const { rUserData = mUserData; return OS_SUCCESS; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsExcept.cpp0000644000175000017500000000610512205613256023327 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsExcept.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsExcept::OsExcept(const int majorCode, const int minorCode, const UtlString& rText, const UtlString& rContext) : mMajorCode(majorCode), mMinorCode(minorCode), mpText(new UtlString(rText)), mpContext(new UtlString(rContext)) { // All of the work is done by the initializers } // Copy constructor OsExcept::OsExcept(const OsExcept& rOsExcept) : mMajorCode(rOsExcept.mMajorCode), mMinorCode(rOsExcept.mMinorCode), mpText(new UtlString(*rOsExcept.mpText)), mpContext(new UtlString(*rOsExcept.mpContext)) { // All of the work is done by the initializers } // Destructor OsExcept::~OsExcept() { delete mpText; mpText = 0; delete mpContext; mpContext = 0; } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsExcept& OsExcept::operator=(const OsExcept& rhs) { if (this == &rhs) // handle the assignment to self case return *this; mMajorCode = rhs.mMajorCode; mMinorCode = rhs.mMinorCode; delete mpText; mpText = new UtlString(*rhs.mpText); delete mpContext; mpContext = new UtlString(*rhs.mpContext); return *this; } // Set major exception code void OsExcept::setMajorCode(const int majorCode) { mMajorCode = majorCode; } // Set minor exception code void OsExcept::setMinorCode(const int minorCode) { mMinorCode = minorCode; } // Set exception context void OsExcept::setContext(const UtlString& rContext) { *mpContext = rContext; } // Set exception text void OsExcept::setText(const UtlString& rText) { *mpText = rText; } /* ============================ ACCESSORS ================================= */ // Get major exception code int OsExcept::getMajorCode(void) const { return mMajorCode; } // Get minor exception code int OsExcept::getMinorCode(void) const { return mMinorCode; } // Get exception context const UtlString& OsExcept::getContext(void) const { return *mpContext; } // Get exception text const UtlString& OsExcept::getText(void) const { return *mpText; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsFileBase.cpp0000644000175000017500000005626712205613256023567 0ustar00danieldaniel00000000000000// // Copyright (C) 2005, 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// //Uncomment next line to add syslog messages to debug OsFileBase //#define DEBUG_FS // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsTask.h" #include "os/OsProcess.h" #include "os/OsFS.h" #include "os/OsLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const unsigned long CopyBufLen = 32768; const unsigned long OsFileLockTimeout = 1000; const int INVALID_PID = 0; #define READ_BUFFER_SIZE 1024 //needed this so vxworks macros will find OK for the stdio funcs #ifdef _VXWORKS #ifndef OK #define OK 0 #endif /* OK */ #endif /* _VXWORKS */ // STATIC VARIABLE INITIALIZATIONS /* const int OsFileBase::READ_ONLY = 1; const int OsFileBase::WRITE_ONLY = 2; const int OsFileBase::READ_WRITE = 4; const int OsFileBase::CREATE = 8; const int OsFileBase::TRUNCATE = 16; const int OsFileBase::APPEND = 32; const int OsFileBase::FSLOCK = 64; const int OsFileBase::FSLOCK_WAIT = 128; */ //OsConfigDb stores filename -> "W" for locked files OsConfigDb *OsFileBase::mpFileLocks = NULL; // Guard to protect Open getting call by multiple threads OsBSem sOpenLock(OsBSem::Q_PRIORITY, OsBSem::FULL); /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsFileBase::OsFileBase(const OsPathBase& filename) : fileMutex(OsMutex::Q_FIFO), mOsFileHandle(NULL), mFilename(filename) { OsLock lock(fileMutex); if (mpFileLocks == NULL) { mpFileLocks = new OsConfigDb(); } } // Copy constructor OsFileBase::OsFileBase(const OsFileBase& rOsFileBase) : fileMutex(OsMutex::Q_FIFO), mFilename("") { #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::OsFileBase ENTER threadid=%d\n", nTaskId); #endif OsPathBase path; rOsFileBase.getFileName(path); mFilename = path; mMode = rOsFileBase.mMode; mOsFileHandle = rOsFileBase.mOsFileHandle; #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::OsFileBase EXIT threadid=%d\n", nTaskId); #endif } // Destructor OsFileBase::~OsFileBase() { #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::~OsFileBase ENTER threadid=%d\n", nTaskId); #endif if (mOsFileHandle) close(); //call our close #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::~OsFileBase EXIT threadid=%d\n", nTaskId); #endif } /* ============================ MANIPULATORS ============================== */ long OsFileBase::openAndRead(const char* filename, UtlString& fileContentsRead) { fileContentsRead.remove(0); OsFile fileToRead(filename); long totalBytesRead = -1; if(OS_SUCCESS == fileToRead.open(READ_ONLY)) { char buffer[READ_BUFFER_SIZE]; unsigned long bytesRead = 0; while(fileToRead.read(buffer, READ_BUFFER_SIZE, bytesRead) == OS_SUCCESS && bytesRead > 0) { fileContentsRead.append(buffer, bytesRead); } totalBytesRead = fileContentsRead.length(); fileToRead.close(); } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "unable to open file: \"%s\" for read", filename ? filename : ""); } return(totalBytesRead); } long OsFileBase::openAndWrite(const char* filename, const UtlString& fileContentsToWrite) { return(openAndWrite(filename, fileContentsToWrite.data(), fileContentsToWrite.length())); } long OsFileBase::openAndWrite(const char* filename, const char* fileContentsToWrite, unsigned int contentLength) { OsFile fileToWrite(filename); long totalBytesWritten = -1; unsigned long bytesWritten = 0; if(OS_SUCCESS == fileToWrite.open(WRITE_ONLY) && OS_SUCCESS == fileToWrite.write(fileContentsToWrite, contentLength, bytesWritten)) { totalBytesWritten = bytesWritten; } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "unable to open file: \"%s\" for write", filename ? filename : ""); } fileToWrite.close(); return(totalBytesWritten); } OsStatus OsFileBase::setReadOnly(UtlBoolean isReadOnly) { #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::setReadOnly ENTER threadid=%d\n", nTaskId); #endif OsStatus status = OsFileSystem::setReadOnly(mFilename,isReadOnly); #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::setReadOnly EXIT threadid=%d\n", nTaskId); #endif return status; } OsStatus OsFileBase::fileunlock() { #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::fileunlock ENTER threadid=%d\n", nTaskId); #endif OsStatus retval = OS_SUCCESS; //no file locking on the base class (yet) (I'm doing linux and windows first) #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::fileunlock EXIT threadid=%d\n", nTaskId); #endif return retval; } OsStatus OsFileBase::filelock(const bool wait) { #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::filelock ENTER threadid=%d\n", nTaskId); #endif OsStatus retval = OS_SUCCESS; //no file locking on the base class (yet) (I'm doing linux and windows first) #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::filelock EXIT threadid=%d\n", nTaskId); #endif return retval; } OsStatus OsFileBase::open(const int mode) { #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::open ENTER threadid=%d, filename=%s\n", nTaskId, mFilename.data()); #endif if ((mode & READ_ONLY) && ((mode & FSLOCK) || (mode & FSLOCK_WAIT))) return OS_FILE_READONLY; //get a lock for the open call sOpenLock.acquire(); OsStatus stat = OS_INVALID; const char* fmode = ""; if (mode & CREATE) fmode = "wb+"; if (mode & READ_ONLY) fmode = "rb"; if (mode & WRITE_ONLY) fmode = "wb"; if (mode & READ_WRITE) fmode = "rb+"; if (mode & APPEND) fmode = "ab+"; if (mode & TRUNCATE) fmode = "wb"; mOsFileHandle = fopen(mFilename.data(),fmode); mMode = mode; #ifndef _VXWORKS // 6/27/03 - Bob - Disabling locking under vxworks - crashes //success if (mOsFileHandle && ((mode & FSLOCK) || (mode & FSLOCK_WAIT))) { #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::open fopen returned mOsFileHandle=0x%08x, fd=%d, threadid=%d, filename=%s\n", mOsFileHandle, fileno(mOsFileHandle), nTaskId, mFilename.data()); #endif //first test to see if we have a local file lock on that file char* pLockName = new char[mFilename.length() + 1]; sprintf(pLockName, "%s", mFilename.data()); UtlString rValue; if (getFileLocks()->get(pLockName,rValue) == OS_SUCCESS) { if (mode & FSLOCK_WAIT) { //we need to wait until the lock is freed for (;;) { OsTask::delay(OsFileLockTimeout); if (getFileLocks()->get(pLockName,rValue) != OS_SUCCESS) break; } stat = OS_SUCCESS; } else { ::fclose(mOsFileHandle); mOsFileHandle = NULL; stat = OS_FILE_ACCESS_DENIED; } } else { rValue = "W"; getFileLocks()->set(pLockName,rValue); stat = OS_SUCCESS; } //if the lock is ok at this point, we need to get a cross-process lock if (stat == OS_SUCCESS) { stat = filelock((mode & FSLOCK_WAIT) ? true : false); if (stat != OS_SUCCESS) { ::fclose(mOsFileHandle); mOsFileHandle = NULL; stat = OS_FILE_ACCESS_DENIED; //remove local process locks getFileLocks()->remove(pLockName); } } delete[] pLockName; } else if (mOsFileHandle) { stat = OS_SUCCESS; } else { switch(errno) { case EACCES : case EMFILE : stat = OS_FILE_ACCESS_DENIED; break; case ENOENT : stat = OS_FILE_NOT_FOUND; break; } } #else if (mOsFileHandle) stat = OS_SUCCESS; #endif sOpenLock.release(); #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::open EXIT threadid=%d\n", nTaskId); #endif return stat; } OsStatus OsFileBase::flush() { OsLock lock(fileMutex); #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::flush EXIT threadid=%d\n", nTaskId); #endif OsStatus stat = OS_INVALID; if (mOsFileHandle) { if (fflush(mOsFileHandle) == 0) stat = OS_SUCCESS; } #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::flush EXIT threadid=%d\n", nTaskId); #endif return stat; } OsStatus OsFileBase::write(const void* buf, unsigned long buflen, unsigned long& bytesWritten) { OsLock lock(fileMutex); #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::write ENTER threadid=%d\n", nTaskId); #endif OsStatus stat = OS_INVALID; if (mOsFileHandle) bytesWritten = ::fwrite(buf,1,buflen,mOsFileHandle); if (bytesWritten == buflen) stat = OS_SUCCESS; #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::write EXIT threadid=%d\n", nTaskId); #endif return stat; } OsStatus OsFileBase::setLength(unsigned long newLength) { #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::setLength ENTER threadid=%d\n", nTaskId); #endif OsStatus stat = OS_SUCCESS; #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::setLength EXIT threadid=%d\n", nTaskId); #endif return stat; } OsStatus OsFileBase::setPosition(long pos, FilePositionOrigin origin) { OsLock lock(fileMutex); #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::setPosition ENTER threadid=%d\n", nTaskId); #endif OsStatus stat = OS_INVALID; if (mOsFileHandle) { int startloc = -1; if (origin == START) startloc = SEEK_SET; else if (origin == CURRENT) startloc = SEEK_CUR; else if (origin == END) startloc = SEEK_END; if (startloc != -1 && fseek(mOsFileHandle,pos,startloc) != -1) stat = OS_SUCCESS; } #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::setPosition EXIT threadid=%d\n", nTaskId); #endif return stat; } OsStatus OsFileBase::getPosition(unsigned long &pos) { OsLock lock(fileMutex); pos = UTL_NOT_FOUND; #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::getPosition ENTER threadid=%d\n", nTaskId); #endif OsStatus stat = OS_INVALID; if (mOsFileHandle) { pos = ftell(mOsFileHandle); if (pos != UTL_NOT_FOUND) { stat = OS_SUCCESS; } } #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::getPosition EXIT threadid=%d\n", nTaskId); #endif return stat; } OsStatus OsFileBase::remove(UtlBoolean bForce) { #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::remove ENTER threadid=%d\n", nTaskId); #endif OsStatus ret = OS_INVALID; //if it's open then close it close(); ret = OsFileSystem::remove(mFilename.data(),FALSE,bForce); #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::remove EXIT threadid=%d\n", nTaskId); #endif return ret; } OsStatus OsFileBase::rename(const OsPathBase& rNewFilename) { OsLock lock(fileMutex); #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::rename ENTER threadid=%d\n", nTaskId); #endif OsStatus ret = OS_INVALID; //if it's open then close it close(); int err = ::rename(mFilename.data(),rNewFilename.data()); if (err != -1) { ret = OS_SUCCESS; } else { // Rename failed, if there is a file that already exists having // the new name, try removing it first OsFile fileInPlace(rNewFilename); if(fileInPlace.exists()) { fileInPlace.remove(TRUE); // Try the move again int err2 = ::rename(mFilename.data(),rNewFilename.data()); if (err2 != -1) { ret = OS_SUCCESS; } } } #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::rename EXIT threadid=%d\n", nTaskId); #endif return ret; } OsStatus OsFileBase::copy(const OsPathBase& newFilename) { #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::copy ENTER threadid=%d\n", nTaskId); #endif OsStatus ret = OS_FILE_WRITE_FAILED; unsigned long copySize = 0; unsigned long totalBytesRead = 0; unsigned long totalBytesWritten = 0; unsigned long BytesRead = 0; unsigned long BytesWritten = 0; UtlBoolean bError = FALSE; OsFile newFile(newFilename); char *buf = new char[CopyBufLen]; if (buf) { //open existsing file if (open() == OS_SUCCESS) { if (getLength(copySize) == OS_SUCCESS) { //open new file newFile.open(CREATE); while (totalBytesRead < copySize && !bError) { //read in one block if (read(buf,CopyBufLen,BytesRead) == OS_SUCCESS) { totalBytesRead += BytesRead; if (newFile.write(buf,BytesRead,BytesWritten) == OS_SUCCESS) { if (BytesWritten != BytesRead) { bError = TRUE; } else totalBytesWritten += BytesWritten; } else { bError = TRUE; } } else bError = TRUE; } if (!bError) ret = OS_SUCCESS; newFile.close(); } close(); } delete [] buf; } #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::copy EXIT threadid=%d\n", nTaskId); #endif return ret; } OsStatus OsFileBase::touch() { #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::touch ENTER threadid=%d\n", nTaskId); #endif OsStatus stat = OS_INVALID; char buf[5]; unsigned long BytesRead; unsigned long BytesWritten; //open read one byte, write it back, then close //hope this is what we need to do for touch if (exists() && open() == OS_SUCCESS) { if (read(buf,1,BytesRead) == OS_SUCCESS) { setPosition(0); if (write(buf,BytesRead,BytesWritten) == OS_SUCCESS) stat = OS_SUCCESS; } close(); } else { open(CREATE); close(); stat = OS_SUCCESS; } #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::touch EXIT threadid=%d\n", nTaskId); #endif return stat; } /* ============================ ACCESSORS ================================= */ void OsFileBase::getFileName(OsPathBase& rOsPath) const { #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::getFileName ENTER threadid=%d\n", nTaskId); #endif rOsPath = mFilename; #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::getFileName EXIT threadid=%d\n", nTaskId); #endif } OsStatus OsFileBase::read(void* buf, unsigned long buflen, unsigned long& bytesRead) { OsLock lock(fileMutex); #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::read ENTER threadid=%d\n", nTaskId); #endif OsStatus stat = OS_INVALID; if (mOsFileHandle) { bytesRead = ::fread(buf,1,buflen,mOsFileHandle); if (bytesRead == 0 && feof(mOsFileHandle)) stat = OS_FILE_EOF; else stat = OS_SUCCESS; if (ferror(mOsFileHandle)) stat = OS_FILE_INVALID_HANDLE; } else stat = OS_FILE_INVALID_HANDLE; #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::read EXIT threadid=%d\n", nTaskId); #endif return stat; } OsStatus OsFileBase::readLine(UtlString &str) { #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::readLine ENTER threadid=%d\n", nTaskId); #endif char buf[2]; unsigned long bytesRead; OsStatus retstat = OS_INVALID; buf[1] = '\0'; str.remove(0); do { retstat = read(buf, 1, bytesRead); if (retstat == OS_SUCCESS && (*buf != '\n' && *buf != '\r')) { str.append(buf, 1); } } while (retstat == OS_SUCCESS && bytesRead == 1 && *buf != '\n'); #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::readLine EXIT threadid=%d\n", nTaskId); #endif return retstat; } UtlBoolean OsFileBase::close() { OsLock lock(fileMutex); #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); int fd = -1; if (mOsFileHandle) fd = fileno(mOsFileHandle); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::close ENTER mOsFileHandle=0x%08x, fd=%d, threadid=%d, filename=%s\n", mOsFileHandle, fd, nTaskId, mFilename.data()); #endif UtlBoolean retval = TRUE; if (mOsFileHandle) { #ifndef _VXWORKS // 6/27/03 - Bob - Disabling locking under vxworks - crashes if ((mMode & FSLOCK) || (mMode & FSLOCK_WAIT)) { char* pLockName = new char[mFilename.length() + 1]; sprintf(pLockName, "%s", mFilename.data()); // remove any local process locks getFileLocks()->remove(pLockName); delete[] pLockName; // remove any cross-process locks fileunlock(); } #endif if (::fclose(mOsFileHandle) != 0) { retval = FALSE; OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::close failed, mOsFileHandle=%p, errno=%d", mOsFileHandle, errno); } mOsFileHandle = 0; } #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::close EXIT threadid=%d\n", nTaskId); #endif return retval; } /* ============================ INQUIRY =================================== */ UtlBoolean OsFileBase::isEOF() { OsLock lock(fileMutex); #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::isEOF ENTER threadid=%d\n", nTaskId); #endif UtlBoolean retval = FALSE; if (mOsFileHandle) { if (feof(mOsFileHandle)) retval = TRUE; } #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::isEOF EXIT threadid=%d\n", nTaskId); #endif return retval; } UtlBoolean OsFileBase::isReadonly() const { #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::isReadonly ENTER threadid=%d\n", nTaskId); #endif OsFileInfoBase info; getFileInfo(info); #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::isReadonly EXIT threadid=%d\n", nTaskId); #endif return info.mbIsReadOnly; } OsStatus OsFileBase::getLength(unsigned long& flength) { #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::getLength ENTER threadid=%d\n", nTaskId); #endif OsStatus ret = OS_INVALID; unsigned long saved_pos; if (getPosition(saved_pos) == OS_SUCCESS) { if (setPosition(0,END) == OS_SUCCESS) { if (getPosition(flength) == OS_SUCCESS) { if (setPosition(saved_pos,START) == OS_SUCCESS) { ret = OS_SUCCESS; } } } } #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::getLength EXIT threadid=%d\n", nTaskId); #endif return ret; } UtlBoolean OsFileBase::exists() { #ifdef DEBUG_FS int nTaskId = 0; OsTask* pTask = OsTask::getCurrentTask(); if (pTask) pTask->id(nTaskId); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::exists ENTER threadid=%d\n", nTaskId); #endif UtlBoolean stat = FALSE; OsFileInfo info; OsStatus retval = getFileInfo(info); if (retval == OS_SUCCESS) stat = TRUE; #ifdef DEBUG_FS OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsFileBase::exists EXIT threadid=%d\n", nTaskId); #endif return stat; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ // Assignment operator OsFileBase& OsFileBase::operator=(const OsFileBase& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsFileInfoBase.cpp0000644000175000017500000000407712205613256024373 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsFileInfoBase.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsFileInfoBase::OsFileInfoBase() { } // Copy constructor OsFileInfoBase::OsFileInfoBase(const OsFileInfoBase& rOsFileInfoBase) { } // Destructor OsFileInfoBase::~OsFileInfoBase() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsFileInfoBase& OsFileInfoBase::operator=(const OsFileInfoBase& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } /* ============================ ACCESSORS ================================= */ OsStatus OsFileInfoBase::getCreateTime(OsTime& time) const { OsStatus stat = OS_SUCCESS; time = mCreateTime; return stat; } OsStatus OsFileInfoBase::getModifiedTime(OsTime& time) const { OsStatus stat = OS_SUCCESS; time = mModifiedTime; return stat; } OsStatus OsFileInfoBase::getSize(unsigned long& size) const { OsStatus stat = OS_SUCCESS; size = mSize; return stat; } /* ============================ INQUIRY =================================== */ UtlBoolean OsFileInfoBase::isReadOnly() const { return mbIsReadOnly; } UtlBoolean OsFileInfoBase::isDir() const { return mbIsDirectory; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsFileIteratorBase.cpp0000644000175000017500000001130612205613256025262 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsFS.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsFileIteratorBase::OsFileIteratorBase(const OsPathBase& pathname) : mUserSpecifiedPath(pathname), mFilterExp(NULL), mSearchHandle(INVALID_HANDLE) { } OsFileIteratorBase::OsFileIteratorBase() : mFilterExp(NULL), mSearchHandle(INVALID_HANDLE) { } void OsFileIteratorBase::Release() { if (mFilterExp) { delete mFilterExp; mFilterExp = NULL; } } // Destructor OsFileIteratorBase::~OsFileIteratorBase() { Release(); } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ OsStatus OsFileIteratorBase::findFirst(OsPathBase& entry, const char* filterExp, OsFileType filetype) { OsFileType entryType; UtlBoolean bDone = FALSE; UtlString name; OsStatus stat = OS_FILE_NOT_FOUND; UtlBoolean bFirstTime = TRUE; UtlBoolean bFoundOne = false; mMatchAttrib = filetype; mFileCount = 0; entry = ""; Release(); mFilterExp = new RegEx(filterExp); //add a sep on the end if there is not already one there if ( mUserSpecifiedPath.length() && *(mUserSpecifiedPath.data()+mUserSpecifiedPath.length()-1) != OsPathBase::separator ) { mUserSpecifiedPath += OsPathBase::separator; } mFullSearchSpec = mUserSpecifiedPath; while (!bDone) { //returns OS_SUCCESS or OS_FILE_NOT_FOUND //because we may have found a file that is not the one we want, the next //search we do we should use NextEntry if (bFirstTime) { stat = getFirstEntryName(name, entryType); } else { stat = getNextEntryName(name, entryType); } //so we don't use FirstEntry next time bFirstTime = FALSE; if (stat == OS_SUCCESS) { if (entryType == mMatchAttrib || mMatchAttrib == ANY_FILE) { //now check if if meets our regexp criteria if (mFilterExp->Search(name.data())) { entry = name; stat = OS_SUCCESS; bDone = TRUE; bFoundOne = TRUE; mFileCount++; } } } else { bDone = TRUE; } } if (!bFoundOne) { stat = OS_FILE_NOT_FOUND; } return stat; } OsStatus OsFileIteratorBase::findNext(OsPathBase& entry) { OsFileType entryType; UtlBoolean bDone = FALSE; OsStatus stat = OS_FILE_NOT_FOUND; UtlString name; UtlBoolean bFoundOne = false; entry = ""; while (!bDone) { //returns OS_SUCCESS or OS_FILE_NOT_FOUND stat = getNextEntryName(name,entryType); if (stat == OS_SUCCESS) { if (entryType == mMatchAttrib || mMatchAttrib == ANY_FILE) { //now check if if meets our regexp criteria if (mFilterExp->Search(name.data())) { //bDone so we get out of the while (!bDone) bDone = TRUE; //name to return to user entry = name; stat = OS_SUCCESS; mFileCount++; bFoundOne = true; } } } else { bDone = TRUE; } } if (!bFoundOne) { stat = OS_FILE_NOT_FOUND; } return stat; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ OsStatus OsFileIteratorBase::getNextEntryName(UtlString &rName, OsFileType &rFileType) { return OS_INVALID; } OsStatus OsFileIteratorBase::getFirstEntryName(UtlString &rName, OsFileType &rFileType) { return OS_INVALID; } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsFileSystem.cpp0000644000175000017500000001752512205613256024173 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #ifdef WINCE # include #else # include # include #endif #ifdef __posix_under_pingtel__ #include #endif #ifdef _WIN32 # ifndef WINCE # include # include # endif #endif #ifdef TEST #include "utl/UtlMemCheck.h" #endif // TEST // APPLICATION INCLUDES #include "os/OsFileSystem.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsFileSystem::OsFileSystem() { #ifdef TEST if (!sIsTested) { sIsTested = true; test(); } #endif // TEST } // Copy constructor OsFileSystem::OsFileSystem(const OsFileSystem& rOsFileSystem) { } // Destructor OsFileSystem::~OsFileSystem() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsFileSystem& OsFileSystem::operator=(const OsFileSystem& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } OsStatus OsFileSystem::setReadOnly(const OsPath& rPath, UtlBoolean isReadOnly) { OsStatus retval = OS_FAILED; #ifdef _VXWORKS #else #ifndef WINCE int mode = S_IREAD; if (!isReadOnly) mode |= S_IWRITE; if (chmod(rPath.data(),mode) != -1) retval = OS_SUCCESS; #endif #endif return retval; } //: Returns OS_SUCCESS if file copied ok. // see OsFile for more return codes OsStatus OsFileSystem::copy(const OsPath& source, const OsPath& dest) { OsFile sourcefile(source); return sourcefile.copy(dest); } //: Removes the directory or file specified by path OsStatus OsFileSystem::remove(const OsPath& path, UtlBoolean bRecursive, UtlBoolean bForce) { OsStatus retval = OS_INVALID; OsFileInfo info; OsPath testpath = path; OsStatus stat = getFileInfo(testpath,info); if (stat == OS_INVALID) { return OS_INVALID; } if (info.isDir()) { if (bRecursive) { retval = removeTree(path,bForce); } else { if (rmdir((char *)path.data()) != -1) retval = OS_SUCCESS; } } else { if (bForce) setReadOnly(path,FALSE); if (::remove(path.data()) != -1) retval = OS_SUCCESS; } return retval; } //: Renames the directory or file specified by path // (no path may be specifed on 2nd parameter) OsStatus OsFileSystem::rename(const OsPath& source, const OsPath& dest) { OsDir dir(source); return dir.rename(dest); } //: Change the current working directory to the specified location OsStatus OsFileSystem::change(const OsPath& path) { OsStatus stat = OS_INVALID; OsPath dir = path; if (chdir((char*) path.data()) != -1) stat = OS_SUCCESS; return stat; } //: Creates the specified directory // Fails if a file by the same name exist in the parent directory OsStatus OsFileSystem::createDir(const OsPath& path, const UtlBoolean createParent) { OsStatus stat = OS_SUCCESS; if (createParent) { stat = createDirRecursive(path); } if ( stat == OS_SUCCESS) { OsDir dir(path); stat = dir.create(); } return stat; } //: returns the current working directory for the process // OsStatus OsFileSystem::getWorkingDirectory(OsPath& path) { char buf[256]; OsStatus stat = OS_INVALID; if (getcwd(buf,256)) { stat = OS_SUCCESS; path=buf; } return stat; } /* ============================ ACCESSORS ================================= */ //: Retrieve system info for specified directory or file OsStatus OsFileSystem::getFileInfo(OsPath& filespec, OsFileInfo& fileInfo) { OsDir dir(filespec); return dir.getFileInfo(fileInfo); } /* ============================ INQUIRY =================================== */ //returns true if the specified file exists UtlBoolean OsFileSystem::exists(const OsPath& filename) { OsDir direntry(filename); return direntry.exists(); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ //: Removes the directory annd all sub-dirs OsStatus OsFileSystem::removeTree(const OsPath& path,UtlBoolean bForce) { UtlBoolean bFailed = FALSE; OsPath origDir; OsFileSystem::getWorkingDirectory(origDir); OsStatus retval = OS_INVALID; OsFileInfo info; OsPath testpath = path; getFileInfo(testpath,info); OsFileIterator::OsFileType fileType = OsFileIterator::ANY_FILE; //only do this if it is a directory if (info.isDir()) { if (OsFileSystem::change(path) == OS_SUCCESS) { OsFileIterator *files = new OsFileIterator(); OsPath entry; OsStatus filestat = files->findFirst(entry,".*", fileType); while (!bFailed && filestat == OS_SUCCESS) { if (entry != "." && entry != "..") { getFileInfo(entry,info); if (info.isDir()) { if (removeTree(entry,bForce) != OS_SUCCESS) { bFailed = TRUE; } } else { OsFile tmpfile(entry); if (tmpfile.remove(bForce) != OS_SUCCESS) { osPrintf("ERROR: can't removing file %s\n",entry.data()); retval = OS_FAILED; bFailed = TRUE; } } } filestat = files->findNext(entry); } delete files; if (OsFileSystem::change(origDir) == OS_SUCCESS) { if (!bFailed && OsFileSystem::remove(path,FALSE,FALSE) != OS_SUCCESS) { osPrintf("ERROR: can't remove dir %s\n",path.data()); retval = OS_FAILED; } else { retval = OS_SUCCESS; } } else { retval = OS_FAILED; } } } return retval; } OsStatus OsFileSystem::createDirRecursive(const OsPath& rOsPath) { OsStatus retval = OS_FAILED; UtlString parentDir; if (!exists(rOsPath)) { // Find last separator and chop last name off path UtlString sep = OsPath::separator; int lastSep = -1; size_t nextSep = rOsPath.index(sep); while (nextSep != UtlString::UTLSTRING_NOT_FOUND) { lastSep = nextSep; nextSep = rOsPath.index(sep, lastSep+1); } if (lastSep != -1) { parentDir = rOsPath(0, lastSep); OsPath parent(parentDir); if (!exists(parent)) { retval = createDirRecursive(parent); if (retval == OS_SUCCESS) { OsDir dir(parent); retval = dir.create(); } } else { retval = OS_SUCCESS; } } } else { retval = OS_SUCCESS; } return retval; } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsLockingList.cpp0000644000175000017500000001052712205613256024324 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsDefs.h" #include #include #include "utl/UtlVoidPtr.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsLockingList::OsLockingList() : listMutex(OsMutex::Q_FIFO), iteratorLockCount(0), list(), listIterator(NULL), currentElement(NULL) { } // Copy constructor OsLockingList::OsLockingList(const OsLockingList& rOsLockingList) : listMutex(OsMutex::Q_FIFO) { } // Destructor OsLockingList::~OsLockingList() { // :TODO: shouldn't this be taking the lock? if(listIterator) { delete listIterator; listIterator = NULL; } list.destroyAll(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsLockingList& OsLockingList::operator=(const OsLockingList& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } void OsLockingList::push(void* element) { assert(element); UtlVoidPtr* elementContainer = new UtlVoidPtr(element); // Lock before accessing the list OsLock localLock(listMutex); list.append(elementContainer); } void* OsLockingList::pop() { void* element = NULL; // Lock before accessing the list OsLock localLock(listMutex); if (list.entries()) { UtlVoidPtr* elementContainer = static_cast(list.last()); list.removeReference(elementContainer); element = (void*) elementContainer->getValue(); delete elementContainer; } return(element); } int OsLockingList::getIteratorHandle() { // Lock for the iterator listMutex.acquire(); // Only one iterator is allowed at a time assert(listIterator == NULL); listIterator = new UtlDListIterator(list); iteratorLockCount++; currentElement=NULL; return(iteratorLockCount); } void OsLockingList::releaseIteratorHandle(int iteratorHandle) { assertIterator(iteratorHandle); delete listIterator; listIterator = NULL; currentElement=NULL; // Release for the iterator listMutex.release(); } void OsLockingList::resetIterator(int iteratorHandle) { assertIterator(iteratorHandle); listIterator->reset(); currentElement=NULL; } void* OsLockingList::next(int iteratorHandle) { void* element = NULL; assertIterator(iteratorHandle); currentElement = (UtlVoidPtr*)((*listIterator)()); if(currentElement) { element = (void*) currentElement->getValue(); } return(element); } void* OsLockingList::remove(int iteratorHandle) { void* element = NULL; assertIterator(iteratorHandle); if (currentElement) { UtlVoidPtr* elementContainer = (UtlVoidPtr*)list.removeReference(currentElement); if(elementContainer) { element = (void*) elementContainer->getValue(); delete elementContainer; currentElement=NULL; } } return(element); } /* ============================ ACCESSORS ================================= */ int OsLockingList::getCount() { OsLock localLock(listMutex); return(list.entries()); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ void OsLockingList::assertIterator(int iteratorHandle) { // Only one iterator is allowed at a time assert(iteratorHandle == iteratorLockCount); assert(listIterator); } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsIntPtrMsg.cpp0000644000175000017500000000416512205613256023772 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsIntPtrMsg.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const UtlContainableType OsIntPtrMsg::TYPE = "OsIntPtrMsg" ; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsIntPtrMsg::OsIntPtrMsg(const unsigned char msgType, const unsigned char msgSubType, intptr_t pData1, intptr_t pData2) : OsMsg(msgType, msgSubType), mpData1(pData1), mpData2(pData2) { // all of the required work is done by the initializers } // Copy constructor OsIntPtrMsg::OsIntPtrMsg(const OsIntPtrMsg& rOsMsg) : OsMsg(rOsMsg), mpData1(rOsMsg.mpData1), mpData2(rOsMsg.mpData2) { } // Create a copy of this msg object (which may be of a derived type) OsMsg* OsIntPtrMsg::createCopy(void) const { return new OsIntPtrMsg(*this); } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsIntPtrMsg& OsIntPtrMsg::operator=(const OsIntPtrMsg& rhs) { if (this != &rhs) // handle the assignment to self case { OsMsg::operator=(rhs); mpData1 = rhs.mpData1; mpData2 = rhs.mpData2; } return *this; } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsMsg.cpp0000644000175000017500000000773212205613256022634 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsMsg.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const UtlContainableType OsMsg::TYPE = "OsMsg" ; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsMsg::OsMsg(const unsigned char msgType, const unsigned char msgSubType) : mMsgType(msgType) , mMsgSubType(msgSubType) , mSentFromISR(FALSE) , mReusable(FALSE) , mInUse(TRUE) { // all of the required work is done by the initializers } // Copy constructor OsMsg::OsMsg(const OsMsg& rOsMsg) : mMsgType(rOsMsg.mMsgType) , mMsgSubType(rOsMsg.mMsgSubType) , mSentFromISR(rOsMsg.mSentFromISR) , mReusable(rOsMsg.mReusable) , mInUse((bool)rOsMsg.mInUse) { } // Create a copy of this msg object (which may be of a derived type) OsMsg* OsMsg::createCopy(void) const { return new OsMsg(*this); } // Done with message, delete it or mark it unused void OsMsg::releaseMsg() { if (isMsgReusable()) { setInUse(FALSE); } else { delete this; } } // Destructor OsMsg::~OsMsg() { // no work required assert(!isMsgReusable()); } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsMsg& OsMsg::operator=(const OsMsg& rhs) { if (this != &rhs) // handle the assignment to self case { mMsgType = rhs.mMsgType; mMsgSubType = rhs.mMsgSubType; mSentFromISR = rhs.mSentFromISR; mReusable = rhs.mReusable; mInUse = (bool)rhs.mInUse; } return *this; } // Set the message subtype void OsMsg::setMsgSubType(unsigned char subType) { mMsgSubType = subType; } // Set the SentFromISR (interrupt service routine) flag. void OsMsg::setSentFromISR(UtlBoolean sentFromISR) { mSentFromISR = sentFromISR; } // Set the Is Reusable (from permanent pool) flag void OsMsg::setReusable(UtlBoolean isReusable) { mReusable = isReusable; } // Set the Is In Use flag void OsMsg::setInUse(UtlBoolean isInUse) { mInUse = isInUse; } /* ============================ ACCESSORS ================================= */ // Return the message type unsigned char OsMsg::getMsgType(void) const { return mMsgType; } // Return the message subtype unsigned char OsMsg::getMsgSubType(void) const { return mMsgSubType; } // Return the size of the message in bytes. // This is a virtual method so that it will return the accurate size for // the message object even if that object has been upcast to the type of // an ancestor class. int OsMsg::getMsgSize(void) const { return sizeof(*this); } // Return TRUE if msg was sent from an interrupt svc routine, else FALSE. UtlBoolean OsMsg::getSentFromISR(void) const { return mSentFromISR; } // Return TRUE if msg is from a permanent pool, else FALSE UtlBoolean OsMsg::isMsgReusable(void) const { return mReusable; } // Return TRUE if msg is currently in use, else FALSE UtlBoolean OsMsg::isMsgInUse(void) const { return mInUse; } //! Implements the interface for a UtlContainable unsigned OsMsg::hash() const { return (uintptr_t) this; } UtlContainableType OsMsg::getContainableType() const { return OsMsg::TYPE ; } int OsMsg::compareTo(UtlContainable const* other) const { return ((uintptr_t) this) - ((uintptr_t) other); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsMsgPool.cpp0000644000175000017500000001442512205613256023463 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsMsgPool.h" #include "utl/UtlString.h" #include "os/OsSysLog.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Default constructor. model is a message of the single type that // will be contained in the pool, and its createCopy virtual method // will be used to populate the pool. The caller disposes of model OsMsgPool::OsMsgPool(const char* name, const OsMsg& model, int initialCount, int softLimit, int hardLimit, int increment, OsMsgPoolSharing sharing) : mIncrement(increment), mNext(0) { int i; OsMsg* pMsg; mpMutex = NULL; mCurrentCount = 0; mpModel = model.createCopy(); mpModel->setReusable(TRUE); mpModel->setInUse(FALSE); mpName = new UtlString((NULL == name) ? "Unknown" : name); mInitialCount = (initialCount > 1) ? initialCount : 10; mSoftLimit = (mInitialCount > softLimit) ? mInitialCount : softLimit; mHardLimit = (mSoftLimit > hardLimit) ? mSoftLimit : hardLimit; if (mHardLimit > mInitialCount) { assert(mIncrement>0); mIncrement = (mIncrement>0) ? mIncrement : 1; } mpElts = new OsMsg*[mHardLimit]; for (i=0; icreateCopy(); if (NULL != pMsg) { pMsg->setReusable(TRUE); pMsg->setInUse(FALSE); mpElts[i] = pMsg; mCurrentCount++; } } if (MULTIPLE_CLIENTS == sharing) { mpMutex = new OsMutex(OsMutex::Q_PRIORITY | OsMutex::DELETE_SAFE | OsMutex::INVERSION_SAFE); assert(NULL != mpMutex); } } // Destructor OsMsgPool::~OsMsgPool() { // Hmmm... int i; OsMsg* pMsg; if (NULL != mpMutex) mpMutex->acquire(); for (i=0; isetReusable(FALSE); if (!pMsg->isMsgInUse()) { mpElts[i] = NULL; delete pMsg; } } } delete[] mpElts; mpModel->setReusable(FALSE); delete mpModel; delete mpName; if (NULL != mpMutex) mpMutex->release(); delete mpMutex; } /* ============================ MANIPULATORS ============================== */ // Find and return an available element of the pool, creating more if // necessary and permitted. Return NULL if failure. OsMsg* OsMsgPool::findFreeMsg() { int i; OsMsg* pMsg; OsMsg* ret = NULL; // If there is a mutex for this pool, acquire it before doing any work. if (NULL != mpMutex) { mpMutex->acquire(); } // Scan mNext through the table looking for a message that is // allocated and not in use. for (i=0; ((iisMsgInUse()) { pMsg->setInUse(TRUE); ret = pMsg; } // Advance mNext, wrapping around if it reaches mCurrentCount. mNext++; if (mNext >= mCurrentCount) { mNext = 0; } } // If no free message was found. if (NULL == ret) { if (mCurrentCount > mSoftLimit) { if (mSoftLimit <= mHardLimit) { OsSysLog::add(FAC_KERNEL, PRI_WARNING, "OsMsgPool::FindFreeMsg '%s' queue size (%d) exceeds soft limit (%d)\n", mpName->data(), mCurrentCount, mSoftLimit); } } if (mCurrentCount < mHardLimit) { int limit; mNext = mCurrentCount; limit = mCurrentCount + mIncrement; if (limit > mHardLimit) limit = mHardLimit; // Create the new elements. for (i=mCurrentCount; icreateCopy(); if (NULL != pMsg) { pMsg->setReusable(TRUE); pMsg->setInUse(FALSE); mpElts[i] = pMsg; mCurrentCount++; } } ret = mpElts[mNext]; assert(NULL!=ret); if ((NULL != ret) && !ret->isMsgInUse()) { ret->setInUse(TRUE); } mNext++; if (mNext >= mCurrentCount) { mNext = 0; } } else { if (mSoftLimit <= mHardLimit) { OsSysLog::add(FAC_KERNEL, PRI_CRIT, "OsMsgPool::FindFreeMsg '%s' queue size (%d) exceeds hard limit (%d)\n", mpName->data(), mCurrentCount, mHardLimit); } mSoftLimit = mHardLimit + 1; } } // If there is a mutex for this pool, release it. if (NULL != mpMutex) { mpMutex->release(); } return ret; } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ // Return the number of items in use. int OsMsgPool::getNoInUse(void) { int i, count; if (NULL != mpMutex) { mpMutex->acquire(); } count = 0; for (i=0; i < mCurrentCount; i++) { if (mpElts[i] != NULL && mpElts[i]->isMsgInUse()) { count++; } } if (NULL != mpMutex) { mpMutex->release(); } return count; } // Return the current soft limit. int OsMsgPool::getSoftLimit(void) { return mSoftLimit; } // Return the current hard limit. int OsMsgPool::getHardLimit(void) { return mHardLimit; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsMsgQ.cpp0000644000175000017500000000715412205613256022753 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #ifdef __pingtel_on_posix__ # include #endif #include "utl/UtlRscTrace.h" // APPLICATION INCLUDES #include "os/OsExcept.h" #include "os/OsMsg.h" #include "os/OsMsgQ.h" #include "os/OsUtil.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS const int OsMsgQBase::DEF_MAX_MSGS = 100; const int OsMsgQBase::DEF_MAX_MSG_LEN = 32; const UtlString OsMsgQBase::MSGQ_PREFIX("MsgQ."); /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor // If the name is specified but is already in use, throw an exception OsMsgQBase::OsMsgQBase(const UtlString& name) : mSendHookFunc(NULL), mFlushHookFunc(NULL), mName(name) { if (mName != "") OsUtil::insertKeyValue(MSGQ_PREFIX, mName, (intptr_t)this); } // Destructor OsMsgQBase::~OsMsgQBase() { OsStatus res; if (mName != "") { res = OsUtil::deleteKeyValue(MSGQ_PREFIX, mName); assert(res == OS_SUCCESS); } } // Return a pointer to the named queue, or NULL if not found OsMsgQBase* OsMsgQBase::getMsgQByName(const UtlString& name) { OsStatus res; intptr_t val; if (name == "") return NULL; else { res = OsUtil::lookupKeyValue(MSGQ_PREFIX, name, &val); if (res == OS_SUCCESS) return ((OsMsgQBase*) val); else return NULL; } } /* ============================ MANIPULATORS ============================== */ // Delete all messages currently in the queue void OsMsgQBase::flush(void) { OsMsg* pMsg; while (receive(pMsg, OsTime::NO_WAIT_TIME) != OS_WAIT_TIMEOUT) { if (mFlushHookFunc != NULL) mFlushHookFunc(*pMsg); pMsg->releaseMsg(); } } // Set the function that is invoked whenever a msg is sent to the queue // The function takes the message to be sent as an argument and returns a // boolean value indicating whether the SendHook method has handled the // message. If TRUE, the message is not inserted into the queue (since it // has already been handled. If FALSE, the (possibly modified) message is // inserted into the queue. void OsMsgQBase::setSendHook(OsMsgQSendHookPtr func) { mSendHookFunc = func; } // Set the function that is invoked whenever a msg is flushed from the // queue. Messages get flushed when the OsMsgQ is deleted while there // are messages still queued. // The function takes an OsMsg reference as an argument. void OsMsgQBase::setFlushHook(OsMsgQFlushHookPtr func) { mFlushHookFunc = func; } /* ============================ ACCESSORS ================================= */ // Return a pointer to the current send hook function OsMsgQSendHookPtr OsMsgQBase::getSendHook(void) const { return mSendHookFunc; } // Return the queue size int OsMsgQBase::maxMsgs() const { return(mMaxMsgs); } /* ============================ INQUIRY =================================== */ // Return TRUE if the message queue is empty, FALSE otherwise UtlBoolean OsMsgQBase::isEmpty(void) { return (numMsgs() == 0); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsMsgDispatcher.cpp0000644000175000017500000000402212205613256024630 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Keith Kyzivat // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsMsgDispatcher.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ OsMsgDispatcher::OsMsgDispatcher() : mMsgsLost(FALSE) { mMsgQueue = new OsMsgQ(); mQueueOwned = true; } OsMsgDispatcher::OsMsgDispatcher(OsMsgQ* msgQ) : mMsgQueue(msgQ) , mQueueOwned(false) , mMsgsLost(FALSE) { } OsMsgDispatcher::~OsMsgDispatcher() { // Only delete the queue if we own it. if(mQueueOwned) { delete mMsgQueue; } } /* ============================ MANIPULATORS ============================== */ OsStatus OsMsgDispatcher::post(const OsMsg& msg) { if (mMsgQueue->numMsgs() == mMsgQueue->maxMsgs()) { setMsgsLost(); return OS_LIMIT_REACHED; } else { // Send the message, give it 1 millisecond to send. mMsgQueue->send(msg, OsTime(1)); return OS_SUCCESS; } }; OsStatus OsMsgDispatcher::receive(OsMsg*& rpMsg, const OsTime& rTimeout) { return mMsgQueue->receive(rpMsg, rTimeout); }; /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsMulticastSocket.cpp0000644000175000017500000001232512205613256025216 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #include #if defined(_WIN32) # include # include #elif defined(_VXWORKS) # include # include # include # include #elif defined(__pingtel_on_posix__) # include # include # include # include # include #else #error Unsupported target platform. #endif // APPLICATION INCLUDES #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsMulticastSocket::OsMulticastSocket(int multicastPortNum, const char* multicastHost, int localHostPortNum, const char* localHost) : OsDatagramSocket() { // Avoid EADDRINUSE error on bind() int iTmp = TRUE; if (setsockopt(socketDescriptor, SOL_SOCKET, SO_REUSEADDR, (char *)&iTmp, sizeof(iTmp))) { osPrintf("setsockopt SO_REUSEADDR call failed with error: %d\n", OsSocketGetERRNO()); } #ifdef SO_REUSEPORT if (setsockopt(socketDescriptor, SOL_SOCKET, SO_REUSEPORT, (char *)&iTmp, sizeof(iTmp))) { osPrintf("setsockopt SO_REUSEPORT call failed with error: %d\n", OsSocketGetERRNO()); } #endif // Bind to the socket bind(localHostPortNum, localHost); if (!isOk()) { goto EXIT; } // Simulate connect: Set multicast address as the default destination doConnect(multicastPortNum, multicastHost, TRUE); // Join the multicast group joinGroup(multicastHost); EXIT: return; } // Destructor OsMulticastSocket::~OsMulticastSocket() { close(); } /* ============================ MANIPULATORS ============================== */ int OsMulticastSocket::joinGroup(const char* multicastHostName) { int error = 0; struct hostent* server = NULL; #if defined(_WIN32) || defined(__pingtel_on_posix__) server = gethostbyname(multicastHostName); #elif defined(_VXWORKS) char hostentBuf[512]; server = resolvGetHostByName((char*) multicastHostName, hostentBuf, sizeof(hostentBuf)); #else # error Unsupported target platform. #endif //_VXWORKS if (server == NULL) { error = OsSocketGetERRNO(); close(); osPrintf("gethostbyname(%s) call failed with error: %d\n",multicastHostName, error); return error; } struct ip_mreq mreq; mreq.imr_multiaddr = *((in_addr*) (server->h_addr)); mreq.imr_interface.s_addr = OsSocket::getDefaultBindAddress(); //mreq.imr_interface.s_addr = htonl(INADDR_ANY); // NOTE: If this setsockopt() call return error 1042 under Windows, it mean // you linked your program with wsock32.lib instead of ws2_32.lib. // If you really want to link with wsock32.lib, change include // to point to instead of . This is known // Winsock bug: // http://blogs.msdn.com/wndp/archive/2006/12/18/winsock-header-weirdness.aspx if (setsockopt(socketDescriptor, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mreq, sizeof(mreq))) { error = OsSocketGetERRNO(); //close(); osPrintf("setsockopt IP_ADD_MEMBERSHIP call failed with error: %d\n", error); } return error; } int OsMulticastSocket::setHopCount(unsigned char hopCount) { int error = 0; if (setsockopt(socketDescriptor, IPPROTO_IP, IP_MULTICAST_TTL, (const char *)&hopCount, sizeof(hopCount))) { error = OsSocketGetERRNO(); //close(); osPrintf("setsockopt IP_MULTICAST_TTL call failed with error: %d\n", error); } return error; } int OsMulticastSocket::setLoopback(bool enabled) { int error = 0; unsigned char loopValue = enabled ? 1 : 0; if (setsockopt(socketDescriptor, IPPROTO_IP, IP_MULTICAST_LOOP, (const char *)&loopValue, sizeof(loopValue))) { error = OsSocketGetERRNO(); //close(); osPrintf("setsockopt IP_MULTICAST_LOOP call failed with error: %d\n", error); } return error; } /* ============================ ACCESSORS ================================= */ OsSocket::IpProtocolSocketType OsMulticastSocket::getIpProtocol() const { return(MULTICAST); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsNameDb.cpp0000644000175000017500000001127612205613256023232 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES // Keep OsNameDbInit.h as the first include! // See OsNameDbInit class description for more information. #include "os/OsNameDbInit.h" #include "os/OsNameDb.h" #include "os/OsReadLock.h" #include "os/OsWriteLock.h" #include "utl/UtlIntPtr.h" #include "utl/UtlString.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS static const int DEFAULT_NAMEDB_SIZE = 100; // STATIC VARIABLE INITIALIZATIONS OsNameDb* OsNameDb::spInstance; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Return a pointer to the singleton object OsNameDb* OsNameDb::getNameDb() { return spInstance; } // Destructor // Since the name database is a singleton object, this destructor should // not get called unless we are shutting down the system. OsNameDb::~OsNameDb() { spInstance = NULL; } /* ============================ MANIPULATORS ============================== */ // Add the key-value pair to the name database // Return OS_SUCCESS if successful, OS_NAME_IN_USE if the key is already in // the database. OsStatus OsNameDb::insert(const UtlString& rKey, const intptr_t value) { OsWriteLock lock(mRWLock); UtlString* pDictKey; UtlIntPtr* pDictValue; UtlString* pInsertedKey; pDictKey = new UtlString(rKey); pDictValue = new UtlIntPtr(value); pInsertedKey = (UtlString*) mDict.insertKeyAndValue(pDictKey, pDictValue); if (pInsertedKey == NULL) { // insert failed delete pDictKey; // clean up the key and value objects delete pDictValue; return OS_NAME_IN_USE; } else { return OS_SUCCESS; } } // Remove the indicated key-value pair from the name database. // If pValue is non-NULL, the value for the key-value pair is returned // via pValue. // Return OS_SUCCESS if the lookup is successful, return OS_NOT_FOUND // if there is no match for the specified key. OsStatus OsNameDb::remove(const UtlString& rKey, intptr_t* pValue) { OsWriteLock lock(mRWLock); OsStatus result = OS_NOT_FOUND; UtlString* pDictKey; UtlIntPtr* pDictValue; pDictKey = (UtlString*) mDict.removeKeyAndValue(&rKey, (UtlContainable*&) pDictValue); // If a value was found and removed ... if (pDictKey != NULL) { // If the caller provided a pointer through which to return the // integer value, do so. if (pValue != NULL) { *pValue = pDictValue->getValue(); } // Delete the key and value objects. delete pDictKey; delete pDictValue; result = OS_SUCCESS; } // Return success or failure as appropriate. return result; } /* ============================ ACCESSORS ================================= */ // Retrieve the value associated with the specified key. // If pValue is non-NULL, the value is returned via pValue. // Return OS_SUCCESS if the lookup is successful, return OS_NOT_FOUND if // there is no match for the specified key. OsStatus OsNameDb::lookup(const UtlString& rKey, intptr_t* pValue) { OsReadLock lock(mRWLock); OsStatus result = OS_NOT_FOUND; UtlIntPtr* pDictValue; pDictValue = (UtlIntPtr*) mDict.findValue(&rKey); // perform the lookup if (pDictValue != NULL) { if (pValue != NULL) // if we have a valid pointer, { // return the corresponding value *pValue = pDictValue->getValue(); } result = OS_SUCCESS; } return result; } // Return the number of key-value pairs in the name database int OsNameDb::numEntries(void) { OsReadLock lock(mRWLock); return mDict.entries(); } /* ============================ INQUIRY =================================== */ // Return TRUE if the name database is empty UtlBoolean OsNameDb::isEmpty(void) { return (numEntries() == 0); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ // Constructor (only available internal to the class) OsNameDb::OsNameDb() : mDict(), mRWLock(OsRWMutex::Q_PRIORITY) { // no other work required } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsNameDbInit.cpp0000644000175000017500000000304012205613256024044 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 Jaroslav Libak // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsNameDbInit.h" #include "os/OsNameDb.h" // DEFINES // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS unsigned int OsNameDBInit::msCount = 0; // MACROS // GLOBAL VARIABLES // GLOBAL FUNCTIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ OsNameDBInit::OsNameDBInit(void) { if (msCount++ == 0) { OsNameDb::spInstance = new OsNameDb(); } } OsNameDBInit::~OsNameDBInit(void) { if (--msCount == 0) { delete OsNameDb::spInstance; OsNameDb::spInstance = NULL; } } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsNatAgentTask.cpp0000644000175000017500000021650312205613256024430 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsNatAgentTask.h" #include "os/IStunSocket.h" #include "os/TurnMessage.h" #include "os/StunMessage.h" #include "os/StunUtils.h" #include "os/OsTimer.h" #include "os/OsMutex.h" #include "os/OsLock.h" #include "os/OsEvent.h" #include "os/OsWriteLock.h" #include "os/OsReadLock.h" #include "os/OsTime.h" #include "os/OsQueuedEvent.h" #include "utl/UtlVoidPtr.h" #include "utl/UtlHashMapIterator.h" #include "utl/UtlSListIterator.h" #ifndef _WIN32 #include #include #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS OsMutex OsNatAgentTask::sLock(OsMutex::Q_FIFO) ; OsNatAgentTask* OsNatAgentTask::spInstance = NULL ; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ OsNatAgentTask::OsNatAgentTask() : OsServerTask("OsNatAgentTask-%d") , mMapsLock(OsMutex::Q_FIFO) , mExternalBindingMutex(OsRWMutex::Q_FIFO) { } OsNatAgentTask::~OsNatAgentTask() { OsLock lock(mMapsLock) ; UtlVoidPtr* pKey ; // Wait for the thread to shutdown waitUntilShutDown() ; // Clear Context map UtlHashMapIterator iterator(mContextMap); while ((pKey = (UtlVoidPtr*)iterator())) { NAT_AGENT_CONTEXT* pContext = (NAT_AGENT_CONTEXT*) pKey->getValue(); mContextMap.destroy(pKey) ; releaseTimer(pContext->pTimer) ; delete pContext ; } // Clear Timers UtlSListIterator listIterator(mTimerPool); while ((pKey = (UtlVoidPtr*)listIterator())) { OsTimer* pTimer = (OsTimer*) pKey->getValue() ; mTimerPool.destroy(pKey) ; delete pTimer ; } // Clear external binding list OsWriteLock bindingLock(mExternalBindingMutex); UtlSListIterator itor(mExternalBindingsList); while ((pKey = (UtlVoidPtr*)itor())) { NAT_AGENT_EXTERNAL_CONTEXT* pContext = (NAT_AGENT_EXTERNAL_CONTEXT*)pKey->getValue(); mExternalBindingsList.destroy(pKey); delete pContext; } } OsNatAgentTask* OsNatAgentTask::getInstance() { OsLock lock(sLock) ; if (spInstance == NULL) { spInstance = new OsNatAgentTask() ; spInstance->start() ; } return spInstance ; } void OsNatAgentTask::releaseInstance() { OsLock lock(sLock) ; if (spInstance != NULL) { delete spInstance ; spInstance = NULL ; } } /* ============================ MANIPULATORS ============================== */ UtlBoolean OsNatAgentTask::handleMessage(OsMsg& rMsg) { UtlBoolean bHandled = false ; switch (rMsg.getMsgType()) { case NAT_MSG_TYPE: if (((NatMsg&) rMsg).getType() == NatMsg::STUN_MESSAGE) { bHandled = handleStunMessage((NatMsg&) rMsg) ; } else if (((NatMsg&) rMsg).getType() == NatMsg::TURN_MESSAGE) { bHandled = handleTurnMessage((NatMsg&) rMsg) ; } else if (((NatMsg&) rMsg).getType() == NatMsg::EXPIRATION_MESSAGE) { NAT_AGENT_CONTEXT* pContext = (NAT_AGENT_CONTEXT*) ((NatMsg&) rMsg).getContext() ; if (pContext) { bHandled = handleTimerEvent(pContext) ; } } else { // Unknown message type assert(false) ; } break ; case SYNC_MSG_TYPE: bHandled = handleSynchronize((OsRpcMsg&) rMsg) ; break ; case OsMsg::OS_EVENT: { // Pull out context NAT_AGENT_CONTEXT* pContext = NULL ; OsStatus rc = ((OsEventMsg&)rMsg).getUserData((intptr_t&) pContext) ; assert(rc == OS_SUCCESS) ; if ((rc == OS_SUCCESS) && (pContext != NULL)) { NatMsg msg(NatMsg::EXPIRATION_MESSAGE, pContext) ; postMessage(msg) ; } } break ; } return bHandled ; } UtlBoolean OsNatAgentTask::handleStunMessage(NatMsg& rMsg) { OsLock lock(mMapsLock) ; StunMessage msg ; size_t nBuffer = rMsg.getLength() ; char* pBuffer = rMsg.getBuffer() ; IStunSocket* pSocket = rMsg.getSocket() ; UtlString sendToAddress ; unsigned short sendToPort ; uint16_t unknownAttributes[STUN_MAX_UNKNOWN_ATTRIBUTES] ; size_t nUnknownAttributes ; if (OsSysLog::willLog(FAC_NET, PRI_DEBUG)) { if (pBuffer != NULL && nBuffer > 0) { UtlString output ; StunUtils::debugDump(pBuffer, nBuffer, output) ; OsSysLog::add(FAC_NET, PRI_DEBUG, "Inbound STUN message (Crude Parse):\n%s\n", output.data()) ; } } if ((nBuffer > 0) && pBuffer && pSocket && msg.parse(pBuffer, nBuffer)) { switch (msg.getType()) { case MSG_STUN_BIND_REQUEST: { StunMessage respMsg ; STUN_TRANSACTION_ID transactionId ; STUN_MAGIC_ID magicId ; // Copy over IDs msg.getTransactionId(&transactionId) ; respMsg.setTransactionId(transactionId) ; msg.getMagicId(&magicId) ; respMsg.setMagicId(magicId) ; // Check for unknown attributes if (msg.getUnknownParsedAttributes(unknownAttributes, STUN_MAX_UNKNOWN_ATTRIBUTES, nUnknownAttributes) && (nUnknownAttributes > 0)) { respMsg.setType(MSG_STUN_BIND_ERROR_RESPONSE) ; for (size_t i = 0; igetSocket()->getLocalIp(), pSocket->getSocket()->getLocalHostPort()) ; // Check for response address char cResponseAddress[64] ; uint16_t responsePort ; if (msg.getResponseAddress(cResponseAddress, responsePort)) { respMsg.setReflectedFrom(pSocket->getSocket()->getLocalIp(), pSocket->getSocket()->getLocalHostPort()) ; sendToAddress = cResponseAddress ; sendToPort = responsePort ; } else { sendToAddress = rMsg.getReceivedIp() ; sendToPort = rMsg.getReceivedPort() ; } sendMessage(&respMsg, pSocket, sendToAddress, sendToPort, STUN_DISCOVERY_PACKET) ; } } break ; case MSG_STUN_BIND_RESPONSE: { STUN_TRANSACTION_ID transactionId ; msg.getTransactionId(&transactionId) ; NAT_AGENT_CONTEXT* pContext = getBinding(&transactionId) ; if (pContext) { char mappedAddress[64] ; uint16_t mappedPort ; if (msg.getMappedAddress(mappedAddress, mappedPort)) { markStunSuccess(pContext, mappedAddress, mappedPort) ; } else { markStunFailure(pContext) ; } } } break ; case MSG_STUN_BIND_ERROR_RESPONSE: { STUN_TRANSACTION_ID transactionId ; msg.getTransactionId(&transactionId) ; NAT_AGENT_CONTEXT* pContext = getBinding(&transactionId) ; if (pContext) { markStunFailure(pContext) ; } } break ; case MSG_STUN_SHARED_SECRET_REQUEST: // TODO: Send error break ; case MSG_STUN_SHARED_SECRET_RESPONSE: case MSG_STUN_SHARED_SECRET_ERROR_RESPONSE: break ; } } if (pBuffer) { free(pBuffer) ; } return true ; } UtlBoolean OsNatAgentTask::handleTurnMessage(NatMsg& rMsg) { OsLock lock(mMapsLock) ; TurnMessage msg; TurnMessage respMsg ; size_t nBuffer = rMsg.getLength() ; char* pBuffer = rMsg.getBuffer() ; IStunSocket* pSocket = rMsg.getSocket() ; STUN_TRANSACTION_ID transactionId ; STUN_MAGIC_ID magicId ; if (OsSysLog::willLog(FAC_NET, PRI_DEBUG)) { if (pBuffer != NULL && nBuffer > 0) { UtlString output ; StunUtils::debugDump(pBuffer, nBuffer, output) ; OsSysLog::add(FAC_NET, PRI_DEBUG, "Inbound TURN message(Crude Parse):\n%s\n", output.data()) ; } } if ((nBuffer > 0) && pBuffer && pSocket && msg.parse(pBuffer, nBuffer)) { switch (msg.getType()) { case MSG_TURN_ALLOCATE_REQUEST: // Not supported on client msg.getTransactionId(&transactionId) ; respMsg.setTransactionId(transactionId) ; msg.getMagicId(&magicId) ; respMsg.setMagicId(magicId) ; respMsg.setError(STUN_ERROR_GLOBAL_CODE, STUN_ERROR_GLOBAL_TEXT) ; sendMessage(&respMsg, pSocket, rMsg.getReceivedIp(), rMsg.getReceivedPort(), TURN_PACKET) ; break ; case MSG_TURN_ALLOCATE_RESPONSE: { STUN_TRANSACTION_ID transactionId ; msg.getTransactionId(&transactionId) ; NAT_AGENT_CONTEXT* pContext = getBinding(&transactionId) ; if ((pContext) && pContext->type == TURN_ALLOCATION) { char relayAddress[64] ; uint16_t relayPort ; if (msg.getMappedAddress(relayAddress, relayPort)) { markTurnSuccess(pContext, relayAddress, relayPort) ; } else { markTurnFailure(pContext) ; } } } break ; case MSG_TURN_ALLOCATE_ERROR_RESPONSE: { STUN_TRANSACTION_ID transactionId ; msg.getTransactionId(&transactionId) ; NAT_AGENT_CONTEXT* pContext = getBinding(&transactionId) ; if ((pContext) && pContext->type == TURN_ALLOCATION) { markTurnFailure(pContext) ; } } break ; case MSG_TURN_SEND_REQUEST: // Not supported on client msg.getTransactionId(&transactionId) ; respMsg.setTransactionId(transactionId) ; msg.getMagicId(&magicId) ; respMsg.setMagicId(magicId) ; respMsg.setError(STUN_ERROR_GLOBAL_CODE, STUN_ERROR_GLOBAL_TEXT) ; sendMessage(&respMsg, pSocket, rMsg.getReceivedIp(), rMsg.getReceivedPort(), TURN_PACKET) ; break ; case MSG_TURN_SEND_RESPONSE: // Drop send response -- not much we can do right now. break ; case MSG_TURN_SEND_ERROR_RESPONSE: // Drop error response -- not much we can do right now. break ; case MSG_TURN_DATA_INDICATION: // Dropping data indication -- only locking onto a single // address for now break ; case MSG_TURN_ACTIVE_DESTINATION_RESPONSE: break ; case MSG_TURN_ACTIVE_DESTINATION_ERROR_RESPONSE: break ; default: // Unknown message type assert(false) ; break ; } } if (pBuffer) { free(pBuffer) ; } return true ; } UtlBoolean OsNatAgentTask::handleSynchronize(OsRpcMsg& rMsg) { OsEvent* pEvent = rMsg.getEvent() ; pEvent->signal(0) ; return true ; } UtlBoolean OsNatAgentTask::handleTimerEvent(NAT_AGENT_CONTEXT* pContext) { OsLock lock(mMapsLock) ; // Refresh the socket if ((pContext) && (pContext = getBinding(pContext))) { switch (pContext->type) { case STUN_PROBE: case STUN_DISCOVERY: handleStunTimeout(pContext) ; break ; case TURN_ALLOCATION: handleTurnTimeout(pContext) ; break ; case CRLF_KEEPALIVE: handleCrLfKeepAlive(pContext) ; break ; case STUN_KEEPALIVE: handleStunKeepAlive(pContext) ; break ; default: assert(false) ; break ; } } return true ; } void OsNatAgentTask::handleStunTimeout(NAT_AGENT_CONTEXT* pContext) { assert(pContext) ; if (pContext) { switch (pContext->status) { case SUCCESS: // Send keep-alive, set state to resending pContext->status = RESENDING ; if (!sendStunRequest(pContext)) { markStunFailure(pContext) ; } break ; case SENDING: // Migrate to sending_error and resend pContext->status = SENDING_ERROR ; if (!sendStunRequest(pContext)) { markStunFailure(pContext) ; } break ; case SENDING_ERROR: // If we have hit the max resends, fail otherwise resend pContext->refreshErrors++ ; if (pContext->refreshErrors < pContext->abortCount) { if (!sendStunRequest(pContext)) { markStunFailure(pContext) ; } } else { markStunFailure(pContext) ; } break ; case RESENDING: // Migrate to resend_error and resend pContext->status = RESENDING_ERROR ; pContext->refreshErrors++ ; if (!sendStunRequest(pContext)) { markStunFailure(pContext) ; } break ; case RESENDING_ERROR: pContext->refreshErrors++ ; if (pContext->refreshErrors < NAT_RESEND_ABORT_COUNT) { if (!sendStunRequest(pContext)) { markStunFailure(pContext) ; } } else { markStunFailure(pContext) ; } break ; case FAILED: // Nothing to do break ; } } } void OsNatAgentTask::handleTurnTimeout(NAT_AGENT_CONTEXT* pContext) { OsTime errorAt(0, NAT_RESPONSE_TIMEOUT_MS * OsTime::USECS_PER_MSEC) ; assert(pContext) ; if (pContext) { switch (pContext->status) { case SUCCESS: // Send keep-alive, set state to resending pContext->status = RESENDING ; pContext->pTimer->stop() ; pContext->pTimer->periodicEvery(errorAt, errorAt) ; if (!sendTurnRequest(pContext)) { markTurnFailure(pContext) ; } break ; case SENDING: // Migrate to sending_error and resend pContext->status = SENDING_ERROR ; if (!sendTurnRequest(pContext)) { markTurnFailure(pContext) ; } break ; case SENDING_ERROR: // If we have hit the max resends, fail otherwise resend pContext->refreshErrors++ ; if (pContext->refreshErrors < pContext->abortCount) { if (!sendTurnRequest(pContext)) { markTurnFailure(pContext) ; } } else { markTurnFailure(pContext) ; } break ; case RESENDING: // Migrate to resend_error and resend pContext->status = RESENDING_ERROR ; pContext->refreshErrors++ ; if (!sendTurnRequest(pContext)) { markTurnFailure(pContext) ; } break ; case RESENDING_ERROR: pContext->refreshErrors++ ; if (pContext->refreshErrors < NAT_RESEND_ABORT_COUNT) { if (!sendTurnRequest(pContext)) { markTurnFailure(pContext) ; } } else { markTurnFailure(pContext) ; } break ; case FAILED: // Nothing to do break ; } } } #define STR_CRLF "\r\n\0" UtlBoolean OsNatAgentTask::handleCrLfKeepAlive(NAT_AGENT_CONTEXT* pContext) { UtlBoolean bRC = false ; // just calling the socketWrite function, which does not do timestamping if (pContext->pSocket->socketWrite(STR_CRLF, 3, pContext->serverAddress, pContext->serverPort, CRLF_KEEPALIVE_PACKET) == 3) { bRC = true ; } else { if (pContext->pKeepaliveListener) { pContext->pKeepaliveListener->OnKeepaliveFailure( populateKeepaliveEvent(pContext)); } } return bRC ; } UtlBoolean OsNatAgentTask::handleStunKeepAlive(NAT_AGENT_CONTEXT* pContext) { UtlBoolean bRC = false ; if (sendStunRequest(pContext)) { bRC = true ; } else { if (pContext->pKeepaliveListener) { pContext->pKeepaliveListener->OnKeepaliveFailure( populateKeepaliveEvent(pContext)); } } return bRC ; } UtlBoolean OsNatAgentTask::sendStunProbe(IStunSocket* pSocket, const UtlString& stunServer, int stunPort, int priority) { OsLock lock(mMapsLock) ; bool bSuccess = false ; StunMessage msgSend ; UtlString serverAddress ; UtlString localHostIp ; pSocket->getSocket()->getLocalHostIp(&localHostIp) ; OsSysLog::add(FAC_NET, PRI_INFO, "Stun probe for %s:%d with server %s:%d priority=%d", localHostIp.data(), pSocket->getSocket()->getLocalHostPort(), stunServer.data(), stunPort, priority) ; assert(pSocket) ; assert(portIsValid(stunPort)) ; assert(stunServer.length() > 0) ; if ( pSocket && portIsValid(stunPort) && (stunServer.length() > 0) && OsSocket::getHostIpByName(stunServer, &serverAddress) && OsSocket::isIp4Address(serverAddress)) { NAT_AGENT_CONTEXT* pContext = new NAT_AGENT_CONTEXT ; //memset(pContext, 0, sizeof(NAT_AGENT_CONTEXT)); if (pContext) { pContext->type = STUN_PROBE ; pContext->status = SENDING ; pContext->serverAddress = serverAddress ; pContext->serverPort = stunPort ; pContext->options = 0 ; memset(&pContext->transactionId, 0, sizeof(STUN_TRANSACTION_ID)) ; pContext->nOldTransactions = 0 ; for (int i=0; ioldTransactionsIds[i], 0, sizeof(STUN_TRANSACTION_ID)) ; } pContext->pSocket = pSocket ; pContext->pTimer = getTimer() ; pContext->keepAliveSecs = 27 ; pContext->abortCount = NAT_PROBE_ABORT_COUNT ; pContext->refreshErrors = 0 ; pContext->port = PORT_NONE ; pContext->priority = priority ; pContext->pKeepaliveListener = NULL ; mContextMap.insertKeyAndValue(new UtlVoidPtr(pContext), new UtlVoidPtr(pSocket)) ; if (sendStunRequest(pContext)) { OsTime errorAt(0, NAT_RESPONSE_TIMEOUT_MS * OsTime::USECS_PER_MSEC) ; OsQueuedEvent* pEvent = (OsQueuedEvent*) pContext->pTimer->getNotifier() ; pEvent->setUserData((intptr_t) pContext) ; pContext->pTimer->periodicEvery(errorAt, errorAt) ; bSuccess = true ; } else { // Unable to Send destroyBinding(pContext) ; } } else { // Unable to allocate context assert(false) ; } } return bSuccess ; } UtlBoolean OsNatAgentTask::enableStun(IStunSocket* pSocket, const UtlString& stunServer, int stunPort, const int stunOptions, int keepAliveSecs) { OsLock lock(mMapsLock) ; bool bSuccess = false ; StunMessage msgSend ; UtlString serverAddress ; UtlString localHostIp ; pSocket->getSocket()->getLocalHostIp(&localHostIp) ; OsSysLog::add(FAC_NET, PRI_INFO, "Stun enabled for %s:%d with server %s:%d options=%d, keepAlive=%d", localHostIp.data(), pSocket->getSocket()->getLocalHostPort(), stunServer.data(), stunPort, stunOptions, keepAliveSecs) ; assert(pSocket) ; assert(portIsValid(stunPort)) ; assert(stunServer.length() > 0) ; if ( pSocket && portIsValid(stunPort) && (stunServer.length() > 0) && OsSocket::getHostIpByName(stunServer, &serverAddress) && OsSocket::isIp4Address(serverAddress)) { NAT_AGENT_CONTEXT* pContext = new NAT_AGENT_CONTEXT ; //memset(pContext, 0, sizeof(NAT_AGENT_CONTEXT)); if (pContext) { pContext->type = STUN_DISCOVERY ; pContext->status = SENDING ; pContext->serverAddress = serverAddress ; pContext->serverPort = stunPort ; pContext->options = stunOptions ; memset(&pContext->transactionId, 0, sizeof(STUN_TRANSACTION_ID)) ; pContext->nOldTransactions = 0 ; for (int i=0; ioldTransactionsIds[i], 0, sizeof(STUN_TRANSACTION_ID)) ; } pContext->pSocket = pSocket ; pContext->pTimer = getTimer() ; pContext->keepAliveSecs = keepAliveSecs; pContext->abortCount = NAT_INITIAL_ABORT_COUNT ; pContext->refreshErrors = 0 ; pContext->port = PORT_NONE ; pContext->priority = 0 ; pContext->pKeepaliveListener = NULL ; mContextMap.insertKeyAndValue(new UtlVoidPtr(pContext), new UtlVoidPtr(pSocket)) ; if (sendStunRequest(pContext)) { OsTime errorAt(0, NAT_RESPONSE_TIMEOUT_MS * OsTime::USECS_PER_MSEC) ; OsQueuedEvent* pEvent = (OsQueuedEvent*) pContext->pTimer->getNotifier() ; pEvent->setUserData((intptr_t) pContext) ; pContext->pTimer->periodicEvery(errorAt, errorAt) ; bSuccess = true ; } else { // Unable to Send destroyBinding(pContext) ; } } else { // Unable to allocate context assert(false) ; } } return bSuccess ; } UtlBoolean OsNatAgentTask::disableStun(IStunSocket* pSocket) { OsLock lock(mMapsLock) ; UtlString localHostIp ; pSocket->getSocket()->getLocalHostIp(&localHostIp) ; OsSysLog::add(FAC_NET, PRI_INFO, "Stun disabled for %s:%d", localHostIp.data(), pSocket->getSocket()->getLocalHostPort()) ; NAT_AGENT_CONTEXT* pBinding = getBinding(pSocket, STUN_DISCOVERY) ; if (pBinding) { destroyBinding(pBinding) ; } return true ; } UtlBoolean OsNatAgentTask::enableTurn(IStunSocket* pSocket, const UtlString& turnServer, int turnPort, int keepAliveSecs, const UtlString& username, const UtlString& password) { OsLock lock(mMapsLock) ; bool bSuccess = false ; TurnMessage msgSend ; UtlString serverAddress ; UtlString localHostIp ; pSocket->getSocket()->getLocalHostIp(&localHostIp) ; OsSysLog::add(FAC_NET, PRI_INFO, "Turn enabled for %s:%d with server %s:%d, keepalive=%d", localHostIp.data(), pSocket->getSocket()->getLocalHostPort(), turnServer.data(), turnPort, keepAliveSecs) ; assert(pSocket) ; assert(turnServer.length() > 0) ; assert(portIsValid(turnPort)) ; if ( pSocket && portIsValid(turnPort) && (turnServer.length() > 0) && OsSocket::getHostIpByName(turnServer, &serverAddress) && OsSocket::isIp4Address(serverAddress)) { NAT_AGENT_CONTEXT* pContext = new NAT_AGENT_CONTEXT ; //memset(pContext, 0, sizeof(NAT_AGENT_CONTEXT)); if (pContext) { pContext->type = TURN_ALLOCATION ; pContext->status = SENDING ; pContext->serverAddress = serverAddress ; pContext->serverPort = turnPort ; pContext->options = 0 ; memset(&pContext->transactionId, 0, sizeof(STUN_TRANSACTION_ID)) ; pContext->nOldTransactions = 0 ; for (int i=0; ioldTransactionsIds[i], 0, sizeof(STUN_TRANSACTION_ID)) ; } pContext->pSocket = pSocket ; pContext->pTimer = getTimer() ; pContext->keepAliveSecs = keepAliveSecs; pContext->abortCount = NAT_INITIAL_ABORT_COUNT ; pContext->refreshErrors = 0 ; pContext->port = PORT_NONE ; pContext->username = username ; pContext->password = password ; pContext->priority = 0 ; pContext->pKeepaliveListener = NULL ; mContextMap.insertKeyAndValue(new UtlVoidPtr(pContext), new UtlVoidPtr(pSocket)) ; if (sendTurnRequest(pContext)) { OsTime errorAt(0, NAT_RESPONSE_TIMEOUT_MS * OsTime::USECS_PER_MSEC) ; OsQueuedEvent* pEvent = (OsQueuedEvent*) pContext->pTimer->getNotifier() ; pEvent->setUserData((intptr_t) pContext) ; pContext->pTimer->periodicEvery(errorAt, errorAt) ; bSuccess = true ; } else { // Unable to Send destroyBinding(pContext) ; } } else { // Unable to allocate context assert(false) ; } } return bSuccess ; } UtlBoolean OsNatAgentTask::primeTurnReception(IStunSocket* pSocket, const char* szAddress, int iPort) { UtlBoolean bRC = false ; OsLock lock(mMapsLock) ; UtlString localHostIp ; pSocket->getSocket()->getLocalHostIp(&localHostIp) ; OsSysLog::add(FAC_NET, PRI_INFO, "Turn Priming %s:%d -> %s:%d", localHostIp.data(), pSocket->getSocket()->getLocalHostPort(), szAddress, iPort) ; NAT_AGENT_CONTEXT* pBinding = getBinding(pSocket, TURN_ALLOCATION) ; if (pBinding) { // Release Binding ... TurnMessage msgSend ; msgSend.allocTransactionId() ; msgSend.setType(MSG_TURN_SEND_REQUEST) ; msgSend.setDestinationAddress(szAddress, iPort) ; if (!pBinding->username.isNull()) { msgSend.setUsername(pBinding->username) ; } if (!pBinding->password.isNull()) { msgSend.setPassword(pBinding->password) ; } msgSend.setData("\r\n", 2) ; bRC = sendMessage(&msgSend, pSocket, pBinding->serverAddress, pBinding->serverPort, TURN_PACKET) ; } return bRC ; } UtlBoolean OsNatAgentTask::setTurnDestination(IStunSocket* pSocket, const char* szAddress, int iPort ) { UtlBoolean bRC = false ; OsLock lock(mMapsLock) ; NAT_AGENT_CONTEXT* pBinding = getBinding(pSocket, TURN_ALLOCATION) ; if (pBinding) { UtlString localHostIp ; pSocket->getSocket()->getLocalHostIp(&localHostIp) ; OsSysLog::add(FAC_NET, PRI_INFO, "Turn destination %s:%d -> %s:%d", localHostIp.data(), pSocket->getSocket()->getLocalHostPort(), szAddress, iPort) ; // Release Binding ... TurnMessage msgSend ; msgSend.allocTransactionId() ; msgSend.setType(MSG_TURN_ACTIVE_DESTINATION_REQUEST) ; msgSend.setDestinationAddress(szAddress, iPort) ; if (!pBinding->username.isNull()) { msgSend.setUsername(pBinding->username) ; } if (!pBinding->password.isNull()) { msgSend.setPassword(pBinding->password) ; } bRC = sendMessage(&msgSend, pSocket, pBinding->serverAddress, pBinding->serverPort, TURN_PACKET) ; } return bRC ; } void OsNatAgentTask::disableTurn(IStunSocket* pSocket) { OsLock lock(mMapsLock) ; UtlString localHostIp ; pSocket->getSocket()->getLocalHostIp(&localHostIp) ; OsSysLog::add(FAC_NET, PRI_INFO, "Turn disabled for %s:%d", localHostIp.data(), pSocket->getSocket()->getLocalHostPort()) ; NAT_AGENT_CONTEXT* pBinding = getBinding(pSocket, TURN_ALLOCATION) ; if (pBinding) { switch (pBinding->status) { case SUCCESS: case SENDING: case SENDING_ERROR: case RESENDING: case RESENDING_ERROR: { // Release Binding ... TurnMessage msgSend ; msgSend.allocTransactionId() ; msgSend.setType(MSG_TURN_ALLOCATE_REQUEST) ; msgSend.setRequestXorOnly() ; msgSend.setLifetime(0) ; if (!pBinding->username.isNull()) { msgSend.setUsername(pBinding->username) ; } if (!pBinding->password.isNull()) { msgSend.setPassword(pBinding->password) ; } sendMessage(&msgSend, pSocket, pBinding->serverAddress, pBinding->serverPort, TURN_PACKET) ; } break ; case FAILED: // No need to release binding break ; default: assert(false) ; break ; } destroyBinding(pBinding) ; } } UtlBoolean OsNatAgentTask::addCrLfKeepAlive(IStunSocket* pSocket, const UtlString& remoteIp, int remotePort, int keepAliveSecs, OsNatKeepaliveListener* pListener) { OsLock lock(mMapsLock) ; UtlBoolean bSuccess = false ; UtlString serverAddress ; if (!doesBindingExist(pSocket, CRLF_KEEPALIVE, remoteIp, remotePort)) { UtlString localHostIp ; pSocket->getSocket()->getLocalHostIp(&localHostIp) ; OsSysLog::add(FAC_NET, PRI_INFO, "Enabled CrLf keep alive %s:%d --> %s:%d every %d secs" , localHostIp.data(), pSocket->getSocket()->getLocalHostPort(), remoteIp.data(), remotePort, keepAliveSecs) ; NAT_AGENT_CONTEXT* pContext = new NAT_AGENT_CONTEXT ; //memset(pContext, 0, sizeof(NAT_AGENT_CONTEXT)); if (pContext) { pContext->type = CRLF_KEEPALIVE ; pContext->status = SUCCESS ; pContext->serverAddress = remoteIp ; pContext->serverPort = remotePort ; pContext->options = 0 ; memset(&pContext->transactionId, 0, sizeof(STUN_TRANSACTION_ID)) ; pContext->nOldTransactions = 0 ; for (int i=0; ioldTransactionsIds[i], 0, sizeof(STUN_TRANSACTION_ID)) ; } pContext->pSocket = pSocket ; pContext->pTimer = getTimer() ; pContext->keepAliveSecs = keepAliveSecs; pContext->abortCount = NAT_INITIAL_ABORT_COUNT ; pContext->refreshErrors = 0 ; pContext->port = PORT_NONE ; pContext->priority = 0 ; pContext->pKeepaliveListener = pListener ; mContextMap.insertKeyAndValue(new UtlVoidPtr(pContext), new UtlVoidPtr(pSocket)) ; if (pContext->pKeepaliveListener) { pContext->pKeepaliveListener->OnKeepaliveStart( populateKeepaliveEvent(pContext)); } handleCrLfKeepAlive(pContext) ; bSuccess = true ; if (keepAliveSecs > 0) { OsTime refreshAt(keepAliveSecs, 0) ; OsQueuedEvent* pEvent = (OsQueuedEvent*) pContext->pTimer->getNotifier() ; pEvent->setUserData((intptr_t) pContext) ; pContext->pTimer->periodicEvery(refreshAt, refreshAt) ; } else { destroyBinding(pContext) ; } } } return bSuccess ; } UtlBoolean OsNatAgentTask::removeCrLfKeepAlive(IStunSocket* pSocket, const UtlString& remoteIp, int remotePort) { NAT_AGENT_CONTEXT* pRC = NULL ; UtlVoidPtr* pKey; UtlBoolean bSuccess = FALSE ; OsLock lock(mMapsLock) ; UtlHashMapIterator iterator(mContextMap); while ((pKey = (UtlVoidPtr*)iterator())) { NAT_AGENT_CONTEXT* pContext = (NAT_AGENT_CONTEXT*) pKey->getValue(); if ( (pContext->pSocket == pSocket) && (pContext->type == CRLF_KEEPALIVE) && (pContext->serverPort == remotePort) && (pContext->serverAddress.compareTo(remoteIp) == 0)) { pRC = pContext ; break ; } } if (pRC) { UtlString localHostIp ; pSocket->getSocket()->getLocalHostIp(&localHostIp) ; OsSysLog::add(FAC_NET, PRI_INFO, "Disable CrLf keep alive %s:%d --> %s:%d" , localHostIp.data(), pSocket->getSocket()->getLocalHostPort(), remoteIp.data(), remotePort) ; destroyBinding(pRC) ; bSuccess = true ; } return bSuccess ; } UtlBoolean OsNatAgentTask::addStunKeepAlive(IStunSocket* pSocket, const UtlString& remoteIp, int remotePort, int keepAliveSecs, OsNatKeepaliveListener* pListener) { OsLock lock(mMapsLock) ; UtlBoolean bSuccess = false ; if (!doesBindingExist(pSocket, STUN_KEEPALIVE, remoteIp, remotePort)) { UtlString localHostIp ; OsSocket* pActualSocket = pSocket->getSocket(); pActualSocket->getLocalHostIp(&localHostIp) ; int port = pActualSocket->getLocalHostPort(); OsSysLog::add(FAC_NET, PRI_INFO, "Enabled STUN keep alive %s:%d --> %s:%d every %d secs" , localHostIp.data(), pSocket->getSocket()->getLocalHostPort(), remoteIp.data(), remotePort, keepAliveSecs) ; NAT_AGENT_CONTEXT* pContext = new NAT_AGENT_CONTEXT ; //memset(pContext, 0, sizeof(NAT_AGENT_CONTEXT)); if (pContext) { pContext->type = STUN_KEEPALIVE ; pContext->status = SUCCESS ; pContext->serverAddress = remoteIp ; pContext->serverPort = remotePort ; pContext->options = 0 ; memset(&pContext->transactionId, 0, sizeof(STUN_TRANSACTION_ID)) ; pContext->nOldTransactions = 0 ; for (int i=0; ioldTransactionsIds[i], 0, sizeof(STUN_TRANSACTION_ID)) ; } pContext->pSocket = pSocket ; pContext->pTimer = getTimer() ; pContext->keepAliveSecs = keepAliveSecs; pContext->abortCount = NAT_INITIAL_ABORT_COUNT ; pContext->refreshErrors = 0 ; pContext->port = PORT_NONE ; pContext->priority = 0 ; pContext->pKeepaliveListener = pListener ; mContextMap.insertKeyAndValue(new UtlVoidPtr(pContext), new UtlVoidPtr(pSocket)) ; if (pContext->pKeepaliveListener) { pContext->pKeepaliveListener->OnKeepaliveStart( populateKeepaliveEvent(pContext)); } handleStunKeepAlive(pContext) ; bSuccess = true ; if (keepAliveSecs > 0) { OsTime refreshAt(keepAliveSecs, 0) ; OsQueuedEvent* pEvent = (OsQueuedEvent*) pContext->pTimer->getNotifier() ; pEvent->setUserData((intptr_t) pContext) ; pContext->pTimer->periodicEvery(refreshAt, refreshAt) ; } else { destroyBinding(pContext) ; } } } return bSuccess ; } UtlBoolean OsNatAgentTask::removeStunKeepAlive(IStunSocket* pSocket, const UtlString& remoteIp, int remotePort) { NAT_AGENT_CONTEXT* pRC = NULL ; UtlVoidPtr* pKey; UtlBoolean bSuccess = FALSE ; OsLock lock(mMapsLock) ; UtlHashMapIterator iterator(mContextMap); while ((pKey = (UtlVoidPtr*)iterator())) { NAT_AGENT_CONTEXT* pContext = (NAT_AGENT_CONTEXT*) pKey->getValue(); if ( (pContext->pSocket == pSocket) && (pContext->type == STUN_KEEPALIVE) && (pContext->serverPort == remotePort) && (pContext->serverAddress.compareTo(remoteIp) == 0)) { pRC = pContext ; break ; } } if (pRC) { UtlString localHostIp ; pSocket->getSocket()->getLocalHostIp(&localHostIp) ; OsSysLog::add(FAC_NET, PRI_INFO, "Disable STUN keep alive %s:%d --> %s:%d" , localHostIp.data(), pSocket->getSocket()->getLocalHostPort(), remoteIp.data(), remotePort) ; destroyBinding(pRC) ; bSuccess = true ; } return bSuccess ; } UtlBoolean OsNatAgentTask::removeKeepAlives(IStunSocket* pSocket) { NAT_AGENT_CONTEXT* pRC = NULL ; UtlVoidPtr* pKey; UtlBoolean bSuccess = FALSE ; OsLock lock(mMapsLock) ; UtlHashMapIterator iterator(mContextMap); while ((pKey = (UtlVoidPtr*)iterator())) { NAT_AGENT_CONTEXT* pContext = (NAT_AGENT_CONTEXT*) pKey->getValue(); if ( (pContext->pSocket == pSocket) && ((pContext->type == STUN_KEEPALIVE) || (pContext->type == CRLF_KEEPALIVE))) { UtlString localHostIp ; pSocket->getSocket()->getLocalHostIp(&localHostIp) ; OsSysLog::add(FAC_NET, PRI_INFO, "Disable %s keep alive %s:%d --> %s:%d", pContext->type == STUN_KEEPALIVE ? "STUN" : "CrLf", localHostIp.data(), pSocket->getSocket()->getLocalHostPort(), pContext->serverAddress.data(), pContext->serverPort) ; destroyBinding(pContext) ; bSuccess = true ; } } return bSuccess ; } UtlBoolean OsNatAgentTask::removeStunProbes(IStunSocket* pSocket) { NAT_AGENT_CONTEXT* pRC = NULL ; UtlVoidPtr* pKey; UtlBoolean bSuccess = FALSE ; OsLock lock(mMapsLock) ; UtlHashMapIterator iterator(mContextMap); while ((pKey = (UtlVoidPtr*)iterator())) { NAT_AGENT_CONTEXT* pContext = (NAT_AGENT_CONTEXT*) pKey->getValue(); if ( (pContext->pSocket == pSocket) && (pContext->type == STUN_PROBE)) { UtlString localHostIp ; pSocket->getSocket()->getLocalHostIp(&localHostIp) ; OsSysLog::add(FAC_NET, PRI_INFO, "Disable stun probe %s:%d --> %s:%d", localHostIp.data(), pSocket->getSocket()->getLocalHostPort(), pContext->serverAddress.data(), pContext->serverPort) ; destroyBinding(pContext) ; bSuccess = true ; } } return bSuccess ; } void OsNatAgentTask::synchronize() { OsLock lock(sLock) ; if (isStarted() && (getCurrentTask() != this)) { // Send an event to ourself and wait for that message to be processed. OsEvent event ; OsRpcMsg msg(SYNC_MSG_TYPE, 0, event) ; if (postMessage(msg) == OS_SUCCESS) { event.wait() ; } } } // Determines if probes of a higher priority are still outstanding UtlBoolean OsNatAgentTask::areProbesOutstanding(IStunSocket* pSocket, int priority) { NAT_AGENT_CONTEXT* pRC = NULL ; UtlVoidPtr* pKey; UtlBoolean bOutstanding = false ; OsLock lock(mMapsLock) ; UtlHashMapIterator iterator(mContextMap); while ((pKey = (UtlVoidPtr*)iterator())) { NAT_AGENT_CONTEXT* pContext = (NAT_AGENT_CONTEXT*) pKey->getValue(); if ( (pContext->pSocket == pSocket) && (pContext->type == STUN_PROBE) && (pContext->priority > priority)) { //UtlString debug ; //dumpContext(&debug, pContext) ; //OutputDebugString(debug) ; //OutputDebugString("\n") ; bOutstanding = true ; break ; } } return bOutstanding ; } // Does a binding of the designated type/server exist UtlBoolean OsNatAgentTask::doesBindingExist(IStunSocket* pSocket, NAT_AGENT_BINDING_TYPE type, const UtlString& serverIp, int serverPort) { NAT_AGENT_CONTEXT* pRC = NULL ; UtlVoidPtr* pKey; UtlBoolean bFound = false ; OsLock lock(mMapsLock) ; UtlHashMapIterator iterator(mContextMap); while ((pKey = (UtlVoidPtr*)iterator())) { NAT_AGENT_CONTEXT* pContext = (NAT_AGENT_CONTEXT*) pKey->getValue(); if ( (pContext->pSocket == pSocket) && (pContext->type == type) && (pContext->serverAddress.compareTo(serverIp) == 0) && (pContext->serverPort == serverPort) ) { bFound = true ; break ; } } return bFound ; } /* ============================ ACCESSORS ================================= */ UtlBoolean OsNatAgentTask::findContactAddress(const UtlString& destHost, int destPort, UtlString* pContactHost, int* pContactPort, int iTimeoutMs) { NAT_AGENT_CONTEXT* pRC = NULL ; UtlVoidPtr* pKey; UtlBoolean bFound = false ; int iAttempts = 0 ; UtlBoolean bTryAgain = false ; UtlBoolean bTimedOut = false ; int iMaxAttempts = 1 ; if (iTimeoutMs > 0) { // Figure out max attempts, rounding to next highest polling chunk (50ms) iMaxAttempts = (iTimeoutMs + (NAT_FIND_BINDING_POOL_MS-1)) / NAT_FIND_BINDING_POOL_MS ; } bFound = findExternalBinding(destHost, destPort, pContactHost, pContactPort, iTimeoutMs, &bTimedOut) ; if (!bFound) { // Poll if the record isn't ready while ((iAttempts == 0 || bTryAgain) && iAttempts < iMaxAttempts) { bTryAgain = false ; iAttempts++ ; mMapsLock.acquire() ; UtlHashMapIterator iterator(mContextMap); while ((pKey = (UtlVoidPtr*)iterator())) { NAT_AGENT_CONTEXT* pContext = (NAT_AGENT_CONTEXT*) pKey->getValue(); // Ignore uninteresting contexts if ( (pContext->type == TURN_ALLOCATION) || (pContext->type == CRLF_KEEPALIVE) || (pContext->status == FAILED) ) { continue ; } // Search for a match if ( (destPort == pContext->serverPort) && (destHost.compareTo(pContext->serverAddress, UtlString::ignoreCase) == 0)) { if (pContext->port != PORT_NONE) { if (pContactHost) { *pContactHost = pContext->address ; } if (pContactPort) { *pContactPort = pContext->port ; } bTryAgain = false ; bFound = true ; break ; } else { // If findExternalBinding timed out -- don't bother // waiting any additional time if (!bTimedOut && iMaxAttempts > 0) { bTryAgain = true ; } } } } mMapsLock.release() ; if (bTryAgain && iAttempts < iMaxAttempts) { OsTask::delay(NAT_FIND_BINDING_POOL_MS) ; } } } return bFound ; } /** * Add an external binding (used for findContactAddress) */ void OsNatAgentTask::addExternalBinding(OsSocket* pSocket, UtlString remoteAddress, int remotePort, UtlString contactAddress, int contactPort) { OsTime now ; OsTime expiration ; if ((remoteAddress.compareTo(contactAddress) == 0) && (remotePort == contactPort)) { // Transport error return ; } OsWriteLock lock(mExternalBindingMutex) ; UtlBoolean bUpdated = false ; // Expire and external binding after 60 seconds OsDateTime::getCurTime(now) ; OsDateTime::getCurTime(expiration) ; if (contactAddress.isNull()) { // If this is a place holder, expire in 1s (default timeout) expiration += OsTime(1, 0) ; } else { expiration += OsTime(NAT_BINDING_EXPIRATION_SECS, 0) ; } // Update contact if found and GC old ones UtlSListIterator itor(mExternalBindingsList) ; while (UtlContainable* pCont = itor()) { NAT_AGENT_EXTERNAL_CONTEXT* pContext = (NAT_AGENT_EXTERNAL_CONTEXT*) ((UtlVoidPtr*) pCont)->getValue() ; if ( (pContext->pSocket == pSocket) && (pContext->remoteAddress.compareTo(remoteAddress) == 0) && (pContext->remotePort == remotePort) ) { pContext->contactAddress = contactAddress ; pContext->contactPort = contactPort ; pContext->expiration = expiration ; bUpdated = true ; } else if (pContext->expiration < now) { mExternalBindingsList.destroy(pCont) ; delete pContext ; } } if (!bUpdated) { NAT_AGENT_EXTERNAL_CONTEXT* pContext = new NAT_AGENT_EXTERNAL_CONTEXT ; pContext->pSocket = pSocket ; pContext->remoteAddress = remoteAddress ; pContext->remotePort = remotePort ; pContext->contactAddress = contactAddress ; pContext->contactPort = contactPort ; pContext->expiration = expiration ; mExternalBindingsList.append(new UtlVoidPtr(pContext)) ; } } void OsNatAgentTask::clearExternalBinding(OsSocket* pSocket, UtlString remoteAddress, int remotePort, bool bOnlyIfEmpty) { OsWriteLock lock(mExternalBindingMutex) ; UtlSListIterator itor(mExternalBindingsList) ; while (UtlContainable* pCont = itor()) { NAT_AGENT_EXTERNAL_CONTEXT* pContext = (NAT_AGENT_EXTERNAL_CONTEXT*) ((UtlVoidPtr*) pCont)->getValue() ; if ( (pContext->remoteAddress.compareTo(remoteAddress) == 0) && (pContext->remotePort == remotePort) ) { if (bOnlyIfEmpty) { if (!pContext->contactAddress.isNull()) { mExternalBindingsList.destroy(pCont) ; delete pContext ; } } else { mExternalBindingsList.destroy(pCont) ; delete pContext ; } break ; } } } UtlBoolean OsNatAgentTask::findExternalBinding(const UtlString& destHost, int destPort, UtlString* pContactHost, int* pContactPort, int iTimeoutMs, UtlBoolean* pTimedOut) { UtlBoolean bFound = false ; int iAttempts = 0 ; UtlBoolean bTryAgain = false ; int iMaxAttempts = 1 ; if (iTimeoutMs > 0) { // Figure out max attempts, rounding to next highest polling chunk (50ms) iMaxAttempts = (iTimeoutMs + (NAT_FIND_BINDING_POOL_MS-1)) / NAT_FIND_BINDING_POOL_MS ; } // Poll for upto 1s if the record isn't ready while ((iAttempts == 0 || bTryAgain) && iAttempts < iMaxAttempts) { bTryAgain = false ; iAttempts++ ; OsTime now ; OsDateTime::getCurTime(now) ; mExternalBindingMutex.acquireRead() ; // Finding matching contact UtlSListIterator itor(mExternalBindingsList) ; while (UtlContainable* pCont = itor()) { NAT_AGENT_EXTERNAL_CONTEXT* pContext = (NAT_AGENT_EXTERNAL_CONTEXT*) ((UtlVoidPtr*) pCont)->getValue() ; if ( (pContext->expiration > now) && (pContext->remoteAddress.compareTo(destHost) == 0) && (pContext->remotePort == destPort) ) { if (pContext->contactAddress.isNull()) { if (iMaxAttempts > 0) { bTryAgain = true ; } } else { if (pContactHost) *pContactHost = pContext->contactAddress ; if (pContactPort) *pContactPort = pContext->contactPort ; bFound = true ; bTryAgain = false ; } break ; } } mExternalBindingMutex.releaseRead() ; if (bTryAgain && iAttempts < iMaxAttempts) { OsTask::delay(NAT_FIND_BINDING_POOL_MS) ; } } // Set the timed out flag if (pTimedOut) { *pTimedOut = (bTryAgain && !bFound) ; } return bFound ; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ UtlBoolean OsNatAgentTask::sendMessage(StunMessage* pMsg, IStunSocket* pSocket, const UtlString& toAddress, unsigned short toPort, PacketType packetType) { UtlBoolean bSuccess = false ; char cEncoded[10240] ; size_t length ; // pMsg->setServer("sipXtapi (www.sipfoundry.org)") ; if (pMsg->encode(cEncoded, sizeof(cEncoded), length)) { if (OsSysLog::willLog(FAC_NET, PRI_DEBUG)) { UtlString output ; StunUtils::debugDump(cEncoded, length, output) ; OsSysLog::add(FAC_NET, PRI_DEBUG, "Outbound STUN/TURN message(Crude Parse):\n%s\n", output.data()) ; } // The IStunSocket keeps track of // the last read/write times, but we need to write to the socket // without updating the timestamp. Added a new function to the // IStunSocket interface that should be implemented as // just a write to the socket, without timestamping. if (pSocket->socketWrite(cEncoded, (int) length, toAddress, toPort, packetType) > 0) { bSuccess = true ; } } else { printf("OsNatAgentTask: Unable to encode message\n") ; assert(false) ; } return bSuccess ; } NAT_AGENT_CONTEXT* OsNatAgentTask::getBinding(IStunSocket* pSocket, NAT_AGENT_BINDING_TYPE type) { NAT_AGENT_CONTEXT* pRC = NULL ; UtlHashMapIterator iterator(mContextMap); UtlVoidPtr* pKey; while ((pKey = (UtlVoidPtr*)iterator())) { NAT_AGENT_CONTEXT* pContext = (NAT_AGENT_CONTEXT*) pKey->getValue(); if ((pContext->pSocket == pSocket) && (pContext->type == type)) { pRC = pContext ; break ; } } return pRC ; } NAT_AGENT_CONTEXT* OsNatAgentTask::getBinding(NAT_AGENT_CONTEXT* pBinding) { NAT_AGENT_CONTEXT* pRC = NULL ; UtlHashMapIterator iterator(mContextMap); UtlVoidPtr* pKey; while ((pKey = (UtlVoidPtr*)iterator())) { NAT_AGENT_CONTEXT* pContext = (NAT_AGENT_CONTEXT*) pKey->getValue(); if (pBinding == pContext) { pRC = pContext ; break ; } } return pRC ; } NAT_AGENT_CONTEXT* OsNatAgentTask::getBinding(STUN_TRANSACTION_ID* pId) { NAT_AGENT_CONTEXT* pRC = NULL ; UtlHashMapIterator iterator(mContextMap); UtlVoidPtr* pKey; while ((pKey = (UtlVoidPtr*)iterator())) { NAT_AGENT_CONTEXT* pContext = (NAT_AGENT_CONTEXT*) pKey->getValue(); if (memcmp(&pId->id[0], &pContext->transactionId.id[0], sizeof(STUN_TRANSACTION_ID)) == 0) { pRC = pContext ; break ; } else { for (int i=0; inOldTransactions; i++) { if (memcmp(&pId->id[0], &pContext->oldTransactionsIds[i].id[0], sizeof(STUN_TRANSACTION_ID)) == 0) { pRC = pContext ; break ; } } } } return pRC ; } void OsNatAgentTask::destroyBinding(NAT_AGENT_CONTEXT* pBinding) { UtlHashMapIterator iterator(mContextMap); UtlVoidPtr* pKey; while ((pKey = (UtlVoidPtr*)iterator())) { NAT_AGENT_CONTEXT* pContext = (NAT_AGENT_CONTEXT*) pKey->getValue(); if (pContext == pBinding) { mContextMap.destroy(pKey) ; releaseTimer(pBinding->pTimer) ; if (pBinding->pKeepaliveListener) { pBinding->pKeepaliveListener->OnKeepaliveStop( populateKeepaliveEvent(pBinding)) ; } delete pBinding ; break ; } } } OsTimer* OsNatAgentTask::getTimer() { OsTimer* pTimer = NULL ; UtlVoidPtr* pWrappedTimer = (UtlVoidPtr*) mTimerPool.get() ; if (pWrappedTimer) { pTimer = (OsTimer*) pWrappedTimer->getValue() ; delete pWrappedTimer ; } else { pTimer = new OsTimer(getMessageQueue(), 0) ; } return pTimer ; } void OsNatAgentTask::releaseTimer(OsTimer* pTimer) { assert(pTimer) ; if (pTimer) { pTimer->stop() ; mTimerPool.insert(new UtlVoidPtr(pTimer)) ; } } UtlBoolean OsNatAgentTask::sendStunRequest(NAT_AGENT_CONTEXT* pBinding) { UtlBoolean bSuccess = false ; StunMessage msgSend ; bool bStunProbe = (pBinding->type == STUN_PROBE); msgSend.allocTransactionId() ; msgSend.setType(MSG_STUN_BIND_REQUEST) ; msgSend.setRequestXorOnly() ; if (pBinding->options & ATTR_CHANGE_FLAG_PORT) { msgSend.setChangePort(true) ; } if (pBinding->options & ATTR_CHANGE_FLAG_IP) { msgSend.setChangeIp(true) ; } // Store old transaction int index = 0 ; if (pBinding->nOldTransactions < MAX_OLD_TRANSACTIONS) { index = pBinding->nOldTransactions ; pBinding->nOldTransactions++ ; } else { index = MAX_OLD_TRANSACTIONS -1 ; for (int i=0; ioldTransactionsIds[i], &pBinding->oldTransactionsIds[i+1], sizeof(STUN_TRANSACTION_ID)) ; } } memcpy(&pBinding->oldTransactionsIds[index], &pBinding->transactionId, sizeof(STUN_TRANSACTION_ID)) ; // Get new transaction Id msgSend.getTransactionId(&pBinding->transactionId) ; // Send message if (sendMessage(&msgSend, pBinding->pSocket, pBinding->serverAddress, pBinding->serverPort, STUN_PROBE_PACKET)) { bSuccess = true ; } return bSuccess ; } UtlBoolean OsNatAgentTask::sendTurnRequest(NAT_AGENT_CONTEXT* pBinding) { UtlBoolean bSuccess = false ; TurnMessage msgSend ; // Store old transaction int index = 0 ; if (pBinding->nOldTransactions < MAX_OLD_TRANSACTIONS) { index = pBinding->nOldTransactions ; pBinding->nOldTransactions++ ; } else { index = MAX_OLD_TRANSACTIONS -1 ; for (int i=0; ioldTransactionsIds[i], &pBinding->oldTransactionsIds[i+1], sizeof(STUN_TRANSACTION_ID)) ; } } memcpy(&pBinding->oldTransactionsIds[index], &pBinding->transactionId, sizeof(STUN_TRANSACTION_ID)) ; msgSend.allocTransactionId() ; msgSend.getTransactionId(&pBinding->transactionId) ; msgSend.setType(MSG_TURN_ALLOCATE_REQUEST) ; msgSend.setRequestXorOnly() ; msgSend.setLifetime(pBinding->keepAliveSecs * 2) ; if (!pBinding->username.isNull()) { msgSend.setUsername(pBinding->username) ; } if (!pBinding->password.isNull()) { msgSend.setPassword(pBinding->password) ; } if (sendMessage(&msgSend, pBinding->pSocket, pBinding->serverAddress, pBinding->serverPort, TURN_PACKET)) { bSuccess = true ; } return bSuccess ; } void OsNatAgentTask::markStunSuccess(NAT_AGENT_CONTEXT* pBinding, const UtlString& mappedAddress, int mappedPort) { bool bAddressChanged = false ; OsTime refreshPeriod(pBinding->keepAliveSecs, 0) ; assert(pBinding != NULL) ; if (pBinding) { UtlString localHostIp ; pBinding->pSocket->getSocket()->getLocalHostIp(&localHostIp) ; OsSysLog::add(FAC_NET, PRI_INFO, "Stun success for %s:%d, mapped address: %s:%d", localHostIp.data(), pBinding->pSocket->getSocket()->getLocalHostPort(), mappedAddress.data(), mappedPort) ; assert(pBinding->pTimer != NULL) ; assert(pBinding->pSocket != NULL) ; // Check for a change in mapped IP/PORT if ( (pBinding->status == RESENDING) || (pBinding->status == RESENDING_ERROR) ) { if ( (mappedAddress.compareTo(pBinding->address) != 0) || (mappedPort != pBinding->port) ) { // This is really a critial problem -- we are likely not able // to communicate if our NAT binding is bouncing around. OsSysLog::add(FAC_NET, PRI_CRIT, "Stun binding changed for %s:%d, %s:%d is now %s:%d", localHostIp.data(), pBinding->pSocket->getSocket()->getLocalHostPort(), pBinding->address.data(), pBinding->port, mappedAddress.data(), mappedPort) ; bAddressChanged = true ; } } // Update State pBinding->address = mappedAddress ; pBinding->port = mappedPort ; pBinding->status = SUCCESS ; pBinding->refreshErrors = 0 ; // Reset Timer pBinding->pTimer->stop() ; if (pBinding->keepAliveSecs > 0) { pBinding->pTimer->periodicEvery(refreshPeriod, refreshPeriod) ; } // Notify Socket if (pBinding->type == STUN_DISCOVERY) { pBinding->pSocket->setStunAddress(mappedAddress, mappedPort) ; pBinding->pSocket->markStunSuccess(bAddressChanged) ; } else if (pBinding->type == STUN_PROBE) { pBinding->pSocket->evaluateDestinationAddress(pBinding->serverAddress, pBinding->serverPort, pBinding->priority) ; } else if (pBinding->type == STUN_KEEPALIVE) { if (pBinding->pKeepaliveListener) { pBinding->pKeepaliveListener->OnKeepaliveFeedback( populateKeepaliveEvent(pBinding)); } } else { // assert(false) ; } } } void OsNatAgentTask::markStunFailure(NAT_AGENT_CONTEXT* pBinding) { assert(pBinding != NULL) ; if (pBinding) { UtlString localHostIp ; pBinding->pSocket->getSocket()->getLocalHostIp(&localHostIp) ; OsSysLog::add(FAC_NET, PRI_INFO, "Stun failure for %s:%d -> %s:%d", localHostIp.data(), pBinding->pSocket->getSocket()->getLocalHostPort(), pBinding->serverAddress.data(), pBinding->serverPort) ; assert(pBinding->pTimer != NULL) ; assert(pBinding->pSocket != NULL) ; pBinding->status = FAILED ; // Clear timer pBinding->pTimer->stop() ; // Notify Socket if (pBinding->type == STUN_DISCOVERY) { UtlString empty ; pBinding->pSocket->setStunAddress(empty, PORT_NONE) ; pBinding->pSocket->markStunFailure() ; } else if (pBinding->type == STUN_PROBE) { destroyBinding(pBinding) ; } else if (pBinding->type == STUN_KEEPALIVE) { // We are currently ignore keep alive responses } else { assert(false) ; } } } void OsNatAgentTask::markTurnSuccess(NAT_AGENT_CONTEXT* pBinding, const UtlString& relayAddress, int relayPort) { OsTime refreshPeriod(pBinding->keepAliveSecs, 0) ; assert(pBinding != NULL) ; if (pBinding) { UtlString localHostIp ; pBinding->pSocket->getSocket()->getLocalHostIp(&localHostIp) ; OsSysLog::add(FAC_NET, PRI_INFO, "Turn success for %s:%d, relay address: %s:%d", localHostIp.data(), pBinding->pSocket->getSocket()->getLocalHostPort(), relayAddress.data(), relayPort) ; assert(pBinding->pTimer != NULL) ; assert(pBinding->pSocket != NULL) ; pBinding->address = relayAddress ; pBinding->port = relayPort ; pBinding->status = SUCCESS ; pBinding->refreshErrors = 0 ; // Reset Timer pBinding->pTimer->stop() ; if (pBinding->keepAliveSecs > 0) { pBinding->pTimer->periodicEvery(refreshPeriod, refreshPeriod) ; } // Notify Socket pBinding->pSocket->setTurnAddress(relayAddress, relayPort) ; pBinding->pSocket->markTurnSuccess() ; } } void OsNatAgentTask::markTurnFailure(NAT_AGENT_CONTEXT* pBinding) { assert(pBinding != NULL) ; if (pBinding) { UtlString localHostIp ; pBinding->pSocket->getSocket()->getLocalHostIp(&localHostIp) ; OsSysLog::add(FAC_NET, PRI_INFO, "Turn failure for %s:%d -> %s:%d", localHostIp.data(), pBinding->pSocket->getSocket()->getLocalHostPort(), pBinding->serverAddress.data(), pBinding->serverPort) ; assert(pBinding->pTimer != NULL) ; assert(pBinding->pSocket != NULL) ; pBinding->status = FAILED ; // Clear timer pBinding->pTimer->stop() ; // Notify Socket UtlString empty ; pBinding->pSocket->setTurnAddress(empty, PORT_NONE) ; pBinding->pSocket->markTurnFailure() ; } } OsNatKeepaliveEvent OsNatAgentTask::populateKeepaliveEvent(NAT_AGENT_CONTEXT* pContext) { OsNatKeepaliveEvent event ; if (pContext) { if (pContext->type == CRLF_KEEPALIVE) event.type = OS_NAT_KEEPALIVE_CRLF ; else if (pContext->type == STUN_KEEPALIVE) event.type = OS_NAT_KEEPALIVE_STUN ; else event.type = OS_NAT_KEEPALIVE_INVALID ; event.remoteAddress = pContext->serverAddress ; event.remotePort = pContext->serverPort ; event.keepAliveSecs = pContext->keepAliveSecs ; event.mappedAddress = pContext->address ; event.mappedPort = pContext->port ; } return event ; } void OsNatAgentTask::dumpContext(UtlString* pResults, NAT_AGENT_CONTEXT* pBinding) { const char* cBindingTypes[] = { "STUN_DISCOVERY", "STUN_PROBE", "TURN_ALLOCATION", "CRLF_KEEPALIVE", "STUN_KEEPALIVE" } ; const char* cStatus[] = { "SUCCESS", "SENDING", "SENDING_ERROR", "RESENDING", "RESENDING_ERROR", "FAILED" } ; char cBuf[2048] ; if (pBinding) { UtlString socketHostIp ; int socketPort = -1 ; if (pBinding->pSocket) { pBinding->pSocket->getSocket()->getLocalHostIp(&socketHostIp) ; socketPort = pBinding->pSocket->getSocket()->getLocalHostPort() ; } sprintf(cBuf, " BindingType: %s\n" " Status : %s\n" " Server Addr: %s\n" " Server Port: %d\n" " Servers Opt: %d\n" " Transaction: %s\n" " Socket : %p (%s:%d)\n" " Timer : %p\n" " KeepAlive : %d\n" " Errors : %d\n" " Address : %s\n" " Port : %d\n" " Username : %s\n" " Password : %s\n" " Priority : %d\n", cBindingTypes[pBinding->type], cStatus[pBinding->status], pBinding->serverAddress.data(), pBinding->serverPort, pBinding->options, "TBD", pBinding->pSocket, socketHostIp.data(), socketPort, pBinding->pTimer, pBinding->keepAliveSecs, pBinding->refreshErrors, pBinding->address.data(), pBinding->port, pBinding->username.data(), pBinding->password.data(), pBinding->priority) ; pResults->append(cBuf) ; } } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsNatDatagramSocket.cpp0000644000175000017500000004651612205613256025445 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #include #ifndef _WIN32 #include #include #include #endif // APPLICATION INCLUDES #include "os/OsNatDatagramSocket.h" #include "os/OsNatAgentTask.h" #include "os/StunMessage.h" #include "os/StunUtils.h" #include "os/OsLock.h" #include "os/OsSysLog.h" #include "os/OsEvent.h" #include "os/OsNotification.h" #include "tapi/sipXtapi.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define DEFAULT_MEDIA_STUN_KEEPALIVE 28 // STATIC VARIABLE INITIALIZATIONS // FORWARD DECLARATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsNatDatagramSocket::OsNatDatagramSocket(int remoteHostPortNum, const char* remoteHost, int localHostPortNum, const char* localHost, OsNotification *pNotification) : OsDatagramSocket(remoteHostPortNum, remoteHost, localHostPortNum, localHost) { miRecordTimes = ONDS_MARK_NONE ; mpReadNotification = NULL ; // Init Stun state mStunState.bEnabled = false ; mStunState.status = NAT_STATUS_UNKNOWN ; mStunState.mappedAddress = NULL ; mStunState.mappedPort = PORT_NONE ; // Init Turn state mTurnState.bEnabled = false ; mTurnState.status = NAT_STATUS_UNKNOWN ; mTurnState.relayAddress = NULL ; mTurnState.relayPort = PORT_NONE ; // Init other attributes mpNatAgent = OsNatAgentTask::getInstance() ; mbTransparentReads = TRUE ; mDestAddress = mRemoteIpAddress ; miDestPort = remoteHostPort ; miDestPriority = -1 ; mpNotification = pNotification ; mbNotified = false ; } // Destructor OsNatDatagramSocket::~OsNatDatagramSocket() { destroy() ; } void OsNatDatagramSocket::destroy() { mpNatAgent->removeKeepAlives(this) ; mpNatAgent->removeStunProbes(this) ; disableStun() ; disableTurn() ; mpNatAgent->synchronize() ; } /* ============================ MANIPULATORS ============================== */ OsSocket* OsNatDatagramSocket::getSocket() { return this; } int OsNatDatagramSocket::read(char* buffer, int bufferLength) { bool bNatPacket ; int iRC ; UtlString receivedIp ; int iReceivedPort ; do { bNatPacket = FALSE ; iRC = OsSocket::read(buffer, bufferLength, &receivedIp, &iReceivedPort) ; if (handleSturnData(buffer, iRC, receivedIp, iReceivedPort)) { if (!mbTransparentReads) iRC = 0 ; else bNatPacket = TRUE ; } } while ((iRC >= 0) && bNatPacket) ; // Make read time for non-NAT packets if (iRC > 0 && !bNatPacket) markReadTime() ; return iRC ; } int OsNatDatagramSocket::read(char* buffer, int bufferLength, UtlString* ipAddress, int* port) { bool bNatPacket ; int iRC ; UtlString receivedIp ; int iReceivedPort ; do { bNatPacket = FALSE ; iRC = OsSocket::read(buffer, bufferLength, &receivedIp, &iReceivedPort) ; if (handleSturnData(buffer, iRC, receivedIp, iReceivedPort)) { if (!mbTransparentReads) iRC = 0 ; else bNatPacket = TRUE ; } } while ((iRC >= 0) && bNatPacket) ; if (ipAddress) { *ipAddress = receivedIp ; } if (port) { *port = iReceivedPort ; } // Make read time for non-NAT packets if (iRC > 0 && !bNatPacket) { markReadTime() ; } return iRC ; } int OsNatDatagramSocket::read(char* buffer, int bufferLength, struct in_addr* ipAddress, int* port) { int iRC ; int iReceivedPort ; UtlString receivedIp ; iRC = read(buffer, bufferLength, &receivedIp, &iReceivedPort) ; if (ipAddress) ipAddress->s_addr = inet_addr(receivedIp) ; if (port) *port = iReceivedPort ; return iRC ; } int OsNatDatagramSocket::read(char* buffer, int bufferLength, long waitMilliseconds) { bool bNatPacket ; int iRC = 0 ; UtlString receivedIp ; int iReceivedPort ; do { bNatPacket = FALSE ; if (isReadyToRead(waitMilliseconds)) { iRC = OsSocket::read(buffer, bufferLength, &receivedIp, &iReceivedPort) ; if (handleSturnData(buffer, iRC, receivedIp, iReceivedPort)) { if (!mbTransparentReads) iRC = 0 ; else bNatPacket = TRUE ; } } else { break ; } } while ((iRC >= 0) && bNatPacket) ; // Make read time for non-NAT packets if (iRC > 0 && !bNatPacket) { markReadTime() ; } return iRC ; } int OsNatDatagramSocket::socketWrite(const char* buffer, int bufferLength, const char* ipAddress, int port, PacketType packetType) { if (packetType == MEDIA_PACKET) { markWriteTime() ; } return OsDatagramSocket::write(buffer, bufferLength, ipAddress, port) ; } int OsNatDatagramSocket::write(const char* buffer, int bufferLength) { int rc ; markWriteTime() ; // Datagram sockets can be simulate a connection-oriented socket (in API) // by allowing a connect(). This filters inbound packets from others (on // Win32 -- not sure if this is the case for all platforms) and breaks // ICE. if (mIsConnected) { rc = OsDatagramSocket::write(buffer, bufferLength) ; } else { if (mDestAddress.length() > 0 && miDestPort > 0) { rc = OsDatagramSocket::write(buffer, bufferLength, mDestAddress.data(), miDestPort) ; } else { // This is suggest something is writing without applying a // destination address. assert(false) ; rc = 0 ; } } return rc ; } int OsNatDatagramSocket::write(const char* buffer, int bufferLength, const char* ipAddress, int port) { markWriteTime() ; return OsDatagramSocket::write(buffer, bufferLength, ipAddress, port) ; } int OsNatDatagramSocket::write(const char* buffer, int bufferLength, long waitMilliseconds) { markWriteTime() ; return OsSocket::write(buffer, bufferLength, waitMilliseconds) ; } void OsNatDatagramSocket::enableStun(const char* szStunServer, int stunPort, int iKeepAlive, int iStunOptions, bool bReadFromSocket) { #ifdef TEST_PRINT OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsNatDatagramSocket::enableStun(szStunServer=%s, stunPort=%d, iKeepAlive=%d, iStunOptions=%d, bReadFromSocket=%s) port: %d descriptor: %d this: %p", szStunServer, stunPort, iKeepAlive, iStunOptions, bReadFromSocket, getLocalHostPort(), getSocketDescriptor(), this); #endif if (!mStunState.bEnabled) { mStunState.bEnabled = true ; UtlBoolean bRC = mpNatAgent->enableStun(this, szStunServer, stunPort, iStunOptions, iKeepAlive) ; if (bRC) { if (bReadFromSocket) { bool bTransparent = mbTransparentReads ; mbTransparentReads = false ; char cBuf[2048] ; while (mStunState.status == NAT_STATUS_UNKNOWN) { read(cBuf, sizeof(cBuf), 100) ; if (mStunState.status == NAT_STATUS_UNKNOWN) { OsTask::yield() ; } } mbTransparentReads = bTransparent ; } } else { mStunState.status = NAT_STATUS_FAILURE ; } } } void OsNatDatagramSocket::disableStun() { if (mStunState.bEnabled) { mStunState.bEnabled = false ; mpNatAgent->disableStun(this) ; } } void OsNatDatagramSocket::enableTurn(const char* szTurnSever, int turnPort, int iKeepAlive, const char* username, const char* password, bool bReadFromSocket) { if (!mTurnState.bEnabled) { mTurnState.bEnabled = true ; UtlBoolean bRC = mpNatAgent->enableTurn(this, szTurnSever, turnPort, iKeepAlive, username, password) ; if (bRC) { if (bReadFromSocket) { bool bTransparent = mbTransparentReads ; mbTransparentReads = false ; char cBuf[2048] ; while (mTurnState.status == NAT_STATUS_UNKNOWN) { read(cBuf, sizeof(cBuf), 100) ; if (mTurnState.status == NAT_STATUS_UNKNOWN) { OsTask::yield() ; } } mbTransparentReads = bTransparent ; } } else { mTurnState.status = NAT_STATUS_FAILURE ; } } } void OsNatDatagramSocket::disableTurn() { if (mTurnState.bEnabled) { mTurnState.bEnabled = false ; mpNatAgent->disableTurn(this) ; } } bool OsNatDatagramSocket::waitForBinding(NAT_BINDING binding, bool bWaitUntilReady) { bool result = false; if (binding != NO_BINDING) { char cBuf[2048]; do { if (!(((binding == STUN_BINDING || binding == STUN_TURN_BINDING) && mStunState.status == NAT_STATUS_UNKNOWN) || ((binding == TURN_BINDING || binding == STUN_TURN_BINDING) && mTurnState.status == NAT_STATUS_UNKNOWN))) { // leave loop, since stun/turn result is known break; } read(cBuf, sizeof(cBuf), 50); } while (bWaitUntilReady); if (!(((binding == STUN_BINDING || binding == STUN_TURN_BINDING) && mStunState.status == NAT_STATUS_UNKNOWN) || ((binding == TURN_BINDING || binding == STUN_TURN_BINDING) && mTurnState.status == NAT_STATUS_UNKNOWN))) { // if stun or turn result is known and is requested result = false; // no need to call this function again } else { // either stun or turn result is not yet available and is requested result = true; // we need to call this function again } } return result; } void OsNatDatagramSocket::enableTransparentReads(bool bEnable) { mbTransparentReads = bEnable ; } UtlBoolean OsNatDatagramSocket::addCrLfKeepAlive(const char* szRemoteIp, const int remotePort, const int keepAliveSecs, OsNatKeepaliveListener* pListener) { #ifdef TEST_PRINT OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsNatDatagramSocket::addCrLfKeepAlive(szRemoteIp=%s, remotePort=%d, keepAliveSecs=%d, pListener=%p) for port: %d descriptor: %d this: %p", szRemoteIp, remotePort, keepAliveSecs, pListener, getLocalHostPort(), getSocketDescriptor(), this); #endif return mpNatAgent->addCrLfKeepAlive(this, szRemoteIp, remotePort, keepAliveSecs, pListener) ; } UtlBoolean OsNatDatagramSocket::removeCrLfKeepAlive(const char* szRemoteIp, const int remotePort) { return mpNatAgent->removeCrLfKeepAlive(this, szRemoteIp, remotePort) ; } UtlBoolean OsNatDatagramSocket::addStunKeepAlive(const char* szRemoteIp, const int remotePort, const int keepAliveSecs, OsNatKeepaliveListener* pListener) { #ifdef TEST_PRINT OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsNatDatagramSocket::addStunKeepAlive(szRemoteIp=%s, remotePort=%d, keepAliveSecs=%d, pListener=%p) for port: %d descriptor: %d this: %p", szRemoteIp, remotePort, keepAliveSecs, pListener, getLocalHostPort(), getSocketDescriptor(), this); #endif return mpNatAgent->addStunKeepAlive(this, szRemoteIp, remotePort, keepAliveSecs, pListener) ; } UtlBoolean OsNatDatagramSocket::removeStunKeepAlive(const char* szRemoteIp, const int remotePort) { return mpNatAgent->removeStunKeepAlive(this, szRemoteIp, remotePort) ; } /* ============================ ACCESSORS ================================= */ // Return the external mapped IP address for this socket. UtlBoolean OsNatDatagramSocket::getMappedIp(UtlString* ip, int* port) { UtlBoolean bSuccess = false ; // Wait for mapped IP to become available while (mStunState.status == NAT_STATUS_UNKNOWN && mStunState.bEnabled) { if (mStunState.status == NAT_STATUS_UNKNOWN && mStunState.bEnabled) { OsTask::yield() ; } } if (mStunState.mappedAddress.length() && mStunState.bEnabled) { if (ip) { *ip = mStunState.mappedAddress ; } if (port) { *port = mStunState.mappedPort ; } // Success if we were able to set either the ip or port if (ip || port) { bSuccess = true ; } } return bSuccess ; } // Return the external relay/return IP address for this socket. UtlBoolean OsNatDatagramSocket::getRelayIp(UtlString* ip, int* port) { UtlBoolean bSuccess = false ; // Wait for relay IP to become available while (mTurnState.status == NAT_STATUS_UNKNOWN && mTurnState.bEnabled) { if (mTurnState.status == NAT_STATUS_UNKNOWN && mTurnState.bEnabled) { OsTask::yield() ; } } if (mTurnState.relayAddress.length() && mTurnState.bEnabled) { if (ip) { *ip = mTurnState.relayAddress ; } if (port) { *port = mTurnState.relayPort ; } // Success if we were able to set either the ip or port if (ip || port) { bSuccess = true ; } } return bSuccess ; } void OsNatDatagramSocket::addAlternateDestination(const char* szAddress, int iPort, int priority) { mpNatAgent->sendStunProbe(this, szAddress, iPort, priority) ; } void OsNatDatagramSocket::setReadNotification(OsNotification* pNotification) { OsLock lock(mReadNotificationLock) ; mpReadNotification = pNotification ; } void OsNatDatagramSocket::readyDestination(const char* szAddress, int iPort) { if (mTurnState.bEnabled && (mTurnState.status == NAT_STATUS_SUCCESS)) { mpNatAgent->primeTurnReception(this, szAddress, iPort) ; } } void OsNatDatagramSocket::setNotifier(OsNotification* pNotification) { mpNotification = pNotification ; mbNotified = false ; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ void OsNatDatagramSocket::setStunAddress(const UtlString& address, const int iPort) { mStunState.mappedAddress = address ; mStunState.mappedPort = iPort ; } void OsNatDatagramSocket::setTurnAddress(const UtlString& address, const int iPort) { mTurnState.relayAddress = address ; mTurnState.relayPort = iPort ; } void OsNatDatagramSocket::markStunSuccess(bool bAddressChanged) { mStunState.status = NAT_STATUS_SUCCESS ; // Signal external identities interested in the STUN outcome. if (mpNotification && (!mbNotified || bAddressChanged)) { UtlString adapterName; getContactAdapterName(adapterName, mLocalIp, false); SIPX_CONTACT_ADDRESS* pContact = new SIPX_CONTACT_ADDRESS(); strcpy(pContact->cIpAddress, mStunState.mappedAddress); pContact->iPort = mStunState.mappedPort; strcpy(pContact->cInterface, adapterName.data()); pContact->eContactType = CONTACT_NAT_MAPPED; pContact->eTransportType = TRANSPORT_UDP ; mpNotification->signal((intptr_t) pContact) ; mbNotified = true ; } } void OsNatDatagramSocket::markStunFailure() { mStunState.status = NAT_STATUS_FAILURE ; // Signal external identities interested in the STUN outcome. if (mpNotification && !mbNotified) { mpNotification->signal(0) ; mbNotified = true ; } } void OsNatDatagramSocket::markTurnSuccess() { mTurnState.status = NAT_STATUS_SUCCESS ; } void OsNatDatagramSocket::markTurnFailure() { mTurnState.status = NAT_STATUS_FAILURE ; } void OsNatDatagramSocket::evaluateDestinationAddress(const UtlString& address, int iPort, int priority) { if ((address.compareTo(mDestAddress, UtlString::ignoreCase) != 0) && (iPort != priority)) { if (priority > miDestPriority) { miDestPriority = priority ; mDestAddress = address ; miDestPort = iPort ; } } else if (priority > miDestPriority) { // No change in host/port, just store updated priority. miDestPriority = priority ; } } UtlBoolean OsNatDatagramSocket::getBestDestinationAddress(UtlString& address, int& iPort) { UtlBoolean bRC = false ; // Wait for stun request to complete for anything of a higher priority while (mpNatAgent->areProbesOutstanding(this, miDestPriority)) { OsTask::delay(20) ; } // Return success value if (mDestAddress.length()) { address = mDestAddress ; iPort = miDestPort ; bRC = portIsValid(iPort) ; } return bRC ; } UtlBoolean OsNatDatagramSocket::applyDestinationAddress(const char* szAddress, int iPort) { UtlBoolean bRC = false ; mDestAddress = szAddress ; miDestPort = iPort ; // ::TODO:: The keepalive period should be configurable (taken from // default stun keepalive setting) if (!addStunKeepAlive(szAddress, iPort, DEFAULT_MEDIA_STUN_KEEPALIVE, NULL)) { // Bob: [2006-06-13] The only way this fails right now is if the // binding is already added. } if (mpNatAgent->setTurnDestination(this, szAddress, iPort)) { bRC = true ; } return bRC ; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsNatConnectionSocket.cpp0000644000175000017500000005637312205613256026026 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2006-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #include #ifndef _WIN32 #include #include #include #include #endif // APPLICATION INCLUDES #include "os/OsSocket.h" #include "os/OsNatConnectionSocket.h" #include "os/OsNatAgentTask.h" #include "os/OsLock.h" #include "os/OsSysLog.h" #include "os/OsEvent.h" #include "tapi/sipXtapi.h" #include "os/OsProtectEvent.h" #include "os/OsProtectEventMgr.h" #include "utl/UtlVoidPtr.h" #include "utl/UtlHashMapIterator.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define DEFAULT_MEDIA_STUN_KEEPALIVE 28 // STATIC VARIABLE INITIALIZATIONS // FORWARD DECLARATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsNatConnectionSocket::OsNatConnectionSocket(int connectedSocketDescriptor, const RtpTcpRoles role) : OsConnectionSocket(connectedSocketDescriptor), mRole(role), mRoleMutex(OsMutex::Q_FIFO), mStreamHandlerMutex(OsMutex::Q_FIFO), mFragmentSize(0), mpDatagramSocket(NULL), mpNatAgent(NULL) { if (0 == mRole) { mRole = RTP_TCP_ROLE_ACTPASS; } socketDescriptor = connectedSocketDescriptor; mpNatAgent = OsNatAgentTask::getInstance() ; mbTransparentReads = TRUE ; mDestAddress = mRemoteIpAddress ; miDestPriority = -1 ; } OsNatConnectionSocket::OsNatConnectionSocket(const char* szLocalIp, int connectedSocketDescriptor, const RtpTcpRoles role) : OsConnectionSocket(szLocalIp, connectedSocketDescriptor), mRole(role), mRoleMutex(OsMutex::Q_FIFO), mStreamHandlerMutex(OsMutex::Q_FIFO), mFragmentSize(0), mpDatagramSocket(NULL), mpNatAgent(NULL) { if (0 == mRole) { mRole = RTP_TCP_ROLE_ACTPASS; } socketDescriptor = connectedSocketDescriptor; mLocalIp = szLocalIp; mpNatAgent = OsNatAgentTask::getInstance() ; mbTransparentReads = TRUE ; mDestAddress = mRemoteIpAddress ; miDestPriority = -1 ; } // Constructor OsNatConnectionSocket::OsNatConnectionSocket(int serverPort, const char* serverName, UtlBoolean blockingConnect, const char* localIp, const bool bConnect, const RtpTcpRoles role) : OsConnectionSocket(serverPort, serverName, blockingConnect, localIp, bConnect), mRole(role), mRoleMutex(OsMutex::Q_FIFO), mStreamHandlerMutex(OsMutex::Q_FIFO), mFragmentSize(0), mpDatagramSocket(NULL), mpNatAgent(NULL) { if (0 == mRole) { mRole = RTP_TCP_ROLE_ACTPASS; } // Init Stun state mStunState.bEnabled = false ; mStunState.status = NAT_STATUS_UNKNOWN ; mStunState.mappedAddress = NULL ; mStunState.mappedPort = PORT_NONE ; // Init Turn state mTurnState.bEnabled = false ; mTurnState.status = NAT_STATUS_UNKNOWN ; mTurnState.relayAddress = NULL ; mTurnState.relayPort = PORT_NONE ; // Init other attributes mpNatAgent = OsNatAgentTask::getInstance() ; mbTransparentReads = TRUE ; mDestAddress = mRemoteIpAddress ; miDestPort = remoteHostPort ; miDestPriority = -1 ; } // Destructor OsNatConnectionSocket::~OsNatConnectionSocket() { destroy(); } void OsNatConnectionSocket::setRole(const RtpTcpRoles role) { mRoleMutex.acquireWrite(); mRole = role; mRoleMutex.releaseWrite(); } const RtpTcpRoles OsNatConnectionSocket::getRole() const { RtpTcpRoles role; mRoleMutex.acquireRead(); role = mRole; mRoleMutex.releaseRead(); return role; } void OsNatConnectionSocket::destroy() { if (mpNatAgent) { mpNatAgent->removeKeepAlives(this) ; mpNatAgent->removeStunProbes(this) ; } disableStun() ; disableTurn() ; mpNatAgent->synchronize() ; } /* ============================ MANIPULATORS ============================== */ OsSocket* OsNatConnectionSocket::getSocket() { return this; } int OsNatConnectionSocket::read(char* buffer, int bufferLength) { int iRC ; UtlString receivedIp ; int iReceivedPort ; iRC = OsSocket::read(buffer, bufferLength, &receivedIp, &iReceivedPort) ; handleFramedStream(buffer, bufferLength, receivedIp.data(), iReceivedPort); return iRC ; } int OsNatConnectionSocket::read(char* buffer, int bufferLength, UtlString* ipAddress, int* port) { int iRC ; iRC = OsSocket::read(buffer, bufferLength, ipAddress, port) ; handleFramedStream(buffer, iRC, ipAddress->data(), *port); return iRC ; } int OsNatConnectionSocket::read(char* buffer, int bufferLength, struct in_addr* ipAddress, int* port) { int iRC ; int iReceivedPort ; UtlString receivedIp ; iRC = read(buffer, bufferLength, &receivedIp, &iReceivedPort) ; if (ipAddress) ipAddress->s_addr = inet_addr(receivedIp) ; if (port) *port = iReceivedPort ; handleFramedStream(buffer, bufferLength, receivedIp.data(), iReceivedPort); return iRC ; } int OsNatConnectionSocket::read(char* buffer, int bufferLength, long waitMilliseconds) { bool bNatPacket = FALSE ; int iRC = 0 ; UtlString receivedIp ; int iReceivedPort ; do { if (isReadyToRead(waitMilliseconds)) { bNatPacket = FALSE ; iRC = OsSocket::read(buffer, bufferLength, &receivedIp, &iReceivedPort) ; if (handleSturnData(buffer, iRC, receivedIp, iReceivedPort)) { if (!mbTransparentReads) iRC = 0 ; else bNatPacket = TRUE ; } } else { break ; } } while ((iRC >= 0) && bNatPacket) ; // Make read time for non-NAT packets if (iRC > 0 && !bNatPacket) { markReadTime() ; } return iRC ; } int OsNatConnectionSocket::write(const char* buffer, int bufferLength) { int framedLength = 0; const char* framedBuffer = frameBuffer(STUN /* use the STUN octet*/, buffer, bufferLength, framedLength); int written = 0; markWriteTime() ; written = OsConnectionSocket::write(framedBuffer, framedLength); free((void*)framedBuffer); return written; } int OsNatConnectionSocket::socketWrite(const char* buffer, int bufferLength, const char* ipAddress, int port, PacketType packetType) { TURN_FRAMING_TYPE type = STUN; // ironically, STUN probes must be sent with the DATA type, not the STUN type, // all other requests are written with the STUN (TURN) type. if (STUN_PROBE_PACKET == packetType) { type = DATA; } int framedLength = 0; const char* framedBuffer = frameBuffer(type, buffer, bufferLength, framedLength); int written = 0; if (MEDIA_PACKET == packetType) { markWriteTime() ; } written = OsConnectionSocket::write(framedBuffer, framedLength, ipAddress, port) ; free((void*)framedBuffer); return written; } int OsNatConnectionSocket::write(const char* buffer, int bufferLength, const char* ipAddress, int port) { int framedLength = 0; const char* framedBuffer = frameBuffer(STUN, buffer, bufferLength, framedLength); int written = 0; markWriteTime() ; written = OsConnectionSocket::write(framedBuffer, framedLength, ipAddress, port) ; free((void*)framedBuffer); return written; } int OsNatConnectionSocket::write(const char* buffer, int bufferLength, long waitMilliseconds) { int framedLength = 0; const char* framedBuffer = frameBuffer(STUN, buffer, bufferLength, framedLength); int written = 0; markWriteTime() ; written = OsConnectionSocket::write(framedBuffer, framedLength, waitMilliseconds) ; free((void*)framedBuffer); return written; } void OsNatConnectionSocket::enableStun(const char* szStunServer, int stunPort, int iKeepAlive, int iStunOptions, bool bReadFromSocket) { assert(false); } void OsNatConnectionSocket::disableStun() { if (mStunState.bEnabled) { mStunState.bEnabled = false ; mpNatAgent->disableStun(this) ; } } void OsNatConnectionSocket::enableTurn(const char* szTurnServer, int turnPort, int iKeepAlive, const char* username, const char* password, bool bReadFromSocket) { if (!mTurnState.bEnabled) { mTurnState.bEnabled = true ; if (!isClientConnected(szTurnServer, turnPort)) { //initialize(szTurnServer, turnPort, true) ; clientConnect(szTurnServer, turnPort); } UtlBoolean bRC = mpNatAgent->enableTurn(this, szTurnServer, turnPort, iKeepAlive, username, password) ; if (bRC) { if (bReadFromSocket) { bool bTransparent = mbTransparentReads ; mbTransparentReads = false ; char cBuf[2048] ; while (mTurnState.status == NAT_STATUS_UNKNOWN) { read(cBuf, sizeof(cBuf), 500) ; if (mTurnState.status == NAT_STATUS_UNKNOWN) { OsTask::yield() ; } } mbTransparentReads = bTransparent ; } } else { mTurnState.status = NAT_STATUS_FAILURE ; } } } void OsNatConnectionSocket::disableTurn() { if (mTurnState.bEnabled) { mTurnState.bEnabled = false ; mpNatAgent->disableTurn(this) ; } } void OsNatConnectionSocket::enableTransparentReads(bool bEnable) { mbTransparentReads = bEnable ; } UtlBoolean OsNatConnectionSocket::addCrLfKeepAlive(const char* szRemoteIp, const int remotePort, const int keepAliveSecs, OsNatKeepaliveListener* pListener) { return mpNatAgent->addCrLfKeepAlive(this, szRemoteIp, remotePort, keepAliveSecs, pListener) ; } UtlBoolean OsNatConnectionSocket::removeCrLfKeepAlive(const char* szRemoteIp, const int remotePort) { return mpNatAgent->removeCrLfKeepAlive(this, szRemoteIp, remotePort) ; } UtlBoolean OsNatConnectionSocket::addStunKeepAlive(const char* szRemoteIp, const int remotePort, const int keepAliveSecs, OsNatKeepaliveListener* pListener) { return mpNatAgent->addStunKeepAlive(this, szRemoteIp, remotePort, keepAliveSecs, pListener) ; } UtlBoolean OsNatConnectionSocket::removeStunKeepAlive(const char* szRemoteIp, const int remotePort) { return mpNatAgent->removeStunKeepAlive(this, szRemoteIp, remotePort) ; } /* ============================ ACCESSORS ================================= */ // Return the external mapped IP address for this socket. UtlBoolean OsNatConnectionSocket::getMappedIp(UtlString* ip, int* port) { UtlBoolean result(false); if (mpDatagramSocket) { mpDatagramSocket->getMappedIp(ip, port); } return result; } // Return the external relay/return IP address for this socket. UtlBoolean OsNatConnectionSocket::getRelayIp(UtlString* ip, int* port) { UtlBoolean bSuccess = false ; // Wait for relay IP to become available while (mTurnState.status == NAT_STATUS_UNKNOWN && mTurnState.bEnabled) { if (mTurnState.status == NAT_STATUS_UNKNOWN && mTurnState.bEnabled) { OsTask::yield() ; } } if (mTurnState.relayAddress.length() && mTurnState.bEnabled) { if (ip) { *ip = mTurnState.relayAddress ; } if (port) { *port = mTurnState.relayPort ; } // Success if we were able to set either the ip or port if (ip || port) { bSuccess = true ; } } return bSuccess ; } void OsNatConnectionSocket::addAlternateDestination(const char* szAddress, int iPort, int priority) { mpNatAgent->sendStunProbe(this, szAddress, iPort, priority) ; } void OsNatConnectionSocket::readyDestination(const char* szAddress, int iPort) { if (mTurnState.bEnabled && (mTurnState.status == NAT_STATUS_SUCCESS)) { mpNatAgent->primeTurnReception(this, szAddress, iPort) ; } } void OsNatConnectionSocket::setNotifier(OsNotification* pNotification) { mpNotification = pNotification ; mbNotified = false ; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ void OsNatConnectionSocket::setStunAddress(const UtlString& address, const int iPort) { mStunState.mappedAddress = address ; mStunState.mappedPort = iPort ; } void OsNatConnectionSocket::setTurnAddress(const UtlString& address, const int iPort) { mTurnState.relayAddress = address ; mTurnState.relayPort = iPort ; } void OsNatConnectionSocket::markStunSuccess(bool bAddressChanged) { mStunState.status = NAT_STATUS_SUCCESS ; // Signal external identities interested in the STUN outcome. if (mpNotification && (!mbNotified || bAddressChanged)) { UtlString adapterName; getContactAdapterName(adapterName, mLocalIp, false); SIPX_CONTACT_ADDRESS* pContact = new SIPX_CONTACT_ADDRESS(); strcpy(pContact->cIpAddress, mStunState.mappedAddress); pContact->iPort = mStunState.mappedPort; strcpy(pContact->cInterface, adapterName.data()); pContact->eContactType = CONTACT_NAT_MAPPED; pContact->eTransportType = TRANSPORT_UDP ; mpNotification->signal((intptr_t) pContact) ; mbNotified = true ; } } void OsNatConnectionSocket::markStunFailure() { mStunState.status = NAT_STATUS_FAILURE ; // Signal external identities interested in the STUN outcome. if (mpNotification && !mbNotified) { mpNotification->signal(0) ; mbNotified = true ; } } void OsNatConnectionSocket::markTurnSuccess() { mTurnState.status = NAT_STATUS_SUCCESS ; } void OsNatConnectionSocket::markTurnFailure() { mTurnState.status = NAT_STATUS_FAILURE ; } void OsNatConnectionSocket::evaluateDestinationAddress(const UtlString& address, int iPort, int priority) { if ((address.compareTo(mDestAddress, UtlString::ignoreCase) != 0) && (iPort != priority)) { if (priority > miDestPriority) { miDestPriority = priority ; mDestAddress = address ; miDestPort = iPort ; } } else if (priority > miDestPriority) { // No change in host/port, just store updated priority. miDestPriority = priority ; } } UtlBoolean OsNatConnectionSocket::getBestDestinationAddress(UtlString& address, int& iPort) { UtlBoolean bRC = false ; // Wait for stun request to complete for anything of a higher priority while (mpNatAgent->areProbesOutstanding(this, miDestPriority)) { OsTask::delay(20) ; } // Return success value if (mDestAddress.length()) { address = mDestAddress ; iPort = miDestPort ; bRC = portIsValid(iPort) ; } return bRC ; } UtlBoolean OsNatConnectionSocket::applyDestinationAddress(const char* szAddress, int iPort) { UtlBoolean bRC = false ; // ::TODO:: The keepalive period should be configurable (taken from // default stun keepalive setting) if (!addStunKeepAlive(szAddress, iPort, DEFAULT_MEDIA_STUN_KEEPALIVE, NULL)) { // Bob: [2006-06-13] The only way this fails right now is if the // binding is already added. } if (mpNatAgent->setTurnDestination(this, szAddress, iPort)) { bRC = true ; } return bRC ; } const char* OsNatConnectionSocket::frameBuffer(TURN_FRAMING_TYPE type, const char* buffer, const int bufferLength, int& framedBufferLen) { /* * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Type | Reserved = 0 | Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * */ char* pBuff = NULL; char* szFramedBuffer = (char*) malloc(MAX_RTP_BYTES + 4); u_short typeByte = 0; typeByte = type; typeByte = typeByte << 8; typeByte = htons((u_short) typeByte); memcpy(szFramedBuffer, &typeByte, sizeof(u_short)); u_short packetLength = htons((u_short) bufferLength); memcpy(szFramedBuffer + sizeof(u_short), &packetLength, sizeof(u_short)); memcpy(szFramedBuffer + (2 * sizeof(u_short)), buffer, bufferLength); framedBufferLen = bufferLength + (2 * sizeof(u_short)); return szFramedBuffer; } void OsNatConnectionSocket::handleFramedStream( char* pData, const int size, const char* receivedIp, const int port) { mStreamHandlerMutex.acquire(); char szStreamChunk [(MAX_RTP_BYTES + 4) * 2]; unsigned int streamBufferSize = size; if (size < 1 || size > (MAX_RTP_BYTES+4)) { mStreamHandlerMutex.release(); return; // can't handle this } // first memcpy in any leftover fragments if (mFragmentSize < 0 || mFragmentSize > ((MAX_RTP_BYTES + 4) * 2)) { assert(false); mFragmentSize = 0; } if (mFragmentSize) { memcpy(szStreamChunk, mszFragment, mFragmentSize); memcpy(szStreamChunk + mFragmentSize, pData, size); streamBufferSize += mFragmentSize; mFragmentSize = 0; } else { memcpy(szStreamChunk, pData, size); } u_short packLen; memcpy(&packLen, szStreamChunk + sizeof(u_short), sizeof(u_short)); packLen = ntohs(packLen); assert(packLen > 0); assert(packLen <= MAX_RTP_BYTES); if (packLen > MAX_RTP_BYTES) { OsSysLog::add(FAC_STREAMING, PRI_DEBUG, "OsNatConnectionSocket::handleFramedStream - Received invalid framing header."); mStreamHandlerMutex.release(); return; } TURN_FRAMING_TYPE type; char* pStreamBuffer = szStreamChunk; if (streamBufferSize >= (packLen + (2*sizeof(u_short))) ) { u_short typeByte = *pStreamBuffer; typeByte = ntohs((u_short)typeByte); type = (TURN_FRAMING_TYPE)typeByte; handleUnframedBuffer(type, pStreamBuffer + (2*sizeof(u_short)), packLen, receivedIp, port); streamBufferSize = streamBufferSize - packLen - (2*sizeof(u_short)); pStreamBuffer = pStreamBuffer + (2*sizeof(u_short)) + packLen; if (streamBufferSize) { handleFramedStream(pStreamBuffer, streamBufferSize, receivedIp, port); } } else { mFragmentSize = streamBufferSize; if (mFragmentSize) { memcpy(mszFragment, pStreamBuffer, mFragmentSize); } } mStreamHandlerMutex.release(); return; } bool OsNatConnectionSocket::handleUnframedBuffer(const TURN_FRAMING_TYPE type, const char* buff, const int buffSize, const char* receivedIp, const int port) { bool bNatPacket = false; int iRC = buffSize; int receivedPort ; UtlString sReceivedIp(receivedIp); bool bHandled = handleSturnData((char*)buff, iRC, sReceivedIp, receivedPort); if (iRC) { if (!mbTransparentReads) iRC = 0 ; else bNatPacket = TRUE ; } // Make read time for non-NAT packets if (iRC > 0 && !bNatPacket) { markReadTime() ; } return bHandled; } void OsNatConnectionSocket::addClientConnection(const char* ipAddress, const int port, OsNatConnectionSocket* pClient) { char szPort[16]; sprintf(szPort, "%d", port); UtlString* key = new UtlString();; *key = UtlString(ipAddress) + UtlString(":") + UtlString(szPort); UtlVoidPtr* container = new UtlVoidPtr(pClient); mClientConnectionSockets.insertKeyAndValue(key, container); } int OsNatConnectionSocket::clientConnect(const char* szServer, const int port) { int iRet = -1; OsNatConnectionSocket* pClient = getClientConnection(szServer, port); if (pClient && !pClient->isConnected()) { iRet = pClient->connect(); } return iRet; } bool OsNatConnectionSocket::isClientConnected(const char* szServer, const int port) { UtlBoolean bRet = false; OsNatConnectionSocket* pClient = getClientConnection(szServer, port); if (pClient) { bRet = pClient->isConnected(); } return bRet==TRUE; } OsNatConnectionSocket* OsNatConnectionSocket::getClientConnection(const char* szServer, const int port) { OsNatConnectionSocket* pClient = NULL; UtlVoidPtr* pSocketContainer = NULL; UtlString key(szServer); key += ":"; char szPort[16]; sprintf(szPort, "%d", port); key += szPort; pSocketContainer = (UtlVoidPtr*)mClientConnectionSockets.findValue(&key); if (pSocketContainer) { pClient = (OsNatConnectionSocket*)pSocketContainer->getValue(); } return pClient; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ /* ///////////////////////// HELPER CLASSES /////////////////////////////// */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsNatSocketBaseImpl.cpp0000644000175000017500000001545312205613256025415 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #include #ifndef _WIN32 #include #endif // APPLICATION INCLUDES #include "os/OsNatSocketBaseImpl.h" #include "os/OsNatDatagramSocket.h" #include "os/OsNatAgentTask.h" #include "os/StunMessage.h" #include "os/StunUtils.h" #include "os/OsLock.h" #include "os/OsSysLog.h" #include "os/OsEvent.h" #include "tapi/sipXtapi.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // FORWARD DECLARATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ OsNatSocketBaseImpl::OsNatSocketBaseImpl() : mReadNotificationLock(OsMutex::Q_FIFO) { miRecordTimes = ONDS_MARK_NONE ; mpReadNotification = NULL ; } // Constructor OsNatSocketBaseImpl::~OsNatSocketBaseImpl() { } bool OsNatSocketBaseImpl::getFirstReadTime(OsDateTime& time) { bool bRC = (miRecordTimes & ONDS_MARK_FIRST_READ) == ONDS_MARK_FIRST_READ ; if (bRC) { time = mFirstRead ; } return bRC ; } bool OsNatSocketBaseImpl::getLastReadTime(OsDateTime& time) { bool bRC = (miRecordTimes & ONDS_MARK_LAST_READ) == ONDS_MARK_LAST_READ ; if (bRC) { time = mLastRead ; } return bRC ; } bool OsNatSocketBaseImpl::getFirstWriteTime(OsDateTime& time) { bool bRC = (miRecordTimes & ONDS_MARK_FIRST_WRITE) == ONDS_MARK_FIRST_WRITE ; if (bRC) { time = mFirstWrite ; } return bRC ; } bool OsNatSocketBaseImpl::getLastWriteTime(OsDateTime& time) { bool bRC = (miRecordTimes & ONDS_MARK_LAST_WRITE) == ONDS_MARK_LAST_WRITE ; if (bRC) { time = mLastWrite ; } return bRC ; } void OsNatSocketBaseImpl::setReadNotification(OsNotification* pNotification) { OsLock lock(mReadNotificationLock) ; mpReadNotification = pNotification ; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ void OsNatSocketBaseImpl::markReadTime() { // Always mark last read miRecordTimes |= ONDS_MARK_LAST_READ ; OsDateTime::getCurTime(mLastRead) ; // Mark first read if not already set if ((miRecordTimes & ONDS_MARK_FIRST_READ) == 0) { miRecordTimes |= ONDS_MARK_FIRST_READ ; mFirstRead = mLastRead ; } OsLock lock(mReadNotificationLock) ; if (mpReadNotification) { mpReadNotification->signal((intptr_t) this) ; mpReadNotification = NULL ; } } void OsNatSocketBaseImpl::markWriteTime() { // Always mark last write miRecordTimes |= ONDS_MARK_LAST_WRITE ; OsDateTime::getCurTime(mLastWrite) ; // Mark first write if not already set if ((miRecordTimes & ONDS_MARK_FIRST_WRITE) == 0) { miRecordTimes |= ONDS_MARK_FIRST_WRITE ; mFirstWrite = mLastWrite ; } } void OsNatSocketBaseImpl::handleStunMessage(char* pBuf, int length, UtlString& fromAddress, int fromPort) { // Make copy and queue it. char* szCopy = (char*) malloc(length) ; if (szCopy) { memcpy(szCopy, pBuf, length) ; NatMsg msg(NatMsg::STUN_MESSAGE, szCopy, length, this, fromAddress, fromPort); OsNatAgentTask::getInstance()->postMessage(msg) ; } } void OsNatSocketBaseImpl::handleTurnMessage(char* pBuf, int length, UtlString& fromAddress, int fromPort) { // Make copy and queue it. char* szCopy = (char*) malloc(length) ; if (szCopy) { memcpy(szCopy, pBuf, length) ; NatMsg msg(NatMsg::TURN_MESSAGE, szCopy, length, this, fromAddress, fromPort); OsNatAgentTask::getInstance()->postMessage(msg) ; } } int OsNatSocketBaseImpl::handleTurnDataIndication(char* buffer, int bufferLength, UtlString* pRecvFromIp, int* pRecvFromPort) { int rc = 0 ; TurnMessage msg ; if (msg.parse(buffer, bufferLength)) { char* pData ; uint16_t nData ; if (msg.getData(pData, nData)) { assert(pData) ; assert(nData < bufferLength) ; if (pData && nData < bufferLength) { memcpy(buffer, pData, nData) ; rc = nData ; if (pRecvFromIp || pRecvFromPort) { char remoteAddr[32] ; uint16_t remotePort ; if (msg.getTurnRemoteAddress(remoteAddr, remotePort)) { if (pRecvFromIp) *pRecvFromIp = remoteAddr ; if (pRecvFromPort) *pRecvFromPort = remotePort ; } } } } } return rc ; } bool OsNatSocketBaseImpl::handleSturnData(char* buffer, int& bufferLength, UtlString& receivedIp, int& receivedPort) { bool bHandled = false ; bool bDataIndication = false ; if ((bufferLength > 0) && TurnMessage::isTurnMessage(buffer, bufferLength, &bDataIndication)) { if (bDataIndication) { bufferLength = handleTurnDataIndication(buffer, bufferLength, &receivedIp, &receivedPort) ; // We need to recurse for DIs -- it may be an encapsulated STUN // message (e.g. ICE) return handleSturnData(buffer, bufferLength, receivedIp, receivedPort) ; } else { handleTurnMessage(buffer, bufferLength, receivedIp, receivedPort) ; bHandled = true ; } } else if ((bufferLength > 0) && StunMessage::isStunMessage(buffer, bufferLength)) { handleStunMessage(buffer, bufferLength, receivedIp, receivedPort) ; bHandled = true ; } return bHandled ; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsPathBase.cpp0000644000175000017500000003074712205613256023577 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsFS.h" #include "utl/UtlDefs.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS #if defined(_VXWORKS) UtlString OsPathBase::separator = "/"; #elif defined(WIN32) UtlString OsPathBase::separator = "\\"; #else UtlString OsPathBase::separator = "/"; #endif //DEFINES #define Extension_ 1 #define Filename_ 2 #define Directory_ 4 #define Drive_ 8 #define Wildname_ 16 #define Wildpath_ 32 /******************************************************************/ /* */ /* has_wild() */ /* */ /* Checks a string for wildcard characters ('?' and '*') */ /* */ /* Arguments 1 - String to check */ /* */ /* Returns: True_ if string contains wildcards, else False_ */ /* */ /* Side Effects: None */ /* */ /******************************************************************/ UtlBoolean has_wild(char *pname) { if (NULL != strchr(pname, '*') || NULL != strchr(pname, '?')) return TRUE; else return FALSE; } /******************************************************************/ /* */ /* fnSplit() */ /* */ /* Splits file specifications into component parts. Similar to */ /* compiler-specific fnsplit() or _splitpath(). */ /* */ /* Arguments 1 - Original file specification */ /* 2 - Buffer to receive drive spec */ /* 3 - Buffer to receive drive/path spec */ /* 4 - Buffer to receive path spec */ /* 5 - Buffer to receive name.ext spec */ /* 6 - Buffer to receive name spec */ /* 7 - Buffer to receive ext spec */ /* */ /* Returns: Bit map as follows (see defines in RBS.H): */ /* Extension_ - File spec included extension */ /* Filename_ - File spec did not end in '\' */ /* Directory_ - File spec included a path */ /* Drive_ - File spec included a drive spec */ /* Wildname_ - File name included wildcards (*.?) */ /* Wildpath_ - File path included wildcards (*.?) */ /* */ /* Side Effects: Calls dos2unix() to convert '\' to '/' */ /* */ /* Notes: Passing NULL in arguments 2-7 causes fnsplit() to */ /* not save the corresponding portion of the path. */ /* */ /******************************************************************/ int fnSplit(char *spec, /* Original file spec */ char *drive, /* Drive spec */ char *pname, /* Path w/ drive spec */ char *path, /* Path spec */ char *fname, /* File name + extension */ char *name, /* File name */ char *ext) /* File extension */ { int ret_code = 0; char *d = spec, *p, *e; if (spec[0] != '\0' && spec[1] == ':') { if (drive) strncpy(drive, spec, 2); drive[2] = 0; d += 2; ret_code |= Drive_; } else { if (drive) *drive = 0; } if (NULL != (p = strrchr(d, *(OsPathBase::separator.data())))) { char ch; ch = *(++p); *p = 0; if (path) strcpy(path, d); if (pname) strcpy(pname, spec); if (has_wild(d)) ret_code |= Wildpath_; *p = ch; ret_code |= Directory_; } else { if (path) *path = 0; if (pname) { if (drive) strcpy(pname, drive); else *pname = 0; } p = d; if ('.' == *p) { size_t dot_length; ret_code |= Directory_; for (dot_length = 0; '.' == p[dot_length]; ++dot_length) ; if (path) { strncat(path, p, dot_length); strcat(path, OsPathBase::separator.data()); } if (pname) { strncat(pname, p, dot_length); strcat(pname, OsPathBase::separator.data()); } if (fname) *fname = 0; if (name) *name = 0; if (ext) *ext = 0; return ret_code; } } if (fname) strcpy (fname, p); if (has_wild(p)) ret_code |= Wildname_; if (*p) ret_code |= Filename_; if (NULL != (e = strrchr(p, '.'))) { *e = 0; if (name) strcpy(name, p); *e = '.'; if (ext) strcpy(ext, e); ret_code |= Extension_; } else { if (name) strcpy(name,p); if (ext) *ext = 0; } return ret_code; } /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsPathBase::OsPathBase() { } // Make one from a char string OsPathBase::OsPathBase(const char *pathname) : UtlString(pathname) { massage(); } // Make one from a UtlStringchar string OsPathBase::OsPathBase(const UtlString &pathname) : UtlString(pathname) { massage(); } // Copy constructor OsPathBase::OsPathBase(const OsPathBase& rOsPath) : UtlString(rOsPath) { *this = rOsPath.data(); massage(); } // Destructor OsPathBase::~OsPathBase() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsPathBase& OsPathBase::operator=(const OsPathBase& rhs) { if (this == &rhs) // handle the assignment to self case return *this; UtlString::operator=(rhs.data()); massage(); return *this; } OsPathBase& OsPathBase::operator+=(const OsPathBase& rhs) { if (this == &rhs) // handle the assignment to self case return *this; UtlString::operator+=(rhs.data()); massage(); return *this; } void OsPathBase::setSeparator(UtlString &rSeparator) { separator = rSeparator; } /* ============================ ACCESSORS ================================= */ UtlString OsPathBase::getSeparator() { return separator; } //: returns just the volme of this object (eg. for DOS c:,d: etc...) UtlString OsPathBase::getVolume() const { return mVolume; } //: returns just the path of this object (without volume or filename) UtlString OsPathBase::getDirName() const { return mDirName; } //: retrieves just the filename part of this object UtlString OsPathBase::getFilename() const { return mFilename; } //: returns just the extension part of this object UtlString OsPathBase::getExt() const { return mExtension; } //: returns the full pathname OsStatus OsPathBase::getNativePath(OsPathBase &rFullPath) const { OsStatus retval = OS_FAILED; OsPath origdir; OsFileSystem::getWorkingDirectory(origdir); OsPath path = *this; //just return if (!OsFileSystem::exists(path)) { rFullPath = *this; return OS_SUCCESS; } //check if this is a dir OsPath temp; OsPath vol = mVolume; OsFileInfo fileInfo; OsFileSystem::getFileInfo(path,fileInfo); if (!fileInfo.isDir()) { if (*vol.data() == '\0') vol = origdir.getVolume(); temp = vol+mDirName; } else temp = *this; if (OsFileSystem::change(temp) == OS_SUCCESS) { OsPath newdir; OsFileSystem::getWorkingDirectory(newdir); rFullPath = newdir; if(!fileInfo.isDir() && !mFilename.isNull()) { rFullPath = rFullPath + OsPath::separator + mFilename + mExtension; } if (OsFileSystem::change(origdir) == OS_SUCCESS) retval = OS_SUCCESS; } return retval; } /* ============================ INQUIRY =================================== */ //: returns true is specified path is valid for the platform UtlBoolean OsPathBase::isValid() { UtlBoolean retval = TRUE; retval = OsFileSystem::exists(*this); return retval; } void OsPathBase::Split() { char drive[10]; char pname[256]; char path[256]; char fname[256]; char name[256]; char ext[256]; fnSplit((char *)data(), /* Original file spec */ drive, /* Drive spec */ pname, /* Path w/ drive spec */ path, /* Path spec */ fname, /* File name + extension */ name, /* File name */ ext); /* File extension */ mVolume = drive; mFilename = name; mDirName = path; mExtension = ext; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ // this function will form the path into the correct path for the given // platform. // It also breaks the path into it's pieces and stores them in the correct member variables void OsPathBase::massage() { UtlString char_to_replace; //due to there not being a command api to do this, I've decided to do this myself.' // (goodluck to me) //now lets figure out which separators to replace if (separator.compareTo("/") == 0) char_to_replace = "\\"; else if (separator.compareTo("\\") == 0) char_to_replace = "/"; size_t pos = index(char_to_replace); while (pos != UTLSTRING_NOT_FOUND) { replace(pos,1,separator); pos = index(char_to_replace,pos+1); } Split(); /* //workbuf to go searching for things UtlString workbuf = *this; //see if this has a drive letter on it if (workbuf(1) == ':') mVolume = workbuf(0,2); //now find out if this file has an extension int period_pos = workbuf.last('.'); if (period_pos != UTLSTRING_NOT_FOUND) { mExtension = workbuf(period_pos,length()-period_pos); } int first_sep_pos = workbuf.index(separator(0)); int last_sep_pos = workbuf.last(separator(0)); if (last_sep_pos != UTLSTRING_NOT_FOUND) { if (first_sep_pos == last_sep_pos) { mDirName = workbuf(mVolume.length(),length()-first_sep_pos); } else mDirName = workbuf(mVolume.length(),last_sep_pos-first_sep_pos); mDirName += separator; } int filenameStart = mVolume.length()+mDirName.length(); if (filenameStart < length()) mFilename = workbuf(filenameStart, length()-last_sep_pos-mExtension.length()-1); */ } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/osPrintf.cpp0000644000175000017500000000512412205613256023401 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include "utl/UtlString.h" #ifdef _WIN32 #include #endif // EXTERNAL FUNCTIONS #if defined(_WIN32) #define WIN32_LEAN_AND_MEAN #include void PrintIt(const char *s) { printf("%s",s); OutputDebugString(s); } #elif defined(ANDROID) #include void PrintIt(const char *s) { // printf("%s",s); __android_log_print(ANDROID_LOG_VERBOSE, "sipXprintf", "%s",s); } #else #define PrintIt(x) printf("%s", (char *) (x)) #endif // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS static volatile int bEnableConsoleOutput = FALSE ; /**< Should osPrintf print to console? */ // FUNCTIONS // Layer of indirection over printf extern "C" void enableConsoleOutput(int bEnable) { bEnableConsoleOutput = bEnable ; } extern "C" void osPrintf(const char* format, ...) { if (bEnableConsoleOutput) { va_list args; va_start(args, format); /* Guess we need no more than 128 bytes. */ int n, size = 128; char *p; p = (char*) malloc(size) ; while (p != NULL) { va_list tmp; /* Argument list must be copied, because we call vsnprintf in a loop * and first call will invalidate list, so on second iteration it * will contain junk. (this is not a problem for i386, but appears * as such on e.g. x86_64) */ va_copy(tmp, args); /* Try to print in the allocated space. */ n = vsnprintf(p, size, format, tmp); va_end(tmp); /* If that worked, return the string. */ if (n > -1 && n < size) { break; } /* Else try again with more space. */ if (n > -1) /* glibc 2.1 */ size = n+1; /* precisely what is needed */ else /* glibc 2.0 */ size *= 2; /* twice the old size */ if ((p = (char*) realloc (p, size)) == NULL) { break; } } if (p != NULL) { PrintIt(p) ; free(p) ; } va_end(args) ; } } sipxtapi-3.3.0~test17/sipXportLib/src/os/OsProcessBase.cpp0000644000175000017500000000654212205613256024315 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #ifdef _VXWORKS #include //needed for putenv #endif // APPLICATION INCLUDES #include "os/OsFS.h" #include "os/OsProcess.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsProcessBase::OsProcessBase() : mPID(-1), mParentPID(-1), mProcessName("") { } // Destructor OsProcessBase::~OsProcessBase() { } /* ============================ MANIPULATORS ============================== */ OsStatus OsProcessBase::setEnv(UtlString &rKey, UtlString &rValue) { OsStatus retval = OS_FAILED; //store the env variable mEnvList.set(rKey.data(),rValue.data()); retval = OS_SUCCESS; return retval; } OsStatus OsProcessBase::unsetEnv(UtlString &rKey) { OsStatus retval = OS_FAILED; //store the env variable if (mEnvList.remove(rKey) == OS_SUCCESS) { retval = OS_SUCCESS; } return retval; } /* ============================ ACCESSORS ================================= */ PID OsProcessBase::getCurrentPID() { return 0; //doesn't mean anything for base class, we need to know platform first } PID OsProcessBase::getPID() { return mPID; } PID OsProcessBase::getParentPID() { return mParentPID; } OsStatus OsProcessBase::getEnv(UtlString &rKey, UtlString &rValue) { OsStatus retval = OS_FAILED; if (mEnvList.get(rKey,rValue) == OS_SUCCESS) { retval = OS_SUCCESS; } return retval; } OsStatus OsProcessBase::getProcessName(UtlString &rProcessName) { OsStatus retval = OS_FAILED; if (!mProcessName.isNull()) { rProcessName = mProcessName; retval = OS_SUCCESS; } return retval; } /* ============================ INQUIRY =================================== */ //dummy wait routine int OsProcessBase::wait(int WaitInSecs) { return -1; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ OsStatus OsProcessBase::ApplyEnv() { OsStatus retval = OS_FAILED; UtlString searchKey = ""; UtlString nextKey; UtlString nextValue; UtlBoolean bFailed = FALSE; #ifndef __pingtel_on_posix__ UtlString fullEnv = ""; #endif mEnvList.getNext(searchKey,nextKey, nextValue); while (nextKey != "") { searchKey = nextKey; #ifndef __pingtel_on_posix__ fullEnv = nextKey; fullEnv += "="; fullEnv += nextValue; if (putenv((char *)fullEnv.data()) != 0) #else if (setenv((char *)nextKey.data(), (char *)nextValue.data(), 1) != 0) #endif { bFailed = TRUE; break; } mEnvList.getNext(searchKey,nextKey, nextValue); } if (!bFailed) retval = OS_SUCCESS; return retval; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsProcessIteratorBase.cpp0000644000175000017500000000242612205613256026024 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsFS.h" #include "os/OsProcessIterator.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsProcessIteratorBase::OsProcessIteratorBase() { } // Destructor OsProcessIteratorBase::~OsProcessIteratorBase() { } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsProcessMgr.cpp0000644000175000017500000005276012205613256024173 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #ifdef __pingtel_on_posix__ #include #endif // APPLICATION INCLUDES #include "os/OsConfigDb.h" #include "os/OsFS.h" #include "os/OsStatus.h" #include "os/OsProcessMgr.h" #include "os/OsTask.h" #include "os/OsSysLog.h" #include "os/OsLock.h" //used for processAlias.dat locking int gFile_descr = -1; // when ProcessMgr calls come funcs internally, we dont want locking to occur // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS OsProcessMgr * OsProcessMgr::spManager = NULL; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsProcessMgr::OsProcessMgr(const char* workingDirectory) : mProcessFilename(PROCESS_ALIAS_FILE), mProcessLockFilename(PROCESS_ALIAS_LOCK_FILE), mWorkPath(workingDirectory), mStdInputFilename(""), mStdOutputFilename(""), mStdErrorFilename(""), pProcessList(NULL), mAliasLockFileCount(0), mMutex(OsMutex::Q_PRIORITY) { if (!pProcessList) { lockAliasFile(); pProcessList = new OsConfigDb(); loadProcessFile(); unlockAliasFile(); } } // Destructor OsProcessMgr::~OsProcessMgr() { if (pProcessList) { delete pProcessList; } } /* ============================ MANIPULATORS ============================== */ //by setting user requested state, you really dont change the current state. //This was added so an external program, through the watchdog, would know what state the user //wanted the process to be in OsStatus OsProcessMgr::setUserRequestState(UtlString &rAlias, int userRequestedState) { OsStatus retval = OS_FAILED; UtlString origVal; UtlString buf; lockAliasFile(); OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG, "ENTERING setUserRequestState %s state = %d\n", rAlias.data(),userRequestedState); switch(userRequestedState) { case USER_PROCESS_START : buf = "USER_START"; break; case USER_PROCESS_STOP : buf = "USER_STOP"; break; case USER_PROCESS_RESTART : buf = "USER_RESTART"; break; default: OsSysLog::add(FAC_PROCESSMGR, PRI_ERR,"setUserRequestState: Invalid state!\n"); break; } //only do it if there is an entry already if (pProcessList->get(rAlias,origVal) == OS_SUCCESS) { //now only make it the first part of the two part value. //we do this because the user may have already set a requested state //and they are changing it to a new value getAliasFirstValue(origVal); //now append the user requested value origVal += " : "; origVal += buf; //no return code for next func... pProcessList->set(rAlias,origVal); //now try to save it if (storeProcessFile() == OS_SUCCESS) { retval = OS_SUCCESS; OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG, "SUCCESS setUserRequestState %s state = %d\n", rAlias.data(),userRequestedState); } else { OsSysLog::add(FAC_PROCESSMGR, PRI_ERR, "setUserRequestState %s state = %d\n", rAlias.data(),userRequestedState); } } unlockAliasFile(); OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG, "EXITING setUserRequestState %s state = %d\n", rAlias.data(),userRequestedState); return retval; } void OsProcessMgr::setProcessListFilename(UtlString &rFilename) { mProcessFilename = rFilename; } OsStatus OsProcessMgr::setIORedirect(OsPath &rStdInputFilename, OsPath &rStdOutputFilename, OsPath &rStdErrorFilename) { mStdInputFilename = rStdInputFilename; mStdOutputFilename = rStdOutputFilename; mStdErrorFilename = rStdErrorFilename; return OS_SUCCESS; } OsStatus OsProcessMgr::startProcess(UtlString &rAlias, UtlString &rExeName, UtlString rParameters[], UtlString &startupDir, OsProcessBase::OsProcessPriorityClass prio, UtlBoolean bExeclusive) { OsStatus retval = OS_FAILED; OsProcess process; lockAliasFile(); OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"Attempting start on %s\n",rAlias.data()); setAliasState(rAlias,PROCESS_STARTING); process.setIORedirect(mStdInputFilename,mStdOutputFilename,mStdErrorFilename); OsPath startDir = startupDir; if (process.launch(rExeName,rParameters,startDir) == OS_SUCCESS) { OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"Before addEntry for alias %s\n",rAlias.data()); retval = addEntry(rAlias,process.getPID()); OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"Started OK for alias %s\n",rAlias.data()); } else { OsSysLog::add(FAC_PROCESSMGR, PRI_ERR,"Start FAILED for %s\n",rAlias.data()); } unlockAliasFile(); return retval; } OsStatus OsProcessMgr::stopProcess(UtlString &rAlias) { OsStatus retval = OS_FAILED; OsProcess process; lockAliasFile(); if (getProcessByAlias(rAlias,process) == OS_SUCCESS) { //must use internal so locking doesn't occur. we already locked int state = getAliasState(rAlias); if (state == PROCESS_STARTED) { OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"Attempting stop on %s\n",rAlias.data()); setAliasState(rAlias,PROCESS_STOPPING); retval = process.kill(); if (retval == OS_SUCCESS) { setAliasState(rAlias,PROCESS_STOPPED); } else { OsSysLog::add(FAC_PROCESSMGR, PRI_ERR,"Error stopping %s\n",rAlias.data()); fprintf(stderr,"process.kill() failed in stopProcess(Alias) \n"); } } } unlockAliasFile(); return retval; } OsStatus OsProcessMgr::stopProcess(PID pid) { OsStatus retval = OS_FAILED; OsProcess process; UtlString aliasName; lockAliasFile(); if (OsProcess::getByPID(pid,process) == OS_SUCCESS) { OsStatus findStatus = getAliasByPID(process.getPID(),aliasName); if (findStatus == OS_SUCCESS) { int state = getAliasState(aliasName); if (state == PROCESS_STARTED) { OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"Attempting stop on %s\n",aliasName.data()); setAliasState(aliasName,PROCESS_STOPPING); retval = process.kill(); if (retval == OS_SUCCESS) { //now find the alias which has that pid OsStatus findStatus = getAliasByPID(process.getPID(),aliasName); if (findStatus == OS_SUCCESS) { setAliasState(aliasName,PROCESS_STOPPED); } } else { OsSysLog::add(FAC_PROCESSMGR, PRI_ERR,"Error stopping %s\n",aliasName.data()); } } } } else { OsSysLog::add(FAC_PROCESSMGR, PRI_ERR, "Error getting process in stopProcess(pid) pid=%d\n",pid); } unlockAliasFile(); return retval; } OsStatus OsProcessMgr::getAliasByPID(PID pid ,UtlString &rAlias) { OsStatus retval = OS_FAILED; UtlString searchKey = ""; UtlString nextKey; UtlString nextValue; UtlString fullEnv = ""; UtlBoolean bFailed = TRUE; rAlias = ""; lockAliasFile(); if (loadProcessFile() == OS_SUCCESS) { pProcessList->getNext(searchKey,nextKey, nextValue); getAliasFirstValue(nextValue); while (nextKey != "") { searchKey = nextKey; if (pid == atoi(nextValue.data())) { rAlias = searchKey; bFailed = FALSE; break; } pProcessList->getNext(searchKey,nextKey, nextValue); getAliasFirstValue(nextValue); } if (!bFailed) { retval = OS_SUCCESS; } } unlockAliasFile(); return retval; } OsStatus OsProcessMgr::getProcessByAlias(UtlString &rAlias, OsProcess &rProcess) { OsStatus retval = OS_FAILED; OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"ENTERING getProcessByAlias %s ",rAlias.data()); lockAliasFile(); if (loadProcessFile() == OS_SUCCESS) { OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG, "SUCCESS getProcessByAlias %s loading process file",rAlias.data()); UtlString value; if (pProcessList->get(rAlias,value) == OS_SUCCESS) { getAliasFirstValue(value); int pid = atoi(value.data()); OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG, "getProcessByAlias checking if pid %d for alias %s is valid", pid, rAlias.data()); if (pid > 0) { retval = OsProcess::getByPID(pid,rProcess); if (retval == OS_SUCCESS) { OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG, "getProcessByAlias alias %s pid %d IS VALID", rAlias.data(),pid); } else { OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG, "getProcessByAlias alias %s pid %d is NOT valid", rAlias.data(),pid); } } } } else { OsSysLog::add(FAC_PROCESSMGR, PRI_ERR, "Error loading process files in getProcessByAlias alias=%s\n", rAlias.data()); } unlockAliasFile(); OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"EXITING getProcessByAlias %s ",rAlias.data()); return retval; } int OsProcessMgr::getAliasState(UtlString &rAlias) { int state = PROCESS_FAILED; OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"ENTERING getAliasState %s ",rAlias.data()); lockAliasFile(); pProcessList->remove(rAlias); loadProcessFile(); UtlString value; if (pProcessList->get(rAlias,value) != OS_SUCCESS) { state = PROCESS_NEVERRUN; } else { //since the value returned contains current_state : request_state //we need to grab only the part we need getAliasFirstValue(value); value.toUpper(); if (value == "STARTING") { state = PROCESS_STARTING; } else if (value == "STOPPING") { state = PROCESS_STOPPING; } else if (value == "STOPPED") { state = PROCESS_STOPPED; } else if (value == "FAILED") { state = PROCESS_FAILED; } else if (atoi(value) > 0) { state = PROCESS_STARTED; OsProcess process; OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG, "getAliasState checking if alias %s has valid PID", rAlias.data()); if (getProcessByAlias(rAlias, process) == OS_FAILED) { OsSysLog::add(FAC_PROCESSMGR, PRI_ERR, "getAliasState - alias %s DOES NOT HAVE a valid PID", rAlias.data()); state = PROCESS_STARTING; setAliasState(rAlias,PROCESS_STARTING); } else { OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG, "getAliasState - alias %s HAS a valid PID",rAlias.data()); } } else { OsSysLog::add(FAC_PROCESSMGR, PRI_ERR, "getAliasState - alias %s HAS a valid PID",rAlias.data()); setAliasState(rAlias,PROCESS_FAILED); } } unlockAliasFile(); OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"EXITING getAliasState %s",rAlias.data()); return state; } void OsProcessMgr::setAliasStopped(UtlString &rAlias) { lockAliasFile(); setAliasState(rAlias,PROCESS_STOPPED); unlockAliasFile(); } /* ============================ ACCESSORS ================================= */ OsProcessMgr *OsProcessMgr::getInstance(const char* workingDirectory) { if (!spManager) { spManager = new OsProcessMgr(workingDirectory); } return spManager; } int OsProcessMgr::getUserRequestState(UtlString &rAlias) { int state = USER_PROCESS_NONE; OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"ENTERING getUserRequestState %s ",rAlias.data()); lockAliasFile(); pProcessList->remove(rAlias); loadProcessFile(); UtlString value; if (pProcessList->get(rAlias,value) != OS_SUCCESS) { state = USER_PROCESS_NONE; } else { //since the value returned contains current_state : request_state //we need to grab only the part we need getAliasSecondValue(value); value.toUpper(); if (value == "USER_START") { state = USER_PROCESS_START; } else if (value == "USER_STOP") { state = USER_PROCESS_STOP; } else if (value == "USER_RESTART") { state = USER_PROCESS_RESTART; } else { state = USER_PROCESS_NONE; } } unlockAliasFile(); OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"EXITING getUserRequestState %s",rAlias.data()); return state; } /* ============================ INQUIRY =================================== */ UtlBoolean OsProcessMgr::isStarted(UtlString &rAlias) { UtlBoolean retval = FALSE; lockAliasFile(); if (getAliasState(rAlias) == PROCESS_STARTED) { retval = TRUE; } unlockAliasFile(); return retval; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ void OsProcessMgr::getAliasFirstValue(UtlString &rinValue) { UtlString retString = ""; //search for a " : " //if found, copy only up to that area size_t separatorPos = rinValue.index(" : "); if (separatorPos != UTL_NOT_FOUND) { rinValue.remove(separatorPos); } } void OsProcessMgr::getAliasSecondValue(UtlString &rinValue) { UtlString retString = ""; //search for a " : " //if found, copy only up to that area size_t separatorPos = rinValue.index(" : "); if (separatorPos != UTL_NOT_FOUND) { rinValue = rinValue.data()+separatorPos+3; } } OsStatus OsProcessMgr::setAliasState(UtlString &rAlias,int newstate) { OsStatus retval = OS_FAILED; UtlString buf; lockAliasFile(); OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"ENTERING setAliasState %s state = %d\n", rAlias.data(),newstate); switch(newstate) { case PROCESS_STARTING : buf = "STARTING"; break; case PROCESS_STOPPING : buf = "STOPPING"; break; case PROCESS_STOPPED : buf = "STOPPED"; break; case PROCESS_FAILED : buf = "FAILED"; break; case PROCESS_NEVERRUN : removeEntry(rAlias); retval = OS_SUCCESS; break; default: OsSysLog::add(FAC_PROCESSMGR, PRI_ERR, "setAliasState: Invalid state %d", newstate); break; } if (newstate != PROCESS_NEVERRUN) { //no return code for next func... pProcessList->set(rAlias,buf); //now try to save it if (storeProcessFile() == OS_SUCCESS) { retval = OS_SUCCESS; OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"SUCCESS setAliasState %s state = %d\n", rAlias.data(),newstate); } else { OsSysLog::add(FAC_PROCESSMGR, PRI_ERR, "setAliasState: %s state = %d\n", rAlias.data(),newstate); } } unlockAliasFile(); OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG, "EXITING setAliasState %s state = %d\n",rAlias.data(),newstate); return retval; } OsStatus OsProcessMgr::addEntry(UtlString &rAlias, int pid) { OsStatus retval = OS_FAILED; char buf[20]; sprintf(buf,"%d",pid); lockAliasFile(); loadProcessFile(); pProcessList->remove(rAlias); //no return code for next func... pProcessList->set(rAlias,buf); //now try to save it OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"Attempting addEntry"); if (storeProcessFile() == OS_SUCCESS) { OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG, "addEntry to %s. PID=%d Flushing processAlias.dat to disk. ", rAlias.data(),pid); retval = OS_SUCCESS; } unlockAliasFile(); return retval; } OsStatus OsProcessMgr::removeEntry(UtlString &rAlias) { OsStatus retval = OS_FAILED; lockAliasFile(); if (pProcessList->remove(rAlias) == OS_SUCCESS) { //now try to save it if (storeProcessFile() == OS_SUCCESS) { retval = OS_SUCCESS; } } unlockAliasFile(); return retval; } void OsProcessMgr::lockAliasFile() { OsLock lock(mMutex); UtlString tmpStr(mWorkPath); tmpStr = mWorkPath; tmpStr += "/"; tmpStr += mProcessLockFilename; OsPath lockFullPath = tmpStr; //if we already have a lock then just return if (mAliasLockFileCount > 0) { mAliasLockFileCount++; return; } UtlBoolean bIsHellFrozenOver = FALSE; int i = 0; while (!bIsHellFrozenOver) { OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG, "Trying to get lock on file: %s...", tmpStr.data()); #ifdef __pingtel_on_posix__ gFile_descr = open(lockFullPath.data(),O_RDWR | O_CREAT | O_EXCL,0644); #elif _WIN32 gFile_descr = _open(lockFullPath.data(),O_RDWR | O_CREAT | O_EXCL); #endif if (gFile_descr == -1) { OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG, "FAILED getting lock!\n"); if (i++ > 60) { i = 0; OsSysLog::add(FAC_PROCESSMGR, PRI_ERR, "FAILED 15 TIMES. Trying remove...\n"); if (OsFileSystem::remove(lockFullPath.data()) == OS_SUCCESS) { OsSysLog::add(FAC_PROCESSMGR, PRI_ERR, "Remove successful. Execution continuing...\n"); } else { OsSysLog::add(FAC_PROCESSMGR, PRI_ERR, "Error removing %s lock file.\n",lockFullPath.data()); } } } else { OsSysLog::add(FAC_SIP, PRI_DEBUG, "Got it!\n"); break; } OsTask::delay(1000); } mAliasLockFileCount++; } void OsProcessMgr::unlockAliasFile() { OsLock lock(mMutex); OsPath lockFullPath = mWorkPath + "/" + mProcessLockFilename; OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"Unlocking AliasLockCount=%d",mAliasLockFileCount); if (mAliasLockFileCount > 0) { mAliasLockFileCount--; } if (mAliasLockFileCount == 0) { if (gFile_descr) #ifdef __pingtel_on_posix__ close(gFile_descr); #elif _WIN32 _close(gFile_descr); #endif if (OsFileSystem::remove(lockFullPath,FALSE,TRUE) != OS_SUCCESS) { OsSysLog::add(FAC_PROCESSMGR, PRI_ERR,"Could not remove lock file!"); } } } OsStatus OsProcessMgr::loadProcessFile() { OsStatus retval = OS_FAILED; OsPath processFullPath = mWorkPath + "/" + mProcessFilename; OsDir processDir(mWorkPath); if (OsFileSystem::exists(processFullPath) == OS_SUCCESS) { OsStatus loadCode = pProcessList->loadFromFile(processFullPath.data()); if (loadCode == OS_SUCCESS) { retval = OS_SUCCESS; } else { OsSysLog::add(FAC_PROCESSMGR, PRI_ERR,"Error loading %s in loadProcessFile\n", processFullPath.data()); } } return retval; } OsStatus OsProcessMgr::storeProcessFile() { OsStatus retval = OS_FAILED; //create the work directory if needed OsDir processDir(mWorkPath); OsPath processFullPath = mWorkPath + "/" + mProcessFilename; OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"ATTEMPTING save on storeProcessFile %s", processFullPath.data()); OsStatus savedCode = pProcessList->storeToFile(processFullPath.data()); if (savedCode == OS_SUCCESS) { OsSysLog::add(FAC_PROCESSMGR, PRI_DEBUG,"SUCCESS saving in storeProcessFile %s", processFullPath.data()); retval = OS_SUCCESS; } else { OsSysLog::add(FAC_PROCESSMGR, PRI_ERR,"storeProcessFile code %d saving in %s ", savedCode, processFullPath.data()); } return retval; } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsProtectEvent.cpp0000644000175000017500000000611112205613305024511 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifdef TEST #include "utl/UtlMemCheck.h" #endif #include "os/OsProtectEvent.h" #include "os/OsUtil.h" #include "os/OsSysLog.h" #include ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// /* ============================ CREATORS ================================== */ OsProtectedEvent::OsProtectedEvent(const intptr_t userData) : OsEvent(userData) , mRefSem(OsBSem::Q_PRIORITY, OsBSem::FULL) , mIntData(0) , mIntData2(0) , mRef(0) { } OsProtectedEvent::~OsProtectedEvent() { // This log statement triggers a "pure virtual method called" // failure (SIGABRT) on some platforms (see Debian bug# 718854), // commented out for now: //OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "Warning OsProtectedEvent deleted"); mStringData = OsUtil::NULL_OS_STRING; } /* ============================ MANIPULATORS ============================== */ OsStatus OsProtectedEvent::signal(const intptr_t eventData) { assert(mRef > 0); return OsEvent::signal(eventData); } // Reset the event so that it may be signaled again. // Return OS_NOT_SIGNALED if the event has not been signaled (or has // already been cleared), otherwise return OS_SUCCESS. OsStatus OsProtectedEvent::reset(void) { OsStatus res; res = OsEvent::reset(); mStringData = OsUtil::NULL_OS_STRING; mIntData = 0; mIntData2 = 0; return res; } // Wait for the event to be signaled. // Return OS_BUSY if the timeout expired, otherwise return OS_SUCCESS. OsStatus OsProtectedEvent::wait(int msgId, const OsTime& rTimeout) { OsStatus res; mIntData2 = msgId; res = OsEvent::wait(rTimeout); assert(mRef > 0); return res; } void OsProtectedEvent::setStringData(UtlString& rStringData) { mStringData = OsUtil::NULL_OS_STRING; if (!rStringData.isNull()) { mStringData = rStringData; } } void OsProtectedEvent::setIntData(intptr_t data) { mIntData = data; } void OsProtectedEvent::setIntData2(intptr_t data) { mIntData2 = data; } void OsProtectedEvent::setInUse(UtlBoolean inUse) { mRefSem.acquire(); mRef = inUse; if (!inUse) reset(); mRefSem.release(); } /* ============================ ACCESSORS ================================= */ OsStatus OsProtectedEvent::getStringData(UtlString& data) { if (!mStringData.isNull()) { data.remove(0); data.append(mStringData.data()); } return OS_SUCCESS; } OsStatus OsProtectedEvent::getIntData(intptr_t& data) { data = mIntData; return OS_SUCCESS; } OsStatus OsProtectedEvent::getIntData2(intptr_t& data) { data = mIntData2; return OS_SUCCESS; } /* ============================ INQUIRY =================================== */ UtlBoolean OsProtectedEvent::isInUse() { return (mRef > 0); } sipxtapi-3.3.0~test17/sipXportLib/src/os/OsProtectEventMgr.cpp0000644000175000017500000001427712205613256025200 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES // Keep OsProtectEventMgrInit.h as the first include! // See OsProtectEventMgrInit class description for more information. #include "os/OsProtectEventMgrInit.h" #include "os/OsProtectEventMgr.h" #include "os/OsSysLog.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS OsProtectEventMgr* OsProtectEventMgr::spInstance; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ OsProtectEventMgr* OsProtectEventMgr::getEventMgr() { return spInstance; } // Constructor OsProtectEventMgr::OsProtectEventMgr(int userData, int initialCount, int softLimit, int hardLimit, int increment) : mListSem(OsBSem::Q_PRIORITY, OsBSem::FULL) { mCurrentCount = 0; mNext = 0; mInitialCount = (initialCount > 1) ? initialCount : 10; mSoftLimit = (initialCount > softLimit) ? initialCount : softLimit; mHardLimit = (softLimit > hardLimit) ? softLimit : hardLimit; mIncrement = increment; if (mHardLimit > initialCount) { assert(mIncrement>0); mIncrement = (mIncrement>0) ? mIncrement : 1; } mpEvents = new OsProtectedEvent*[mHardLimit]; int i; for (i=0; isetInUse(FALSE); mpEvents[i] = pEvent; mCurrentCount++; } } mAllocs = 0; mFrees = 0; } // Destructor OsProtectEventMgr::~OsProtectEventMgr() { OsProtectedEvent* pEvent; mListSem.acquire(); for (int i=0; iisInUse()) { mpEvents[i] = NULL; delete pEvent; } } } delete[] mpEvents; mpEvents = NULL; mListSem.release(); } /* ============================ MANIPULATORS ============================== */ // Find and return an available element of the pool, creating more if // necessary and permitted. Return NULL if failure. OsProtectedEvent* OsProtectEventMgr::alloc(int userData) { int i; OsProtectedEvent* pEvent = NULL; OsProtectedEvent* ret = NULL; mListSem.acquire(); for (i=0; ((iisInUse()) { pEvent->setInUse(TRUE); ret = pEvent; break; } if (mNext >= mCurrentCount) mNext = 0; } if (NULL == ret) { if (mCurrentCount > mSoftLimit) { OsSysLog::add(FAC_KERNEL, PRI_INFO, "*** OsProtectedEvent: pool exceeds soft limit (%d>%d) ***", mCurrentCount, mSoftLimit); } if (mCurrentCount < mHardLimit) { int limit; mNext = mCurrentCount; limit = mCurrentCount + mIncrement; if (limit > mHardLimit) limit = mHardLimit; for (i=mCurrentCount; isetInUse(FALSE); mpEvents[i] = pEvent; mCurrentCount++; } } ret = mpEvents[mNext]; assert(NULL!=ret); if ((NULL != ret) && !ret->isInUse()) { ret->setInUse(TRUE); } mNext++; if (mNext >= mCurrentCount) mNext = 0; } else { OsSysLog::add(FAC_KERNEL, PRI_CRIT, "*** OsProtectEventMgr: pool exceeds hard limit (%d) *** ", mHardLimit); } } if (ret != NULL) mAllocs++; // If the number of outstanding events is a multiple of 10 if(((mAllocs - mFrees) % (mIncrement/5)) == 0) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsProtectEventMgr::alloc in use: %d pool size: %d num. allocs:%d", mAllocs - mFrees, mCurrentCount, mAllocs); } mListSem.release(); return ret; } OsStatus OsProtectEventMgr::release(OsProtectedEvent* pEvent) { mListSem.acquire(); pEvent->setInUse(FALSE); mFrees++; mListSem.release(); return OS_SUCCESS; } /* ============================ ACCESSORS ================================= */ // Return the event data that was signaled by the notifier task. // Return OS_NOT_SIGNALED if the event has not been signaled (or has // already been cleared), otherwise return OS_SUCCESS. int OsProtectEventMgr::allocCnt() { return mAllocs; } // Return the user data specified when this object was constructed. // Always returns OS_SUCCESS. int OsProtectEventMgr::availCnt() { return (mCurrentCount - mAllocs + mFrees); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsProtectEventMgrInit.cpp0000644000175000017500000000320312205613256026007 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 Jaroslav Libak // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsProtectEventMgrInit.h" #include "os/OsProtectEventMgr.h" // DEFINES // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS unsigned int OsProtectEventMgrInit::msCount = 0; // MACROS // GLOBAL VARIABLES // GLOBAL FUNCTIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ OsProtectEventMgrInit::OsProtectEventMgrInit(void) { if (msCount++ == 0) { OsProtectEventMgr::spInstance = new OsProtectEventMgr(); } } OsProtectEventMgrInit::~OsProtectEventMgrInit(void) { if (--msCount == 0) { delete OsProtectEventMgr::spInstance; OsProtectEventMgr::spInstance = NULL; } } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsPtrMsg.cpp0000644000175000017500000000415212205613256023313 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsPtrMsg.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const UtlContainableType OsPtrMsg::TYPE = "OsPtrMsg" ; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsPtrMsg::OsPtrMsg(const unsigned char msgType, const unsigned char msgSubType, void* pData, void* pData2) : OsMsg(msgType, msgSubType), mpData(pData), mpData2(pData2) { // all of the required work is done by the initializers } // Copy constructor OsPtrMsg::OsPtrMsg(const OsPtrMsg& rOsMsg) : OsMsg(rOsMsg), mpData(rOsMsg.mpData), mpData2(rOsMsg.mpData2) { } // Create a copy of this msg object (which may be of a derived type) OsMsg* OsPtrMsg::createCopy(void) const { return new OsPtrMsg(*this); } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsPtrMsg& OsPtrMsg::operator=(const OsPtrMsg& rhs) { if (this != &rhs) // handle the assignment to self case { OsMsg::operator=(rhs); mpData = rhs.mpData; mpData2 = rhs.mpData2; } return *this; } /* ============================ ACCESSORS ================================= */ void* OsPtrMsg::getPtr() { return mpData; } void* OsPtrMsg::getPtr2() { return mpData2; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsQueuedEvent.cpp0000644000175000017500000000624712205613256024340 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsQueuedEvent::OsQueuedEvent(OsMsgQ& rMsgQ, const intptr_t userData) : mUserData(userData), mpMsgQ(&rMsgQ) { } // Destructor OsQueuedEvent::~OsQueuedEvent() { mpMsgQ = NULL; // no work required } /* ============================ MANIPULATORS ============================== */ // Set the event data and send an event message to the designated queue // Return the result of the message send operation. OsStatus OsQueuedEvent::signal(const intptr_t eventData) { OsStatus res; res = doSendEventMsg(OsEventMsg::NOTIFY, eventData); return res; } // Set the user data value for this object // Always returns OS_SUCCESS. OsStatus OsQueuedEvent::setUserData(intptr_t userData) { mUserData = userData; return OS_SUCCESS; } /* ============================ ACCESSORS ================================= */ // Return the user data specified when this object was constructed. // Always returns OS_SUCCESS. OsStatus OsQueuedEvent::getUserData(intptr_t& rUserData) const { rUserData = mUserData; return OS_SUCCESS; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ // Send an event message to the designated message queue. // Return the result of the message send operation. OsStatus OsQueuedEvent::doSendEventMsg(const int msgType, const intptr_t eventData) const { OsTime timestamp; OsDateTime::getCurTimeSinceBoot(timestamp); OsEventMsg msg(msgType, // event msg type *this, // this event eventData, // data signaled with event timestamp); // event timestamp (time since boot) OsStatus rc; if (mpMsgQ) { rc = mpMsgQ->send(msg, mSignalTimeout); if(rc == OS_WAIT_TIMEOUT) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsQueuedEvent failed to queue \"%s\" (%p) event %p due to timeout (%d.%6d). Queue contains %d messages with a max of %d", mpMsgQ->getName().data(), mpMsgQ, this, mSignalTimeout.seconds(), mSignalTimeout.usecs(), mpMsgQ->numMsgs(), mpMsgQ->maxMsgs()); } } else { rc = OS_FAILED; } return rc; } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsRpcMsg.cpp0000644000175000017500000000454512205613256023300 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsRpcMsg.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsRpcMsg::OsRpcMsg(const unsigned char msgType, const unsigned char msgSubType, const OsEvent& rEvent) : OsMsg(msgType, msgSubType), mpEvent((OsEvent*) &rEvent) { // all of the necessary work is done by the initializers } // Copy constructor OsRpcMsg::OsRpcMsg(const OsRpcMsg& rOsRpcMsg) : OsMsg(rOsRpcMsg) { mpEvent = rOsRpcMsg.mpEvent; } // Create a copy of this msg object (which may be of a derived type) OsMsg* OsRpcMsg::createCopy(void) const { return new OsRpcMsg(*this); } // Destructor OsRpcMsg::~OsRpcMsg() { // no work required } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsRpcMsg& OsRpcMsg::operator=(const OsRpcMsg& rhs) { if (this != &rhs) // handle the assignment to self case { OsMsg::operator=(rhs); mpEvent = rhs.mpEvent; } return *this; } /* ============================ ACCESSORS ================================= */ // Return the size of the message in bytes. // This is a virtual method so that it will return the accurate size for // the message object even if that object has been upcast to the type of // an ancestor class. int OsRpcMsg::getMsgSize(void) const { return sizeof(*this); } // Return the pointer to the OsEvent object used to signal completion OsEvent* OsRpcMsg::getEvent(void) const { return mpEvent; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsServerSocket.cpp0000644000175000017500000002003012321267455024514 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #if defined(_WIN32) # include #undef OsSS_CONST #define OsSS_CONST const #elif defined(_VXWORKS) #define OsSS_CONST # include # include # include #elif defined(__pingtel_on_posix__) #undef OsSS_CONST #define OsSS_CONST const # include # include # include # include # include # include # include # include #else #error Unsupported target platform. #endif // APPLICATION INCLUDES #include #include "os/OsSysLog.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define SOCKET_LEN_TYPE #ifdef __pingtel_on_posix__ #undef SOCKET_LEN_TYPE #define SOCKET_LEN_TYPE (socklen_t *) #endif // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsServerSocket::OsServerSocket(int connectionQueueSize, int serverPort, const char* szBindAddr, const bool bPerformBind) { const int one = 1; int error = 0; socketDescriptor = 0; struct sockaddr_in localAddr; int addrSize; // Windows specific startup if(!OsSocket::socketInit()) { goto EXIT; } localHostPort = serverPort; OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsServerSocket::_ queue=%d port=%d bindaddr=%s", connectionQueueSize, serverPort, szBindAddr ); // Create the socket socketDescriptor = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(socketDescriptor == OS_INVALID_SOCKET_DESCRIPTOR) { error = OsSocketGetERRNO(); OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsServerSocket: socket call failed with error: %d=0x%x", error, error); socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; goto EXIT; } #ifndef WIN32 if(setsockopt(socketDescriptor, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one))) OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsServerSocket: setsockopt(SO_REUSEADDR) failed!"); #endif /* Don't know why we don't want to route...we do support subnets, do we not? setsockopt(socketDescriptor, SOL_SOCKET, SO_DONTROUTE, (char *)&one, sizeof(one)) ; */ # if defined(__APPLE__) // Under OS X, we use SO_NOSIGPIPE here because MSG_NOSIGNAL // is not supported for the write() call. if(setsockopt(socketDescriptor, SOL_SOCKET, SO_NOSIGPIPE, (char *)&one, sizeof(one))) { error = OsSocketGetERRNO(); close(); OsSysLog::add(FAC_SIP, PRI_ERR, "setsockopt call failed with error: 0x%x in OsServerSocket::OsServerSocket", error); goto EXIT; } # endif memset(&localAddr, 0, sizeof(localAddr)); localAddr.sin_family = AF_INET; // Bind to a specific server port if given, or let the system pick // any available port number if PORT_DEFAULT. localAddr.sin_port = htons((PORT_DEFAULT == serverPort) ? 0 : serverPort); // Allow IP in on any of this host's addresses or NICs. if (szBindAddr) { localAddr.sin_addr.s_addr = inet_addr (szBindAddr); mLocalIp = szBindAddr; } else { localAddr.sin_addr.s_addr=OsSocket::getDefaultBindAddress(); mLocalIp = inet_ntoa(localAddr.sin_addr); } if (bPerformBind) { error = bind(socketDescriptor, (OsSS_CONST struct sockaddr*) &localAddr, sizeof(localAddr)); if (error == OS_INVALID_SOCKET_DESCRIPTOR) { error = OsSocketGetERRNO(); OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsServerSocket: bind to port %d failed with error: %d = 0x%x", ((PORT_DEFAULT == serverPort) ? 0 : serverPort), error, error); socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; goto EXIT; } } addrSize = sizeof(struct sockaddr_in); error = getsockname(socketDescriptor, (struct sockaddr*) &localAddr, SOCKET_LEN_TYPE &addrSize); if (error) { error = OsSocketGetERRNO(); OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsServerSocket: getsockname call failed with error: %d=0x%x", error, error); } else { localHostPort = htons(localAddr.sin_port); } // Setup the queue for connection requests if (bPerformBind) { error = listen(socketDescriptor, connectionQueueSize); if (error) { error = OsSocketGetERRNO(); OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsServerSocket: listen call failed with error: %d=0x%x", error, error); socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; } } EXIT: ; } // Destructor OsServerSocket::~OsServerSocket() { close(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsServerSocket& OsServerSocket::operator=(const OsServerSocket& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } OsConnectionSocket* OsServerSocket::accept() { OsConnectionSocket* connectSock = NULL; /* Block while waiting for a client to connect. */ struct sockaddr_in clientSocketAddr; int clientAddrLength = sizeof clientSocketAddr; int clientSocket = ::accept(socketDescriptor, (struct sockaddr*) &clientSocketAddr, SOCKET_LEN_TYPE &clientAddrLength); if (clientSocket < 0) { int error = OsSocketGetERRNO(); OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsServerSocket: accept call failed with error: %d=0x%x", error, error); socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; return NULL; } #ifdef WIN32 const int one = 1 ; setsockopt(clientSocket, SOL_SOCKET, SO_DONTROUTE, (char *)&one, sizeof(one)) ; #endif connectSock = createConnectionSocket(mLocalIp, clientSocket); return(connectSock); } void OsServerSocket::close() { if(socketDescriptor > OS_INVALID_SOCKET_DESCRIPTOR) { // OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsServerSocket::close: socket fd: %d\n", (int)socketDescriptor); #if defined(_WIN32) closesocket(socketDescriptor); #elif defined(_VXWORKS) || defined(__pingtel_on_posix__) // Call shutdown first to unblock blocking calls on Linux // HZM: Note that this is suspiciously different from the structure of OsSocket::close() ::shutdown(socketDescriptor,2); ::close(socketDescriptor); #else #error Unsupported target platform. #endif socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; } } /* ============================ ACCESSORS ================================= */ // Returns the socket descriptor // Warning: use of this method risks the creation of platform // dependent code. int OsServerSocket::getSocketDescriptor() const { return(socketDescriptor); } int OsServerSocket::getLocalHostPort() const { return(localHostPort); } void OsServerSocket::getBindIp(UtlString& ip) const { ip = mLocalIp ; } /* ============================ INQUIRY =================================== */ UtlBoolean OsServerSocket::isOk() const { return(socketDescriptor != OS_INVALID_SOCKET_DESCRIPTOR); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ OsConnectionSocket* OsServerSocket::createConnectionSocket(UtlString localIp, int descriptor) { return new OsConnectionSocket(localIp, descriptor); } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsServerTask.cpp0000644000175000017500000001243412205613256024172 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsServerTask.h" #include "os/OsMsg.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const int OsServerTask::DEF_MAX_MSGS = OsMsgQ::DEF_MAX_MSGS; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsServerTask::OsServerTask(const UtlString& name, void* pArg, const int maxRequestQMsgs, const int priority, const int options, const int stackSize) : OsTask(name, pArg, priority, options, stackSize), mIncomingQ(maxRequestQMsgs, OsMsgQ::DEF_MAX_MSG_LEN, OsMsgQ::Q_PRIORITY) // other than initialization, no work required { /* // Only useful when debugging queue problems -- very small case and doesn't // warrant spam in general case -- my opinion anyways. if (OsSysLog::willLog(FAC_KERNEL, PRI_INFO)) { OsSysLog::add(FAC_KERNEL, PRI_INFO, "OsServerTask::OsServerTask %s queue: %p queue limit: %d", mName.data(), &mIncomingQ, maxRequestQMsgs); } */ } // Destructor // As part of destroying the task, flush all messages from the incoming // OsMsgQ. OsServerTask::~OsServerTask() { waitUntilShutDown(20000); // upto 20 seconds mIncomingQ.flush(); // dispose of any messages in the request queue } /* ============================ MANIPULATORS ============================== */ // Handle an incoming message. // This is the message handler of last resort. It should only be called when // the handleMessage() method in the derived class returns FALSE (indicating // that the message has not been handled. UtlBoolean OsServerTask::handleMessage(OsMsg& rMsg) { UtlBoolean handled; handled = FALSE; switch (rMsg.getMsgType()) { case OsMsg::OS_SHUTDOWN: handled = TRUE; break; default: osPrintf( "OsServerTask::handleMessage(): msg type is %d.%d, not OS_SHUTDOWN\n", rMsg.getMsgType(), rMsg.getMsgSubType()); // assert(FALSE); break; } return handled; } // Post a message to this task. // Return the result of the message send operation. OsStatus OsServerTask::postMessage(const OsMsg& rMsg, const OsTime& rTimeout, UtlBoolean sentFromISR) { OsStatus res; if (sentFromISR) res = mIncomingQ.sendFromISR((OsMsg&)rMsg); else res = mIncomingQ.send(rMsg, rTimeout); return res; } // Call OsTask::requestShutdown() and then post an OS_SHUTDOWN message // to the incoming message queue to unblock the task. void OsServerTask::requestShutdown(void) { OsStatus res; OsMsg msg(OsMsg::OS_SHUTDOWN, 0); OsTask::requestShutdown(); res = postMessage(msg); assert(res = OS_SUCCESS); } /* ============================ ACCESSORS ================================= */ // Get the pointer to the incoming message queue OsMsgQ* OsServerTask::getMessageQueue() { return(&mIncomingQ); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ // Waits for a message to arrive on the task's incoming message queue. OsStatus OsServerTask::receiveMessage(OsMsg*& rpMsg) { return mIncomingQ.receive(rpMsg); } // Waits for a message to arrive on the task's incoming message queue. OsStatus OsServerTask::receiveMessage(OsMsg*& rpMsg, const OsTime& rTimeout) { return mIncomingQ.receive(rpMsg, rTimeout); } // The entry point for the task. // This method executes a message processing loop until either // requestShutdown(), deleteForce(), or the destructor for this object // is called. int OsServerTask::run(void* pArg) { UtlBoolean doShutdown = FALSE; OsMsg* pMsg = NULL; OsStatus res; do { res = receiveMessage((OsMsg*&) pMsg); // wait for a message if(res == OS_SUCCESS) { doShutdown = isShuttingDown(); if (!doShutdown) { // comply with shutdown if (!handleMessage(*pMsg)) // process the message OsServerTask::handleMessage(*pMsg); } if (!pMsg->getSentFromISR()) pMsg->releaseMsg(); // free the message } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsServerTask receiveMessage returned: %d", res); OsSysLog::flush(); //assert(res == OS_SUCCESS); } } while (!doShutdown); return 0; // and then exit } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsSharedLibMgr.cpp0000644000175000017500000000356612205613256024412 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsSharedLibMgr.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS OsSharedLibMgrBase* OsSharedLibMgrBase::spInstance = 0; OsBSem OsSharedLibMgrBase::sLock(OsBSem::Q_PRIORITY, OsBSem::FULL); /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ OsSharedLibMgrBase* OsSharedLibMgrBase::getOsSharedLibMgr() { if (spInstance != NULL) return spInstance; // If the task does not yet exist or hasn't been started, then acquire // the lock to ensure that only one instance of the task is started sLock.acquire(); if (spInstance == NULL) spInstance = new OsSharedLibMgr(); sLock.release(); return spInstance; } // Constructor OsSharedLibMgrBase::OsSharedLibMgrBase() { } // Copy constructor OsSharedLibMgrBase::OsSharedLibMgrBase(const OsSharedLibMgrBase& rOsSharedLibMgrBase) { } // Destructor OsSharedLibMgrBase::~OsSharedLibMgrBase() { mLibraryHandles.destroyAll(); } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsSocket.cpp0000644000175000017500000010656212205613256023337 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #include #ifndef WINCE # include #endif //uncomment and recompile to make the socket layer fail after 20 calls. //after that, every 10 calls //#define FORCE_SOCKET_ERRORS #if defined(_WIN32) # include #elif defined(_VXWORKS) # include # include # include # include # include # include # include # include #elif defined(__pingtel_on_posix__) # include # include # include # include # include # include # include # include # include # include /* for some reason this isn't defined on Solaris... */ # ifndef INADDR_NONE # define INADDR_NONE ((unsigned long) -1) # endif #else #error Unsupported target platform. #endif #ifdef __linux__ #include "os/linux/host_address.h" #endif #define DOMAIN_NAME_LENGTH 512 #define HOST_NAME_LENGTH 512 // APPLICATION INCLUDES #include #include #include #include // EXTERNAL FUNCTIONS #ifdef _VXWORKS extern "C" int enetIsLinkActive(void); #endif #ifdef ANDROID // [ #include int getdomainname(char *name, size_t len) { struct utsname un; if ( !uname(&un) ) return -1; if ( len < strlen(un.domainname)+1 ) { errno = EINVAL; return -1; } strcpy(name, un.domainname); return 0; } #endif // ANDROID ] /*--------------------------------------------------------------------------- ** Define VxWorks ethernet, sem copied from NCP **-------------------------------------------------------------------------*/ #if defined(_VXWORKS) #define ECTRL_NAME "cpmac" #define IF_UNIT_NAME "cpmac0" /* includes the Unit number ie "0" */ #endif // EXTERNAL VARIABLES // CONSTANTS const UtlContainableType OsSocket::TYPE = "OsSocket"; // STATIC VARIABLE INITIALIZATIONS UtlBoolean OsSocket::socketInitialized = FALSE; UtlString OsSocket::m_DomainName = ""; // this should be htonl(INADDR_ANY) but count on it being 0... // seems that g++ won't compile it with optimization enabled for some reason. unsigned long OsSocket::m_DefaultBindAddress = INADDR_ANY; OsBSem OsSocket::mInitializeSem(OsBSem::Q_PRIORITY, OsBSem::FULL); /* //////////////////////////// PUBLIC //////////////////////////////////// */ //static method for accessing the bind address from C source unsigned long osSocketGetDefaultBindAddress() { return OsSocket::getDefaultBindAddress(); } /* ============================ CREATORS ================================== */ // Constructor OsSocket::OsSocket() { socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; localHostPort = OS_INVALID_SOCKET_DESCRIPTOR; remoteHostPort = OS_INVALID_SOCKET_DESCRIPTOR; mIsConnected = FALSE; } // Copy constructor /* Abstract class OsSocket::OsSocket(const OsSocket& rOsSocket) { } */ // Destructor OsSocket::~OsSocket() { close(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator /* Abstract class OsSocket& OsSocket::operator=(const OsSocket& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } */ int OsSocket::write(const char* buffer, int bufferLength) { #ifdef FORCE_SOCKET_ERRORS static int numForFailure = 30; static int count = 0; count++; if (count > numForFailure) { count = 0; numForFailure = 10; close(); return 0; } #endif // FORCE_SOCKET_ERRORS int bytesSent; int flags = 0; #if defined(__linux__) || defined(sun) // We do not want send to throw signals if there is a // problem with the socket as this results in the process // getting aborted. We just want it to return an error. // (Under OS X, we use SO_NOSIGPIPE because this is not // supported... this is done in the constructors for // stream socket types as it is a one-time-only thing.) flags = MSG_NOSIGNAL; #endif # if defined(_WIN32) || defined(__pingtel_on_posix__) bytesSent = send(socketDescriptor, buffer, bufferLength, flags); if (bytesSent != bufferLength) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSocket::write send returned %d, errno=%d\n", bytesSent, errno); } #ifdef TEST_PRINT else { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSocket::write send %d bytes", bytesSent); } #endif // 10038 WSAENOTSOCK not a valid socket descriptor # elif defined(_VXWORKS) bytesSent = send(socketDescriptor, (char*)buffer, bufferLength, 0); # else # error Unsupported target platform. # endif return(bytesSent); } int OsSocket::write(const char* buffer, int bufferLength, long waitMilliseconds) { int numBytes = 0; if(isReadyToWrite(waitMilliseconds)) { numBytes = write(buffer, bufferLength); } return(numBytes); } int OsSocket::read(char* buffer, int bufferLength) { #ifdef FORCE_SOCKET_ERRORS static int numForFailure = 30; static int count = 0; count++; if (count > numForFailure) { count = 0; numForFailure = 10; close(); return 0; } #endif //FORCE_SOCKET_ERRORS int flags = 0; #if defined(__linux__) || defined(sun) // We do not want send to throw signals if there is a // problem with the socket as this results in the process // getting aborted. We just want it to return an error. // (Under OS X, we use SO_NOSIGPIPE because this is not // supported... this is done in the constructors for // stream socket types as it is a one-time-only thing.) flags = MSG_NOSIGNAL; #endif int bytesRead = recv(socketDescriptor, buffer, bufferLength, flags); #ifdef _WIN32 if ((bytesRead == 0) && (OsSocketGetERRNO() == 0)) { // Under windows, recv returns 0 and the errno is zero if the // socket has been closed down. We need to close it down for // our bookwork. We also need to -1 to signal the upper // layers (what unix returns). close() ; bytesRead = -1 ; } #endif return bytesRead; } int OsSocket::read(char* buffer, int bufferLength, struct in_addr* fromAddress, int* fromPort) { #ifdef FORCE_SOCKET_ERRORS static int numForFailure = 30; static int count = 0; count++; if (count > numForFailure) { count = 0; numForFailure = 10; close(); return 0; } #endif //FORCE_SOCKET_ERRORS int error; struct sockaddr_in fromSockAddress; int fromLength = sizeof(fromSockAddress); if (NULL != fromPort) *fromPort = PORT_NONE; if (NULL != fromAddress) fromAddress->s_addr = 0; int flags = 0; #if defined(__linux__) || defined(sun) // We do not want send to throw signals if there is a // problem with the socket as this results in the process // getting aborted. We just want it to return an error. // (Under OS X, we use SO_NOSIGPIPE because this is not // supported... this is done in the constructors for // stream socket types as it is a one-time-only thing.) flags = MSG_NOSIGNAL; #endif int bytesRead = recvfrom(socketDescriptor, buffer, bufferLength, flags, (struct sockaddr*) &fromSockAddress, #ifdef __pingtel_on_posix__ (socklen_t *) #endif &fromLength); if(bytesRead == -1) { error = OsSocketGetERRNO(); // 10038 WSAENOTSOCK not a valid socket descriptor if(error) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "recvfrom(%d) call failed with error: %d\n", (int)socketDescriptor, error); #ifdef _WIN32 if (error != WSAECONNRESET) { close(); } #else close(); #endif // perror("OsSocket::read call to recvfrom failed\n"); } } else { if (NULL != fromPort) *fromPort = ntohs(fromSockAddress.sin_port); if (NULL != fromAddress) *fromAddress = fromSockAddress.sin_addr; } return (bytesRead); } int OsSocket::read(char* buffer, int bufferLength, UtlString* fromAddress, int* fromPort) { #ifdef FORCE_SOCKET_ERRORS static int numForFailure = 30; static int count = 0; count++; if (count > numForFailure) { count = 0; numForFailure = 10; close(); return 0; } #endif //FORCE_SOCKET_ERRORS int bytesRead; struct in_addr fromSockAddress; if (NULL != fromAddress) fromAddress->remove(0); bytesRead = OsSocket::read(buffer, bufferLength, &fromSockAddress, fromPort); if(bytesRead != -1) { if (NULL != fromAddress) inet_ntoa_pt(fromSockAddress, *fromAddress); } return(bytesRead); } int OsSocket::read(char* buffer, int bufferLength, long waitMilliseconds) { int numBytes = 0; if(isReadyToRead(waitMilliseconds)) { numBytes = OsSocket::read(buffer, bufferLength); } return(numBytes); } UtlBoolean OsSocket::isReadyToReadEx(long waitMilliseconds,UtlBoolean &rSocketError) const { int tempSocketDescr = OS_INVALID_SOCKET_DESCRIPTOR; rSocketError = FALSE; #ifdef FORCE_SOCKET_ERRORS static int numForFailure = 30; static int count = 0; count++; if (count > numForFailure) { count = 0; numForFailure = 10; close(); rSocketError = TRUE; return FALSE; } #endif //FORCE_SOCKET_ERRORS int numReady = 0; //making a temp copy of the descriptor because it may change from another //thread. And we wouldn't want to use a bad descriptor //in this next piece of code. tempSocketDescr = socketDescriptor; if(tempSocketDescr > OS_INVALID_SOCKET_DESCRIPTOR) { #ifdef __pingtel_on_posix__ /* [ */ #define POLLSET(XX) ((pollState.revents & XX) != 0) int resCode; struct pollfd pollState; pollState.fd = tempSocketDescr; pollState.events = POLLIN | POLLPRI | POLLERR | POLLHUP | POLLNVAL; // In a POSIX system the system call might be interrupted... while(1) { pollState.revents = 0; resCode = poll(&pollState, 1, waitMilliseconds); if ( (resCode == -1 && errno == EINTR) // system call was interrupted && socketDescriptor > OS_INVALID_SOCKET_DESCRIPTOR // socket has not been closed ) { usleep(100); } else { // Otherwise, break out of the loop. break; } } if(resCode < 0) { rSocketError = TRUE; numReady = -1; OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSocket::isReadyToRead poll returned %d (errno=%d) in socket: %x %p\n", resCode, errno, tempSocketDescr, this); } else if(resCode > 0 && pollState.revents && ! POLLSET(POLLIN)) { numReady = -1; OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSocket::isReadyToRead polllState.revents = %d: " "POLLIN: %d POLLPRI: %d POLLERR: %d POLLHUP: %d POLLNVAL: %d\n", pollState.revents, POLLSET(POLLIN), POLLSET(POLLPRI), POLLSET(POLLERR), POLLSET(POLLHUP), POLLSET(POLLNVAL)); } else if(resCode > 0 && POLLSET(POLLIN)) { # if 0 // turn on to debug socket polling problems OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSocket::isReadyToRead socket: %x READY POLLIN", tempSocketDescr); # endif numReady = 1; } else if(resCode == 0) { numReady = 0; if(waitMilliseconds < 0) { # if 0 // turn on to debug socket polling problems OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSocket::isReadyToRead poll returned %d in socket: %x 0%p\n", resCode, tempSocketDescr, this); # endif } } else { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSocket::isReadyToRead socket: %x READY %d", tempSocketDescr, resCode); numReady = resCode; } #else /* __pingtel_on_posix__ ] [ */ fd_set read_fdset; fd_set exc_fdset; int resCode; struct timeval tv; struct timeval *pTv; if (waitMilliseconds < 0) { pTv = NULL; } else { if (0 == waitMilliseconds) { tv.tv_sec = 0; tv.tv_usec = 0; } else { tv.tv_sec = waitMilliseconds / 1000; tv.tv_usec = (waitMilliseconds % 1000) * 1000; } pTv = &tv; } FD_ZERO(&read_fdset); FD_ZERO(&exc_fdset); //making a temp copy of the descriptor because it may change from another //thread. And we wouldn't want to use a bad descriptor //in this next piece of code. tempSocketDescr = socketDescriptor; if (tempSocketDescr > OS_INVALID_SOCKET_DESCRIPTOR) { FD_SET((unsigned int) tempSocketDescr, &read_fdset); FD_SET((unsigned int) tempSocketDescr, &exc_fdset); // if wait time is less than zero block indefinitely resCode = select(tempSocketDescr + 1, &read_fdset, NULL, &exc_fdset, pTv); // if select returns an error, then numReady is set to -1 // if there has been an exception on the socket, then numReady is set to -1 // otherwise, numReady is set to the value returned by select() //test socketDescriptor to be sure it didn't become invalid //while in select if (resCode == -1 || socketDescriptor <= OS_INVALID_SOCKET_DESCRIPTOR) { numReady = -1; rSocketError = TRUE; } else if (resCode > 0 && FD_ISSET(tempSocketDescr, &exc_fdset)) numReady = -1; else numReady = resCode; if(numReady < 0 || numReady > 1 || (numReady == 0 && waitMilliseconds < 0)) { // perror("OsSocket::isReadyToRead()"); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSocket::isReadyToRead select returned %d in socket: %d 0%x\n", resCode, tempSocketDescr, this); } } //if tempSocketDescr if ok #endif /* __pingtel_on_posix__ ] */ } return(numReady == 1); } UtlBoolean OsSocket::isReadyToRead(long waitMilliseconds) const { UtlBoolean bSocketError = FALSE; return isReadyToReadEx(waitMilliseconds,bSocketError); } UtlBoolean OsSocket::isReadyToWrite(long waitMilliseconds) const { int tempSocketDescr = OS_INVALID_SOCKET_DESCRIPTOR; #ifdef FORCE_SOCKET_ERRORS static int numForFailure = 30; static int count = 0; count++; if (count > numForFailure) { count = 0; numForFailure = 10; close(); return FALSE; } #endif //FORCE_SOCKET_ERRORS int numReady = 0; if(socketDescriptor > OS_INVALID_SOCKET_DESCRIPTOR) { fd_set write_fdset; fd_set exc_fdset; int resCode = 0; struct timeval tv; struct timeval *pTv; if (waitMilliseconds < 0) { pTv = NULL; } else { if (0 == waitMilliseconds) { tv.tv_sec = 0; tv.tv_usec = 0; } else { tv.tv_sec = waitMilliseconds / 1000; tv.tv_usec = (waitMilliseconds % 1000) * 1000; } pTv = &tv; } // In a POSIX system the system call might be interrupted... #ifdef __pingtel_on_posix__ while(1) { #endif FD_ZERO(&write_fdset); FD_ZERO(&exc_fdset); //making a temp copy of the descriptor because it may change from another //thread. And we wouldn't want to use a bad descriptor //in this next piece of code. tempSocketDescr = socketDescriptor; if (tempSocketDescr > OS_INVALID_SOCKET_DESCRIPTOR) { FD_SET((unsigned int) tempSocketDescr, &write_fdset); FD_SET((unsigned int) tempSocketDescr, &exc_fdset); // if wait time is less than zero block indefinitely resCode = select(tempSocketDescr + 1, NULL, &write_fdset, &exc_fdset, pTv); } #ifdef __pingtel_on_posix__ // If the system call was interrupted, stay in the loop. // Otherwise, break out of the loop. if (resCode == -1 && errno == EINTR) { usleep(100); } else { break; } } //while (1) if(resCode < 0) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSocket::isReadyToWrite select returned %d (errno=%d) in socket: %d %p\n", resCode, errno, tempSocketDescr, this); } #endif // if select returns an error, then numReady is set to -1 // if there has been an exception on the socket, then numReady is set to -1 // otherwise, numReady is set to the value returned by select() //test socketDescriptor to be sure it didn't become invalid //while in select if (resCode == -1 || socketDescriptor <= OS_INVALID_SOCKET_DESCRIPTOR) numReady = -1; else if (resCode > 0 && FD_ISSET(tempSocketDescr, &exc_fdset)) numReady = -1; else numReady = resCode; if(numReady < 0 || numReady > 1 || (numReady == 0 && waitMilliseconds < 0)) { // perror("OsSocket::isReadyToWrite()"); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSocket::isReadyToWrite select returned %d in socket: %d %p\n", resCode, tempSocketDescr, this); } } //socketDescriptor > OS_INVALID_SOCKET_DESCRIPTOR return(numReady == 1); } void OsSocket::close() { // There seems to be a race condition in the unit tests where // close is called twice. Trying to avoid adding a lock on the // socket itself as locking of the socket is supposed to be an // application problem. For now close the window where a socket // descriptor can be closed twice in two threads at nearly the // same time as this seems to be a bad thing. int tempSocketDescriptor = socketDescriptor; socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; if(tempSocketDescriptor > OS_INVALID_SOCKET_DESCRIPTOR) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSocket::close: Closing type: %d, socket: %d\n", getIpProtocol(), tempSocketDescriptor); #ifdef TEST_PRINT osPrintf("Closing type: %d socket: %d\n", getIpProtocol(), tempSocketDescriptor); #endif # if defined(_WIN32) closesocket(tempSocketDescriptor); # elif defined(_VXWORKS) || defined(__pingtel_on_posix__) # if defined(__pingtel_on_posix__) // This forces any selects which are blocked on // this socket to return shutdown(tempSocketDescriptor, SHUT_RDWR); # endif ::close(tempSocketDescriptor); # else # error Unsupported target platform. # endif } } const char* socketType_UNKNOWN = "UNKNOWN"; const char* socketType_TCP = "TCP"; const char* socketType_UDP = "UDP"; const char* socketType_MULTICAST = "MULTICAST"; const char* socketType_SSL = "TLS"; const char* socketType_custom = "CUSTOM"; const char* socketType_invalid = "INVALID"; const char* OsSocket::ipProtocolString(OsSocket::IpProtocolSocketType type) { switch (type) { case OsSocket::UNKNOWN: return socketType_UNKNOWN; break; case OsSocket::TCP: return socketType_TCP; break; case OsSocket::UDP: return socketType_UDP; break; case OsSocket::MULTICAST: return socketType_MULTICAST; break; case OsSocket::SSL_SOCKET: return socketType_SSL; break; case OsSocket::CUSTOM: return socketType_custom; default: return socketType_invalid; } } void OsSocket::makeNonblocking() { #if defined(_WIN32) unsigned long c_ONDELAY=1; ioctlsocket(socketDescriptor, FIONBIO, &c_ONDELAY); #elif defined(_VXWORKS) #elif defined(__pingtel_on_posix__) int flags = fcntl(socketDescriptor, F_GETFL); fcntl(socketDescriptor, F_SETFL, flags | O_NDELAY); #else # error Unsupported target platform. #endif } void OsSocket::makeBlocking() { #if defined(_WIN32) unsigned long c_ONDELAY=0; ioctlsocket(socketDescriptor, FIONBIO, &c_ONDELAY); #elif defined(_VXWORKS) #elif defined(__pingtel_on_posix__) int flags = fcntl(socketDescriptor, F_GETFL); fcntl(socketDescriptor, F_SETFL, flags&~O_NDELAY); #else # error Unsupported target platform. #endif } UtlBoolean OsSocket::socketInit() { UtlBoolean returnCode = TRUE; mInitializeSem.acquire(); if(!socketInitialized) { socketInitialized = TRUE; mInitializeSem.release(); // Windows specific startup #ifdef _WIN32 WORD wVersionRequested = MAKEWORD( 1, 1 ); WSADATA wsaData; int error = WSAStartup(wVersionRequested, &wsaData); if(error) { osPrintf("WSAStartup call failed with error: %d in OsServerSocket::OsServerSocket\n", error); osPrintf("winsock version: %d.%d supported\n", LOBYTE( wsaData.wVersion ), HIBYTE( wsaData.wVersion )); returnCode = FALSE; } #endif } else { mInitializeSem.release(); } return(returnCode); } ///////////////////////////// // // returns the corredct ipaddress in network byte order // // ///////////////////////////////// unsigned long OsSocket::initDefaultAdapterID(UtlString &interface_id) { mInitializeSem.acquire(); UtlString address = ""; unsigned long retip = htonl(INADDR_ANY); #ifdef WIN32 // Under windows it is possible for many network devices to be present. // in this case we will either return an empty string // or if the configuration parameter PHONESET_BIND_MAC_ADDRESS is defined // we will look up the mac address against the windows adapters // and then return the correct ip address for that adapter int numAdapters = getAdaptersInfo(); //fills in the structure with the adapter info if (numAdapters < 2) { retip = htonl(INADDR_ANY); } else { char ipaddress[20]; char adapter_id[30]; *ipaddress = '\0'; *adapter_id = '\0'; strcpy(adapter_id, interface_id.data()); //if this fails, then we need to choose any address if (strlen(adapter_id) == 0 || lookupIpAddressByMacAddress(adapter_id, ipaddress) == -1) { retip = htonl(INADDR_ANY); } else { address = ipaddress; } } //now convert if it has a string ip address if (address != "") { struct in_addr ipAddr; ipAddr.s_addr = inet_addr (address.data()); retip = ipAddr.s_addr; } #endif mInitializeSem.release(); return retip; } /* ============================ ACCESSORS ================================= */ // Returns the socket descriptor // Warning: use of this method risks the creation of platform // dependent code. int OsSocket::getSocketDescriptor() const { return(socketDescriptor); } void OsSocket::setDefaultBindAddress(const unsigned long bind_address) { mInitializeSem.acquire(); m_DefaultBindAddress = bind_address; mInitializeSem.release(); } unsigned long OsSocket::getDefaultBindAddress() { return(m_DefaultBindAddress); } //gets static member m_DomainName void OsSocket::getDomainName(UtlString &domain_name) { if (m_DomainName == NULL) { #ifdef __pingtel_on_posix__ char nameBuffer[DOMAIN_NAME_LENGTH]; getdomainname(nameBuffer, DOMAIN_NAME_LENGTH - 1); m_DomainName = nameBuffer; #endif //__pingtel_on_posix__ #ifdef _VXWORKS RESOLV_PARAMS_S resolvParams; resolvParamsGet(&resolvParams); m_DomainName = resolvParams.domainName; #endif //VXWORKS #ifdef WIN32 char domain[DOMAIN_NAME_LENGTH]; getWindowsDomainName (domain); m_DomainName = domain; #endif //WIN32 } domain_name = m_DomainName; } void OsSocket::getHostName(UtlString* hostName) { socketInit(); char nameBuffer[HOST_NAME_LENGTH]; gethostname(nameBuffer, HOST_NAME_LENGTH - 1); hostName->remove(0); hostName->append(nameBuffer); } void OsSocket::getHostIp(UtlString* hostAddress) { socketInit(); UtlString thisHost; #ifdef _VXWORKS /* [ */ char ipAddr[100]; ipAddr[0] = '\0'; hostAddress->remove(0); if(!ifAddrGet(IF_UNIT_NAME, ipAddr)) hostAddress->append(ipAddr); #elif defined(__pingtel_on_posix__) /* ] [ */ #ifdef __linux__ char ipAddr[100]; unsigned int ip_int = ntohl(getExternalHostAddressLinux()); sprintf(ipAddr, "%d.%d.%d.%d", ip_int >> 24, (ip_int >> 16) & 255, (ip_int >> 8) & 255, ip_int & 255); hostAddress->remove(0); hostAddress->append(ipAddr); #else getHostName(&thisHost); getHostIpByName(thisHost.data(), hostAddress); #endif /* __linux__ */ #elif defined(_WIN32) /* ] [ */ unsigned long address_val = OsSocket::getDefaultBindAddress(); if (address_val == htonl(INADDR_ANY)) { // get the first local address and // make it the default address const HostAdapterAddress* addresses[MAX_IP_ADDRESSES]; int numAddresses = MAX_IP_ADDRESSES; memset(addresses, 0, sizeof(addresses)); getAllLocalHostIps(addresses, numAddresses); assert(numAddresses > 0); if (numAddresses && hostAddress && addresses[0]) { // Bind to the first address in the list. *hostAddress = (char*)addresses[0]->mAddress.data(); } // Now free up the list. for (int i = 0; i < numAddresses; i++) delete addresses[i]; } else { struct in_addr in; char tmp[50]; in.S_un.S_addr = address_val; strcpy(tmp,inet_ntoa(in)); *hostAddress = tmp; } #else /* ] [ */ #error Unsupported target platform. #endif /* ] */ thisHost.remove(0); } void OsSocket::getRemoteHostIp(struct in_addr* remoteHostAddress, int* remotePort) { struct sockaddr_in remoteAddr; #ifdef __pingtel_on_posix__ socklen_t len; #else int len; #endif len = sizeof(struct sockaddr_in); if (getpeername(socketDescriptor, (struct sockaddr *)&remoteAddr, &len) != 0) { memset(&remoteAddr, 0, len); } // *remoteHostAddress = remoteAddr.sin_addr; memcpy(remoteHostAddress, &(remoteAddr.sin_addr), sizeof(struct in_addr)); #ifdef TEST_PRINT { UtlString output_address; inet_ntoa_pt(remoteAddr.sin_addr, output_address); osPrintf("Remote name: %s\n", output_address.data()); } #endif if (NULL != remotePort) { *remotePort = ntohs(remoteAddr.sin_port); } } void OsSocket::getRemoteHostIp(UtlString* remoteHostAddress, int* remotePort) { struct in_addr remoteAddr; getRemoteHostIp(&remoteAddr, remotePort); remoteHostAddress->remove(0); inet_ntoa_pt(remoteAddr, *remoteHostAddress); } void OsSocket::getRemoteHostName(UtlString* remoteHostNameString) const { remoteHostNameString->remove(0); remoteHostNameString->append(remoteHostName); } int OsSocket::getRemoteHostPort() const { return(remoteHostPort); } UtlBoolean OsSocket::getHostIpByName(const char* hostName, UtlString* hostAddress) { UtlBoolean bSuccess = FALSE; struct hostent* server; socketInit(); // If this is aleady an IP address if (isIp4Address(hostName)) { *hostAddress = hostName; bSuccess = TRUE ; } else if (strcmp(hostName, "localhost") == 0) { *hostAddress = "127.0.0.1"; bSuccess = TRUE ; } #ifdef _VXWORKS // $$$ (rschaaf) // ToDo: Extend the OS abstraction layer with a method to determine // whether the network interface is available. else if (!enetIsLinkActive()) { *hostAddress = "0.0.0.0"; osPrintf("getHostIpByName failed for %s %s\n %s\n", hostName, hostAddress->data(), "network is unavailable"); } #endif // if no default domain name and host name not fully qualified else if (!hasDefaultDnsDomain() && (strchr(hostName, '.') == NULL)) { *hostAddress = "0.0.0.0"; } else { #if defined(_WIN32) || defined(__pingtel_on_posix__) server = gethostbyname(hostName); #elif defined(_VXWORKS) char hostentBuf[512]; server = resolvGetHostByName((char*) hostName, hostentBuf, sizeof(hostentBuf)); #else #error Unsupported target platform. #endif //_VXWORKS if(server) { inet_ntoa_pt(*((in_addr*) (server->h_addr)), *hostAddress); bSuccess = TRUE ; } else { //osPrintf("getHostIpByName DNS look up failed: %s %s\n", // hostName, hostAddress->data()); // if host name has valid ip, then use the name if(INADDR_NONE != inet_addr(hostName)) { *hostAddress = hostName; } else { *hostAddress = "0.0.0.0"; } } } return bSuccess ; } void OsSocket::getLocalHostIp(UtlString* localHostAddress) const { OsSocket::getHostIp(localHostAddress) ; } int OsSocket::getLocalHostPort() const { return(localHostPort); } /* ============================ INQUIRY =================================== */ UtlBoolean OsSocket::isOk() const { return(socketDescriptor != OS_INVALID_SOCKET_DESCRIPTOR); } UtlBoolean OsSocket::isConnected() const { return(mIsConnected); } UtlBoolean OsSocket::isLocalHost(const char* hostAddress) { UtlBoolean local; UtlString thisHost; UtlString thisHostAddr; getHostName(&thisHost); getHostIp(&thisHostAddr); if(strcmp(hostAddress, "127.0.0.1") == 0 || strcmp(hostAddress, "localhost") == 0 || strcmp(hostAddress, thisHost.data()) == 0 || strcmp(hostAddress, thisHostAddr.data()) == 0) { local = TRUE; } else { local = FALSE; } thisHost.remove(0); thisHostAddr.remove(0); return(local); } UtlBoolean OsSocket::isIp4Address(const char* address) { // nnn.nn.n.nnn // ^==== dot3 // ^====== dot2 // ^========= dot1 const char* dot1 = strchr(address, '.'); UtlBoolean isIp4 = FALSE; if(dot1) { const char* dot2 = strchr(dot1 + 1, '.'); if((dot2) && (dot2-dot1 > 1)) { const char* dot3 = strchr(dot2 + 1, '.'); if((dot3) && (dot3-dot2 > 1)) { const char* dot4 = strchr(dot3 + 1, '.'); if((dot4 == NULL) && strlen(dot3) > 1) { if(INADDR_NONE != inet_addr(address)) { isIp4 = TRUE; } } } } } return(isIp4); } UtlBoolean OsSocket::isMcastAddr(const char* ipAddress) { int a, b, c, d; if (!ipAddress || sscanf(ipAddress, "%d.%d.%d.%d", &a, &b, &c, &d) != 4) return FALSE; if (a >= 224 && a <= 239) return TRUE; else return FALSE; } UtlBoolean OsSocket::isSameHost(const char* host1, const char* host2) { UtlBoolean same; UtlBoolean isSubDomain = FALSE; //osPrintf("OsSocket::isSameHost host1: %s host2: %s\n", host1, host2); if (!isIp4Address(host1) && !isIp4Address(host2)) { if( (strstr(host1, host2) == host1 || // && need to compare w/ local domain name strstr(host2, host1) == host2 )) { // && need to compare w/ local domain name isSubDomain = TRUE; } } if(strcmp(host1, host2) == 0 || (isLocalHost(host1) && isLocalHost(host2)) || isSubDomain ) { same = TRUE; } else { // Avoid using gethostbyname if possible UtlString host1Addr; UtlString host2Addr; getHostIpByName(host1, &host1Addr); getHostIpByName(host2, &host2Addr); if(host1Addr.compareTo(host2Addr) == 0) { same = TRUE; } else { same = FALSE; } host1Addr.remove(0); host2Addr.remove(0); } return(same); } const UtlString& OsSocket::getLocalIp() const { return mLocalIp; } // change the ip address into the dot ip address void OsSocket::inet_ntoa_pt(struct in_addr input_address, UtlString& output_address) { output_address.remove(0); #ifdef _VXWORKS char temp_addr[30]; inet_ntoa_b(input_address, temp_addr); output_address.append(temp_addr); #elif defined(_WIN32) || defined(__pingtel_on_posix__) output_address.append(inet_ntoa(input_address)); #else #error Unsupported target platform. #endif } //:Returns TRUE if the given IpProtocolSocketType is a framed message protocol // (that is, every read returns exactly one message), and so the Content-Length // header may be omitted. UtlBoolean OsSocket::isFramed(IpProtocolSocketType type) { UtlBoolean r; switch (type) { case TCP: case SSL_SOCKET: // UNKNOWN and all other values return FALSE for safety. case UNKNOWN: case CUSTOM: default: r = FALSE; break; case UDP: case MULTICAST: r = TRUE; break; } return r; } UtlContainableType OsSocket::getContainableType() const { return OsSocket::TYPE; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ // Returns TRUE if this host has a default DNS domain UtlBoolean OsSocket::hasDefaultDnsDomain() { #ifdef _VXWORKS RESOLV_PARAMS_S resolvParams; resolvParamsGet(&resolvParams); return (strlen(resolvParams.domainName) != 0); #else // For now, on non-vxWorks platforms, assume that the host has a // default domain name. return TRUE; #endif } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsSocketCrypto.cpp0000644000175000017500000002455312205613256024537 0ustar00danieldaniel00000000000000// // Copyright (C) 2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2008 Mutualink, Inc. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // Author: Sergey Kostanbaev #ifdef HAVE_SSL // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsIntTypes.h" #include "os/OsDefs.h" #include "os/OsSysLog.h" #include "os/OsSocketCrypto.h" #include "utl/UtlCryptoKeySym.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // TYPEDEFS // DEFINES #define SDP_CODEC_PCMU 0 //#define SDP_CODEC_PCMU 8 #define SRTP_PAYLOADTYPE_PCMU 1 struct rtpHeader { uint8_t vpxcc; ///< Version, Padding, Extension and CSRC Count bits. uint8_t mpt; ///< Marker and Payload Type bits. uint16_t seq; ///< Sequence Number (Big Endian!) uint32_t timestamp; ///< Timestamp (Big Endian!) uint32_t ssrc; ///< SSRC (Big Endian!) }; #define RTP_P_MASK 0x20 ///< Mask for Padding bit in RtpHeader::vpxcc #define RTP_PT_MASK 0x7F ///< Mask for Payload Type bits in RtpHeader::mpt #define RTP_M_MASK 0x80 ///< Mask for Marker bit in RtpHeader::mpt // MACROS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////////// PUBLIC //////////////////////////////// */ /* =============================== CREATORS =============================== */ OsSocketCryptoProxy::OsSocketCryptoProxy(OsSocket* pureSocket, int (OsSocket::*read1)(char*, int), int (OsSocket::*read2)(char*, int, UtlString*, int*), int (OsSocket::*read3)(char*, int, struct in_addr*, int*), int (OsSocket::*read4)(char*, int, long), int (OsSocket::*write1)(const char*, int), int (OsSocket::*write2)(const char*, int, const char*, int), int (OsSocket::*write3)(const char*, int, long), const char* pEncBinData, int encBinLength, const char* pDecBinData, int decBinLength) : mDoPadding(FALSE) , mpRtpEncryptKey(NULL) , mpRtpDecryptKey(NULL) , mPureSocket(pureSocket) , mRead1(read1) , mRead2(read2) , mRead3(read3) , mRead4(read4) , mWrite1(write1) , mWrite2(write2) , mWrite3(write3) { setSymKeys(pEncBinData, encBinLength, pDecBinData, decBinLength); } OsSocketCryptoProxy::~OsSocketCryptoProxy() { delete mpRtpEncryptKey; delete mpRtpDecryptKey; } /* ============================= MANIPULATORS ============================= */ UtlBoolean OsSocketCryptoProxy::setSymKeys(const char* pEncBinData, int encBinLength, const char* pDecBinData, int decBinLength) { if (mpRtpEncryptKey != NULL) delete mpRtpEncryptKey; mpRtpEncryptKey = new UtlCryptoKeySym(); if (mpRtpEncryptKey->loadBinaryKey((const uint8_t*)pEncBinData, encBinLength) != 0) return FALSE; if (mpRtpDecryptKey != NULL) delete mpRtpDecryptKey; mpRtpDecryptKey = new UtlCryptoKeySym(); if (mpRtpDecryptKey->loadBinaryKey((const uint8_t*)pDecBinData, decBinLength) != 0) return FALSE; return TRUE; } UtlBoolean OsSocketCryptoProxy::decode(char* buffer, int bufferLength, int originalLength, int& decodedLen) { struct rtpHeader* ph = (struct rtpHeader* )mDecodeBuffer; unsigned char* payloadData = (unsigned char* )ph + sizeof(struct rtpHeader); UtlBoolean padding = ((ph->vpxcc & RTP_P_MASK) == RTP_P_MASK); int payloadOctets = originalLength - sizeof(struct rtpHeader); if (padding) { uint8_t padBytes = buffer[originalLength - 1]; if ((padBytes & (~3)) != 0) { // For security reason padBytes = 0; } payloadOctets -= padBytes; } int payloadType = (ph->mpt & RTP_PT_MASK); if (SRTP_PAYLOADTYPE_PCMU == payloadType) { ph->vpxcc &= ~RTP_P_MASK; ph->mpt = (SDP_CODEC_PCMU & RTP_PT_MASK) | (ph->mpt & RTP_M_MASK); memcpy(buffer, mDecodeBuffer, sizeof(struct rtpHeader)); UtlCryptoKey* pKey = mpRtpDecryptKey; int len = bufferLength - sizeof(struct rtpHeader); if (pKey->decrypt(payloadData, payloadOctets, (unsigned char*)buffer + sizeof(struct rtpHeader), &len) == 0) { OsSysLog::add(FAC_MP, PRI_DEBUG, "OsSocketCrypto RTP decrypt failed: PayloadLen=%d", payloadOctets); return 0; } decodedLen = len + sizeof(struct rtpHeader); return TRUE; } else { decodedLen = originalLength; memcpy(buffer, mDecodeBuffer, decodedLen); return FALSE; } } UtlBoolean OsSocketCryptoProxy::encode(const char* buffer, int bufferLength, int& encodedLen) { // We assume that buffer is RTP packet, if so and payload == pcmu // perform encryption before send struct rtpHeader* ph = (struct rtpHeader* )buffer; int payloadOctets = bufferLength - sizeof(struct rtpHeader); if (payloadOctets <= 0) return FALSE; unsigned char* payloadData = (unsigned char* )ph + sizeof(struct rtpHeader); UtlBoolean padding = ((ph->vpxcc & RTP_P_MASK) == RTP_P_MASK); if (padding) { uint8_t padBytes = buffer[bufferLength - 1]; if ((padBytes & (~3)) != 0) { // For security reason padBytes = 0; } payloadOctets -= padBytes; } // Encrypt the payload if necessary UtlCryptoKey* pKey = mpRtpEncryptKey; if ((pKey) && ((ph->mpt & RTP_PT_MASK) == SDP_CODEC_PCMU)) { // Move the clear payload into an allocated array memcpy(mCryptoBuffer, buffer, sizeof(struct rtpHeader)); int encLen = MAX_CRYPTOBUFFER - sizeof(struct rtpHeader); if (pKey->encrypt(payloadData, payloadOctets, mCryptoBuffer + sizeof(struct rtpHeader), &encLen) == 0) { OsSysLog::add(FAC_MP, PRI_DEBUG, "OsSocketCrypto RTP encrypt failed: PayloadLen=%d", payloadOctets); return 0; } struct rtpHeader* ph2 = (struct rtpHeader* )mCryptoBuffer; ph2->vpxcc &= ~RTP_P_MASK; ph2->mpt = (SRTP_PAYLOADTYPE_PCMU & RTP_PT_MASK) | (ph2->mpt & RTP_M_MASK); int pad = mDoPadding ? ((4 - (3 & encLen)) & 3) : 0; switch (pad) { case 3: payloadData[encLen+1] = 0; /* fall through */ case 2: payloadData[encLen] = 0; /* fall through */ case 1: payloadData[encLen+pad-1] = pad; ph2->vpxcc |= RTP_P_MASK; case 0: break; } encodedLen = sizeof(struct rtpHeader) + encLen + pad; return TRUE; } else { return FALSE; } } int OsSocketCryptoProxy::write(const char* buffer, int bufferLength) { int encodedLen; if (encode(buffer, bufferLength, encodedLen)) { return (mPureSocket->*mWrite1)((const char*)mCryptoBuffer, encodedLen); } else { return (mPureSocket->*mWrite1)(buffer, bufferLength); } } int OsSocketCryptoProxy::write(const char* buffer, int bufferLength, const char* ipAddress, int port) { int encodedLen; if (encode(buffer, bufferLength, encodedLen)) { return (mPureSocket->*mWrite2)((const char*)mCryptoBuffer, encodedLen, ipAddress, port); } else { return (mPureSocket->*mWrite2)(buffer, bufferLength, ipAddress, port); } } int OsSocketCryptoProxy::write(const char* buffer, int bufferLength, long waitMilliseconds) { int encodedLen; if (encode(buffer, bufferLength, encodedLen)) { return (mPureSocket->*mWrite3)((const char*)mCryptoBuffer, encodedLen, waitMilliseconds); } else { return (mPureSocket->*mWrite3)(buffer, bufferLength, waitMilliseconds); } } int OsSocketCryptoProxy::read(char* buffer, int bufferLength) { if (mpRtpDecryptKey == NULL) { return (mPureSocket->*mRead1)(buffer, bufferLength); } assert(MAX_CRYPTOBUFFER >= bufferLength); int res = (mPureSocket->*mRead1)((char*)mDecodeBuffer, bufferLength); if (res <= 0) return res; int decoded; decode(buffer, bufferLength, res, decoded); return decoded; } int OsSocketCryptoProxy::read(char* buffer, int bufferLength, UtlString* fromAddress, int* fromPort) { if (mpRtpDecryptKey == NULL) { return (mPureSocket->*mRead2)(buffer, bufferLength, fromAddress, fromPort); } assert(MAX_CRYPTOBUFFER >= bufferLength); int res = (mPureSocket->*mRead2)((char*)mDecodeBuffer, bufferLength, fromAddress, fromPort); if (res <= 0) return res; int decoded; decode(buffer, bufferLength, res, decoded); return decoded; } int OsSocketCryptoProxy::read(char* buffer, int bufferLength, struct in_addr* ipAddress, int* port) { if (mpRtpDecryptKey == NULL) { return (mPureSocket->*mRead3)(buffer, bufferLength, ipAddress, port); } assert(MAX_CRYPTOBUFFER >= bufferLength); int res = (mPureSocket->*mRead3)((char*)mDecodeBuffer, bufferLength, ipAddress, port); if (res <= 0) return res; int decoded; decode(buffer, bufferLength, res, decoded); return decoded; } int OsSocketCryptoProxy::read(char* buffer, int bufferLength, long waitMilliseconds) { if (mpRtpDecryptKey == NULL) { return (mPureSocket->*mRead4)(buffer, bufferLength, waitMilliseconds); } assert(MAX_CRYPTOBUFFER >= bufferLength); int res = (mPureSocket->*mRead4)((char*)mDecodeBuffer, bufferLength, waitMilliseconds); if (res <= 0) return res; int decoded; decode(buffer, bufferLength, res, decoded); return decoded; } /* ============================== ACCESSORS =============================== */ /* =============================== INQUIRY ================================ */ /* ////////////////////////////// PROTECTED /////////////////////////////// */ /* /////////////////////////////// PRIVATE //////////////////////////////// */ /* ============================== FUNCTIONS =============================== */ #endif sipxtapi-3.3.0~test17/sipXportLib/src/os/OsSSL.cpp0000644000175000017500000004462512205613256022551 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #if defined(HAVE_SSL) // SYSTEM INCLUDES #ifdef _WIN32 # include #endif #include #include #include #include // APPLICATION INCLUDES #include "os/OsSSL.h" #include "os/OsLock.h" #include "os/OsSysLog.h" #include "utl/UtlString.h" #include "utl/UtlSList.h" #ifndef SIPX_CONFDIR # define SIPX_CONFDIR "." #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define TEST_DEBUG const char* defaultPublicCertificateFile = SIPX_CONFDIR "/ssl/ssl.crt"; const char* defaultPrivateKeyFile = SIPX_CONFDIR "/ssl/ssl.key"; const char* defaultAuthorityPath = SIPX_CONFDIR "/ssl/authorities"; bool OsSSL::sInitialized = false; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsSSL::OsSSL(const char* authorityPath, const char* publicCertificateFile, const char* privateKeyPath ) { if (!sInitialized) { // Initialize random number generator before using SSL // TODO: this is a bad way to do this - it may need to be fixed. // // We should be using better randomness if possible, but at the very // least we should be saving the current rand state in a file so that // is not reset each time. I think that on a modern Linux, this has // no effect because OpenSSL will use /dev/urandom internally anyway? // // This needs to be examined. /* make a random number and set the top and bottom bits */ int seed[32]; for (unsigned int i = 0; i < sizeof(seed)/sizeof(int);i++) { seed[i] = rand(); } RAND_seed(seed,sizeof(seed)); SSLeay_add_ssl_algorithms(); // It is suggested by the OpenSSL group that embedded systems // only enable loading of error strings when debugging. // Perhaps this should be conditional? SSL_load_error_strings(); sInitialized = true; } mCTX = SSL_CTX_new(SSLv23_method()); if (mCTX) { if (SSL_CTX_load_verify_locations(mCTX, NULL, // we do not support using a bundled CA file authorityPath ? authorityPath : defaultAuthorityPath) > 0) { if (SSL_CTX_use_certificate_file(mCTX, publicCertificateFile ? publicCertificateFile : defaultPublicCertificateFile, SSL_FILETYPE_PEM) > 0) { if (SSL_CTX_use_PrivateKey_file(mCTX, privateKeyPath ? privateKeyPath : defaultPrivateKeyFile, SSL_FILETYPE_PEM) > 0) { if (SSL_CTX_check_private_key(mCTX)) { OsSysLog::add(FAC_KERNEL, PRI_INFO ,"OsSSL::_ %p CTX %p loaded key pair:\n" " public '%s'\n" " private '%s'" ,this, mCTX, publicCertificateFile ? publicCertificateFile : defaultPublicCertificateFile, privateKeyPath ? privateKeyPath : defaultPrivateKeyFile ); // TODO: log our own certificate data // Establish verification rules SSL_CTX_set_verify(mCTX, SSL_VERIFY_PEER + SSL_VERIFY_CLIENT_ONCE, verifyCallback ); // disable server connection caching // TODO: Investigate turning this on... SSL_CTX_set_session_cache_mode(mCTX, SSL_SESS_CACHE_OFF); } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSL::_ Private key '%s' does not match certificate '%s'", privateKeyPath ? privateKeyPath : defaultPrivateKeyFile, publicCertificateFile ? publicCertificateFile : defaultPublicCertificateFile ); } } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSL::_ Private key '%s' could not be initialized.", privateKeyPath ? privateKeyPath : defaultPrivateKeyFile ); } } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSL::_ Public key '%s' could not be initialized.", publicCertificateFile ? publicCertificateFile : defaultPublicCertificateFile ); } } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSL::_ SSL_CTX_load_verify_locations failed\n" " authorityDir: '%s'", authorityPath ? authorityPath : defaultAuthorityPath); } } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSL::_ SSL_CTX_new failed"); } } // Destructor OsSSL::~OsSSL() { // Since error queue data structures are allocated automatically for new threads, // they must be freed when threads are terminated in order to avoid memory leaks. ERR_remove_state(0); if (mCTX) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSL::~ SSL_CTX free %p", mCTX); SSL_CTX_free(mCTX); mCTX = NULL; } } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /// Get an SSL server connection handle SSL* OsSSL::getServerConnection() { SSL* server = SSL_new(mCTX); if (server) { # if SSL_DEBUG UtlString ciphers; const char* cipher; for (int i = 0; cipher = SSL_get_cipher_list(server, i); i++) { ciphers.append("\n "); ciphers.append(cipher); } OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSL::getServerConnection returning %p%s", server, ciphers.isNull() ? " NO CIPHERS" : ciphers.data()); // SSL_set_accept_state(server); // SSL_set_options(server, SSL_OP_NO_SSLv2); # endif } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSL::getServerConnection SSL_new failed."); } return server; } /// Get an SSL client connection handle SSL* OsSSL::getClientConnection() { SSL* client = SSL_new(mCTX); if (client) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSL::getClientConnection returning %p", client); // SSL_set_connect_state(client); } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSL::getClientConnection SSL_new failed."); } return client; } /// Release an SSL connection handle void OsSSL::releaseConnection(SSL*& connection) { if (connection) { SSL_free(connection); ERR_remove_state(0); connection = NULL; } } void OsSSL::logConnectParams(const OsSysLogFacility facility, ///< callers facility const OsSysLogPriority priority, ///< log priority const char* callerMsg, ///< Identifies circumstances of connection SSL* connection ///< SSL connection to be described ) { if (connection) { char* subjectStr = NULL; char* issuerStr = NULL; UtlString* subjectAltNameURI = NULL; UtlString* subjectAltNameDNS = NULL; // Extract the subject and issuer information about the peer // and the certificate validation result. Neither of these // are meaningful without the other. // (note various dynamically allocated items - freed below) int validity = SSL_get_verify_result(connection); X509* peer_cert = SSL_get_peer_certificate(connection); if (peer_cert) { subjectStr = X509_NAME_oneline(X509_get_subject_name(peer_cert),0,0); issuerStr = X509_NAME_oneline(X509_get_issuer_name(peer_cert),0,0); // Look for the subjectAltName URI or DNS attributes GENERAL_NAMES* names; names = (GENERAL_NAMES*)X509_get_ext_d2i(peer_cert, NID_subject_alt_name, NULL, NULL); for(int i = 0; i < sk_GENERAL_NAME_num(names); i++) { GENERAL_NAME* name = sk_GENERAL_NAME_value(names, i); switch (name->type) { case GEN_DNS: { ASN1_IA5STRING* uri = name->d.uniformResourceIdentifier; subjectAltNameDNS = new UtlString((const char*)(uri->data),uri->length); } break; case GEN_URI: { ASN1_IA5STRING* uri = name->d.uniformResourceIdentifier; subjectAltNameURI = new UtlString((const char*)(uri->data),uri->length); } break; default: // don't care about any other values break; } } sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free); } // Get the name of the encryption applied to the connection const char* cipher = SSL_get_cipher(connection); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "%s SSL Connection:\n" " status: %s\n" " peer: '%s'\n" " alt URI: '%s'\n" " alt DNS: '%s'\n" " cipher: '%s'\n" " issuer: '%s'", callerMsg, validity == X509_V_OK ? "Verified" : "NOT VERIFIED", subjectStr ? subjectStr : "", subjectAltNameURI ? subjectAltNameURI->data() : "", subjectAltNameDNS ? subjectAltNameDNS->data() : "", cipher ? cipher : "", issuerStr ? issuerStr : "" ); // Release the various dynamic things if (subjectStr) { OPENSSL_free(subjectStr); } if (issuerStr) { OPENSSL_free(issuerStr); } if (subjectAltNameDNS) { delete subjectAltNameDNS; } if (subjectAltNameURI) { delete subjectAltNameURI; } if (peer_cert) { X509_free(peer_cert); } } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSL::logConnectParams called by %s with NULL connection", callerMsg ); } } /* Get the validated names for the connection peer. * * Usually, the names in the altNames will be easier to parse and use than commonName * Returns * - true if the connection peer is validated by a trusted authority * - false if not, in which case no names are returned. */ bool OsSSL::peerIdentity( SSL* connection ///< SSL connection to be described ,UtlSList* altNames /**< UtlStrings for verfied subjectAltNames * are added to this - caller must free them. */ ,UtlString* commonName ///< the Subject name is returned here ) { bool peerCertTrusted = false; # ifdef TEST_DEBUG UtlString debugMsg; # endif if (altNames) { altNames->destroyAll(); } if (commonName) { commonName->remove(0); } if (connection) { // Extract the subject and issuer information about the peer // and the certificate validation result. Neither of these // are meaningful without the other. // (note various dynamically allocated items - freed below) X509* peer_cert = SSL_get_peer_certificate(connection); if (peer_cert) { if (X509_V_OK == SSL_get_verify_result(connection)) { peerCertTrusted = true; char* subjectStr = X509_NAME_oneline(X509_get_subject_name(peer_cert),NULL,0); # ifdef TEST_DEBUG debugMsg.append("OsSSL::peerIdentity verified"); # endif if (subjectStr) { // this should always be true, I think... if (commonName) { commonName->append(subjectStr); } # ifdef TEST_DEBUG debugMsg.append(" '"); debugMsg.append(subjectStr); debugMsg.append("'"); # endif OPENSSL_free(subjectStr); } if (altNames) { // Look for the subjectAltName attributes GENERAL_NAMES* names; names = (GENERAL_NAMES*)X509_get_ext_d2i(peer_cert, NID_subject_alt_name, NULL, NULL); for(int i = 0; i < sk_GENERAL_NAME_num(names); i++) { GENERAL_NAME* name = sk_GENERAL_NAME_value(names, i); ASN1_IA5STRING* uri; switch (name->type) { case GEN_DNS: case GEN_URI: uri = name->d.uniformResourceIdentifier; altNames->append(new UtlString((const char*)(uri->data),uri->length)); # ifdef TEST_DEBUG debugMsg.append(" '"); debugMsg.append((const char*)(uri->data),uri->length); debugMsg.append("'"); # endif break; default: // don't care about any other values break; } } sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free); } # ifdef TEST_DEBUG OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "%s", debugMsg.data()); # endif } else { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSL::peerIdentity peer not validated"); } X509_free(peer_cert); } else { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSL::peerIdentity no peer certificate"); } } else { OsSysLog::add(FAC_KERNEL, PRI_CRIT, "OsSSL::peerIdentity called with NULL connection"); } return peerCertTrusted; } void OsSSL::logError(const OsSysLogFacility facility, const OsSysLogPriority priority, const char* callerMsg, int errCode) { char sslErrorString[256]; ERR_error_string_n(errCode, sslErrorString, sizeof(sslErrorString)); OsSysLog::add(facility, priority, "%s:\n SSL error: %d '%s'", callerMsg, errCode, sslErrorString ); } void OsSSL::dumpCipherList() { char humanReadableName[1024]; SSL_CIPHER *cipher = NULL; int cipherCount = 0; const char* tokenName = NULL; while(cipherCount < sk_SSL_CIPHER_num(mCTX->cipher_list)) { // Get a cipher from the context cipher = sk_SSL_CIPHER_value(mCTX->cipher_list, cipherCount); if(cipher) { // Get the cypher name SSL_CIPHER_description(cipher, humanReadableName, sizeof(humanReadableName)); // get the cypher name token tokenName = SSL_CIPHER_get_name(cipher); printf("Openssl cypher: %d %s %s\n", cipherCount, tokenName, humanReadableName); } cipherCount++; } } /********************************************************************************/ OsSSL* OsSharedSSL::get() { // critical region to ensure that only one shared ssl context is created OsLock lock(*spSslLock); if (!spSharedSSL) { spSharedSSL = new OsSSL(); } return spSharedSSL; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ OsBSem* OsSharedSSL::spSslLock = new OsBSem(OsBSem::Q_PRIORITY, OsBSem::FULL); OsSSL* OsSharedSSL::spSharedSSL = NULL; /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ int OsSSL::verifyCallback(int valid, // validity so far from openssl X509_STORE_CTX* store // certificate information db ) { X509* cert = X509_STORE_CTX_get_current_cert(store); if (valid) { // apply any additional logic we want } else { // log the details of why openssl thinks this is not valid char issuer[256]; char subject[256]; X509_NAME_oneline(X509_get_issuer_name(cert), issuer, sizeof(issuer)); X509_NAME_oneline(X509_get_subject_name(cert), subject, sizeof(subject)); OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSL::verifyCallback invalid certificate at depth %d\n" " error='%s'\n" " issuer='%s'\n" " subject='%s'", X509_STORE_CTX_get_error_depth(store), X509_verify_cert_error_string(X509_STORE_CTX_get_error(store)), issuer, subject); } return valid; } #endif // HAVE_SSL sipxtapi-3.3.0~test17/sipXportLib/src/os/OsSSLConnectionSocket.cpp0000644000175000017500000002514312205613256025734 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #if defined(HAVE_SSL) // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #include #if defined(_WIN32) # include #elif defined(_VXWORKS) # include # include # include # include #elif defined(__pingtel_on_posix__) # include # include # include # include # include #else #error Unsupported target platform. #endif // APPLICATION INCLUDES //SSL related includes #include #include #include #include #include #include "utl/UtlSListIterator.h" #include "os/OsSSL.h" #include "os/OsSSLConnectionSocket.h" #include "os/OsUtil.h" #include "os/OsSysLog.h" #include "os/OsTask.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsSSLConnectionSocket::OsSSLConnectionSocket(int connectedSocketDescriptor, long timeoutInSecs) : OsConnectionSocket(NULL, connectedSocketDescriptor), mSSL(NULL), mPeerIdentity(NOT_IDENTIFIED) { if (mIsConnected) { mbExternalSSLSocket = FALSE; SSLInitSocket(connectedSocketDescriptor, timeoutInSecs); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSLConnectionSocket::_(socket %d , timeout %ld)", connectedSocketDescriptor, timeoutInSecs ); } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSLConnectionSocket::_ underlying OsConnectionSocket not connected!!"); } } OsSSLConnectionSocket::OsSSLConnectionSocket(SSL *s, int connectedSocketDescriptor) : OsConnectionSocket(NULL, connectedSocketDescriptor), mSSL(s), mPeerIdentity(NOT_IDENTIFIED) { mbExternalSSLSocket = TRUE; socketDescriptor = connectedSocketDescriptor; OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSLConnectionSocket::_(SSL %p, socket %d)", s, connectedSocketDescriptor); } // Constructor OsSSLConnectionSocket::OsSSLConnectionSocket(int serverPort, const char* serverName, long timeoutInSecs) : OsConnectionSocket(serverPort,serverName), mSSL(NULL), mPeerIdentity(NOT_IDENTIFIED) { mbExternalSSLSocket = FALSE; if (mIsConnected) { SSLInitSocket(socketDescriptor, timeoutInSecs); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSLConnectionSocket::_(port %d, name '%s', timeout %ld)", serverPort, serverName, timeoutInSecs ); } } // Destructor OsSSLConnectionSocket::~OsSSLConnectionSocket() { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSLConnectionSocket::~" ); remoteHostName = OsUtil::NULL_OS_STRING; mAltNames.destroyAll(); close(); } /* ============================ MANIPULATORS ============================== */ UtlBoolean OsSSLConnectionSocket::reconnect() { return FALSE; //TODO } void OsSSLConnectionSocket::close() { if (mSSL) { if (mIsConnected) SSL_shutdown(mSSL); else SSL_clear(mSSL); } /* Clean up. */ OsConnectionSocket::close(); if (mSSL) { SSL_free(mSSL); ERR_remove_state(0); mSSL = NULL; } } int OsSSLConnectionSocket::write(const char* buffer, int bufferLength) { int bytesWritten = -1; bytesWritten = SSL_write (mSSL, buffer, bufferLength); return(bytesWritten); } int OsSSLConnectionSocket::write(const char* buffer, int bufferLength, long waitMilliseconds) { int bytesWritten = -1; if(isReadyToWrite(waitMilliseconds)) { bytesWritten = SSL_write (mSSL, buffer, bufferLength); } return(bytesWritten); } int OsSSLConnectionSocket::read(char* buffer, int bufferLength) { // Use base class implementation int bytesRead = -1; bytesRead = SSL_read (mSSL, buffer, bufferLength); #ifdef VALGRIND_MAKE_READABLE // If we are using Valgrind, we have to compensate for the fact that // Valgrind thinks all the output of SSL_read is undefined. // (This probably comes from SSL's use of uninitialized memory as part // of its key-generation algorithm.) VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(&bytesRead, sizeof (bytesRead))); if (bytesRead > 0) { VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(buffer, bytesRead)); } #endif /* VALGRIND_MAKE_READABLE */ return(bytesRead); } int OsSSLConnectionSocket::read(char* buffer, int bufferLength, UtlString* ipAddress, int* port) { // Overide base class version as recvfrom does not // seem to return host info correctly for TCP // Use base class version without the remote host info int bytesRead = -1; bytesRead = SSL_read (mSSL, buffer, bufferLength); #ifdef VALGRIND_MAKE_READABLE // If we are using Valgrind, we have to compensate for the fact that // Valgrind thinks all the output of SSL_read is undefined. // (This probably comes from SSL's use of uninitialized memory as part // of its key-generation algorithm.) VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(&bytesRead, sizeof (bytesRead))); if (bytesRead > 0) { VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(buffer, bytesRead)); } #endif /* VALGRIND_MAKE_READABLE */ // Explicitly get the remote host info. getRemoteHostIp(ipAddress); *port = getRemoteHostPort(); return(bytesRead); } // Because we have overided one read method, we // must implement them all in OsSSLConnectionSocket or // we end up hiding some of the methods. int OsSSLConnectionSocket::read(char* buffer, int bufferLength, long waitMilliseconds) { int bytesRead = -1; if(isReadyToRead(waitMilliseconds)) { bytesRead = SSL_read (mSSL, buffer, bufferLength); } #ifdef VALGRIND_MAKE_READABLE // If we are using Valgrind, we have to compensate for the fact that // Valgrind thinks all the output of SSL_read is undefined. // (This probably comes from SSL's use of uninitialized memory as part // of its key-generation algorithm.) VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(&bytesRead, sizeof (bytesRead))); if (bytesRead > 0) { VALGRIND_DISCARD(VALGRIND_MAKE_READABLE(buffer, bytesRead)); } #endif /* VALGRIND_MAKE_READABLE */ return(bytesRead); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ OsSocket::IpProtocolSocketType OsSSLConnectionSocket::getIpProtocol() const { return(OsSocket::SSL_SOCKET); } /// Is this connection encrypted using TLS/SSL? bool OsSSLConnectionSocket::isEncrypted() const { return true; } /// Get any authenticated peer host names. bool OsSSLConnectionSocket::peerIdentity( UtlSList* altNames ,UtlString* commonName ) const { if (NOT_IDENTIFIED == mPeerIdentity) { // examine cert to get identity and cache the results mPeerIdentity = OsSSL::peerIdentity( mSSL, &mAltNames, &mCommonName ) ? TRUSTED : UNTRUSTED; if ( TRUSTED == mPeerIdentity ) { OsSysLog::add(FAC_SIP, PRI_INFO, "OsSSLConnectionSocket::peerIdentity %p OsSSL returned trusted", this); } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "OsSSLConnectionSocket::peerIdentity %p OsSSL returned NOT trusted", this); } } /* * - true if the connection is TLS/SSL and the peer has presented * a certificate signed by a trusted certificate authority * - false if not */ if (commonName) { commonName->remove(0); } if (altNames) { altNames->destroyAll(); } if (TRUSTED == mPeerIdentity) { if (commonName) { *commonName = mCommonName; } if (altNames) { UtlString* altName; UtlSListIterator names(mAltNames); while ( (altName = dynamic_cast(names())) ) { altNames->insert(new UtlString(*altName)); } } } return TRUSTED == mPeerIdentity; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ void OsSSLConnectionSocket::SSLInitSocket(int socket, long timeoutInSecs) { if (mIsConnected) { int err = -1; // TODO: eventually this should allow for other SSL contexts... mSSL = OsSharedSSL::get()->getServerConnection(); if (mSSL && (socketDescriptor > OS_INVALID_SOCKET_DESCRIPTOR)) { SSL_set_fd (mSSL, socketDescriptor); err = SSL_connect(mSSL); if (err > 0) { OsSSL::logConnectParams(FAC_KERNEL, PRI_DEBUG, "OsSSLConnectionSocket", mSSL); } else { OsSSL::logError(FAC_KERNEL, PRI_ERR, "OsSSLConnectionSocket SSL_connect failed: ", SSL_get_error(mSSL, err)); mIsConnected = FALSE; OsConnectionSocket::close(); socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; } } else { OsSysLog::add(FAC_KERNEL, PRI_DEBUG , "OsSSLConnectionSocket bad parameters mSSL=%p,%d, closing socket..." , mSSL, (int)socketDescriptor); mIsConnected = FALSE; OsConnectionSocket::close(); socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; } } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSLConnectionSocket::SSLInitSocket called on unconnected socket" ); } } /* ============================ FUNCTIONS ================================= */ #endif // HAVE_SSL sipxtapi-3.3.0~test17/sipXportLib/src/os/OsSSLServerSocket.cpp0000644000175000017500000001377012205613305025101 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #if defined(HAVE_SSL) // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #define OsSS_CONST #if defined(_WIN32) # include #undef OsSS_CONST #define OsSS_CONST const #elif defined(_VXWORKS) # include # include # include #elif defined(__pingtel_on_posix__) # include # include # include # include # include # include #else #error Unsupported target platform. #endif // APPLICATION INCLUDES #include "os/OsSSL.h" #include "os/OsSSLServerSocket.h" #include "os/OsDefs.h" #include "os/OsSysLog.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define SOCKET_LEN_TYPE #ifdef __pingtel_on_posix__ #undef SOCKET_LEN_TYPE #define SOCKET_LEN_TYPE (socklen_t *) #endif // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsSSLServerSocket::OsSSLServerSocket(int connectionQueueSize, int serverPort) : OsServerSocket(connectionQueueSize,serverPort) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSLServerSocket::_ %p", this ); } // Destructor OsSSLServerSocket::~OsSSLServerSocket() { close(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsSSLServerSocket& OsSSLServerSocket::operator=(const OsSSLServerSocket& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } OsConnectionSocket* OsSSLServerSocket::accept() { OsSSLConnectionSocket* newSocket = NULL; if (socketDescriptor == OS_INVALID_SOCKET_DESCRIPTOR) { OsSysLog::add(FAC_KERNEL, PRI_ERR , "OsSSLServerSocket: accept exiting because socketDescriptor is %d" ,(int)socketDescriptor); } else { /* Block while waiting for a client to connect. */ struct sockaddr_in clientSocketAddr; int clientAddrLength = sizeof clientSocketAddr; int clientSocket = ::accept(socketDescriptor, (struct sockaddr*) &clientSocketAddr, SOCKET_LEN_TYPE &clientAddrLength); if (clientSocket < 0) { int error = OsSocketGetERRNO(); if (0 != error) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSLServerSocket: accept call failed with error: %d=%x", error, error); socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; } } else { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSLServerSocket::accept socket accepted: %d", clientSocket); // TODO: allow this to be a non-shared context... SSL* pSSL = OsSharedSSL::get()->getServerConnection(); if (pSSL) { SSL_set_fd (pSSL, clientSocket); newSocket = new OsSSLConnectionSocket(pSSL,clientSocket); if (newSocket) { int result = SSL_accept(pSSL); if (1 == result) { OsSSL::logConnectParams(FAC_KERNEL, PRI_DEBUG ,"OsSSLServerSocket::accept" ,pSSL); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsSSLServerSocket::accept connection %p", this ); // test and cache the peer identity newSocket->peerIdentity(NULL, NULL); } else { OsSSL::logError(FAC_KERNEL, PRI_ERR, ( result == 0 ? "OsSSLServerSocket SSL_accept - incompatible client?" : "OsSSLServerSocket SSL_accept SSL handshake error" ), SSL_get_error(pSSL, result)); // SSL failed, so clear this out. delete newSocket; newSocket = NULL; } } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsSSLServerSocket::accept - new OsSSLConnectionSocket failed" ); } } else { OsSysLog::add(FAC_KERNEL, PRI_ERR , "OsSSLConnectionSocket::accept - Error creating new SSL connection."); } } } return(newSocket); } // HZM: This override is unnecessary, the parent method already does this check. void OsSSLServerSocket::close() { if(socketDescriptor > OS_INVALID_SOCKET_DESCRIPTOR) { OsServerSocket::close(); } } /* ============================ ACCESSORS ================================= */ int OsSSLServerSocket::getLocalHostPort() const { return(localHostPort); } /* ============================ INQUIRY =================================== */ OsSocket::IpProtocolSocketType OsSSLServerSocket::getIpProtocol() const { return(OsSocket::SSL_SOCKET); } UtlBoolean OsSSLServerSocket::isOk() const { return(socketDescriptor != OS_INVALID_SOCKET_DESCRIPTOR); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ #endif // HAVE_SSL sipxtapi-3.3.0~test17/sipXportLib/src/os/OsSysLog.cpp0000644000175000017500000007011212321301427023307 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // Android log defines #define LOG_NDEBUG 0 #define LOG_TAG "sipXsyslog" // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #include #include #include #include #include #ifdef __pingtel_on_posix__ # include #endif #ifdef ANDROID # include #endif // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "os/OsSysLog.h" #include "os/OsSysLogMsg.h" #include "os/OsSysLogTask.h" #include "os/OsStatus.h" #include "os/OsServerTask.h" #include "os/OsDateTime.h" #include "os/OsSocket.h" // EXTERNAL FUNCTIONS #if defined(_VXWORKS) extern "C" char* strdup(const char* str); #else #ifndef WIN32 extern char* strdup(const char*) ; #endif #endif // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS OsAtomicLightPtr OsSysLog::spOsSysLogTask(NULL); OsAtomicULong OsSysLog::sEventCount(0L); UtlString OsSysLog::sProcessId = "" ; UtlString OsSysLog::sHostname = "" ; OsSysLogPriority OsSysLog::spPriorities[FAC_MAX_FACILITY] ; // Initial logging level is PRI_ERR. OsSysLogPriority OsSysLog::sLoggingPriority = PRI_ERR ; UtlBoolean OsSysLog::bPrioritiesInitialized = FALSE ; // A static array of priority names uses for displaying log entries const char* OsSysLog::sPriorityNames[] = { "DEBUG", "INFO", "NOTICE", "WARNING", "ERR", "CRIT", "ALERT", "EMERG" }; const int OsSysLog::sPriorityNamesNum = sizeof(OsSysLog::sPriorityNames)/sizeof(OsSysLog::sPriorityNames[0]); // LOCAL FUNCTIONS static void mysprintf(UtlString& results, const char* format, ...) ; static void myvsprintf(UtlString& results, const char* format, va_list args) ; #ifdef ANDROID static int androidPri(OsSysLogPriority pri) { switch (pri) { case PRI_DEBUG: return ANDROID_LOG_DEBUG; case PRI_INFO: case PRI_NOTICE: return ANDROID_LOG_INFO; case PRI_WARNING: return ANDROID_LOG_WARN; case PRI_ERR: return ANDROID_LOG_ERROR; case PRI_CRIT: case PRI_ALERT: case PRI_EMERG: return ANDROID_LOG_FATAL; default: return ANDROID_LOG_INFO; } } #endif /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ // Initialize the log OsStatus OsSysLog::initialize(const int maxInMemoryLogEntries, const char* processId, const int options /* = OPT_NONE */) { OsStatus rc = OS_SUCCESS ; setLoggingPriority(OsSysLog::sLoggingPriority) ; if (isTaskPtrNull()) { spOsSysLogTask = new OsSysLogTask(maxInMemoryLogEntries, options) ; if(isTaskPtrNull()) { rc = OS_FAILED; } sProcessId = processId ; OsSocket::getHostName(&sHostname) ; } else rc = OS_UNSPECIFIED ; return rc ; } // Shutdown log OsStatus OsSysLog::shutdown() { OsSysLogTask* pTask = spOsSysLogTask ; spOsSysLogTask = NULL ; if (pTask != NULL) { pTask->flush() ; pTask->requestShutdown() ; delete pTask ; } return OS_SUCCESS ; } OsTimer* OsSysLog::getTimer() { OsSysLogTask *pOsSysLogTask = spOsSysLogTask; return pOsSysLogTask->getTimer(); } // Set the output file target OsStatus OsSysLog::setOutputFile(const int minFlushPeriod, const char* logfile) { OsStatus rc = OS_SUCCESS ; OsSysLogTask *pOsSysLogTask = spOsSysLogTask; if (pOsSysLogTask != NULL) { OsSysLogMsg msgFlush(OsSysLogMsg::SET_FLUSH_PERIOD, (void*) minFlushPeriod) ; pOsSysLogTask->postMessage(msgFlush) ; if (logfile) { OsSysLogMsg msgSetFile(OsSysLogMsg::SET_FILE, strdup(logfile)) ; pOsSysLogTask->postMessage(msgSetFile) ; } else { OsSysLogMsg msgSetFile(OsSysLogMsg::SET_FILE, NULL) ; pOsSysLogTask->postMessage(msgSetFile) ; } } else rc = OS_UNSPECIFIED ; return rc ; } OsStatus OsSysLog::setCallbackFunction(OsSysLogCallback pCallback) { OsStatus rc = OS_SUCCESS ; OsSysLogTask *pOsSysLogTask = spOsSysLogTask; if (pOsSysLogTask != NULL) { OsSysLogMsg msgSetCallback(OsSysLogMsg::SET_CALLBACK, (void*) pCallback); pOsSysLogTask->postMessage(msgSetCallback); } else { rc = OS_UNSPECIFIED; } return rc; } // Add a target output socket OsStatus OsSysLog::addOutputSocket(const char* remoteHost) { OsStatus rc = OS_SUCCESS ; OsSysLogTask *pOsSysLogTask = spOsSysLogTask; if (pOsSysLogTask != NULL) { OsSysLogMsg msg(OsSysLogMsg::ADD_SOCKET, (void*) strdup(remoteHost)) ; pOsSysLogTask->postMessage(msg) ; } else rc = OS_UNSPECIFIED ; return rc ; } // Enable/disable console output OsStatus OsSysLog::enableConsoleOutput(const UtlBoolean enable) { OsStatus rc = OS_SUCCESS ; OsSysLogTask *pOsSysLogTask = spOsSysLogTask; if (pOsSysLogTask != NULL) { OsSysLogMsg msg(enable ? OsSysLogMsg::ENABLE_CONSOLE : OsSysLogMsg::DISABLE_CONSOLE, NULL) ; pOsSysLogTask->postMessage(msg) ; } else rc = OS_UNSPECIFIED ; return rc ; } // Set the logging priority for all facilities OsStatus OsSysLog::setLoggingPriority(const OsSysLogPriority priority) { OsStatus rc = OS_SUCCESS ; int iNumFacilities = getNumFacilities() ; for (int i=0; isyslog(FAC_LOG, PRI_INFO, "logging priority changed to %s (%d)", OsSysLog::sPriorityNames[priority], priority) ; } return rc ; } // Set the logging priority for a specific facility OsStatus OsSysLog::setLoggingPriorityForFacility(const OsSysLogFacility facility, const OsSysLogPriority priority) { OsStatus rc = OS_SUCCESS ; int iNumFacilities = getNumFacilities() ; if ((facility >= 0) && (facility < iNumFacilities)) { spPriorities[facility] = priority ; OsSysLogTask *pOsSysLogTask = spOsSysLogTask; if (pOsSysLogTask != NULL) { pOsSysLogTask->syslog(FAC_LOG, PRI_INFO, "priority changed to %s for facility %s", OsSysLog::sPriorityNames[priority], OsSysLog::sFacilityNames[facility]); } } else { rc = OS_INVALID_ARGUMENT ; } return rc ; } // Add a log entry OsStatus OsSysLog::add(const char* taskName, const int taskId, const OsSysLogFacility facility, const OsSysLogPriority priority, const char* format, ...) { OsStatus rc = OS_UNSPECIFIED; // If the log has not been initialized, print everything if (isTaskPtrNull()) { // Convert the variable arguments into a single string UtlString data ; va_list ap; va_start(ap, format); myvsprintf(data, format, ap) ; data = escape(data) ; va_end(ap); // Display all of the data osPrintf("%s %s %s 0x%08X %s\n", OsSysLog::sFacilityNames[facility], OsSysLog::sPriorityNames[priority], (taskName == NULL) ? "" : taskName, taskId, data.data()) ; rc = OS_SUCCESS ; } // Otherwise make sure we want to handle the log entry before we process // the variable arguments. else { if (willLog(facility, priority)) { va_list ap; va_start(ap, format); rc = vadd(taskName, taskId, facility, priority, format, ap); va_end(ap); } } return rc; } void OsSysLog::getTaskInfo(UtlString& taskName, OsTaskId_t& taskId) { OsTaskBase* pBase = OsTask::getCurrentTask() ; if (pBase != NULL) { taskName = pBase->getName() ; pBase->id(taskId) ; } else { // TODO: should get abstracted into a OsTaskBase method #ifdef __pingtel_on_posix__ OsTaskLinux::getCurrentTaskId(taskId); #endif taskName = "Anon"; // OsTask::getIdString_d(taskName, taskId); } } // Add a log entry OsStatus OsSysLog::add(const OsSysLogFacility facility, const OsSysLogPriority priority, const char* format, ...) { OsStatus rc = OS_UNSPECIFIED; // If the log has not been initialized, print everything if (!isTaskPtrNull()) { if (willLog(facility, priority)) { UtlString taskName ; OsTaskId_t taskId = 0 ; va_list ap; va_start(ap, format); getTaskInfo(taskName, taskId); rc = vadd(taskName.data(), taskId, facility, priority, format, ap); va_end(ap); } } else rc = OS_SUCCESS ; return rc; } // Add a log entry given a variable argument list OsStatus OsSysLog::vadd(const OsSysLogFacility facility, const OsSysLogPriority priority, const char* format, va_list ap) { UtlString taskName; OsTaskId_t taskId = 0; getTaskInfo(taskName, taskId); return(vadd(taskName, taskId, facility, priority, format, ap)); } // Add a log entry given a variable argument list OsStatus OsSysLog::vadd(const char* taskName, const OsTaskId_t taskId, const OsSysLogFacility facility, const OsSysLogPriority priority, const char* format, va_list ap) { // If the log has not been initialized, print everything to the console if (!isTaskPtrNull()) { if (willLog(facility, priority)) { UtlString logData; UtlString logEntry; myvsprintf(logData, format, ap) ; logData = escape(logData) ; #ifdef ANDROID __android_log_print(androidPri(priority), "sipXsyslog", "[%s] %s", OsSysLog::sFacilityNames[facility], logData.data()); #endif OsTime timeNow; OsDateTime::getCurTime(timeNow); OsDateTime logTime(timeNow); UtlString strTime ; logTime.getIsoTimeStringZus(strTime) ; UtlString taskHex; // TODO: Should get abstracted into a OsTaskBase method #ifdef __pingtel_on_posix__ OsTaskLinux::getIdString_X(taskHex, taskId); #endif mysprintf(logEntry, "\"%s\":%d:%s:%s:%s:%s:%s:%s:\"%s\"", strTime.data(), ++sEventCount, OsSysLog::sFacilityNames[facility], OsSysLog::sPriorityNames[priority], sHostname.data(), (taskName == NULL) ? "" : taskName, taskHex.data(), sProcessId.data(), logData.data()) ; // If the logger for some reason trys to log a message // there is a recursive problem. Drop the message on the // floor for now. This can occur if one of the os utilities // logs a message. if(strcmp("syslog", taskName) == 0) { // Just discard the log entry // // (rschaaf): // NOTE: Don't try to use osPrintf() to emit the log entry since this // can cause consternation for applications (e.g. CGIs) that expect to // use stdout for further processing. } else { char* szPtr = strdup(logEntry.data()) ; OsSysLogMsg msg(OsSysLogMsg::LOG, szPtr) ; OsTime timeout(1000) ; OsSysLogTask *pOsSysLogTask = spOsSysLogTask; if ( pOsSysLogTask != NULL && pOsSysLogTask->postMessage(msg, timeout) != OS_SUCCESS) { printf("OsSysLog jammed: %s\n", szPtr) ; free(szPtr) ; OsTask::yield() ; } } } } return OS_SUCCESS ; } // Clear the in memory log buffer OsStatus OsSysLog::clearInMemoryLog() { OsStatus rc = OS_SUCCESS ; OsSysLogTask *pOsSysLogTask = spOsSysLogTask; if (pOsSysLogTask != NULL) { pOsSysLogTask->clear() ; } else rc = OS_UNSPECIFIED ; return rc ; } // Flushes the in-memory circular buffer log to disk or an unbounded log file. OsStatus OsSysLog::flush(const OsTime& rTimeout) { OsStatus rc = OS_UNSPECIFIED ; OsSysLogTask *pOsSysLogTask = spOsSysLogTask; if (pOsSysLogTask != NULL) { rc = pOsSysLogTask->flush(rTimeout) ; } return rc ; } // Initialize the OsSysLog priority void OsSysLog::initSysLog(const OsSysLogFacility facility, const char* processID, const char* logname, const char* loglevel) { initialize(0, processID) ; setOutputFile(0, logname) ; UtlString logLevel(loglevel); struct tagPrioriotyLookupTable { const char* pIdentity; OsSysLogPriority ePriority; }; struct tagPrioriotyLookupTable lkupTable[] = { { "DEBUG", PRI_DEBUG}, { "INFO", PRI_INFO}, { "NOTICE", PRI_NOTICE}, { "WARNING", PRI_WARNING}, { "ERR", PRI_ERR}, { "CRIT", PRI_CRIT}, { "ALERT", PRI_ALERT}, { "EMERG", PRI_EMERG} }; logLevel.toUpper(); OsSysLogPriority priority = PRI_ERR; int iEntries = sizeof(lkupTable)/sizeof(struct tagPrioriotyLookupTable); for (int i=0; igetMaxEntries(maxEntries); } else rc = OS_UNSPECIFIED ; return rc ; } // Display the last numEntries log entries to the console OsStatus OsSysLog::tailMemoryLog(const int numEntries) { OsStatus rc = OS_SUCCESS ; OsSysLogTask *pOsSysLogTask = spOsSysLogTask; if (pOsSysLogTask != NULL) { OsSysLogMsg msg(OsSysLogMsg::TAIL, (void*) numEntries) ; pOsSysLogTask->postMessage(msg) ; } else rc = OS_UNSPECIFIED ; return rc ; } // Display the first numEntries log entries to the console OsStatus OsSysLog::headMemoryLog(const int numEntries) { OsStatus rc = OS_SUCCESS ; OsSysLogTask *pOsSysLogTask = spOsSysLogTask; if (pOsSysLogTask != NULL) { OsSysLogMsg msg(OsSysLogMsg::HEAD, (void*) numEntries) ; pOsSysLogTask->postMessage(msg) ; } else rc = OS_UNSPECIFIED ; return rc ; } // Get at most maxEntries log entries OsStatus OsSysLog::getLogEntries( const int maxEntries, char* entries[], int& actualEntries) { OsStatus rc = OS_SUCCESS ; OsSysLogTask *pOsSysLogTask = spOsSysLogTask; if (pOsSysLogTask != NULL) { pOsSysLogTask->getLogEntries(maxEntries, entries, actualEntries); } else rc = OS_UNSPECIFIED ; return rc ; } //:Parses a log string into its parts. OsStatus OsSysLog::parseLogString(const char *szSource, UtlString& date, UtlString& eventCount, UtlString& facility, UtlString& priority, UtlString& hostname, UtlString& taskname, UtlString& taskId, UtlString& processId, UtlString& content) { #define PS_DATE 0 #define PS_EVENTCOUNT 1 #define PS_FACILITY 2 #define PS_PRIORITY 3 #define PS_HOSTNAME 4 #define PS_TASKNAME 5 #define PS_TASKID 6 #define PS_PROCESSID 7 #define PS_CONTENT 8 const char* pTraverse = szSource ; // Traverses the source string UtlBoolean bWithinQuote = FALSE; // Are we within a quoted string? UtlBoolean bEscapeNext = FALSE; // The next char is an escape char. int iParseState ; // What are we parsing (PS_*) // Clean all of the passed objects date.remove(0) ; eventCount.remove(0) ; facility.remove(0) ; priority.remove(0) ; hostname.remove(0) ; taskname.remove(0) ; processId.remove(0) ; content.remove(0) ; // Loop through the source string and add characters to the appropriate // data object iParseState = PS_DATE ; while (*pTraverse) { switch (*pTraverse) { case ':': if (!bWithinQuote) { iParseState++ ; pTraverse++ ; continue ; } break ; case '"': if (!bEscapeNext) { bWithinQuote = !bWithinQuote; pTraverse++ ; continue ; } break ; case '\\': bEscapeNext = true ; break ; } switch (iParseState) { case PS_DATE: date.append(*pTraverse) ; break ; case PS_EVENTCOUNT: eventCount.append(*pTraverse) ; break ; case PS_FACILITY: facility.append(*pTraverse) ; break ; case PS_PRIORITY: priority.append(*pTraverse) ; break ; case PS_HOSTNAME: hostname.append(*pTraverse) ; break ; case PS_TASKNAME: taskname.append(*pTraverse) ; break ; case PS_TASKID: taskId.append(*pTraverse) ; break ; case PS_PROCESSID: processId.append(*pTraverse) ; break ; case PS_CONTENT: content.append(*pTraverse) ; break ; } pTraverse++ ; } content = unescape(content) ; return OS_SUCCESS ; } OsStatus OsSysLog::getPriorityName(OsSysLogPriority priorityId, UtlString& name) { OsStatus status = OS_NOT_FOUND; if(priorityId >= 0 && priorityId < sPriorityNamesNum) { name = sPriorityNames[priorityId]; status = OS_SUCCESS; } return(status); } OsStatus OsSysLog::getPriorityForName(const UtlString& name, OsSysLogPriority& priorityId) { OsStatus status = OS_NOT_FOUND; priorityId = (OsSysLogPriority) sPriorityNamesNum; for(int nameIndex = 0; nameIndex < sPriorityNamesNum; nameIndex++) { if(name.compareTo(sPriorityNames[nameIndex]) == 0) { priorityId = (OsSysLogPriority) nameIndex; status = OS_SUCCESS; break; } } return(status); } /* ============================ INQUIRY =================================== */ // Get the present logging priority OsSysLogPriority OsSysLog::getLoggingPriority() { return sLoggingPriority ; } // Get the logging priority for a specific facility OsSysLogPriority OsSysLog::getLoggingPriorityForFacility(const OsSysLogFacility facility) { OsSysLogPriority rc = PRI_DEBUG ; if ((facility >=0) && (facility < getNumFacilities())) { rc = spPriorities[facility] ; } return rc ; } // Determine if a message will be logged given a facility and priority UtlBoolean OsSysLog::willLog(OsSysLogFacility facility, OsSysLogPriority priority) { UtlBoolean bwillLog = false ; if ((facility >=0) && (facility < getNumFacilities())) { initializePriorities(); bwillLog = (spPriorities[facility] <= priority) ; } return bwillLog ; } void OsSysLog::initializePriorities() { if (bPrioritiesInitialized == FALSE) { setLoggingPriority(PRI_ERR); } } // Return the max number of facilities int OsSysLog::getNumFacilities() { return (FAC_MAX_FACILITY) ; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ // Assignment operator OsSysLog& OsSysLog::operator=(const OsSysLog& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } // Constructor OsSysLog::OsSysLog() { } // Copy constructor OsSysLog::OsSysLog(const OsSysLog& rOsSysLog) { } // Destructor OsSysLog::~OsSysLog() { } // Returns an escaped version of the specified source string UtlString OsSysLog::escape(const UtlString& source) { UtlString results ; const char* pStart = source.data() ; const char* pTraverse = pStart ; const char* pLast = pStart ; while (*pTraverse) { switch (*pTraverse) { case '\\': // Copy old data if (pLast < pTraverse) { results.append(pLast, pTraverse-pLast); } pLast = pTraverse + 1 ; // Add escaped Text results.append("\\\\") ; break ; case '\r': // Copy old data if (pLast < pTraverse) { results.append(pLast, pTraverse-pLast); } pLast = pTraverse + 1 ; // Add escaped Text results.append("\\r") ; break ; case '\n': // Copy old data if (pLast < pTraverse) { results.append(pLast, pTraverse-pLast); } pLast = pTraverse + 1 ; // Add escaped Text results.append("\\n") ; break ; case '\"': // Copy old data if (pLast < pTraverse) { results.append(pLast, pTraverse-pLast); } pLast = pTraverse + 1 ; // Add escaped Text results.append("\\\"") ; break ; default: break ; } pTraverse++ ; } // if nothing to escape, short-circuit if (pLast == pStart) { return source ; } else if (pLast < pTraverse) { results.append(pLast, pTraverse-pLast); } return results ; } // Unescapes previously escaped Quotes and CrLfs UtlString OsSysLog::unescape(const UtlString& source) { UtlString results ; const char* pStart = source.data() ; const char* pTraverse = pStart ; const char* pLast = pStart ; UtlBoolean bLastWasEscapeChar = false; while (*pTraverse) { if (bLastWasEscapeChar) { switch (*pTraverse) { case '\\': case '"': if (pLast < pTraverse) { results.append(pLast, pTraverse-pLast-1); } pLast = pTraverse + 1 ; results.append(*pTraverse) ; break ; case 'r': if (pLast < pTraverse) { results.append(pLast, pTraverse-pLast-1); } pLast = pTraverse + 1 ; results.append("\r") ; break ; case 'n': if (pLast < pTraverse) { results.append(pLast, pTraverse-pLast-1); } pLast = pTraverse + 1 ; results.append("\n") ; break; default: // Invalid/Illegal Escape Character break ; } bLastWasEscapeChar = false ; } else { if (*pTraverse == '\\') { bLastWasEscapeChar = true ; } } pTraverse++ ; } // if nothing to escape, short-circuit if (pLast == pStart) { return source ; } else if (pLast < pTraverse) { results.append(pLast, (pTraverse-1)-pLast); } return results ; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ // a version of sprintf that stores results into an UtlString void mysprintf(UtlString& results, const char* format, ...) { va_list args; va_start(args, format); myvsprintf(results, format, args) ; va_end(args); } // a version of vsprintf that stores results in an UtlString void myvsprintf(UtlString& results, const char* format, va_list args) { /* Guess we need no more than 384 bytes. */ int n, size = 384; char *p; results.remove(0) ; p = (char*) malloc(size) ; while (p != NULL) { va_list args_copy; /* Argument list must be copied, because we call vsnprintf in a loop * and first call will invalidate list, so on second iteration it * will contain junk. (this is not a problem for i386, but appears * as such on e.g. x86_64) */ va_copy(args_copy, args); /* Try to print in the allocated space. */ n = vsnprintf (p, size, format, args_copy); va_end(args_copy); /* If that worked, return the string. */ if (n > -1 && n < size) { break; } /* Else try again with more space. */ if (n > -1) /* glibc 2.1 */ size = n+1; /* precisely what is needed */ else /* glibc 2.0 */ size *= 2; /* twice the old size */ if ((p = (char*) realloc (p, size)) == NULL) { break; } } if (p != NULL) { results.append(p) ; free(p) ; } } OsStackTraceLogger::OsStackTraceLogger(const OsSysLogFacility facility, const OsSysLogPriority priority, const char* methodName) : mMethodName(methodName), mFacility(facility), mPriority(priority) { OsTaskId_t tid; UtlString taskHex("ENTER FUNC (tid="); OsTask::getCurrentTaskId(tid); //TODO: should get abstracted into a OsTaskBase method #ifdef __pingtel_on_posix__ OsTaskLinux::getIdString_X(taskHex, tid); #endif OsSysLog::add(mFacility, mPriority, "%s) %s\n", taskHex.data(), methodName); } OsStackTraceLogger::~OsStackTraceLogger() { OsTaskId_t tid; UtlString taskHex("EXIT FUNC (tid="); OsTask::getCurrentTaskId(tid); // TODO: should get abstracted into a OsTaskBase method #ifdef __pingtel_on_posix__ OsTaskLinux::getIdString_X(taskHex, tid); #endif OsSysLog::add(mFacility, mPriority, "%s) %s\n", taskHex.data(), mMethodName.data()); } OsStackTraceLogger::OsStackTraceLogger(const OsSysLogFacility facility, const OsSysLogPriority priority, const char* methodName, const OsStackTraceLogger& oneBackInStack) : mMethodName(methodName), mFacility(facility), mPriority(priority) { OsTaskId_t tid; UtlString taskHex("ENTER FUNC (tid="); mMethodName = UtlString(oneBackInStack.mMethodName) + UtlString("->") + mMethodName; OsTask::getCurrentTaskId(tid); // TODO: should get abstracted into an OsTaskBase method #ifdef __pingtel_on_posix__ OsTaskLinux::getIdString_X(taskHex, tid); #endif OsSysLog::add(mFacility, mPriority, "%s) %s\n", taskHex.data(), mMethodName.data()); } sipxtapi-3.3.0~test17/sipXportLib/src/os/OsSysLogFacilities.cpp0000644000175000017500000000417612205613256025322 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #include #include #include // APPLICATION INCLUDES #include "os/OsSysLogFacilities.h" #include "os/OsSysLog.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // sFacilityName provides string based representations of the various // facilities within the system. Indexed by enum tagOsSysLogFacility values. const char* OsSysLog::sFacilityNames[] = { "PERF", "KERNEL", "AUTH", "NET", "RTP", "PHONESET", "HTTP", "SIP", "CP", "MP", "TAO", "JNI", "JAVA", "LOG", "WATCHDOG", "OUTGOING", "INCOMING", "INCOMING_PARSED", "MEDIASERVER_CGI", "MEDIASERVER_VXI", "ACD", "PARK", "APACHE_AUTH", "UPGRADE", "LINE_MGR", "REFRESH_MGR", "PROCESSCGI", "STREAMING", "REPLICATION_CGI", "SIPDB", "PROCESSMGR", "PROCESS", "SIPXTAPI", "AUDIO", "CONFERENCE", "ODBC", "CDR", "RLS", "VOICEENGINE", "VIDEOENGINE", "APP", "SIP_CUSTOM", "SDP", "UNKNOWN" } ; const int OsSysLog::sFacilityNamesNum = sizeof(OsSysLog::sFacilityNames)/sizeof(OsSysLog::sFacilityNames[0]); /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsSysLogMsg.cpp0000644000175000017500000000375412205613256023775 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsSysLogMsg.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsSysLogMsg::OsSysLogMsg(const unsigned char msgSubType, const void* pData) : OsMsg(OS_SYSLOG, msgSubType) { mpData = pData ; // all of the required work is done by the initializers } // Copy constructor OsSysLogMsg::OsSysLogMsg(const OsSysLogMsg& rOsSysLogMsg) : OsMsg(rOsSysLogMsg) { mpData = rOsSysLogMsg.mpData ; } // Create a copy of this msg object (which may be of a derived type) OsMsg* OsSysLogMsg::createCopy(void) const { return new OsSysLogMsg(*this); } // Destructor OsSysLogMsg::~OsSysLogMsg() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsSysLogMsg& OsSysLogMsg::operator=(const OsSysLogMsg& rhs) { if (this == &rhs) // handle the assignment to self case return *this; OsMsg::operator=(rhs); mpData = rhs.mpData ; return *this; } /* ============================ ACCESSORS ================================= */ // Get the message data const void* OsSysLogMsg::getData() const { return mpData; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsSysLogTask.cpp0000644000175000017500000005246112205613256024150 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #include #include #include #include #include #ifdef __pingtel_on_posix__ #include #include #endif // APPLICATION INCLUDES #include "os/OsSysLogTask.h" #include "os/OsSysLogMsg.h" #include "os/OsStatus.h" #include "os/OsServerTask.h" #include "os/OsDateTime.h" #include "os/OsTimer.h" #include "os/OsQueuedEvent.h" #include "os/OsEventMsg.h" #include "os/OsConnectionSocket.h" #include "os/OsFS.h" #include "os/OsEvent.h" // EXTERNAL FUNCTIONS #if defined(_VXWORKS) extern "C" char* strdup(const char* str); #else #ifndef WIN32 extern char* strdup(const char*) ; #endif #endif // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // LOCAL FUNCTIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsSysLogTask::OsSysLogTask(const int maxInMemoryLogEntries /* = 0 */, const int options /* = OsSysLog:OPT_NONE */) : OsServerTask("syslog", NULL, 1000, 250) , mConsoleEnabled(FALSE) , mpRingBuffer(NULL) , mLogCount(0) , mRingBufferNext(0) , mpUnboundedLog(NULL) , mFlushPeriod(0) , mLogChanged(FALSE) , mpTimer(NULL) , mpCallback(NULL) , mRWMutex(OsRWMutex::Q_PRIORITY) , mpLastReopen() { // Init Ring Buffer mRingBufferLength = maxInMemoryLogEntries; if (mRingBufferLength > 0) { mpRingBuffer = new char*[mRingBufferLength]; for (int i=0; iwait(rTimeout); if ( rc == OS_SUCCESS || pFlushSync->signal(0) == OS_ALREADY_SIGNALED) { delete pFlushSync; } return rc; } /* ============================ ACCESSORS ================================= */ // Get the max number of log entries OsStatus OsSysLogTask::getMaxEntries(int& maxEntries) { mRWMutex.acquireRead() ; maxEntries = mRingBufferLength ; mRWMutex.releaseRead() ; return OS_SUCCESS ; } // Get a log entried OsStatus OsSysLogTask::getLogEntries( const int maxEntries, char* entries[], int& actualEntries) { mRWMutex.acquireRead() ; OsStatus status = OS_SUCCESS ; int iIndex ; actualEntries = maxEntries ; // Make sure the requested length is sane if (actualEntries > mLogCount) actualEntries = mLogCount; if (actualEntries > mRingBufferLength) actualEntries = mRingBufferLength; if (actualEntries < 0) actualEntries = 0 ; // Traverse ring buffer and copy entries for (int i=0; igetMsgSubType()) { case OsSysLogMsg::LOG: data = (char*) pSysLogMsg->getData(); processAdd(data); mLogCount++; break ; case OsSysLogMsg::ENABLE_CONSOLE: processConsoleEnable(TRUE); break ; case OsSysLogMsg::DISABLE_CONSOLE: processConsoleEnable(FALSE); break ; case OsSysLogMsg::HEAD: processHeadCommand((intptr_t) pSysLogMsg->getData()); break ; case OsSysLogMsg::TAIL: processTailCommand((intptr_t) pSysLogMsg->getData()); break ; case OsSysLogMsg::ADD_SOCKET: data = (char*) pSysLogMsg->getData(); if (data != NULL) { processAddSocket(data) ; free(data) ; } break ; case OsSysLogMsg::SET_FILE: data = (char*) pSysLogMsg->getData(); processSetFile(data) ; if (data != NULL) { free(data) ; } break ; case OsSysLogMsg::SET_CALLBACK: processSetCallback((OsSysLogCallback) pSysLogMsg->getData()); break ; case OsSysLogMsg::SET_FLUSH_PERIOD: processSetFlushPeriod((intptr_t) pSysLogMsg->getData()) ; break ; case OsSysLogMsg::FLUSH_LOG: processFlushLog((OsEvent*) pSysLogMsg->getData()); break ; default: break ; } bRC = TRUE ; break ; default: bRC = OsServerTask::handleMessage(eventMessage); break ; } return bRC ; } // Handles adding a log entry to the tail of the list OsStatus OsSysLogTask::processAddTail(char* pEntry) { mRWMutex.acquireWrite() ; OsStatus status = OS_SUCCESS ; // Add to Circular Buffer if ((mpRingBuffer != NULL) && (mLogCount < mRingBufferLength)) { int iIndex = (mRingBufferNext - (mLogCount + 1)) ; while (iIndex < 0) iIndex += mRingBufferLength ; iIndex %= mRingBufferLength ; if (mpRingBuffer[iIndex] != NULL) { free(mpRingBuffer[iIndex]) ; } mpRingBuffer[iIndex] = pEntry ; mLogCount++ ; } else status = OS_LIMIT_REACHED ; mRWMutex.releaseWrite() ; return status ; } // Process a log addition OsStatus OsSysLogTask::processAdd(char* pEntry) { OsStatus status = OS_SUCCESS ; mRWMutex.acquireWrite() ; /* * Display to the console if enabled */ if (mConsoleEnabled) { osPrintf("%s\n", pEntry) ; } /* * If we have a ring buffer initialized, add to it. */ if (mpRingBuffer != NULL) { if (mpRingBuffer[mRingBufferNext] != NULL) { free(mpRingBuffer[mRingBufferNext]) ; } mpRingBuffer[mRingBufferNext] = pEntry ; mRingBufferNext = (mRingBufferNext + 1) % mRingBufferLength ; } if (mOptions & OsSysLog::OPT_SHARED_LOGFILE) { if (mUnboundedLogFile.length()) { if ((mpUnboundedLog = fopen(mUnboundedLogFile.data(), "a+")) == NULL) { syslog(FAC_LOG, PRI_ERR, "Error reopening logfile %s", mUnboundedLogFile.data()); } #ifdef __pingtel_on_posix__ else { int fd = fileno(mpUnboundedLog); fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC); } #endif // Keep track of the last reopen OsDateTime::getCurTimeSinceBoot(mpLastReopen) ; } if (mpUnboundedLog) { fprintf(mpUnboundedLog, "%s\n", pEntry) ; fclose(mpUnboundedLog); mpUnboundedLog = NULL ; } } else { /* * If an unbounded log is initialized, add to it */ if (mpUnboundedLog) { // Decide if we should close/reopen the log OsTime now ; OsTime reopenAfter ; OsDateTime::getCurTimeSinceBoot(now) ; reopenAfter = mpLastReopen + OsTime(MAX_REOPEN_LOG_DELAY_SEC, 0) ; if (now > reopenAfter) { // Close Log fclose(mpUnboundedLog) ; mpUnboundedLog = NULL ; // Reopen Log if ((mpUnboundedLog = fopen(mUnboundedLogFile.data(), "a+")) == NULL) { syslog(FAC_LOG, PRI_ERR, "Error reopening logfile %s", mUnboundedLogFile.data()); } #ifdef __pingtel_on_posix__ else { int fd = fileno(mpUnboundedLog); fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC); } #endif // Keep track of the last reopen OsDateTime::getCurTimeSinceBoot(mpLastReopen) ; } if (mpUnboundedLog) { fprintf(mpUnboundedLog, "%s\n", pEntry) ; fflush(mpUnboundedLog); } } } /* * If we have been initialized with target sockets- fire off events to * interested parties. */ for (int i=0; iwrite(pEntry, strlen(pEntry), 0) <= 0) { UtlString hostName; mpSockets[i]->getRemoteHostName(&hostName); syslog(FAC_LOG, PRI_ERR, "unable to write to socket, closing: %s", hostName.data()); delete mpSockets[i] ; mpSockets[i] = NULL ; } else mpSockets[i]->write("\n", 1, 0) ; } } /* * If a callback funtion was registered, call and hand over the log entry */ if ( mpCallback != NULL ) { UtlString date; UtlString eventCount; UtlString facility; UtlString priority; UtlString hostname; UtlString taskname; UtlString taskId; UtlString processId; UtlString content; // Parse the log entry to extract the priority OsSysLog::parseLogString(pEntry, date, eventCount, facility, priority, hostname, taskname, taskId, processId, content); mpCallback(priority, "SIPxua", pEntry); } /* * Clean up the entry of no ring buffer was installed. Otherwise, the * ring buffer is responsible for clean up. */ if (!mpRingBuffer) free(pEntry); // Mark the log as changed mLogChanged = true ; mRWMutex.releaseWrite() ; return status ; } // Process a console enable/disable command OsStatus OsSysLogTask::processConsoleEnable(const UtlBoolean enable) { mRWMutex.acquireRead() ; OsStatus status = OS_SUCCESS ; mConsoleEnabled = enable ; syslog(FAC_LOG, PRI_INFO, "console logging enabled: %s", enable ? "true" : "false") ; mRWMutex.releaseRead() ; return status ; } // Process a head command (displays start of in-memory log) OsStatus OsSysLogTask::processHeadCommand(const int iEntries) { mRWMutex.acquireRead() ; OsStatus status = OS_SUCCESS ; int iIndex ; int iCount = iEntries ; // Make sure the requested length is sane if (iCount > mLogCount) iCount = mLogCount; if (iCount > mRingBufferLength) iCount = mRingBufferLength; if (iCount <= 0) iCount = 16 ; // Traverse ring buffer and display entries for (int i=0; i mLogCount) iCount = mLogCount; if (iCount > mRingBufferLength) iCount = mRingBufferLength; if (iCount <= 0) iCount = 16 ; // Traverse ring buffer and display entries for (int i=0; i"); // Clean up if a log files if already in use if (mpUnboundedLog != NULL) { syslog(FAC_LOG, PRI_INFO, "Closing unbounded logfile %s", mUnboundedLogFile.data()); fclose(mpUnboundedLog) ; mUnboundedLogFile.remove(0) ; } mBoundedLogFile.remove(0) ; if (szFile) { // If the flush period is 0, open a unbounded log, otherwise, bounded log // files are opened/closed on flushes. if (mFlushPeriod == 0) { // Open the log file, if not asked to use a shared logfile. if (!(mOptions & OsSysLog::OPT_SHARED_LOGFILE)) { // Open a unbounded Log if ((mpUnboundedLog = fopen(szFile, "a+")) == NULL) { syslog(FAC_LOG, PRI_ERR, "Error opening logfile %s", szFile); } else { #ifdef __pingtel_on_posix__ int fd = fileno(mpUnboundedLog); fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC); #endif } } mUnboundedLogFile = szFile ; OsDateTime::getCurTimeSinceBoot(mpLastReopen) ; mRWMutex.releaseWrite() ; } else { mBoundedLogFile = szFile ; mRWMutex.releaseWrite() ; // Populate OsFile file(mBoundedLogFile.data()) ; if (file.open(OsFile::READ_ONLY) == OS_SUCCESS) { UtlString line ; while (file.readLine(line) == OS_SUCCESS) { if (processAddTail(strdup(line.data())) != OS_SUCCESS) break ; } } file.close() ; } } else { mRWMutex.releaseWrite(); } return status; } // Process the setting of a flush period. This should be performed // before processSetFile. OsStatus OsSysLogTask::processSetFlushPeriod(const int iSeconds) { mRWMutex.acquireWrite() ; OsStatus status = OS_SUCCESS ; mFlushPeriod = iSeconds ; syslog(FAC_LOG, PRI_INFO, "file flush period set to %d", iSeconds) ; if (iSeconds > 0) { // Enable a new timer / reschedule existing timer if (mpTimer == NULL) { mpTimer = new OsTimer(getMessageQueue(), 0) ; } else mpTimer->stop() ; // Set time mpTimer->periodicEvery(OsTime(), OsTime(iSeconds, 0)) ; } else { // Disable the timer if scheduled. if (mpTimer != NULL) { mpTimer->stop() ; delete mpTimer ; mpTimer = NULL ; } } mRWMutex.releaseWrite() ; return status; } // Process the addition of an output socket OsStatus OsSysLogTask::processAddSocket(const char* remoteHost) { mRWMutex.acquireWrite() ; OsStatus status = OS_SUCCESS; UtlBoolean bFoundSpace = FALSE; char* host = strdup(remoteHost); int port = PORT_NONE; // Parse remoteHost into a host and port char* portStart = strrchr(host, (int) ':'); if ((portStart != NULL) && (strlen(portStart) > 1)) { port = atoi((char*) &portStart[1]); *portStart = 0; } else { syslog(FAC_LOG, PRI_ERR, "output socket missing port %s", host) ; status = OS_INVALID_ARGUMENT ; } // If we parsed correctly, go ahead and construct the socket if (status == OS_SUCCESS) { for (int i=0; i mRingBufferLength) iCount = mRingBufferLength; // Traverse ring buffer and output entries for (int i=0; isignal(0); if (rc == OS_ALREADY_SIGNALED) { delete pEvent; } } return status; } OsStatus OsSysLogTask::processSetCallback(OsSysLogCallback fn) { OsStatus status = OS_SUCCESS; mRWMutex.acquireWrite() ; mpCallback = fn; mRWMutex.releaseWrite() ; return status; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsTask.cpp0000644000175000017500000001615412205617431023005 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #ifdef __pingtel_on_posix__ # include #endif #include #include // APPLICATION INCLUDES #include "os/OsExcept.h" #include "os/OsLock.h" #include "os/OsTask.h" #include "os/OsUtil.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS const int OsTaskBase::DEF_OPTIONS = 0; // default task options const int OsTaskBase::DEF_PRIO = 128; // default task priority const int OsTaskBase::DEF_STACKSIZE = 256*1024; // default task stack size const UtlString OsTaskBase::TASK_PREFIX("Task."); // Task name db prefix const UtlString OsTaskBase::TASKID_PREFIX("TaskID."); // TaskId name db prefix OsAtomicInt OsTaskBase::taskCount(0); /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ // Request a task shutdown. // The run() method of the derived class is expected to call the // isShuttingDown() method to detect when a task shutdown has been // requested. void OsTaskBase::requestShutdown(void) { OsLock lock(mDataGuard); if (!isStarted() && !isShuttingDown()) mState = SHUT_DOWN; else mState = SHUTTING_DOWN; } // Set the userData for the task. // The class does not use this information itself, but merely stores // it on behalf of the caller. void OsTaskBase::setUserData(int data) { mUserData = data; } // Adds a syslog entry of the given facility and priority OsStatus OsTaskBase::syslog(const OsSysLogFacility facility, const OsSysLogPriority priority, const char* format, ...) { OsTaskId_t taskId; int processId; if (OsSysLog::willLog(facility, priority)) { id(taskId); processId = 0; va_list ap; va_start(ap, format); OsSysLog::vadd(mName.data(), taskId, facility, priority, format, ap) ; va_end(ap); } return OS_SUCCESS ; } /* ============================ ACCESSORS ================================= */ // Get the void* value passed as an argument to the task void* OsTaskBase::getArg(void) { return mpArg; } // Get the name associated with the task const UtlString& OsTaskBase::getName(void) { return mName; } // Return the userData for the task. int OsTaskBase::getUserData(void) { return mUserData; } void OsTaskBase::yield(void) { OsTask::yield(); } OsStatus OsTaskBase::delay(const int milliSecs) { return(OsTask::delay(milliSecs)); } /* ============================ INQUIRY =================================== */ // Return TRUE is the task is started and not suspended, otherwise FALSE. UtlBoolean OsTaskBase::isReady(void) { OsLock lock(mDataGuard); if (!isStarted()) return FALSE; return !isSuspended(); } // Return TRUE if a task shutdown has been requested and acknowledged UtlBoolean OsTaskBase::isShutDown(void) { OsLock lock(mDataGuard); return (mState == SHUT_DOWN); } // Return TRUE if a task shutdown has been requested but not acknowledged UtlBoolean OsTaskBase::isShuttingDown(void) { OsLock lock(mDataGuard); return (mState == SHUTTING_DOWN); } // Return TRUE if the task has been started (and has not been shut down) UtlBoolean OsTaskBase::isStarted(void) { OsLock lock(mDataGuard); return (mState == STARTED); } // Return TRUE if the task is un-initialized UtlBoolean OsTaskBase::isUnInitialized(void) { OsLock lock(mDataGuard); return (mState == UNINITIALIZED); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ // Constructor OsTaskBase::OsTaskBase(const UtlString& name, void* pArg, const int priority, const int options, const int stackSize) : mDataGuard(OsMutex::Q_PRIORITY + OsMutex::INVERSION_SAFE), mState(UNINITIALIZED), mpArg(pArg), mUserData(0) { // If name contains %d insert the task count/index assert(name.length() < 240); char nameBuffer[256]; sprintf(nameBuffer, name.data(), taskCount++); mName.append(nameBuffer); if (mName != "") OsUtil::insertKeyValue(TASK_PREFIX, mName, (intptr_t) this); } // Destructor OsTaskBase::~OsTaskBase() { OsStatus res; assert(isUnInitialized()); if (mName != "") { res = OsUtil::deleteKeyValue(TASK_PREFIX, mName); //assert(res == OS_SUCCESS); } mName = OsUtil::NULL_OS_STRING; } // Wait until the task is shut down and the run method has exited. // Most sub classes of OsTask should call this method in // the destructor before deleting any members which are // accessed by the run method. UtlBoolean OsTaskBase::waitUntilShutDown(int milliSecToWait) { // If task is already shut down, just return. if (isShutDown()) return TRUE; UtlString taskName = getName(); if (isStarted() || isUnInitialized()) { requestShutdown(); // ask the task to shut itself down yield(); // yield the CPU so the target task can terminate } // wait up to another nineteen seconds (20 total) for the task to terminate // printing out a console complaint every second if (isShuttingDown()) { int i; // wait up to a second for the task to terminate. for (i = 0; (i < 10) && isShuttingDown(); i++) delay(milliSecToWait/200); // wait 1/10 second for (i = 1; (i < 20) && isShuttingDown(); i++) { OsSysLog::add(FAC_KERNEL, PRI_WARNING, "Task: %s failed to terminate after %f seconds", taskName.data(), (milliSecToWait * i) / 20000.0); delay(milliSecToWait/20); } // if still no response from the task, assume it is unresponsive and // destroy the object if (isShuttingDown()) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "Task: %s failed to terminate after %f seconds", taskName.data(), milliSecToWait / 1000.0); } } // Do not exit if not shut down while (isShuttingDown()) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "Task: %s failed to terminate, waiting...", taskName.data()); delay(300000); } return(isShutDown()); } // Acknowledge a shutdown request // The platform specific entry point which calls the run // method should call this method immediately after run exits. // to indicate that it is now shut down. void OsTaskBase::ackShutdown(void) { OsLock lock(mDataGuard); assert(isStarted() || isShuttingDown() || isShutDown()); mState = SHUT_DOWN; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsTime.cpp0000644000175000017500000001573512205613256023006 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsTime.h" // DEFINES #define INFINITE_TIME 0x7FFFFFFF // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS const long OsTime::MSECS_PER_SEC = 1000; const long OsTime::USECS_PER_MSEC = 1000; const long OsTime::USECS_PER_SEC = 1000000; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor (creates a zero duration interval) OsTime::OsTime() { init(); } // Constructor OsTime::OsTime(const long msecs) { init(); // Calculate the number of seconds and microseconds if (msecs < 0 || msecs >= MSECS_PER_SEC) { mSeconds = msecs / MSECS_PER_SEC; mUsecs = (msecs % MSECS_PER_SEC) * USECS_PER_MSEC; if (msecs < 0) { mSeconds -= 1; mUsecs += USECS_PER_SEC; } } else // 0 <= msecs < MSECS_PER_SEC { mUsecs = msecs * USECS_PER_MSEC; } } // Constructor OsTime::OsTime(TimeQuantity quantity) { init(); if (quantity == OS_INFINITY) { mSeconds = INFINITE_TIME; mUsecs = INFINITE_TIME; } else { // NO_WAIT_TIME mSeconds = 0; mUsecs = 0; } } // Constructor OsTime::OsTime(const long seconds, const long usecs) { init(); mSeconds = seconds; // if necessary, adjust seconds and usecs so that the following holds: // 0 <= usecs <= (USECS_PER_SEC-1) if (usecs < 0 || usecs >= USECS_PER_SEC) { mSeconds += usecs / USECS_PER_SEC; mUsecs = usecs % USECS_PER_SEC; if (usecs < 0) { mSeconds -= 1; mUsecs += USECS_PER_SEC; } } else // 0 <= usecs < USECS_PER_SEC { mUsecs = usecs; } } // Copy constructor OsTime::OsTime(const OsTime& rOsTime) { mSeconds = rOsTime.mSeconds; mUsecs = rOsTime.mUsecs; } // Destructor OsTime::~OsTime() { // no work required } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsTime& OsTime::operator=(TimeQuantity rhs) { if (rhs == OS_INFINITY) { mSeconds = INFINITE_TIME; mUsecs = INFINITE_TIME; } else { // NO_WAIT_TIME mSeconds = 0; mUsecs = 0; } return *this; } // Assignment operator OsTime& OsTime::operator=(const OsTime& rhs) { if (this == &rhs) // handle the assignment to self case return *this; mSeconds = rhs.mSeconds; mUsecs = rhs.mUsecs; return *this; } // Addition operator OsTime OsTime::operator+(const OsTime& rhs) { OsTime sum(this->mSeconds + rhs.mSeconds, this->mUsecs + rhs.mUsecs); return sum; } // Subtraction operator OsTime OsTime::operator-(const OsTime& rhs) { OsTime diff(this->mSeconds - rhs.mSeconds, this->mUsecs - rhs.mUsecs); return diff; } // Increment operator OsTime OsTime::operator+=(const OsTime& rhs) { *this = *this + rhs; return *this; } // Decrement operator OsTime OsTime::operator-=(const OsTime& rhs) { *this = *this - rhs; return *this; } // Test for equality operator bool OsTime::operator==(const OsTime& rhs) const { return (this->mSeconds == rhs.mSeconds) && (this->mUsecs == rhs.mUsecs); } // Test for inequality operator bool OsTime::operator!=(const OsTime& rhs) const { return (this->mSeconds != rhs.mSeconds) || (this->mUsecs != rhs.mUsecs); } // Test for greater than bool OsTime::operator>(const OsTime& rhs) const { if (this->mSeconds >= 0) { // "this" is a positive time value return (this->mSeconds > rhs.mSeconds) || ((this->mSeconds == rhs.mSeconds) && (this->mUsecs > rhs.mUsecs)); } else { // "this" is a negative time value return (this->mSeconds > rhs.mSeconds) || ((this->mSeconds == rhs.mSeconds) && (this->mUsecs < rhs.mUsecs)); } } // Test for greater than or equal bool OsTime::operator>=(const OsTime& rhs) const { if (this->mSeconds >= 0) { // "this" is a positive time value return (this->mSeconds > rhs.mSeconds) || ((this->mSeconds == rhs.mSeconds) && (this->mUsecs >= rhs.mUsecs)); } else { // "this" is a negative time value return (this->mSeconds > rhs.mSeconds) || ((this->mSeconds == rhs.mSeconds) && (this->mUsecs <= rhs.mUsecs)); } } // Test for less than bool OsTime::operator<(const OsTime& rhs) const { if (this->mSeconds >= 0) { // "this" is a positive time value return (this->mSeconds < rhs.mSeconds) || ((this->mSeconds == rhs.mSeconds) && (this->mUsecs < rhs.mUsecs)); } else { // "this" is a negative time value return (this->mSeconds < rhs.mSeconds) || ((this->mSeconds == rhs.mSeconds) && (this->mUsecs > rhs.mUsecs)); } } // Test for less than or equal bool OsTime::operator<=(const OsTime& rhs) const { if (this->mSeconds >= 0) { // "this" is a positive time value return (this->mSeconds < rhs.mSeconds) || ((this->mSeconds == rhs.mSeconds) && (this->mUsecs <= rhs.mUsecs)); } else { // "this" is a negative time value return (this->mSeconds < rhs.mSeconds) || ((this->mSeconds == rhs.mSeconds) && (this->mUsecs >= rhs.mUsecs)); } } /* ============================ ACCESSORS ================================= */ // Convert the time interval to milliseconds long OsTime::cvtToMsecs(void) const { return (mSeconds * MSECS_PER_SEC) + (mUsecs / USECS_PER_MSEC); } double OsTime::getDouble() const { return(((double) mSeconds) + ((double) mUsecs) / ((double) USECS_PER_SEC)); } /* ============================ INQUIRY =================================== */ // Return TRUE if the time interval is infinite UtlBoolean OsTime::isInfinite(void) const { if (mSeconds == INFINITE_TIME && mUsecs == INFINITE_TIME) return TRUE; else return FALSE; } // Return TRUE if the time interval is zero (no wait) UtlBoolean OsTime::isNoWait(void) const { if (mSeconds == 0 && mUsecs == 0) return TRUE; else return FALSE; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ // Initialize the instance variables for a newly constructed object void OsTime::init(void) { mSeconds = 0; mUsecs = 0; } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsTimeLog.cpp0000644000175000017500000001526112205613256023442 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsTimeLog.h" #include "os/OsDateTime.h" #include "utl/UtlString.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #ifdef _VXWORKS static int MICROSECS_PER_SEC = 1000000; #endif // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsTimeLog::OsTimeLog(int maxEventCount) { mMaxEventCount = maxEventCount; mNumEvents = 0; mpaEventNames = new UtlString*[mMaxEventCount]; mpaEventTimes = new OsTime*[mMaxEventCount]; for(int index = 0; index < mMaxEventCount; index++) { mpaEventNames[index] = NULL; mpaEventTimes[index] = NULL; } } // Copy constructor OsTimeLog::OsTimeLog(const OsTimeLog& rOsTimeLog) { mMaxEventCount = rOsTimeLog.mMaxEventCount; mNumEvents = rOsTimeLog.mNumEvents; mpaEventNames = new UtlString*[mMaxEventCount]; mpaEventTimes = new OsTime*[mMaxEventCount]; for(int index = 0; index < mMaxEventCount; index++) { if(rOsTimeLog.mpaEventNames && rOsTimeLog.mpaEventNames[index]) { mpaEventNames[index] = new UtlString(*(rOsTimeLog.mpaEventNames[index])); } else if(rOsTimeLog.mpaEventNames) { mpaEventNames[index] = NULL; } if(rOsTimeLog.mpaEventTimes && rOsTimeLog.mpaEventTimes[index]) { mpaEventTimes[index] = new OsTime(*(rOsTimeLog.mpaEventTimes[index])); } else if(rOsTimeLog.mpaEventTimes) { mpaEventTimes[index] = NULL; } } } // Destructor OsTimeLog::~OsTimeLog() { for(int index = 0; index < mMaxEventCount; index++) { if(mpaEventNames && mpaEventNames[index]) { delete (UtlString*)mpaEventNames[index]; mpaEventNames[index] = NULL; } if(mpaEventTimes && mpaEventTimes[index]) { delete (OsTime*)mpaEventTimes[index]; mpaEventTimes[index] = NULL; } } delete[] mpaEventNames; delete[] mpaEventTimes; mpaEventNames = 0; mpaEventTimes = 0; } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsTimeLog& OsTimeLog::operator=(const OsTimeLog& rhs) { if (this == &rhs) // handle the assignment to self case return *this; int index; for(index = 0; index < mMaxEventCount; index++) { if(mpaEventNames && mpaEventNames[index]) delete mpaEventNames[index]; if(mpaEventTimes && mpaEventTimes[index]) delete mpaEventTimes[index]; } // Need bigger arrays if(mMaxEventCount < rhs.mMaxEventCount) { if(mpaEventNames) delete[] mpaEventNames; if(mpaEventTimes) delete[] mpaEventTimes; mpaEventNames = new UtlString*[mMaxEventCount]; mpaEventTimes = new OsTime*[mMaxEventCount]; } mMaxEventCount = rhs.mMaxEventCount; mNumEvents = rhs.mNumEvents; for(index = 0; index < mMaxEventCount; index++) { if(rhs.mpaEventNames && rhs.mpaEventNames[index]) { mpaEventNames[index] = new UtlString(*(rhs.mpaEventNames[index])); } else if(rhs.mpaEventNames) { mpaEventNames[index] = NULL; } if(rhs.mpaEventTimes && rhs.mpaEventTimes[index]) { mpaEventTimes[index] = new OsTime(*(rhs.mpaEventTimes[index])); } else if(rhs.mpaEventTimes) { mpaEventTimes[index] = NULL; } } return *this; } //: Adds an event to the log for the current time void OsTimeLog::addEvent(const char* eventName) { #ifdef _VXWORKS OsTime* now = new OsTime(); OsDateTimeVxw::highResTime( *now ); #else OsTime* now = new OsTime(); OsDateTime::getCurTime(*now); #endif addEvent(eventName, now); } //: Adds an event to the log for the given time void OsTimeLog::addEvent(const char* eventName, OsTime* eventTime) { if(mNumEvents < mMaxEventCount) { UtlString* name = new UtlString(eventName); mpaEventNames[mNumEvents] = name; mpaEventTimes[mNumEvents] = eventTime; mNumEvents++; } } //: Dumps the log out using osPrintf void OsTimeLog::dumpLog() const { UtlString log; getLogString(log); osPrintf("%s", log.data()); log.remove(0); } void OsTimeLog::getLogString(UtlString& log) const { int index; OsTime time; OsTime deltaTime; OsTime tZero; OsTime previousTime; size_t maxNameLength = 0; char timeString[40]; for(index = 0; index < mMaxEventCount; index++) { if(mpaEventNames[index] && mpaEventNames[index]->length() > maxNameLength) { maxNameLength = mpaEventNames[index]->length(); } } int nameColumnTabs = ((int) (maxNameLength / 8)) + 1; // Put a header in after we know how long the event names are log.append("Name"); for(index = 0; index < nameColumnTabs; index++) log.append('\t'); log.append("Time\tIncremental Time\n"); if(mpaEventTimes[0]) tZero = *(mpaEventTimes[0]); for(index = 0; index < mMaxEventCount; index++) { if(mpaEventNames[index]) { log.append(mpaEventNames[index]->data()); } if(mpaEventTimes[index]) { time = *mpaEventTimes[index] - tZero;; sprintf(timeString, "\t%ld.%.6ld", time.seconds(), time.usecs()); log.append(timeString); if(index > 0) { deltaTime = time - previousTime; sprintf(timeString, "\t%ld.%.6ld", deltaTime.seconds(), deltaTime.usecs()); log.append(timeString); } else { log.append("\tN/A"); } previousTime = time; } if(mpaEventNames[index] || mpaEventTimes[index] || index < mNumEvents) log.append("\n"); } } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsTimer.cpp0000644000175000017500000002236412205613256023164 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2007 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsTimer.h" #include "os/OsTimerTask.h" #include "os/OsQueuedEvent.h" #include "os/OsLock.h" #include "os/OsEvent.h" #include "os/OsTimerMsg.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS const UtlContainableType OsTimer::TYPE = "OsTimer" ; #ifdef VALGRIND_TIMER_ERROR // Dummy static variable to receive values from tracking variables. static char dummy; #endif /* VALGRIND_TIMER_ERROR */ /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor // Timer expiration event notification happens using the // newly created OsQueuedEvent object OsTimer::OsTimer(OsMsgQ* pQueue, intptr_t userData) : mBSem(OsBSem::Q_PRIORITY, OsBSem::FULL), mApplicationState(0), mTaskState(0), // Always initialize mDeleting, as we may print its value. mDeleting(FALSE), mpNotifier(new OsQueuedEvent(*pQueue, userData)) , mbManagedNotifier(TRUE), mOutstandingMessages(0), mWasFired(FALSE), mTimerQueueLink(0) { #ifdef VALGRIND_TIMER_ERROR // Initialize the variables for tracking timer access. mLastStartBacktrace = NULL; mLastDestructorBacktrace = NULL; #endif /* VALGRIND_TIMER_ERROR */ } // The address of "this" OsTimer object is the eventData that is // conveyed to the Listener when the notification is signaled. OsTimer::OsTimer(OsNotification& rNotifier) : mBSem(OsBSem::Q_PRIORITY, OsBSem::FULL), mApplicationState(0), mTaskState(0), // Always initialize mDeleting, as we may print its value. mDeleting(FALSE), mpNotifier(&rNotifier) , mbManagedNotifier(FALSE), mOutstandingMessages(0), mWasFired(FALSE), mTimerQueueLink(0) { #ifdef VALGRIND_TIMER_ERROR // Initialize the variables for tracking timer access. mLastStartBacktrace = NULL; mLastDestructorBacktrace = NULL; #endif /* VALGRIND_TIMER_ERROR */ } // Destructor OsTimer::~OsTimer() { #ifndef NDEBUG CHECK_VALIDITY(this); #endif // Update members and determine whether we need to send an UPDATE_SYNC // to stop the timer or ensure that the timer task has no queued message // about this timer. UtlBoolean sendMessage = FALSE; { OsLock lock(mBSem); #ifndef NDEBUG assert(!mDeleting); // Lock out all further application methods. mDeleting = TRUE; #endif // Check if the timer needs to be stopped. if (isStarted(mApplicationState)) { sendMessage = TRUE; mApplicationState++; } // Check if there are outstanding messages that have to be waited for. if (mOutstandingMessages > 0) { sendMessage = TRUE; } // If we have to send a message, make note of it. if (sendMessage) { mOutstandingMessages++; } } // Send a message to the timer task if we need to. if (sendMessage) { OsEvent event; OsTimerMsg msg(OsTimerMsg::OS_TIMER_UPDATE_SYNC, this, &event); OsStatus res = OsTimerTask::getTimerTask()->postMessage(msg); assert(res == OS_SUCCESS); event.wait(); } // If mbManagedNotifier, free *mpNotifier. if (mbManagedNotifier) { delete mpNotifier; } } // Non-blocking asynchronous delete operation void OsTimer::deleteAsync() { #ifndef NDEBUG CHECK_VALIDITY(this); #endif // Update members. { OsLock lock(mBSem); #ifndef NDEBUG assert(!mDeleting); // Lock out all further application methods. mDeleting = TRUE; #endif // Check if the timer needs to be stopped. if (isStarted(mApplicationState)) { mApplicationState++; } // Note we will be sending a message. mOutstandingMessages++; } // Send the message. OsTimerMsg msg(OsTimerMsg::OS_TIMER_UPDATE_DELETE, this, NULL); OsStatus res = OsTimerTask::getTimerTask()->postMessage(msg); assert(res == OS_SUCCESS); } /* ============================ MANIPULATORS ============================== */ // Arm the timer to fire once at the indicated date and time OsStatus OsTimer::oneshotAt(const OsDateTime& when) { OsTime whenTime; when.cvtToTimeSinceEpoch(whenTime); return startTimer(whenTime, FALSE, OsTime::NO_WAIT_TIME); } // Arm the timer to fire once at the current time + offset OsStatus OsTimer::oneshotAfter(const OsTime& offset) { OsTime curTime; OsDateTime::getCurTime(curTime); return startTimer(curTime + offset, FALSE, OsTime::NO_WAIT_TIME); } // Arm the timer to fire periodically starting at the indicated date/time OsStatus OsTimer::periodicAt(const OsDateTime& when, const OsTime &period) { OsTime whenTime; when.cvtToTimeSinceEpoch(whenTime); return startTimer(whenTime, TRUE, period); } // Arm the timer to fire periodically starting at current time + offset OsStatus OsTimer::periodicEvery(const OsTime &offset, const OsTime &period) { OsTime curTime; OsDateTime::getCurTime(curTime); return startTimer(curTime + offset, TRUE, period); } // Disarm the timer OsStatus OsTimer::stop(UtlBoolean synchronous) { #ifndef NDEBUG CHECK_VALIDITY(this); #endif OsStatus result; UtlBoolean sendMessage = FALSE; // Update members. { OsLock lock(mBSem); #ifndef NDEBUG assert(!mDeleting); #endif // Determine whether the call is successful. if (isStarted(mApplicationState)) { mWasFired = FALSE; // Update state to stopped. mApplicationState++; result = OS_SUCCESS; if (mOutstandingMessages == 0) { // We will send a message. sendMessage = TRUE; mOutstandingMessages++; } } else { result = OS_FAILED; } } // If we need to, send an UPDATE message to the timer task. if (sendMessage) { if (synchronous) { // Send message and wait. OsEvent event; OsTimerMsg msg(OsTimerMsg::OS_TIMER_UPDATE_SYNC, this, &event); OsStatus res = OsTimerTask::getTimerTask()->postMessage(msg); assert(res == OS_SUCCESS); event.wait(); } else { // Send message. OsTimerMsg msg(OsTimerMsg::OS_TIMER_UPDATE, this, NULL); OsStatus res = OsTimerTask::getTimerTask()->postMessage(msg); assert(res == OS_SUCCESS); } } return result; } /* ============================ ACCESSORS ================================= */ // Return the OsNotification object for this timer OsNotification* OsTimer::getNotifier(void) const { return mpNotifier; } unsigned OsTimer::hash() const { return (uintptr_t) this; } UtlContainableType OsTimer::getContainableType() const { return OsTimer::TYPE; } UtlBoolean OsTimer::getWasFired() { OsLock lock(mBSem); return mWasFired; } /* ============================ INQUIRY =================================== */ // Return the state value for this OsTimer object OsTimer::OsTimerState OsTimer::getState() { OsLock lock(mBSem); return isStarted(mApplicationState) ? STARTED : STOPPED; } int OsTimer::compareTo(UtlContainable const * inVal) const { int result; if (inVal->isInstanceOf(OsTimer::TYPE)) { result = ((uintptr_t) this) - ((uintptr_t) inVal); } else { result = -1; } return result; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ // Get the current time as a Time. /*OsTimer::Time OsTimer::now() { OsTime t; OsDateTime::getCurTime(t); return (Time)(t.seconds()) * 1000000 + t.usecs(); } */ // Start the OsTimer object. OsStatus OsTimer::startTimer(OsTime start, UtlBoolean periodic, OsTime period) { #ifndef NDEBUG CHECK_VALIDITY(this); #endif OsStatus result; UtlBoolean sendMessage = FALSE; // Update members. { OsLock lock(mBSem); #ifndef NDEBUG assert(!mDeleting); #endif // Determine whether the call is successful. if (isStopped(mApplicationState)) { mWasFired = FALSE; // Update state to started. mApplicationState++; result = OS_SUCCESS; if (mOutstandingMessages == 0) { // We will send a message. sendMessage = TRUE; mOutstandingMessages++; } // Set time values. mExpiresAt = start; mPeriodic = periodic; mPeriod = period; } else { result = OS_FAILED; } } // If we need to, send an UPDATE message to the timer task. if (sendMessage) { OsTimerMsg msg(OsTimerMsg::OS_TIMER_UPDATE, this, NULL); OsStatus res = OsTimerTask::getTimerTask()->postMessage(msg); assert(res == OS_SUCCESS); } return result; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsTimerMsg.cpp0000644000175000017500000000447312205613256023634 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsTimerMsg.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsTimerMsg::OsTimerMsg(const unsigned char subType, OsTimer* pTimer, OsEvent* pEvent) : OsRpcMsg(OsMsg::OS_TIMER, subType, *pEvent), mpTimer(pTimer) { init(); } // Copy constructor OsTimerMsg::OsTimerMsg(const OsTimerMsg& rOsTimerMsg) : OsRpcMsg(rOsTimerMsg) { mpTimer = rOsTimerMsg.mpTimer; } // Create a copy of this msg object (which may be of a derived type) OsMsg* OsTimerMsg::createCopy(void) const { return new OsTimerMsg(*this); } // Destructor OsTimerMsg::~OsTimerMsg() { // no work required } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsTimerMsg& OsTimerMsg::operator=(const OsTimerMsg& rhs) { if (this == &rhs) // handle the assignment to self case return *this; OsMsg::operator=(rhs); // assign fields for parent class mpTimer = rhs.mpTimer; return *this; } /* ============================ ACCESSORS ================================= */ // Return the size of the message in bytes. // This is a virtual method so that it will return the accurate size for // the message object even if that object has been upcast to the type of // an ancestor class. int OsTimerMsg::getMsgSize(void) const { return sizeof(*this); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ // Initialization common to all constructors void OsTimerMsg::init(void) { } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsTimerTask.cpp0000644000175000017500000004151312205613256024004 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2007 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsEvent.h" #include "os/OsTimer.h" #include "os/OsTimerMsg.h" #include "os/OsTimerTask.h" #include "os/OsLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // spInstance can be tested and set asynchronously by different threads. volatile OsTimerTask* OsTimerTask::spInstance = 0; // Create a semaphore at run time rather than declaring a static semaphore, // so that the shut-down code does not try to destroy the semaphore, // which can lead to problems with the ordering of destructors. OsBSem* OsTimerTask::sLock = new OsBSem(OsBSem::Q_PRIORITY, OsBSem::FULL); const int OsTimerTask::TIMER_MAX_REQUEST_MSGS = 10000; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Return a pointer to the timer task, creating it if necessary. OsTimerTask* OsTimerTask::getTimerTask(void) { // If the task object already exists, and the corresponding low-level task // has been started, then use it if (spInstance == NULL) { // If the task does not yet exist or hasn't been started, then acquire // the lock to ensure that only one instance of the task is started sLock->acquire(); // Test again, as the previous test was not interlocked against other // threads. if (spInstance == NULL) { spInstance = new OsTimerTask(); assert( spInstance ); // Have to cast spInstance to remove volatile, according to C++ // rules. UtlBoolean isStarted = ((OsTimerTask*) spInstance)->start(); assert(isStarted); } sLock->release(); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTimerTask::getTimerTask OsTimerTask started"); } return (OsTimerTask*) spInstance; } // Destroy the singleton instance of the timer task. void OsTimerTask::destroyTimerTask(void) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTimerTask::destroyTimerTask entered"); sLock->acquire(); if (spInstance) { delete spInstance ; spInstance = NULL ; } sLock->release(); } // Destructor OsTimerTask::~OsTimerTask() { // Shut down the task. OsEvent event; OsTimerMsg msg(OsTimerMsg::OS_TIMER_SHUTDOWN, NULL, &event); // Send the OS_TIMER_SHUTDOWN message. OsStatus res = OsTimerTask::getTimerTask()->postMessage(msg); assert(res == OS_SUCCESS); // Wait for the response. event.wait(); // Since this code is locked by sLock, no (few) messages will have // been added to the incoming queue while we were waiting for the // OS_TIMER_SHUTDOWN message to get through the queue, as getTimerTask would // have waited for sLock. } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ // Default constructor (called only indirectly via getTimerTask()) OsTimerTask::OsTimerTask(void) : OsServerTask("OsTimer-%d", NULL, TIMER_MAX_REQUEST_MSGS , 5 // high priority so that we get reasonable clock heartbeats for media ) , mTimerQueue(0) , mSignalTimeout(0, 50000) { } // The entry point for the task. // This method executes a message processing loop until either // requestShutdown(), deleteForce(), or the destructor for this object // is called. int OsTimerTask::run(void* pArg) { UtlBoolean doShutdown = FALSE; OsMsg* pMsg = NULL; OsStatus res; OsTime now; // "now" is the current time. OsDateTime::getCurTime(now); do { // Do not attempt to receive message if a timer has already fired. // (This also avoids an edge case if the timeout value is zero // or negative.) if (!mTimerQueue || (now < mTimerQueue->mQueuedExpiresAt)) { // Set the timeout till the next timer fires. OsTime timeout; if (mTimerQueue) { timeout = mTimerQueue->mQueuedExpiresAt - now; } else { timeout = OsTime::OS_INFINITY; } res = receiveMessage((OsMsg*&) pMsg, timeout); // wait for a message if (res == OS_SUCCESS) { // A message was received. Process it. doShutdown = isShuttingDown(); if (!doShutdown) { // comply with shutdown if (!handleMessage(*pMsg)) // process the message { OsServerTask::handleMessage(*pMsg); } } if (!pMsg->getSentFromISR()) { pMsg->releaseMsg(); // free the message } } else { assert(pMsg==NULL); } OsDateTime::getCurTime(now); // Update our record of the current time. } // Now check for timers that have expired. while (mTimerQueue && now >= mTimerQueue->mQueuedExpiresAt) { // Fire the the timer (and remove it from the queue). OsTimer* timer = mTimerQueue; mTimerQueue = timer->mTimerQueueLink; // Clear the timer's mTimerQueueLink to indicate it is not // in the timer queue. timer->mTimerQueueLink = 0; fireTimer(timer); } if (OsSysLog::willLog(FAC_KERNEL, PRI_WARNING)) { // Check to see if timer firing took too long. OsTime after; OsDateTime::getCurTime(after); OsTime t = after - now; if (t.getDouble() >= 0.1 /* seconds */) { OsSysLog::add(FAC_KERNEL, PRI_WARNING, "OsTimerTask::run firing took %ld.%06ld usecs," " queue length = %d, before fire = %ld.%06ld, after fire = %ld.%06ld", t.seconds(), t.usecs(), getMessageQueue()->numMsgs(), now.seconds(), now.usecs(), after.seconds(), after.usecs()); } } } while (!doShutdown); OsSysLog::add(FAC_KERNEL, PRI_INFO, "OsTimerTask::run OsTimerTask shutting down"); return 0; // and then exit } // Handle a timer service request. // Return TRUE if the request was handled, otherwise FALSE. UtlBoolean OsTimerTask::handleMessage(OsMsg& rMsg) { // Process a message. // If not an OS_TIMER message, return FALSE to indicate it should be // passed to our superclass. if (rMsg.getMsgType() != OsMsg::OS_TIMER) { return FALSE; } // Process an OS_TIMER message. OsTimerMsg& message = static_cast (rMsg); // Process a OS_TIMER_SHUTDOWN message, which is special if (message.getMsgSubType() == OsTimerMsg::OS_TIMER_SHUTDOWN) { OsSysLog::add(FAC_KERNEL, PRI_INFO, "OsTimerTask::handleMessage OS_TIMER_SHUTDOWN seen, mState = %d", mState); // Verify that there are no other requests in the timer task's queue. assert(getMessageQueue()->isEmpty()); // Stop all the timers in the timer queue. OsTimer* link; for (OsTimer* timer = mTimerQueue; timer; timer = link) { // This lock should never block, since the application should not // be accessing the timer. OsLock lock(timer->mBSem); // Check that the application and task states are the same. // If they aren't, the application is mucking with the timer. assert(timer->mTaskState == timer->mApplicationState); // Increment the state fields, to show the timer is stopped. timer->mTaskState = timer->mApplicationState = timer->mApplicationState + 1; // Get the link field. link = timer->mTimerQueueLink; // Clear the link field of the timer. timer->mTimerQueueLink = 0; } // Empty the timer queue. mTimerQueue = 0; // Change mState so the main loop will exit. requestShutdown(); // Signal the event so our caller knows we're done. message.getEventP()->signal(0); OsSysLog::add(FAC_KERNEL, PRI_INFO, "OsTimerTask::handleMessage OS_TIMER_SHUTDOWN seen, mState = %d", mState); return TRUE; } OsTimer* timer = message.getTimerP(); #ifndef NDEBUG CHECK_VALIDITY(timer); #endif unsigned int applicationState; OsTime expiresAt; UtlBoolean periodic; OsTime period; { OsLock lock(timer->mBSem); // mDeleting may be true, if the destructor has started running. // Decrement the outstanding message count. timer->mOutstandingMessages--; // Get mApplicationState. applicationState = timer->mApplicationState; // Get the timing information. expiresAt = timer->mExpiresAt; periodic = timer->mPeriodic; period = timer->mPeriod; } // Determine whether the timer needs to be stopped. // (The comparison between applicationState and mTaskState is really // ">", taking into account wraparound. But that is difficult to // implement, so given that mApplicationState is always >= mTaskState // by design, we can use "!=".) if (applicationState != timer->mTaskState && OsTimer::isStarted(timer->mTaskState)) { // Stop the timer. removeTimer(timer); } // Determine whether the timer needs to be started. if (applicationState != timer->mTaskState && OsTimer::isStarted(applicationState)) { // Start the timer. // Set the saved timing information. timer->mQueuedExpiresAt = expiresAt; timer->mQueuedPeriodic = periodic; timer->mQueuedPeriod = period; insertTimer(timer); } // Update the task state. timer->mTaskState = applicationState; switch (message.getMsgSubType()) { case OsTimerMsg::OS_TIMER_UPDATE: // No further processing is needed. break; case OsTimerMsg::OS_TIMER_UPDATE_SYNC: // If it is an UPDATE_SYNC message, signal the event. message.getEventP()->signal(0); break; case OsTimerMsg::OS_TIMER_UPDATE_DELETE: // If it is an UPDATE_DELETE, delete the timer. // Timer will not be accessed by any other thread, so we // can access it without locking. #ifndef NDEBUG // Deletion in progress. assert(timer->mDeleting); #endif // Timer should be stopped already. assert(OsTimer::isStopped(timer->mApplicationState)); // No outstanding messages. assert(timer->mOutstandingMessages == 0); #ifndef NDEBUG // Set mDeleting to FALSE to the destructor won't fail. timer->mDeleting = FALSE; #endif // Use ordinary destructor to delete the timer. // Because of the state of the timer, it will not send a message to // the timer task. delete timer; break; default: // Catch invalid values. assert(FALSE); } return TRUE; } /** Fire a timer because it has expired. * Calls the if notification routine, if the timer hasn't been stopped * already. * If the timer is periodic and hasn't been stopped, reinserts it into * the queue. * Advances the timer's state if it is one-shot or has been stopped. */ void OsTimerTask::fireTimer(OsTimer* timer) { OsLock lock(timer->mBSem); UtlBoolean report; // mDeleting may be true, if the destructor has started running. // Determine if this firing should be reported, or whether the // timer has been stopped since we were informed that it started. report = timer->mTaskState == timer->mApplicationState; if (!report) { // If this firing is after the timer has been stopped by // the application, advance mTaskState to a stopped state // to recognize that the timer has been removed from the // timer queue. timer->mTaskState++; } else if (report && !timer->mQueuedPeriodic) { // If this firing should be reported, and this is a one-shot // timer, stop the timer: // advance both mTaskState and mApplicationState timer->mTaskState = timer->mApplicationState = timer->mTaskState + 1; } // If this firing should be reported, and this is a periodic // timer, re-set its firing time. if (report && timer->mQueuedPeriodic) { timer->mQueuedExpiresAt = timer->mQueuedExpiresAt + timer->mQueuedPeriod; // Insert the timer into the active timer queue. insertTimer(timer); } // Call the event routine if we are supposed to. if (report) { // Use a timeout when signalling. Otherwise if the event blocks for a long time // (e.g. a queued event blocks because queue is full) the timer task then blocks // and bad things happen. timer->mpNotifier->setTimeout(mSignalTimeout); OsStatus status = timer->mpNotifier->signal((intptr_t) timer); if(status == OS_WAIT_TIMEOUT) { OsSysLog::add(FAC_KERNEL, PRI_CRIT, "OsTimer event %p timed (%d.%6d sec) out during signal. Timer not fired.", timer->mpNotifier, (int) mSignalTimeout.seconds(), (int) mSignalTimeout.usecs()); } else if(status != OS_SUCCESS) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsTimer event %p returned error: %d from signal", status); } timer->mWasFired = TRUE; } } // Insert a timer into the timer queue. void OsTimerTask::insertTimer(OsTimer* timer) { OsTimer** previous_ptr; OsTimer* current; assert(timer->mTimerQueueLink == 0); // Check to see if the firing time is in the past. // This is not an error, but is unusual and probably indicates a backlog // in processing. if (OsSysLog::willLog(FAC_KERNEL, PRI_WARNING)) { // Check to see if timer firing took too long. OsTime now; OsDateTime::getCurTime(now); if (timer->mQueuedExpiresAt < now) { OsSysLog::add(FAC_KERNEL, PRI_WARNING, "OsTimerTask::insertTimer timer to fire %ldms in the past" " (now=%ld.%06ld, fire=%ld.%06ld)", (now - timer->mQueuedExpiresAt).cvtToMsecs(), now.seconds(), now.usecs(), timer->mQueuedExpiresAt.seconds(), timer->mQueuedExpiresAt.usecs()); } } // Scan through the timer queue, looking for the right place to // insert the timer. for (previous_ptr = &mTimerQueue, current = mTimerQueue; current && (timer->mQueuedExpiresAt > current->mQueuedExpiresAt); previous_ptr = ¤t->mTimerQueueLink, current = current->mTimerQueueLink) { /* null */ } // Insert the timer. *previous_ptr = timer; timer->mTimerQueueLink = current; } // Remove a timer from the timer queue. void OsTimerTask::removeTimer(OsTimer* timer) { OsTimer** previous_ptr; OsTimer* current; // Scan through the timer queue, looking for this timer. for (previous_ptr = &mTimerQueue, current = mTimerQueue; current && current != timer; previous_ptr = ¤t->mTimerQueueLink, current = current->mTimerQueueLink) { /* null */ } // Remove the timer, if we found it. if (!current) { OsSysLog::add(FAC_KERNEL, PRI_EMERG, "OsTimerTask::removeTimer timer not found in queue"); // mDeleting is not used if NDEBUG is defined, but we always initialize // it to FALSE in the constructors anyway. OsSysLog::add(FAC_KERNEL, PRI_EMERG, "OsTimerTask::removeTimer timer = %p, mApplicationState = %d, mTaskState = %d, mDeleting = %d, mPeriodic = %d, mTimerQueueLink = %p", timer, timer->mApplicationState, timer->mTaskState, timer->mDeleting, timer->mPeriodic, timer->mTimerQueueLink); OsTimer* p; for (p = mTimerQueue; p; p = p->mTimerQueueLink) { OsSysLog::add(FAC_KERNEL, PRI_EMERG, "OsTimerTask::removeTimer in queue %p", p); } OsSysLog::add(FAC_KERNEL, PRI_EMERG, "OsTimerTask::removeTimer end of queue"); } assert(current); *previous_ptr = timer->mTimerQueueLink; // Clear the timer's mTimerQueueLink to indicate it is not in the // timer queue. timer->mTimerQueueLink = 0; } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/OsTLSServerSocket.cpp0000644000175000017500000002077112205613256025106 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifdef SIP_TLS_NSS // SYSTEM INCLUDES #include #include #if defined(_WIN32) # include # include // hack to define int32 for nss-3.9.1 as they have a bug typedef int32_t int32; #undef OsSS_CONST #define OsSS_CONST const #elif defined(_VXWORKS) # include # include # include #elif defined(__pingtel_on_posix__) # include # include # include # include # include # include #else #error Unsupported target platform. #endif #include #include #include #include #include #include #include #include "pk11func.h" // APPLICATION INCLUDES #include "os/OsTLS.h" #include "os/OsTLSServerSocket.h" #include "os/OsTLSServerConnectionSocket.h" #include "os/OsDefs.h" #include "os/OsSysLog.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define SOCKET_LEN_TYPE #ifdef __pingtel_on_posix__ #undef SOCKET_LEN_TYPE #define SOCKET_LEN_TYPE (socklen_t *) #endif // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* Make these what you want for cert & key files */ /* ============================ CREATORS ================================== */ // Constructor OsTLSServerSocket::OsTLSServerSocket(int connectionQueueSize, int serverPort, UtlString certNickname, UtlString certPassword, UtlString dbLocation, const UtlString bindAddress) : OsServerSocket(connectionQueueSize,serverPort, bindAddress.data(), false), mCertNickname(certNickname), mCertPassword(certPassword), mDbLocation(dbLocation), mpMozillaSSLSocket(NULL), mpCert(NULL), mpPrivKey(NULL), mTlsInitCode(TLS_INIT_SUCCESS) { PRSocketOptionData socketOption; PRStatus prStatus; SECStatus secStatus; // import the newly created socket into NSS, and set the PRFileDesc. if (socketDescriptor > OS_INVALID_SOCKET_DESCRIPTOR) { /* Call the NSPR initialization routines. */ PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1); /* Set the cert database password callback. */ PK11_SetPasswordFunc(OsTLS::PasswordCallback); secStatus = NSS_Init(dbLocation.data()); if (secStatus != SECSuccess) { mTlsInitCode = TLS_INIT_DATABASE_FAILURE; return ; } /* Set the policy for this server (REQUIRED - no default). */ secStatus = NSS_SetExportPolicy(); if (secStatus != SECSuccess) { mTlsInitCode = TLS_INIT_DATABASE_FAILURE; return ; } /* Get own certificate and private key. */ mpCert = PK11_FindCertFromNickname((char*) certNickname.data(), (void*)certPassword.data()); if (mpCert == NULL) { return ; } unsigned char* szPwd = (unsigned char*) PR_Malloc(certPassword.length()+ 1); strncpy((char*)szPwd, certPassword.data(), certPassword.length()+1); mpPrivKey = PK11_FindKeyByAnyCert(mpCert, (void*)szPwd); if (mpPrivKey == NULL) { mTlsInitCode = TLS_INIT_BAD_PASSWORD; // probably a wrong password return ; } /* Configure the server's cache for a multi-process application * using default timeout values (24 hrs) and directory location (/tmp). */ SSL_ConfigMPServerSIDCache(256, 0, 0, NULL); mpMozillaSSLSocket = PR_ImportTCPSocket(socketDescriptor); if (!mpMozillaSSLSocket) { mTlsInitCode = TLS_INIT_TCP_IMPORT_FAILURE; } else { /* Make the socket blocking. */ socketOption.option = PR_SockOpt_Nonblocking; socketOption.value.non_blocking = PR_FALSE; prStatus = PR_SetSocketOption(mpMozillaSSLSocket, &socketOption); if (prStatus != PR_SUCCESS) { mTlsInitCode = TLS_INIT_NSS_FAILURE; return; } secStatus = SSL_CipherPrefSetDefault(SSL_RSA_WITH_NULL_MD5, PR_TRUE); if (secStatus != SECSuccess) { mTlsInitCode = TLS_INIT_NSS_FAILURE; return; } PRNetAddr addr; /* Configure the network connection. */ addr.inet.family = PR_AF_INET; addr.inet.ip = inet_addr(bindAddress.data()); addr.inet.port = PR_htons(serverPort); /* Bind the address to the listener socket. */ prStatus = PR_Bind(mpMozillaSSLSocket, &addr); if (prStatus != PR_SUCCESS) { mTlsInitCode = TLS_INIT_NSS_FAILURE; return; } /* Listen for connection on the socket. The second argument is * the maximum size of the queue for pending connections. */ prStatus = PR_Listen(mpMozillaSSLSocket, connectionQueueSize); if (prStatus != PR_SUCCESS) { mTlsInitCode = TLS_INIT_NSS_FAILURE; return; } } } } // Destructor OsTLSServerSocket::~OsTLSServerSocket() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsTLSServerSocket& OsTLSServerSocket::operator=(const OsTLSServerSocket& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } OsConnectionSocket* OsTLSServerSocket::accept() { OsConnectionSocket* newSocket = NULL; if (socketDescriptor == OS_INVALID_SOCKET_DESCRIPTOR) { OsSysLog::add(FAC_KERNEL, PRI_ERR , "OsTLSServerSocket: accept exiting because socketDescriptor is %d" ,socketDescriptor); } else { /* Block while waiting for a client to connect. */ struct sockaddr_in clientSocketAddr; int clientAddrLength = sizeof clientSocketAddr; PRNetAddr addr; PRFileDesc *tcpSocket; PRFileDesc* listenSocket = PR_ImportTCPSocket(socketDescriptor); /* Accept a connection to the socket. */ tcpSocket = PR_Accept(listenSocket, &addr, PR_INTERVAL_NO_TIMEOUT); if (!tcpSocket) { int error = OsSocketGetERRNO(); OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsTLSServerSocket: accept call failed with error: %d=%x", error, error); socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; } else { // need to create a new OsTLSConnectionSocket int socketDescriptor = PR_FileDesc2NativeHandle(tcpSocket); newSocket = new OsTLSServerConnectionSocket(socketDescriptor, mCertNickname, mCertPassword, mDbLocation ); if (newSocket) { } } } return(newSocket); } void OsTLSServerSocket::close() { if (mpMozillaSSLSocket) { PR_Shutdown(mpMozillaSSLSocket, PR_SHUTDOWN_BOTH); PR_Close(mpMozillaSSLSocket); mpMozillaSSLSocket = NULL; socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; } } /* ============================ ACCESSORS ================================= */ int OsTLSServerSocket::getLocalHostPort() const { return(localHostPort); } /* ============================ INQUIRY =================================== */ OsSocket::IpProtocolSocketType OsTLSServerSocket::getIpProtocol() const { return(OsSocket::SSL_SOCKET); } UtlBoolean OsTLSServerSocket::isOk() const { return(socketDescriptor != OS_INVALID_SOCKET_DESCRIPTOR); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ #endif sipxtapi-3.3.0~test17/sipXportLib/src/os/OsTLSConnectionSocket.cpp0000644000175000017500000002551412205613256025737 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifdef SIP_TLS_NSS // SYSTEM INCLUDES #include #include #if defined(_WIN32) # include # include // hack to define int32 for nss-3.9.1 as they have a bug typedef int32_t int32; #elif defined(_VXWORKS) # include # include # include # include #elif defined(__pingtel_on_posix__) # include # include # include # include # include #else #error Unsupported target platform. #endif #include #include #include #include #include "pk11func.h" // APPLICATION INCLUDES #include "os/OsTLS.h" #include "os/OsTLSConnectionSocket.h" #include "os/OsUtil.h" #include "os/OsSysLog.h" #include "os/OsTask.h" #include "os/OsLock.h" #include "os/OsDateTime.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsTLSConnectionSocket::OsTLSConnectionSocket(int socketDescriptor, const UtlString certNickname, const UtlString password, const UtlString dbLocation, long timeoutInSecs ) : OsConnectionSocket(socketDescriptor), mSocketGuard(OsMutex::Q_FIFO), mpPRfd(NULL), mCertNickname(certNickname), mCertPassword(password), mDbLocation(dbLocation), mpPrivKey(NULL), mpCert(NULL), mbHandshakeComplete(false) { OsTLS::Initialize(dbLocation.data()); } // Constructor OsTLSConnectionSocket::OsTLSConnectionSocket(int serverPort, const char* serverName, const UtlString certNickname, const UtlString password, const UtlString dbLocation, long timeoutInSecs, const char* localIp) : OsConnectionSocket(serverPort,serverName, TRUE, localIp, false), mSocketGuard(OsMutex::Q_FIFO), mpPRfd(NULL), mCertNickname(certNickname), mCertPassword(password), mDbLocation(dbLocation), mbHandshakeComplete(false) { OsTLS::Initialize(dbLocation.data()); } // Destructor OsTLSConnectionSocket::~OsTLSConnectionSocket() { // OsLock lock(mSocketGuard) ; OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTLSConnectionSocket::~" ); remoteHostName = OsUtil::NULL_OS_STRING; close(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsTLSConnectionSocket& OsTLSConnectionSocket::operator=(const OsTLSConnectionSocket& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } void OsTLSConnectionSocket::close() { // OsLock lock(mSocketGuard) ; if (socketDescriptor > OS_INVALID_SOCKET_DESCRIPTOR && mpPRfd) { PR_Shutdown(mpPRfd, PR_SHUTDOWN_BOTH); PR_Close(mpPRfd); mpPRfd = NULL; socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; } } UtlBoolean OsTLSConnectionSocket::reconnect() { return FALSE; //TODO } int OsTLSConnectionSocket::write(const char* buffer, int bufferLength) { int bytesWritten = -1; if (mpPRfd) { bytesWritten = PR_Write(mpPRfd, buffer, bufferLength); int nssError = PR_GetError(); // if connection reset by peer, try again if (-5961 == nssError) { OsTask::delay(100); bytesWritten = PR_Write(mpPRfd, buffer, bufferLength); } if (bytesWritten > 0) { UtlString bytes(buffer, bytesWritten); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTLSConnectionSocket::write %s", bytes.data() ); } } return(bytesWritten); } int OsTLSConnectionSocket::write(const char* buffer, int bufferLength, long waitMilliseconds) { int bytesWritten = -1; if(isReadyToWrite(waitMilliseconds)) { bytesWritten = PR_Write(mpPRfd, buffer, bufferLength); int nssError = PR_GetError(); // if connection reset by peer, try again if (-5961 == nssError) { OsTask::delay(100); bytesWritten = PR_Write(mpPRfd, buffer, bufferLength); } if (bytesWritten) { UtlString bytes(buffer, bytesWritten); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTLSConnectionSocket::write %s", bytes.data() ); } } return(bytesWritten); } int OsTLSConnectionSocket::read(char* buffer, int bufferLength) { // Use base class implementation int bytesRead = -1; if (mpPRfd)// && SSL_DataPending(mpPRfd)) { bytesRead = PR_Read (mpPRfd, buffer, bufferLength); } if (bytesRead > 0) { UtlString bytes(buffer, bytesRead); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTLSConnectionSocket::read %s", bytes.data() ); } return(bytesRead); } int OsTLSConnectionSocket::read(char* buffer, int bufferLength, UtlString* ipAddress, int* port) { // Overide base class version as recvfrom does not // seem to return host info correctly for TCP // Use base class version without the remote host info int bytesRead = -1; if (mpPRfd)// && SSL_DataPending(mpPRfd)) { bytesRead = PR_Read (mpPRfd, buffer, bufferLength); } if (bytesRead > 0) { UtlString bytes(buffer, bytesRead); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTLSConnectionSocket::read %s", bytes.data() ); } // Explicitly get the remote host info. getRemoteHostIp(ipAddress); *port = getRemoteHostPort(); return(bytesRead); } // Because we have overided one read method, we // must implement them all in OsTLSServerConnectionSocket or // we end up hiding some of the methods. int OsTLSConnectionSocket::read(char* buffer, int bufferLength, long waitMilliseconds) { int bytesRead = -1; if(isReadyToRead(waitMilliseconds)) { bytesRead = PR_Read (mpPRfd, buffer, bufferLength); if (bytesRead > 0) { UtlString bytes(buffer, bytesRead); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTLSConnectionSocket::read %s", bytes.data() ); } } return(bytesRead); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ OsSocket::IpProtocolSocketType OsTLSConnectionSocket::getIpProtocol() const { return(OsSocket::SSL_SOCKET); } UtlBoolean OsTLSConnectionSocket::isReadyToReadEx(long waitMilliseconds, UtlBoolean &rSocketError) const { return OsConnectionSocket::isReadyToReadEx(waitMilliseconds, rSocketError); } UtlBoolean OsTLSConnectionSocket::isReadyToRead(long waitMilliseconds) const { UtlBoolean bReady = TRUE; UtlBoolean bSocketError = FALSE; bReady = isReadyToReadEx(waitMilliseconds, bSocketError); return bReady; } UtlBoolean OsTLSConnectionSocket::isReadyToWrite(long timeoutMilliSec) const { UtlBoolean readyToWrite = FALSE; return OsSocket::isReadyToWrite(timeoutMilliSec); if (true)//waitForHandshake(timeoutMilliSec)) { PRIntervalTime prTimeout = PR_INTERVAL_NO_WAIT; if(timeoutMilliSec < 0) { prTimeout = PR_INTERVAL_NO_TIMEOUT; } else if(timeoutMilliSec > 0) { prTimeout = PR_SecondsToInterval(timeoutMilliSec / 1000); } PRPollDesc pollDescriptor; pollDescriptor.fd = mpPRfd; pollDescriptor.in_flags = PR_POLL_WRITE | PR_POLL_EXCEPT; pollDescriptor.out_flags = 0; PRInt32 numDescriptorsReady = PR_Poll(&pollDescriptor, 1, // only one descriptor prTimeout); if(numDescriptorsReady > 0) { if(pollDescriptor.out_flags | PR_POLL_WRITE) { readyToWrite = TRUE; } else if(pollDescriptor.out_flags | PR_POLL_ERR) { printf("error polling if NSS SSL socket is ready to write"); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "error polling if NSS SSL socket is ready to write"); } else if(pollDescriptor.out_flags | PR_POLL_NVAL) { printf("invalid NSS SSL socket while polling if ready to write"); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "invalid NSS SSL socket while polling if ready to write"); } else if(pollDescriptor.out_flags | PR_POLL_EXCEPT) { printf("NSS SSL socket exception while polling if ready to write"); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "NSS SSL socket exception while polling if ready to write"); } else { printf("unknown NSS SSL socket state while polling if ready to write"); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "unknown NSS SSL socket state while polling if ready to write"); } } } return(readyToWrite); } bool OsTLSConnectionSocket::waitForHandshake(long milliseconds) const { OsTime start; OsTime now; OsTime end; OsDateTime::getCurTime(start); if (milliseconds < 0) { milliseconds = 30000; } end = OsTime(OsTime(milliseconds) + start); while (!mbHandshakeComplete) { OsDateTime::getCurTime(now); if (now > end) { break; } OsTask::delay(40); } return mbHandshakeComplete; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ #endif sipxtapi-3.3.0~test17/sipXportLib/src/os/OsTLSClientConnectionSocket.cpp0000644000175000017500000002240012205613256027065 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifdef SIP_TLS_NSS // SYSTEM INCLUDES #include #include #if defined(_WIN32) # include # include // hack to define int32 for nss-3.9.1 as they have a bug typedef int32_t int32; #elif defined(_VXWORKS) # include # include # include # include #elif defined(__pingtel_on_posix__) # include # include # include # include # include #else #error Unsupported target platform. #endif #include #include #include #include #include "pk11func.h" // APPLICATION INCLUDES #include "os/OsTLSClientConnectionSocket.h" #include "os/OsUtil.h" #include "os/OsSysLog.h" #include "os/OsTask.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsTLSClientConnectionSocket::OsTLSClientConnectionSocket(int serverPort, const char* serverName, const UtlString certNickname, const UtlString password, const UtlString dbLocation, long timeoutInSecs, const char* localIp, ITlsSink* pSink) : OsTLSConnectionSocket(serverPort,serverName,certNickname,password,dbLocation,timeoutInSecs, localIp), mpTlsSink(pSink) { mCertPassword = password; NSSInitSocket(socketDescriptor, timeoutInSecs, password.data()); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTLSClientConnectionSocket::_(port %d, name '%s', timeout %ld)", serverPort, serverName, timeoutInSecs ); } // Destructor OsTLSClientConnectionSocket::~OsTLSClientConnectionSocket() { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTLSClientConnectionSocket::~" ); remoteHostName = OsUtil::NULL_OS_STRING; close(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsTLSClientConnectionSocket& OsTLSClientConnectionSocket::operator=(const OsTLSClientConnectionSocket& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ void OsTLSClientConnectionSocket::NSSInitSocket(int socket, long timeoutInSecs, const char* szPassword) { PRFileDesc *tcpSocket = NULL; PRSocketOptionData socketOption; PRStatus prStatus; SECStatus secStatus; PRIntn hostenum; PRNetAddr addr; unsigned char* szPwd = NULL; if (socketDescriptor > OS_INVALID_SOCKET_DESCRIPTOR) { mpCert = PK11_FindCertFromNickname((char*)mCertNickname.data(), (char*)mCertPassword.data()); if (mpCert) { szPwd = (unsigned char*) PR_Malloc(mCertPassword.length()+ 1); strncpy((char*)szPwd, mCertPassword.data(), mCertPassword.length()+1); mpPrivKey = PK11_FindKeyByAnyCert(mpCert, (unsigned char*) szPwd); if (mpPrivKey == NULL) { mpTlsSink->onTlsEvent(E_SECURITY_CAUSE_TLS_BAD_PASSWORD); goto TlsFailure; } } tcpSocket = PR_ImportTCPSocket(socketDescriptor); if (tcpSocket) { /* Make the socket blocking. */ socketOption.option = PR_SockOpt_Nonblocking; socketOption.value.non_blocking = PR_FALSE; prStatus = PR_SetSocketOption(tcpSocket, &socketOption); if (prStatus != PR_SUCCESS) { mpTlsSink->onTlsEvent(E_SECURITY_CAUSE_TLS_LIBRARY_FAILURE); goto TlsFailure; } /* Import the socket into the SSL layer. */ mpPRfd = SSL_ImportFD(NULL, tcpSocket); if (!mpPRfd) { mpTlsSink->onTlsEvent(E_SECURITY_CAUSE_TLS_LIBRARY_FAILURE); goto TlsFailure; } OsTLS::setTlsSink(mpPRfd, mpTlsSink); /* Set configuration options. */ secStatus = SSL_OptionSet(mpPRfd, SSL_SECURITY, PR_TRUE); if (secStatus != SECSuccess) { mpTlsSink->onTlsEvent(E_SECURITY_CAUSE_TLS_LIBRARY_FAILURE); goto TlsFailure; } secStatus = SSL_OptionSet(mpPRfd, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE); if (secStatus != SECSuccess) { mpTlsSink->onTlsEvent(E_SECURITY_CAUSE_TLS_LIBRARY_FAILURE); goto TlsFailure; } /* Set SSL callback routines. */ secStatus = SSL_GetClientAuthDataHook(mpPRfd, (SSLGetClientAuthData)OsTLS::GetClientAuthData, (void *)mCertNickname.data()); if (secStatus != SECSuccess) { mpTlsSink->onTlsEvent(E_SECURITY_CAUSE_TLS_LIBRARY_FAILURE); goto TlsFailure; } secStatus = SSL_AuthCertificateHook(mpPRfd, (SSLAuthCertificate)OsTLS::AuthCertificate, (void *)CERT_GetDefaultCertDB()); if (secStatus != SECSuccess) { mpTlsSink->onTlsEvent(E_SECURITY_CAUSE_TLS_LIBRARY_FAILURE); goto TlsFailure; } secStatus = SSL_BadCertHook(mpPRfd, (SSLBadCertHandler)OsTLS::BadCertHandler, NULL); if (secStatus != SECSuccess) { mpTlsSink->onTlsEvent(E_SECURITY_CAUSE_TLS_LIBRARY_FAILURE); goto TlsFailure; } secStatus = SSL_HandshakeCallback(mpPRfd, (SSLHandshakeCallback)OsTLS::HandshakeCallback, (void*)this); if (secStatus != SECSuccess) { mpTlsSink->onTlsEvent(E_SECURITY_CAUSE_TLS_LIBRARY_FAILURE); goto TlsFailure; } secStatus = SSL_SetURL(mpPRfd, remoteHostName.data() ); if (secStatus != SECSuccess) { mpTlsSink->onTlsEvent(E_SECURITY_CAUSE_REMOTE_HOST_UNREACHABLE); goto TlsFailure; } PRHostEnt hostEntry; /* Prepare and setup network connection. */ char buffer[PR_NETDB_BUF_SIZE]; PR_GetHostByName(remoteHostName.data(), buffer, sizeof(buffer), &hostEntry); hostenum = PR_EnumerateHostEnt(0, &hostEntry, remoteHostPort, &addr); prStatus = PR_Connect(mpPRfd, &addr, PR_INTERVAL_NO_TIMEOUT); if (prStatus != PR_SUCCESS) { mpTlsSink->onTlsEvent(E_SECURITY_CAUSE_TLS_CONNECTION_FAILURE); goto TlsFailure; } /* Established SSL connection, ready to send data. */ secStatus = SSL_ResetHandshake(mpPRfd, /* asServer */ PR_FALSE); if (secStatus != SECSuccess) { prStatus = PR_Shutdown(mpPRfd, PR_SHUTDOWN_BOTH); prStatus = PR_Close(mpPRfd); if (prStatus != PR_SUCCESS) { } mpTlsSink->onTlsEvent(E_SECURITY_CAUSE_TLS_HANDSHAKE_FAILURE); goto TlsFailure; } CERTCertificate *pServerCert = SSL_PeerCertificate(mpPRfd); PR_Free(szPwd); } else { mIsConnected = FALSE; OsConnectionSocket::close(); } } TlsFailure: return; } /* ============================ FUNCTIONS ================================= */ #endif sipxtapi-3.3.0~test17/sipXportLib/src/os/OsTokenizer.cpp0000644000175000017500000000654712205613256024063 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// /* This code was taken from a program I wrote some time ago. It parses a string * for whitespace and quotes much like a shell would. Characters enclosed in * quotes are counted as a single token. Extra whitespace at the beginning and * end of the string is removed. The tokenizing function returns a token * structure, which can be used to access the tokens in the original string * (which will have been modified). Once the tokens have been used by the * caller, the token structure must be destroyed to free the token pointers. */ #include #include #include "os/OsTokenizer.h" pt_token_t * parse_tokenize(char * string, int * args) { pt_token_t * first, * t; int which = 0, offset = 0, quoted; first = t = (pt_token_t *) malloc(sizeof(pt_token_t)); if(!t) return NULL; *args = 0; t->string = string; t->offsets = 0; t->next = NULL; while(string[offset]) { while(string[offset] && (string[offset] == ' ' || string[offset] == '\t')) { offset++; } if(!string[offset]) { break; } if((quoted = (string[offset] == '"'))) { offset++; } /* add a token offset */ t->offset[which] = offset; t->offsets = ++which; ++*args; if(which == 8) { t->next = (pt_token_t *) malloc(sizeof(pt_token_t)); if(!t) { parse_kill(first); return NULL; } t = t->next; t->string = string; t->offsets = which = 0; t->next = NULL; } /* scan for end of token */ if(!quoted) { while(string[offset] && string[offset] != ' ' && string[offset] != '\t') { offset++; } } else { while(string[offset] && string[offset] != '"') { offset++; } } if(!string[offset]) { break; } string[offset++] = 0; } return first; } const char * parse_token(pt_token_t * t, int which) { if(t && t->offsets == 1 && which == 1) { return ""; } while(which > 7) { if(t) t = t->next; which -= 8; } if(!t) { return NULL; } if(which >= t->offsets) { return NULL; } return t->string + t->offset[which]; } void parse_kill(pt_token_t * t) { pt_token_t * next; while(t) { next = t->next; free(t); t = next; } } sipxtapi-3.3.0~test17/sipXportLib/src/os/OsUtil.cpp0000644000175000017500000003554112205613305023015 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsIntTypes.h" #include #include #include #include #ifdef __pingtel_on_posix__ #include #endif #ifdef _VXWORKS #include #endif // APPLICATION INCLUDES #include "os/OsExcept.h" #include "os/OsNameDb.h" #include "os/OsUtil.h" #include "os/OsSocket.h" #include "os/OsSysLog.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS const UtlString OsUtil::NULL_OS_STRING; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ // Scans a binary buffer in memory for instances of another binary buffer in memory. char *OsUtil::memscan(const char *lookIn, int lookInLen, const char *lookFor, int lookForLen) { char *found = NULL; if (lookIn != NULL && lookFor != NULL && lookInLen > 0 && lookForLen > 0) { char *p = (char *)memchr(lookIn, lookFor[0], lookInLen); while (p != NULL) { int distanceFromBeginning = (int)(p - lookIn); int distanceToEnd = (int)lookInLen - distanceFromBeginning; if (distanceToEnd < lookForLen) { break; } else if (memcmp(p, lookFor, lookForLen) == 0) { found = (char *)p; break; } else { p = (char *)memchr((const char *)(p + 1), lookFor[0], distanceToEnd); } } } return found; } // Insert a key-value pair into the name database. // The key is constructed by concatenating rPrefix and rName. // If exceptOnErr is TRUE, then upon encountering an error, this method // will throw an exception. This is sometimes useful for indicating an // error from within an object constructor. OsStatus OsUtil::insertKeyValue(const UtlString& rPrefix, const UtlString& rName, const intptr_t value, UtlBoolean exceptOnErr) { OsNameDb* pDict; OsStatus res; assert(rName != "" || rPrefix != ""); pDict = OsNameDb::getNameDb(); UtlString key = rPrefix + rName; res = pDict->insert(key, value); if (exceptOnErr) { switch (res) { case OS_SUCCESS: break; // success, do nothing case OS_NAME_IN_USE: OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsUtil::insertKeyValue - " "name already in use: %s%s", rPrefix.data(), rName.data()); break; default: OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsUtil::insertKeyValue - " "OsStatus = %d", res); break; } } return res; } // Remove the indicated key-value pair from the name database. // The key is constructed by concatenating rPrefix and rName. // If pValue is non-NULL, the value for the key-value pair is returned // via pValue. // Return OS_SUCCESS if the lookup is successful, return // OS_NOT_FOUND if there is no match for the specified key. OsStatus OsUtil::deleteKeyValue(const UtlString& rPrefix, const UtlString& rName, intptr_t* pValue) { OsNameDb* pDict; assert(rName != "" || rPrefix != ""); pDict = OsNameDb::getNameDb(); UtlString key = rPrefix + rName; OsStatus res = pDict->remove(key, pValue); key = OsUtil::NULL_OS_STRING; return res; } // Retrieve the value associated with the specified key. // The key is constructed by concatenating rPrefix and rName. // If pValue is non-NULL, the value is returned via pValue. // Return OS_SUCCESS if the lookup is successful, return // OS_NOT_FOUND if there is no match for the specified key. OsStatus OsUtil::lookupKeyValue(const UtlString& rPrefix, const UtlString& rName, intptr_t* pValue) { OsNameDb* pDict; assert(rName != "" || rPrefix != ""); pDict = OsNameDb::getNameDb(); return pDict?pDict->lookup(rPrefix + rName, pValue):OS_NOT_FOUND; } // Convert the value in rStr to an integer. // Uses strtol() with base==0 to perform the conversion. // Return OS_SUCCESS if the conversion was successful and set rInt to // the converted value in rInt. If the conversion failed, return // OS_FAILED and set rInt to -1. OsStatus OsUtil::convertUtlStringToInt(const UtlString& rStr, int& rInt) { const char *pBegin = rStr.data(); char *pEnd; int i; pBegin = rStr.data(); i = (int) strtol(pBegin, &pEnd, 0); // verify that the string is non-empty and we were able to parse all of it if (*pBegin && *pEnd == 0) { rInt = i; return OS_SUCCESS; } else { rInt = -1; return OS_FAILED; } } // :Check the designated ip address for validity: // 1) 4 octets separated by '.' // 2) Each octet is between 0 and 255 // 3) Address is not 0.0.0.0 or 255.255.255.255 // Return OS_SUCCESS if the addr is valid, otherwise return OS_INVALID OsStatus OsUtil::checkIpAddress(const char* addr) { OsStatus status = OS_INVALID ; if ( OsSocket::isIp4Address(addr) && (strcmp(addr, "0.0.0.0") != 0) && (strcmp(addr, "255.255.255.255") != 0)) { status = OS_SUCCESS ; } return status ; } // :Check the designated netmask for validity: // 1) Between 255.0.0.0 and 255.255.255.254 // Return OS_SUCCESS if the addr is valid, otherwise return OS_INVALID OsStatus OsUtil::checkNetmask(const char* netmask) { OsStatus status = OS_INVALID ; unsigned char octets[4] ; // Make sure this is in the format nnn.nnn.nnn.nnn if (convertIpAddressToOctets(netmask, octets)) { // Check bounds cases: 255.* and last bit must be off if ((octets[0] == 0xFF) && (!(octets[3] & 0x01))) { UtlBoolean bSet = TRUE ; UtlBoolean bError = FALSE ; int i ; // Make sure the mask is contiguous for (i=1;i<4;i++) { for (int j=7; j>=0; j--) { if (bSet) { // Note when we encounter the first non-contiguous set bit if (!(octets[i] & (1 << j))) { bSet = FALSE ; } } else { // Error we if find set bit after an unset bit. if ((octets[i] & (1 << j))) { bError = TRUE ; break ; } } } } if (!bError) status = OS_SUCCESS ; } } return status ; } // :Return TRUE if the destIpAddress is on the same logical network as // myIpAddr given the net mask myNetMask. Returns FALSE otherwise. UtlBoolean OsUtil::isSameNetwork(const char* destIpAddr, const char* myIpAddr, const char* myNetMask) { UtlBoolean bSame = TRUE ; unsigned char octetsDest[4] ; unsigned char octetsIp[4] ; unsigned char octetsNetMask[4] ; int i ; // Sanity Check the input if ( OsUtil::convertIpAddressToOctets(destIpAddr, octetsDest) && OsUtil::convertIpAddressToOctets(myIpAddr, octetsIp) && OsUtil::convertIpAddressToOctets(myNetMask, octetsNetMask)) { // Make sure bits match where the NetMask is set... for (i=0;i<4;i++) { for (int j=7; j>=0; j--) { if (octetsNetMask[i] & (1 << j)) { if ((octetsIp[i] & (1 << j)) != (octetsDest[i] & (1 << j))) { bSame = FALSE ; } } } } } else bSame = FALSE ; return bSame ; } //returns OS_SUCCESS if the host repsonds within timeout OsStatus OsUtil::checkDnsAvailability(char *dnsServer, OsTime timeout) { OsStatus retval = OS_SUCCESS; struct hostent* server; UtlString temp_output_address; # if defined(_VXWORKS) char hostentBuf[512]; # endif # if defined(_WIN32) || defined(__pingtel_on_posix__) server = gethostbyname(dnsServer); # elif defined(_VXWORKS) server = resolvGetHostByName((char*) dnsServer, hostentBuf, sizeof(hostentBuf)); # else # error Unsupported target platform. # endif //_VXWORKS if(! server) { osPrintf("DNS failed to lookup host: %s\n",dnsServer); retval = OS_DNS_UNAVAILABLE; } temp_output_address.remove(0); return retval; } //returns OS_SUCCESS if the host repsonds within timeout OsStatus OsUtil::checkResponsiveDest(char *destHost, OsTime timeout) { OsStatus retval = OS_SUCCESS; return retval; } /* ============================ ACCESSORS ================================= */ //:Return the current date. // An example showing the date format is: "Wed 10/14/98" void OsUtil::getCurDate(UtlString& dateStr, const struct tm* pCurTime, int maxLen) { int len; char str[20]; if (maxLen >= 16) { // Wed Oct 14, 1998 len = strftime(str, 19, "%a %b %d, %Y", pCurTime); // convert all but the first character of the day to lowercase str[1] = tolower(str[1]); str[2] = tolower(str[2]); // convert all but the first character of the month to lowercase str[5] = tolower(str[5]); str[6] = tolower(str[6]); } else if (maxLen >= 12) { // Wed 10/14/98 len = strftime(str, 19, "%a %m/%d/", pCurTime); // :HACK: getting the two digit year this way avoids a silly compiler warning in gcc when you use %y char tmpYear[5]; strftime(tmpYear, 5, "%Y", pCurTime); strcat(str,tmpYear+2); // convert all but the first character of the day to lowercase str[1] = tolower(str[1]); str[2] = tolower(str[2]); } else if (maxLen >= 8) { // 10/14/98 len = strftime(str, 19, "%a %m/%d/", pCurTime); // :HACK: getting the two digit year this way avoids a silly compiler warning in gcc when you use %y char tmpYear[5]; strftime(tmpYear, 5, "%Y", pCurTime); strcat(str,tmpYear+2); } else { str[0] = '\0'; // can't return a useful date } // using less than eight characters dateStr = str; } // Return the current time. // An example showing the time format is: "8:03P" void OsUtil::getCurTime(UtlString& timeStr, const struct tm* pCurTime, int maxLen) { int hour; UtlBoolean isAm; char str[10]; // convert from 24 hour to 12 hour representation hour = pCurTime->tm_hour; isAm = (hour < 12); if (hour == 0) hour = 12; if (hour > 12) hour -= 12; if (maxLen >= 9) { sprintf(str, "%d:%02d:%02d%s", hour, pCurTime->tm_min, pCurTime->tm_sec, isAm ? "A" : "P"); } else if (maxLen >= 6) { sprintf(str, "%d:%02d%s", hour, pCurTime->tm_min, isAm ? "A" : "P"); } else { str[0] = '\0'; // can't return a useful time string } // using less than six characters timeStr = str; } // Return the type of platform we are running on (e.g., PLATFORM_TCAS2) int OsUtil::getPlatformType(void) { int platform; platform = PLATFORM_UNKNOWN; #if defined(_WIN32) /* ] [ */ platform = PLATFORM_WIN32; #elif defined(__APPLE__) platform = PLATFORM_MACOSX; #elif defined(__linux__) /* ] [ */ platform = PLATFORM_LINUX; #elif defined(sun) /* ] [ */ platform = PLATFORM_SOLARIS; #elif defined(ANDROID) /* ] [ */ platform = PLATFORM_ANDROID; #else /* ] [ */ #error Unexpected Platform/CPU type #endif /* ] ]*/ return platform; } int OsUtil::getProductType(void) { int productType = PRODUCT_UNKNOWN; #if defined(_WIN32) || defined(__pingtel_on_posix__) productType = PRODUCT_INSTANT_XPRESSA; #else assert(FALSE); productType = PRODUCT_UNKNOWN; #endif return productType; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ // Convert a nnn.nnn.nnn.nnn ip address string into an array of 4 unsigned // chars. // Returns FALSE on error otherwise TRUE UtlBoolean OsUtil::convertIpAddressToOctets(const char* ipAddr, unsigned char octets[]) { UtlBoolean bSuccess = FALSE ; // Make sure the data is well formed before attempting... if (OsSocket::isIp4Address(ipAddr)){ int index = 0 ; int lastIndex = 0 ; int i ; // The data looks ok, so blindly parse away... UtlString strTest(ipAddr) ; for(i=0; (i<4) && (lastIndex != -1); i++) { if (i > 0) { index = strTest.index(".", lastIndex) ; if (index != -1) index++ ; } if (index != -1) { octets[i] = (unsigned char) strtoul(strTest(index, strTest.length()).data(), NULL, 10) ; } lastIndex = index ; } bSuccess = TRUE ; strTest.remove(0); } return bSuccess ; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/StunMessage.cpp0000644000175000017500000012514412205613256024040 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 Robert J. Andreasen, Jr. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // OS INT TYPES #include "os/OsIntTypes.h" // SYSTEM INCLUDES #include #if defined(__pingtel_on_posix__) # include # include # include # include # include #endif // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsSocket.h" #include "os/OsDatagramSocket.h" #include "os/StunMessage.h" #include "os/TurnMessage.h" #include "utl/UtlCrc32.h" // EXTERNAL FUNCTIONS extern "C" void hmac_sha1(const char* pBlob, size_t nBlob, const char* pKey, size_t nKey, char* digest) ; // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor StunMessage::StunMessage(StunMessage* pRequest, bool bLegacyMode) { mpRawData = NULL ; mbLegacyMode = bLegacyMode ; reset() ; if (pRequest) { STUN_TRANSACTION_ID transactionId ; STUN_MAGIC_ID magicId ; pRequest->getTransactionId(&transactionId) ; pRequest->getMagicId(&magicId) ; setTransactionId(transactionId) ; setMagicId(magicId) ; // Force legacy mode if magicId isn't for bis4+ if (magicId.id != STUN_MAGIC_COOKIE) { mbLegacyMode = true ; } } else { allocTransactionId() ; } } // Destructor StunMessage::~StunMessage() { if (mpRawData) free(mpRawData) ; } /* ============================ MANIPULATORS ============================== */ void StunMessage::reset() { memset(&mMsgHeader, 0, sizeof(STUN_MESSAGE_HEADER)) ; mbMsgHeaderValid = false ; memset(&mMappedAddress, 0, sizeof(STUN_ATTRIBUTE_ADDRESS)) ; mbMappedAddressValid = false ; memset(&mResponseAddress, 0, sizeof(STUN_ATTRIBUTE_ADDRESS)) ; mbResponseAddressValid = false ; memset(&mChangedAddress, 0, sizeof(STUN_ATTRIBUTE_ADDRESS)) ; mbChangedAddressValid = false ; mChangeRequest = 0 ; mbChangeRequestValid = false ; memset(&mSourceAddress, 0, sizeof(STUN_ATTRIBUTE_ADDRESS)) ; mbSourceAddressValid = false ; memset(&mUsername, 0, STUN_MAX_STRING_LENGTH+1) ; mbUsernameValid = false ; memset(&mPassword, 0, STUN_MAX_STRING_LENGTH+1) ; mbPasswordValid = false ; memset(&mRealm, 0, STUN_MAX_STRING_LENGTH+1) ; mbRealmValid = false ; memset(&mNonce, 0, STUN_MAX_STRING_LENGTH+1) ; mbNonceValid = false ; memset(&mMessageIntegrity, 0, sizeof(mMessageIntegrity)) ; mbMessageIntegrityValid = false ; memset(&mError, 0, sizeof(STUN_ATTRIBUTE_ERROR)) ; mbErrorValid = false ; memset(&mUnknownAttributes, 0, sizeof(STUN_ATTRIBUTE_UNKNOWN)) ; mbUnknownAttributesValid = false ; memset(&mReflectedFrom, 0, sizeof(STUN_ATTRIBUTE_ADDRESS)) ; mbReflectedFromValid = false ; memset(&mServer, 0, STUN_MAX_STRING_LENGTH+1) ; mbServerValid = false ; mbSendXorOnly = false ; mbRequestXorOnly = false; mbIncludeMessageIntegrity = false ; memset(&mAltServer, 0, sizeof(STUN_ATTRIBUTE_ADDRESS)) ; mbAltServerValid = false ; mbIncludeFingerPrint = !mbLegacyMode ; mbFingerPrintValid = false ; mFingerPrint = 0 ; free(mpRawData) ; mpRawData = NULL ; mnRawData = 0 ; memset(&mUnknownParsedAttributes, 0, sizeof(STUN_ATTRIBUTE_UNKNOWN)) ; } bool StunMessage::parse(const char* pBuf, size_t nBufLength) { reset() ; bool bValid = false ; if (nBufLength >= sizeof(STUN_MESSAGE_HEADER)) { mnRawData = nBufLength ; mpRawData = (char*) malloc(mnRawData) ; if (mpRawData) memcpy(mpRawData, pBuf, mnRawData) ; else mnRawData = NULL ; char* pTraverse = (char*) pBuf ; // Copy header memcpy(&mMsgHeader, pTraverse, sizeof(STUN_MESSAGE_HEADER)) ; pTraverse += sizeof(STUN_MESSAGE_HEADER) ; mMsgHeader.type = ntohs(mMsgHeader.type) ; mMsgHeader.length = ntohs(mMsgHeader.length) ; mMsgHeader.magicId.id = ntohl(mMsgHeader.magicId.id) ; if (mMsgHeader.magicId.id == STUN_MAGIC_COOKIE) { mbLegacyMode = false ; } // Validate Header / Sanity if ( (nBufLength == (sizeof(STUN_MESSAGE_HEADER) + mMsgHeader.length)) && validateMessageType(mMsgHeader.type)) { bValid = true ; // Loop through each attribute int iBytesLeft = mMsgHeader.length ; while (bValid && (iBytesLeft >= sizeof(STUN_ATTRIBUTE_HEADER))) { STUN_ATTRIBUTE_HEADER header ; memcpy(&header, pTraverse, sizeof(STUN_ATTRIBUTE_HEADER)) ; header.type = ntohs(header.type) ; header.length = ntohs(header.length) ; int paddedLength = mbLegacyMode ? header.length : ((header.length + 3) / 4) * 4 ; pTraverse += sizeof(STUN_ATTRIBUTE_HEADER) ; iBytesLeft -= sizeof(STUN_ATTRIBUTE_HEADER) ; if (header.length <= iBytesLeft) { bValid = parseAttribute(&header, pTraverse) ; pTraverse += paddedLength ; iBytesLeft -= paddedLength ; } else { // Malformed packet: header describes more data then is available bValid = false ; } } if (iBytesLeft != 0) { // Malformed packet: We had bytes left over bValid = false ; } } } return bValid ; } #include bool StunMessage::encode(char* pBuf, size_t nBufLength, size_t& nActualLength) { bool bError = true ; char* pTraverse = pBuf ; size_t nBytesLeft = nBufLength ; // Skip length for Header if (nBufLength >= sizeof(STUN_MESSAGE_HEADER)) { pTraverse += sizeof(STUN_MESSAGE_HEADER) ; nBytesLeft -= sizeof(STUN_MESSAGE_HEADER) ; bError = false ; } // Add Body if (!bError) { bError = encodeBody(pTraverse, nBytesLeft, nActualLength) ; pTraverse += nActualLength ; nActualLength += sizeof(STUN_MESSAGE_HEADER) ; // Make room for message integrity if (mbIncludeMessageIntegrity && isRequestOrNonErrorResponse()) { if (nBytesLeft >= sizeof(STUN_ATTRIBUTE_HEADER) + sizeof(mMessageIntegrity)) { nBytesLeft -= sizeof(STUN_ATTRIBUTE_HEADER) + sizeof(mMessageIntegrity) ; nActualLength += sizeof(STUN_ATTRIBUTE_HEADER) + sizeof(mMessageIntegrity) ; } else { bError = true ; } } // Make room for fingerprint if (mbIncludeFingerPrint && !mbLegacyMode) { if (nBytesLeft >= sizeof(STUN_ATTRIBUTE_HEADER) + sizeof(mFingerPrint)) { nBytesLeft -= sizeof(STUN_ATTRIBUTE_HEADER) + sizeof(mFingerPrint) ; nActualLength += sizeof(STUN_ATTRIBUTE_HEADER) + sizeof(mFingerPrint) ; } else { bError = true ; } } } else { nActualLength = 0 ; } // Added message header w/ correct length if (!bError) { char* pStart = pBuf ; size_t nIgnore = nBufLength ; mMsgHeader.length = (uint16_t) nActualLength - sizeof(STUN_MESSAGE_HEADER) ; bError = !encodeHeader(&mMsgHeader, pStart, nIgnore) ; } // Calc/add message integrity (already made room) if (mbIncludeMessageIntegrity && isRequestOrNonErrorResponse()) { int nSHA1Length = nActualLength - (sizeof(STUN_ATTRIBUTE_HEADER) + sizeof(mMessageIntegrity)) ; if (mbIncludeFingerPrint) { nSHA1Length -= (sizeof(STUN_ATTRIBUTE_HEADER) + sizeof(mFingerPrint)) ; } calculateHmacSha1(pBuf, nSHA1Length, NULL, STUN_MAX_MESSAGE_INTEGRITY_LENGTH, mMessageIntegrity) ; mbMessageIntegrityValid = true ; bError = !(encodeAttributeHeader(ATTR_STUN_MESSAGE_INTEGRITY, sizeof(mMessageIntegrity), pTraverse, nBytesLeft) && encodeRaw(mMessageIntegrity, STUN_MAX_MESSAGE_INTEGRITY_LENGTH, pTraverse, nBytesLeft)) ; } // Add finger print (already made room) if (mbIncludeFingerPrint && !mbLegacyMode) { int nCrcLength = nActualLength - (sizeof(STUN_ATTRIBUTE_HEADER) + sizeof(mFingerPrint)) ; UtlCrc32 crc32 ; crc32.calc((unsigned char*) pBuf, nCrcLength) ; mbFingerPrintValid = true ; bError = !(encodeAttributeHeader(ATTR_STUN_FINGERPRINT, sizeof(mFingerPrint), pTraverse, nBytesLeft) && encodeLong(crc32.getValue(), pTraverse, nBytesLeft)) ; } if (!bError) { mnRawData = nActualLength ; free(mpRawData) ; mpRawData = (char*) malloc(mnRawData) ; if (mpRawData) memcpy(mpRawData, pBuf, mnRawData) ; else mnRawData = 0 ; } return !bError ; } bool StunMessage::encodeBody(char* pBuf, size_t nBufLength, size_t& nBytesUsed) { bool bError = false ; char* pTraverse = pBuf ; size_t nBytesLeft = nBufLength ; // Add Mapped Address if ((!bError) && mbMappedAddressValid) { if (!mbSendXorOnly) { bError = !encodeAttributeAddress(ATTR_STUN_MAPPED_ADDRESS, &mMappedAddress, pTraverse, nBytesLeft) ; } if (!bError) { bError = !encodeXorAttributeAddress(ATTR_STUN_XOR_MAPPED_ADDRESS, &mMappedAddress, pTraverse, nBytesLeft) ; } } // Add Response Address if ((!bError) && mbResponseAddressValid) { bError = !encodeAttributeAddress(ATTR_STUN_RESPONSE_ADDRESS, &mResponseAddress, pTraverse, nBytesLeft) ; } // Add Changed Address if ((!bError) && mbChangedAddressValid) { bError = !encodeAttributeAddress(ATTR_STUN_CHANGED_ADDRESS, &mChangedAddress, pTraverse, nBytesLeft) ; } // Add Change Request if ((!bError) && mbChangeRequestValid) { bError = !(encodeAttributeHeader(ATTR_STUN_CHANGE_REQUEST, sizeof(uint32_t), pTraverse, nBytesLeft) && encodeLong(mChangeRequest, pTraverse, nBytesLeft)) ; } // Add Source Address if ((!bError) && mbSourceAddressValid) { bError = !encodeAttributeAddress(ATTR_STUN_SOURCE_ADDRESS, &mSourceAddress, pTraverse, nBytesLeft) ; } // Add Username if ((!bError) && mbUsernameValid) { bError = !encodeString(ATTR_STUN_USERNAME, mUsername, pTraverse, nBytesLeft) ; } // Add Password if ((!bError) && mbPasswordValid) { bError = !encodeString(ATTR_STUN_PASSWORD, mPassword, pTraverse, nBytesLeft) ; } // Add Realm if ((!bError) && mbRealmValid) { bError = !encodeString(ATTR_STUN_REALM, mRealm, pTraverse, nBytesLeft) ; } // Add Nonce if ((!bError) && mbNonceValid) { bError = !encodeString(ATTR_STUN_NONCE, mNonce, pTraverse, nBytesLeft) ; } // Add Error if ((!bError) && mbErrorValid) { bError = !encodeAttributeError(&mError, pTraverse, nBytesLeft) ; } // Add Unknown Attributes if ((!bError) && mbUnknownAttributesValid) { bError = !encodeAttributesUnknown(&mUnknownAttributes, pTraverse, nBytesLeft) ; } // Add Reflected From if ((!bError) && mbReflectedFromValid) { bError = !encodeAttributeAddress(ATTR_STUN_REFLECTED_FROM, &mReflectedFrom, pTraverse, nBytesLeft) ; } // Add Alt server if ((!bError) && mbAltServerValid) { bError = !encodeAttributeAddress(ATTR_STUN_ALTERNATE_SERVER, &mAltServer, pTraverse, nBytesLeft) ; } // Add server if ((!bError) && mbServerValid) { bError = !encodeString(ATTR_STUN_SERVER, mServer, pTraverse, nBytesLeft) ; } nBytesUsed = nBufLength - nBytesLeft ; return bError ; } void StunMessage::setMagicId(STUN_MAGIC_ID& rMagicId) { memcpy(&mMsgHeader.magicId, &rMagicId, sizeof(STUN_MAGIC_ID)) ; } void StunMessage::setTransactionId(STUN_TRANSACTION_ID& rTransactionId) { memcpy(&mMsgHeader.transactionId, &rTransactionId, sizeof(STUN_TRANSACTION_ID)) ; } void StunMessage::allocTransactionId() { if (mbLegacyMode) mMsgHeader.magicId.id = (STUN_MAGIC_COOKIE ^ 0xAAAAAAAA) ; else mMsgHeader.magicId.id = STUN_MAGIC_COOKIE ; for (int i=0; i<12; i++) { mMsgHeader.transactionId.id[i] = (unsigned char) (mbRandomGenerator.rand() % 0x0100) ; } } void StunMessage::setType(uint16_t type) { mMsgHeader.type = type ; } void StunMessage::setMappedAddress(const char* szIp, const uint16_t port) { mMappedAddress.family = ATTR_ADDRESS_FAMILY_IPV4 ; mMappedAddress.address = ntohl(inet_addr(szIp)) ; mMappedAddress.port = port ; mbMappedAddressValid = true ; } void StunMessage::setResponseAddress(const char* szIp, const uint16_t port) { mResponseAddress.family = ATTR_ADDRESS_FAMILY_IPV4 ; mResponseAddress.address = ntohl(inet_addr(szIp)) ; mResponseAddress.port = port ; mbResponseAddressValid = true ; } void StunMessage::setChangePort(const bool bChange) { if (bChange) { mChangeRequest |= ATTR_CHANGE_FLAG_PORT ; } else { mChangeRequest &= ~ATTR_CHANGE_FLAG_PORT ; } mbChangeRequestValid = true ; } void StunMessage::setChangeIp(const bool bChange) { if (bChange) { mChangeRequest |= ATTR_CHANGE_FLAG_IP ; } else { mChangeRequest &= ~ATTR_CHANGE_FLAG_IP ; } mbChangeRequestValid = true ; } void StunMessage::setSourceAddress(const char* szIp, const uint16_t port) { mSourceAddress.family = ATTR_ADDRESS_FAMILY_IPV4 ; mSourceAddress.address = ntohl(inet_addr(szIp)) ; mSourceAddress.port = port ; mbSourceAddressValid = true ; } void StunMessage::setChangedAddress(const char* szIp, const uint16_t port) { mChangedAddress.family = ATTR_ADDRESS_FAMILY_IPV4 ; mChangedAddress.address = ntohl(inet_addr(szIp)) ; mChangedAddress.port = port ; mbChangedAddressValid = true ; } void StunMessage::setUsername(const char* szUsername) { if (szUsername && strlen(szUsername)) { strncpy(mUsername, szUsername, STUN_MAX_STRING_LENGTH) ; mbUsernameValid = true ; } } void StunMessage::setPassword(const char* szPassword) { if (szPassword && strlen(szPassword)) { strncpy(mPassword, szPassword, STUN_MAX_STRING_LENGTH) ; mbPasswordValid = true ; } } void StunMessage::setRealm(const char* szRealm) { if (szRealm && strlen(szRealm)) { strncpy(mRealm, szRealm, STUN_MAX_STRING_LENGTH) ; mbRealmValid = true ; } } void StunMessage::setNonce(const char* szNonce) { if (szNonce && strlen(szNonce)) { strncpy(mNonce, szNonce, STUN_MAX_STRING_LENGTH) ; mbNonceValid = true ; } } void StunMessage::setError(const uint16_t code, const char* szReason) { mError.errorClass = code / 100 ; mError.errorNumber = code % 100 ; strncpy(mError.szReasonPhrase, szReason, STUN_MAX_STRING_LENGTH) ; mbErrorValid = true ; } void StunMessage::addUnknownAttribute(uint16_t attributeId) { if (mUnknownAttributes.nTypes < STUN_MAX_UNKNOWN_ATTRIBUTES) { mUnknownAttributes.type[mUnknownAttributes.nTypes++] = attributeId ; } mbUnknownAttributesValid = true ; } void StunMessage::setReflectedFrom(const char* szIp, const uint16_t port) { mReflectedFrom.family = ATTR_ADDRESS_FAMILY_IPV4 ; mReflectedFrom.address = ntohl(inet_addr(szIp)) ; mReflectedFrom.port = port ; mbReflectedFromValid = true ; } void StunMessage::setServer(const char* szServer) { if (szServer && strlen(szServer)) { strncpy(mServer, szServer, STUN_MAX_STRING_LENGTH) ; mbServerValid = true ; } } void StunMessage::setRequestXorOnly() { mbRequestXorOnly = true ; } void StunMessage::setSendXorOnly() { mbSendXorOnly = true ; } void StunMessage::setIncludeMessageIntegrity(bool bInclude) { mbIncludeMessageIntegrity = bInclude ; } void StunMessage::setIncludeFingerPrint(bool bInclude) { mbIncludeFingerPrint = bInclude ; } void StunMessage::setAltServer(const char* szIp, uint16_t port) { mAltServer.family = ATTR_ADDRESS_FAMILY_IPV4 ; mAltServer.address = ntohl(inet_addr(szIp)) ; mAltServer.port = port ; mbAltServerValid = true ; } /* ============================ ACCESSORS ================================= */ void StunMessage::getMagicId(STUN_MAGIC_ID* pMagic) { memcpy(pMagic, &mMsgHeader.magicId, sizeof(STUN_MAGIC_ID)) ; } void StunMessage::getTransactionId(STUN_TRANSACTION_ID* pTransactionId) { memcpy(pTransactionId, &mMsgHeader.transactionId, sizeof(STUN_TRANSACTION_ID)) ; } uint16_t StunMessage::getType() { return mMsgHeader.type ; } bool StunMessage::getMappedAddress(char* szIp, uint16_t& rPort) { if (mbMappedAddressValid) { uint32_t address = htonl(mMappedAddress.address) ; strcpy(szIp, inet_ntoa(*((in_addr*) &address))) ; rPort = mMappedAddress.port ; } return mbMappedAddressValid ; } bool StunMessage::getResponseAddress(char* szIp, uint16_t& rPort) { if (mbResponseAddressValid) { uint32_t address = htonl(mResponseAddress.address) ; strcpy(szIp, inet_ntoa(*((in_addr*) &address))) ; rPort = mResponseAddress.port ; } return mbResponseAddressValid ; } bool StunMessage::getChangePort() { bool bChange = false ; if (mbChangeRequestValid) { if (mChangeRequest & ATTR_CHANGE_FLAG_PORT) { bChange = true ; } } return bChange ; } bool StunMessage::getChangeIp() { bool bChange = false ; if (mbChangeRequestValid) { if (mChangeRequest & ATTR_CHANGE_FLAG_IP) { bChange = true ; } } return bChange ; } bool StunMessage::getSourceAddress(char* szIp, uint16_t& rPort) { if (mbSourceAddressValid) { uint32_t address = htonl(mSourceAddress.address) ; strcpy(szIp, inet_ntoa(*((in_addr*) &address))) ; rPort = mSourceAddress.port ; } return mbSourceAddressValid ; } bool StunMessage::getChangedAddress(char* szIp, uint16_t& rPort) { if (mbChangedAddressValid) { uint32_t address = htonl(mChangedAddress.address) ; strcpy(szIp, inet_ntoa(*((in_addr*) &address))) ; rPort = mChangedAddress.port ; } return mbChangedAddressValid ; } bool StunMessage::getUsername(char* szUsername) { if (mbUsernameValid) { strncpy(szUsername, mUsername, STUN_MAX_STRING_LENGTH) ; } return mbUsernameValid ; } bool StunMessage::getPassword(char* szPassword) { if (mbPasswordValid) { strncpy(szPassword, mPassword, STUN_MAX_STRING_LENGTH) ; } return mbPasswordValid ; } bool StunMessage::getRealm(char* szRealm) { if (mbRealmValid) { strncpy(szRealm, mRealm, STUN_MAX_STRING_LENGTH) ; } return mbRealmValid ; } bool StunMessage::getNonce(char* szNone) { if (mbNonceValid) { strncpy(szNone, mNonce, STUN_MAX_STRING_LENGTH) ; } return mbNonceValid ; } bool StunMessage::getMessageIntegrity(char* cMessageIntegrity) { if (mbMessageIntegrityValid) { memcpy(cMessageIntegrity, mMessageIntegrity, STUN_MAX_MESSAGE_INTEGRITY_LENGTH) ; } return mbMessageIntegrityValid ; } bool StunMessage::getError(uint16_t& rCode, char* szReason) { if (mbErrorValid) { rCode = mError.errorClass * 100 + mError.errorNumber ; strncpy(szReason, mError.szReasonPhrase, STUN_MAX_STRING_LENGTH) ; } return mbErrorValid ; } bool StunMessage::getUnknownAttributes(uint16_t* pList, size_t nMaxItems, size_t& nActualItems) { nActualItems = 0 ; if (mbUnknownAttributesValid) { nActualItems = sipx_min(nMaxItems, mUnknownAttributes.nTypes) ; for (size_t i=0; i 0) ; } bool StunMessage::getAltServer(char* szIp, uint16_t& rPort) { if (mbAltServerValid) { uint32_t address = htonl(mAltServer.address) ; strcpy(szIp, inet_ntoa(*((in_addr*) &address))) ; rPort = mAltServer.port ; } return mbAltServerValid ; } /* ============================ INQUIRY =================================== */ bool StunMessage::validateMessageType(uint16_t type) { bool bValid = false ; switch (type) { case MSG_STUN_BIND_REQUEST: case MSG_STUN_BIND_RESPONSE: case MSG_STUN_BIND_ERROR_RESPONSE: case MSG_STUN_SHARED_SECRET_REQUEST: case MSG_STUN_SHARED_SECRET_RESPONSE: case MSG_STUN_SHARED_SECRET_ERROR_RESPONSE: bValid = true ; break ; default: break ; } return bValid ; } bool StunMessage::isStunMessage(const char* pBuf, uint16_t nBufLength) { bool bValid = false ; if (nBufLength >= sizeof(STUN_MESSAGE_HEADER)) { STUN_MESSAGE_HEADER header ; char* pTraverse = (char*) pBuf ; // Copy header memcpy(&header, pTraverse, sizeof(STUN_MESSAGE_HEADER)) ; header.type = ntohs(header.type) ; header.length = ntohs(header.length) ; if (nBufLength == (sizeof(STUN_MESSAGE_HEADER) + header.length)) { switch (header.type) { case MSG_STUN_BIND_REQUEST: case MSG_STUN_SHARED_SECRET_REQUEST: // Is using bis4+, finger print is required with magic // cookie if (ntohl(header.magicId.id) == (uint32_t) STUN_MAGIC_COOKIE) { bValid = isFingerPrintValid(pBuf, nBufLength, false) ; } else { // Legacy Mode bValid = true ; } break ; case MSG_STUN_BIND_RESPONSE: case MSG_STUN_BIND_ERROR_RESPONSE: case MSG_STUN_SHARED_SECRET_RESPONSE: case MSG_STUN_SHARED_SECRET_ERROR_RESPONSE: if (ntohl(header.magicId.id) == (uint32_t) STUN_MAGIC_COOKIE) { // Not requiring the FINGERPRINT in responses to // provide some backwards compatibility -- in reality, // the other side should complain about the // FINGERPRINT -- so this only impacts servers which // ignore the unknown attribute. bValid = isFingerPrintValid(pBuf, nBufLength, true) ; } else { // Legacy Mode bValid = true ; } break ; default: break ; } } } return bValid ; } bool StunMessage::isFingerPrintValid(const char* pBuf, uint16_t nBufLength, bool bMissingOk) { bool bValid = false ; // Make sure we have enough room to check for the finger print if ( pBuf && (nBufLength >= (sizeof(STUN_MESSAGE_HEADER) + sizeof(STUN_ATTRIBUTE_HEADER) + sizeof(uint32_t)))) { // Assume this is the last parameter (required) const char* pLoc = pBuf + (nBufLength - (sizeof(STUN_ATTRIBUTE_HEADER) + sizeof(uint32_t))) ; // Make sure the attributes indicate a FingerPrint STUN_ATTRIBUTE_HEADER* pHeader = (STUN_ATTRIBUTE_HEADER*) pLoc ; if ((ntohs(pHeader->type) == ATTR_STUN_FINGERPRINT) && ntohs(pHeader->length) == sizeof(uint32_t)) { uint32_t fingerPrintValue = 0 ; memcpy(&fingerPrintValue, ((char*) pHeader) + sizeof(STUN_ATTRIBUTE_HEADER), sizeof(uint32_t)) ; fingerPrintValue = ntohl(fingerPrintValue) ; UtlCrc32 crc32 ; crc32.calc((unsigned char*) pBuf, pLoc-pBuf) ; if (crc32.getValue() == fingerPrintValue) { bValid = true ; } } else if ((ntohs(pHeader->type) != ATTR_STUN_FINGERPRINT) && bMissingOk) { bValid = true ; } } return bValid ; } bool StunMessage::isRequestOrNonErrorResponse() { bool bRequestOrNonErrorResponse ; switch (getType()) { case MSG_STUN_BIND_REQUEST: case MSG_STUN_BIND_RESPONSE: case MSG_STUN_SHARED_SECRET_REQUEST: case MSG_STUN_SHARED_SECRET_RESPONSE: bRequestOrNonErrorResponse = true ; break ; case MSG_STUN_BIND_ERROR_RESPONSE: case MSG_STUN_SHARED_SECRET_ERROR_RESPONSE: default: bRequestOrNonErrorResponse = false ; break ; } return bRequestOrNonErrorResponse ; } bool StunMessage::isMessageIntegrityValid(const char* cPassword, size_t nPassword) { return false ; } bool StunMessage::isFingerPrintValid() { bool bValid = isFingerPrintValid(mpRawData, mnRawData, false) ; return bValid ; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ bool StunMessage::encodeByte(char c, char*& pBuf, size_t& nBytesLeft) { bool bRC = false ; if (nBytesLeft >= sizeof(char)) { *pBuf = c ; nBytesLeft -= sizeof(char) ; pBuf += sizeof(char) ; bRC = true ; } return bRC ; } bool StunMessage::encodeShort(uint16_t value, char*& pBuf, size_t& nBytesLeft) { bool bRC = false ; if (nBytesLeft >= sizeof(uint16_t)) { value = htons(value) ; memcpy(pBuf, &value, sizeof(uint16_t)) ; nBytesLeft -= sizeof(uint16_t) ; pBuf += sizeof(uint16_t) ; bRC = true ; } return bRC ; } bool StunMessage::encodeLong(uint32_t value, char*& pBuf, size_t& nBytesLeft) { bool bRC = false ; if (nBytesLeft >= sizeof(uint32_t)) { value = htonl(value) ; memcpy(pBuf, &value, sizeof(uint32_t)) ; nBytesLeft -= sizeof(uint32_t) ; pBuf += sizeof(uint32_t) ; bRC = true ; } return bRC ; } bool StunMessage::encodeRaw(const char* cRaw, size_t length, char*& pBuf, size_t& nBytesLeft) { bool bRC = false ; if (nBytesLeft >= length) { if (length > 0) { memcpy(pBuf, cRaw, length) ; nBytesLeft -= length ; pBuf += length ; } bRC = true ; } return bRC ; } bool StunMessage::encodeHeader(STUN_MESSAGE_HEADER* pHeader, char*& pBuf, size_t& nBytesLeft) { bool bRC = false ; if ( (nBytesLeft >= sizeof(STUN_MESSAGE_HEADER)) && encodeShort(pHeader->type, pBuf, nBytesLeft) && encodeShort(pHeader->length, pBuf, nBytesLeft) && encodeLong(pHeader->magicId.id, pBuf, nBytesLeft) && encodeRaw((char*) pHeader->transactionId.id, sizeof(STUN_TRANSACTION_ID), pBuf, nBytesLeft)) { bRC = true ; } return bRC ; } bool StunMessage::encodeAttributeHeader(int16_t type, int16_t length, char*& pBuf, size_t& nBytesLeft) { bool bRC = false ; if ( (nBytesLeft >= sizeof(STUN_ATTRIBUTE_HEADER)) && encodeShort(type, pBuf, nBytesLeft) && encodeShort(length, pBuf, nBytesLeft)) { bRC = true ; } return bRC ; } bool StunMessage::encodeAttributeAddress(uint16_t type, STUN_ATTRIBUTE_ADDRESS* pAddress, char*& pBuf, size_t& nBytesLeft) { bool bRC = false ; if ( (nBytesLeft >= (sizeof(STUN_ATTRIBUTE_ADDRESS) + sizeof(STUN_ATTRIBUTE_HEADER))) && encodeAttributeHeader(type, sizeof(STUN_ATTRIBUTE_ADDRESS), pBuf, nBytesLeft) && encodeByte(pAddress->unused, pBuf, nBytesLeft) && encodeByte(pAddress->family, pBuf, nBytesLeft) && encodeShort(pAddress->port, pBuf, nBytesLeft) && encodeLong(pAddress->address, pBuf, nBytesLeft)) { bRC = true ; } return bRC ; } bool StunMessage::encodeXorAttributeAddress(uint16_t type, STUN_ATTRIBUTE_ADDRESS* pAddress, char*& pBuf, size_t& nBytesLeft) { bool bRC = false ; uint16_t usPort = pAddress->port ; uint32_t ulLong = pAddress->address ; usPort = htons(usPort) ^ ((uint16_t) (htonl(mMsgHeader.magicId.id) & 0x0000FFFF)) ; ulLong = htonl(ulLong) ^ htonl(mMsgHeader.magicId.id) ; if ( (nBytesLeft >= (sizeof(STUN_ATTRIBUTE_ADDRESS) + sizeof(STUN_ATTRIBUTE_HEADER))) && encodeAttributeHeader(type, sizeof(STUN_ATTRIBUTE_ADDRESS), pBuf, nBytesLeft) && encodeByte(pAddress->unused, pBuf, nBytesLeft) && encodeByte(pAddress->family, pBuf, nBytesLeft) && encodeRaw((const char*) &usPort, 2, pBuf, nBytesLeft) && encodeRaw((const char*) &ulLong, 4, pBuf, nBytesLeft)) { bRC = true ; } return bRC ; } bool StunMessage::encodeString(uint16_t type, const char* szString, char*& pBuf, size_t& nBytesLeft) { bool bRC = false ; if (mbLegacyMode) { size_t nActualLength ; size_t nPaddedLength ; char cPadding[STUN_MIN_CHAR_PAD] ; nActualLength = strlen(szString) ; nPaddedLength = ((nActualLength + (STUN_MIN_CHAR_PAD-1)) / STUN_MIN_CHAR_PAD) * STUN_MIN_CHAR_PAD ; memset(cPadding, 0x20, sizeof(cPadding)) ; if ( (nBytesLeft >= (nPaddedLength + sizeof(STUN_ATTRIBUTE_HEADER))) && encodeAttributeHeader(type, (int16_t) nPaddedLength, pBuf, nBytesLeft) && encodeRaw(szString, nActualLength, pBuf, nBytesLeft) && encodeRaw(cPadding, nPaddedLength - nActualLength, pBuf, nBytesLeft)) { bRC = true ; } } else { size_t nActualLength ; size_t nPaddedLength ; char cPadding[STUN_MIN_CHAR_PAD] ; nActualLength = strlen(szString) ; nPaddedLength = ((nActualLength + (STUN_MIN_CHAR_PAD-1)) / STUN_MIN_CHAR_PAD) * STUN_MIN_CHAR_PAD ; memset(cPadding, 0x00, sizeof(cPadding)) ; if ( (nBytesLeft >= (nPaddedLength + sizeof(STUN_ATTRIBUTE_HEADER))) && encodeAttributeHeader(type, (int16_t) nActualLength, pBuf, nBytesLeft) && encodeRaw(szString, nActualLength, pBuf, nBytesLeft) && encodeRaw(cPadding, nPaddedLength - nActualLength, pBuf, nBytesLeft)) { bRC = true ; } } return bRC ; } bool StunMessage::encodeAttributeError(STUN_ATTRIBUTE_ERROR* pError, char*& pBuf, size_t& nBytesLeft) { bool bRC = false; size_t nReason = strlen(pError->szReasonPhrase) ; size_t nPaddedReason = ((nReason + (STUN_MIN_CHAR_PAD-1)) / STUN_MIN_CHAR_PAD) * STUN_MIN_CHAR_PAD ; char cPad[STUN_MIN_CHAR_PAD] ; size_t nTotalLength = sizeof(STUN_ATTRIBUTE_HEADER) + nPaddedReason + 4 ; memset(cPad, 0, sizeof(cPad)) ; if ( (nBytesLeft >= nTotalLength) && encodeAttributeHeader(ATTR_STUN_ERROR_CODE, (int16_t) nTotalLength - sizeof(STUN_ATTRIBUTE_HEADER), pBuf, nBytesLeft) && encodeShort(pError->unused, pBuf, nBytesLeft) && encodeByte(pError->errorClass & 0x0F, pBuf, nBytesLeft) && encodeByte(pError->errorNumber, pBuf, nBytesLeft) && encodeRaw(pError->szReasonPhrase, nReason, pBuf, nBytesLeft) && encodeRaw(cPad, nPaddedReason - nReason, pBuf, nBytesLeft)) { bRC = true ; } return bRC ; } bool StunMessage::encodeAttributesUnknown(STUN_ATTRIBUTE_UNKNOWN* pAttributes, char*& pBuf, size_t& nBytesLeft) { bool bRC = false; size_t nAttributes = pAttributes->nTypes ; size_t nPaddedAttributes = ((nAttributes + 1) / 2) * 2 ; if (nBytesLeft >= (sizeof(STUN_ATTRIBUTE_HEADER) + nPaddedAttributes * sizeof(uint16_t))) { // Repeat last attribute if an odd number if (nPaddedAttributes != nAttributes) { pAttributes->type[nPaddedAttributes] = pAttributes->type[nAttributes] ; } bRC = encodeAttributeHeader(ATTR_STUN_UNKNOWN_ATTRIBUTE, (int16_t) (nPaddedAttributes * sizeof(uint16_t)), pBuf, nBytesLeft) ; for (size_t i = 0; (itype[i], pBuf, nBytesLeft) ; } } return bRC ; } bool StunMessage::parseAttribute(STUN_ATTRIBUTE_HEADER* pHeader, char* pBuf) { bool bValid = false ; switch (pHeader->type) { case ATTR_STUN_MAPPED_ADDRESS: if (!mbMappedAddressValid) { bValid = parseAddressAttribute(pBuf, pHeader->length, &mMappedAddress) ; mbMappedAddressValid = bValid ; } else { bValid = true ; } break ; case ATTR_STUN_RESPONSE_ADDRESS: bValid = parseAddressAttribute(pBuf, pHeader->length, &mResponseAddress) ; mbResponseAddressValid = bValid ; break ; case ATTR_STUN_CHANGE_REQUEST: bValid = parseLongAttribute(pBuf, pHeader->length, &mChangeRequest) ; mbChangeRequestValid = bValid ; break ; case ATTR_STUN_SOURCE_ADDRESS: bValid = parseAddressAttribute(pBuf, pHeader->length, &mSourceAddress) ; mbSourceAddressValid = bValid ; break ; case ATTR_STUN_CHANGED_ADDRESS: bValid = parseAddressAttribute(pBuf, pHeader->length, &mChangedAddress) ; mbChangedAddressValid = bValid ; break ; case ATTR_STUN_USERNAME: bValid = parseStringAttribute(pBuf, pHeader->length, mUsername) ; mbUsernameValid = bValid ; break ; case ATTR_STUN_PASSWORD: bValid = parseStringAttribute(pBuf, pHeader->length, mPassword) ; mbPasswordValid = bValid ; break ; case ATTR_STUN_REALM: bValid = parseStringAttribute(pBuf, pHeader->length, mRealm) ; mbRealmValid = bValid ; break ; case ATTR_STUN_NONCE: bValid = parseStringAttribute(pBuf, pHeader->length, mNonce) ; mbNonceValid = bValid ; break ; case ATTR_STUN_MESSAGE_INTEGRITY: bValid = parseRawAttribute(pBuf, pHeader->length, mMessageIntegrity, sizeof(mMessageIntegrity)) ; mbMessageIntegrityValid = bValid ; break ; case ATTR_STUN_FINGERPRINT: bValid = parseLongAttribute(pBuf, pHeader->length, &mFingerPrint) ; mbFingerPrintValid = bValid ; break ; case ATTR_STUN_ERROR_CODE: bValid = parseErrorAttribute(pBuf, pHeader->length, &mError) ; mbErrorValid = bValid ; break ; case ATTR_STUN_UNKNOWN_ATTRIBUTE: bValid = parseUnknownAttribute(pBuf, pHeader->length, &mUnknownAttributes) ; mbUnknownAttributesValid = bValid ; break ; case ATTR_STUN_REFLECTED_FROM: bValid = parseAddressAttribute(pBuf, pHeader->length, &mReflectedFrom) ; mbReflectedFromValid = bValid ; break ; case ATTR_STUN_XOR_MAPPED_ADDRESS: case ATTR_STUN_XOR_MAPPED_ADDRESS2: bValid = parseXorAddressAttribute(pBuf, pHeader->length, &mMappedAddress) ; mbMappedAddressValid = bValid ; break ; case ATTR_STUN_XOR_ONLY: mbRequestXorOnly = true ; bValid = true ; break ; case ATTR_STUN_SERVER: case ATTR_STUN_SERVER2: bValid = parseStringAttribute(pBuf, pHeader->length, mServer) ; mbServerValid = bValid ; break ; case ATTR_STUN_ALTERNATE_SERVER: case ATTR_STUN_ALTERNATE_SERVER2: bValid = parseAddressAttribute(pBuf, pHeader->length, &mAltServer) ; mbAltServerValid = bValid ; break ; default: if ((pHeader->type <= 0x7FFF) && (mUnknownParsedAttributes.nTypes < STUN_MAX_UNKNOWN_ATTRIBUTES)) { mUnknownParsedAttributes.type[mUnknownParsedAttributes.nTypes++] = pHeader->type ; } break ; } return bValid ; } bool StunMessage::parseAddressAttribute(char *pBuf, size_t nLength, STUN_ATTRIBUTE_ADDRESS* pAddress) { bool bValid = false ; if (nLength == sizeof(STUN_ATTRIBUTE_ADDRESS)) { memcpy(pAddress, pBuf, sizeof(STUN_ATTRIBUTE_ADDRESS)) ; pAddress->port = ntohs(pAddress->port) ; pAddress->address = ntohl(pAddress->address) ; bValid = true ; } return bValid ; } bool StunMessage::parseXorAddressAttribute(char *pBuf, size_t nLength, STUN_ATTRIBUTE_ADDRESS* pAddress) { bool bValid = false ; if (nLength == sizeof(STUN_ATTRIBUTE_ADDRESS)) { memcpy(pAddress, pBuf, sizeof(STUN_ATTRIBUTE_ADDRESS)) ; pAddress->port ^= (uint16_t) (htonl(mMsgHeader.magicId.id) & 0x0000FFFF) ; pAddress->address ^= htonl(mMsgHeader.magicId.id) ; pAddress->port = ntohs(pAddress->port) ; pAddress->address = ntohl(pAddress->address) ; bValid = true ; } return bValid ; } bool StunMessage::parseShortAttribute(char *pBuf, size_t nLength, uint16_t* pShort) { bool bValid = false ; if (nLength == sizeof(uint16_t)) { memcpy(pShort, pBuf, sizeof(uint16_t)) ; *pShort = ntohs(*pShort) ; bValid = true ; } return bValid ; } bool StunMessage::parseLongAttribute(char *pBuf, size_t nLength, uint32_t* pLong) { bool bValid = false ; if (nLength == sizeof(uint32_t)) { memcpy(pLong, pBuf, sizeof(uint32_t)) ; *pLong = ntohl(*pLong) ; bValid = true ; } return bValid ; } bool StunMessage::parseStringAttribute(char* pBuf, size_t nLength, char* pString) { bool bValid = false ; if (nLength > 0) { memset(pString, 0, STUN_MAX_STRING_LENGTH+1) ; memcpy(pString, pBuf, sipx_min(nLength, STUN_MAX_STRING_LENGTH)) ; if (mbLegacyMode && strlen(pString)) { // Strip trailing spaces char* szEnd = pString + (strlen(pString) - 1) ; while (szEnd >= pString && *szEnd == 0x20) { *szEnd-- = 0 ; } } bValid = true ; } return bValid ; } bool StunMessage::parseRawAttribute(char* pBuf, size_t nLength, char* pDest, size_t nDest) { bool bValid = false ; if (nLength == nDest) { memcpy(pDest, pBuf, nDest) ; bValid = true ; } return bValid ; } bool StunMessage::parseErrorAttribute(char *pBuf, size_t nLength, STUN_ATTRIBUTE_ERROR* pError) { bool bValid = false ; if (nLength > sizeof(uint32_t) && ((nLength % STUN_MIN_CHAR_PAD) == 0)) { pError->unused = 0 ; pError->unused2 = 0 ; pBuf += 2 ; pError->errorClass = (*pBuf++ & 0xF0) ; pError->errorNumber = *pBuf++ ; nLength -= 4 ; memset(pError->szReasonPhrase, 0, STUN_MAX_STRING_LENGTH+1) ; memcpy(pError->szReasonPhrase, pBuf, sipx_min(nLength, STUN_MAX_STRING_LENGTH)) ; bValid = true ; } return bValid ; } bool StunMessage::parseUnknownAttribute(char* pBuf, size_t nLength, STUN_ATTRIBUTE_UNKNOWN* pAttributes) { bool bValid = false ; if ((nLength > 0) && ((nLength % STUN_MIN_CHAR_PAD) == 0)) { size_t i ; uint16_t* pShort = (uint16_t*) pBuf ; for (i=0; (itype[i] = *pShort++ ; } pAttributes->nTypes = i ; bValid = true ; } return bValid ; } // zero pads to 64 boundry and results will be 20 bytes long for hmac/sha1 void StunMessage::calculateHmacSha1(const char* pDataIn, size_t nDataIn, const char* pKey, size_t nKey, char results[20]) { size_t nPaddedLength = ((nDataIn + 63) / 64) * 64 ; char* pTempBuf = (char*) malloc(nPaddedLength) ; memset(pTempBuf, 0, nPaddedLength) ; memcpy(pTempBuf, pDataIn, nDataIn) ; memset(results, 0, 20) ; hmac_sha1(pTempBuf, nPaddedLength, pKey, nKey, results) ; free(pTempBuf) ; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/os/StunUtils.cpp0000644000175000017500000004353012205613256023552 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // OS INT TYPES #include "os/OsIntTypes.h" // SYSTEM INCLUDES #if defined(__pingtel_on_posix__) # include # include # include # include # include #endif #include // APPLICATION INCLUDES #include "os/StunUtils.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ STUN_NAT_TYPE StunUtils::determineStunNatType(const char* szServer, const int port) { OsDatagramSocket* pSocket = new OsDatagramSocket(0, NULL, 0, NULL) ; StunMessage msg ; UtlString stunIp ; UtlString localIp; STUN_NAT_TYPE rc = STUN_NAT_ERROR_BAD_SERVER ; char cMappedIp[64] ; uint16_t usMappedPort ; char cChangedIp[64] ; uint16_t usChangedPort ; OsSocket::getHostIp(&localIp) ; if (OsSocket::getHostIpByName(szServer, &stunIp)) { if (sendStunNatTest(pSocket, stunIp, port, false, false, cMappedIp, &usMappedPort, cChangedIp, &usChangedPort)) { if ((localIp.compareTo(cMappedIp) == 0) && usMappedPort == pSocket->getLocalHostPort()) { if (sendStunNatTest(pSocket, stunIp, port, true, true, NULL, NULL, NULL, NULL)) { rc = STUN_NAT_OPEN ; } else { rc = STUN_NAT_SYMMETRIC_FIREWALL ; } } else { if (sendStunNatTest(pSocket, stunIp, port, true, true, cMappedIp, &usMappedPort, NULL, NULL)) { rc = STUN_NAT_FULL_CONE ; } else { char cMappedIp2[64] ; uint16_t usMappedPort2 ; if (sendStunNatTest(pSocket, cChangedIp, usChangedPort, false, false, cMappedIp2, &usMappedPort2, NULL, NULL)) { // Check mapped IP if ((strcmp(cMappedIp, cMappedIp2) == 0) && (usMappedPort2 == usMappedPort)) { rc = STUN_NAT_SYMMETRIC ; } else { // Send Test III if (sendStunNatTest(pSocket, cChangedIp, usChangedPort, true, false, NULL, NULL, NULL, NULL)) { rc = STUN_NAT_RESTRICTED_CONE ; } else { rc = STUN_NAT_PORT_RESTRICTED_CONE ; } } } else { // UNKNOWN -- what does this mean? assert(false) ; } } } } else { rc = STUN_NAT_BLOCKED ; } } delete pSocket ; return rc ; } bool StunUtils::allocateTurnAddress(OsDatagramSocket* pSocket, const char* szServerIp, const int port, char* szRelayIp, uint16_t* piRelayPort, uint32_t* plLifetime) { bool bSuccess = false ; TurnMessage msgSend ; size_t nLength ; char cMsgSend[2048] ; TurnMessage msgReceive ; char cMsgReceive[2048] ; msgSend.allocTransactionId() ; msgSend.setType(MSG_TURN_ALLOCATE_REQUEST) ; msgSend.setRequestXorOnly() ; if (msgSend.encode(cMsgSend, sizeof(cMsgSend), nLength)) { for (int i=0; (i<3) && (bSuccess == false); i++) { if (pSocket->write(cMsgSend, (int) nLength, szServerIp, port) > 0) { if (pSocket->isReadyToRead(500)) { int length = pSocket->read(cMsgReceive, sizeof(cMsgReceive)) ; if ((length > 0) && msgReceive.parse(cMsgReceive, length)) { if (msgReceive.getType() == MSG_TURN_ALLOCATE_RESPONSE) { bSuccess = true ; // Get optional mapped address if (szRelayIp && piRelayPort) { msgReceive.getMappedAddress(szRelayIp, *piRelayPort) ; } if (plLifetime) { msgReceive.getLifetime(*plLifetime) ; } } else { // Abort on error response break ; } } } } else { break ; } } } else { assert(false) ; } return bSuccess ; } bool StunUtils::sendStunNatTest(OsDatagramSocket* pSocket, const char* szServerIp, const int port, bool bChangePort, bool bChangeIP, char* szMappedIp, uint16_t* piMappedPort, char* szChangedIp, uint16_t* piChangedPort) { StunMessage msgSend ; char cMsgSend[2048] ; StunMessage msgReceive ; char cMsgReceive[2048] ; size_t nLength ; bool bSuccess = false ; msgSend.setType(MSG_STUN_BIND_REQUEST) ; msgSend.allocTransactionId() ; msgSend.setRequestXorOnly() ; if (bChangePort) { msgSend.setChangePort(true) ; } if (bChangeIP) { msgSend.setChangeIp(true) ; } if (msgSend.encode(cMsgSend, sizeof(cMsgSend), nLength)) { for (int i=0; (i<3) && (bSuccess == false); i++) { if (pSocket->write(cMsgSend, (int) nLength, szServerIp, port) > 0) { if (pSocket->isReadyToRead(500)) { int length = pSocket->read(cMsgReceive, sizeof(cMsgReceive)) ; if ((length > 0) && msgReceive.parse(cMsgReceive, length)) { if (msgReceive.getType() == MSG_STUN_BIND_RESPONSE) { bSuccess = true ; // Get optional mapped address if (szMappedIp && piMappedPort) { msgReceive.getMappedAddress(szMappedIp, *piMappedPort) ; } // Get optional changed address if (szChangedIp && piChangedPort) { msgReceive.getChangedAddress(szChangedIp, *piChangedPort) ; } } else { // Abort on error response break ; } } } } else { break ; } } } else { assert(false) ; } return bSuccess ; } const char* StunUtils::natTypeToString(STUN_NAT_TYPE type) { const char* szRC ; switch (type) { case STUN_NAT_ERROR_BAD_SERVER: szRC = "STUN_NAT_ERROR_BAD_SERVER" ; break ; case STUN_NAT_BLOCKED: szRC = "STUN_NAT_BLOCKED" ; break ; case STUN_NAT_SYMMETRIC_FIREWALL: szRC = "STUN_NAT_SYMMETRIC_FIREWALL" ; break ; case STUN_NAT_OPEN: szRC = "STUN_NAT_OPEN" ; break ; case STUN_NAT_FULL_CONE: szRC = "STUN_NAT_FULL_CONE" ; break ; case STUN_NAT_RESTRICTED_CONE: szRC = "STUN_NAT_RESTRICTED_CONE" ; break ; case STUN_NAT_PORT_RESTRICTED_CONE: szRC = "STUN_NAT_PORT_RESTRICTED_CONE" ; break ; case STUN_NAT_SYMMETRIC: szRC = "STUN_NAT_SYMMETRIC" ; break ; default: szRC = "UNKNOWN (ERROR)" ; break ; } return szRC ; } static const char* convertRequestToString(unsigned short request) { const char* szRequest = "Unknown" ; switch (request) { case MSG_STUN_BIND_REQUEST: szRequest = "MSG_STUN_BIND_REQUEST" ; break ; case MSG_STUN_BIND_RESPONSE: szRequest = "MSG_STUN_BIND_RESPONSE" ; break ; case MSG_STUN_BIND_ERROR_RESPONSE: szRequest = "MSG_STUN_BIND_ERROR_RESPONSE" ; break ; case MSG_STUN_SHARED_SECRET_REQUEST: szRequest = "MSG_STUN_SHARED_SECRET_REQUEST" ; break ; case MSG_STUN_SHARED_SECRET_RESPONSE: szRequest = "MSG_STUN_SHARED_SECRET_RESPONSE" ; break ; case MSG_STUN_SHARED_SECRET_ERROR_RESPONSE: szRequest = "MSG_STUN_SHARED_SECRET_ERROR_RESPONSE" ; break ; case MSG_TURN_ALLOCATE_REQUEST: szRequest = "MSG_TURN_ALLOCATE_REQUEST" ; break ; case MSG_TURN_ALLOCATE_RESPONSE: szRequest = "MSG_TURN_ALLOCATE_RESPONSE" ; break ; case MSG_TURN_ALLOCATE_ERROR_RESPONSE: szRequest = "MSG_TURN_ALLOCATE_ERROR_RESPONSE" ; break ; case MSG_TURN_SEND_REQUEST: szRequest = "MSG_TURN_SEND_REQUEST" ; break ; case MSG_TURN_SEND_RESPONSE: szRequest = "MSG_TURN_SEND_RESPONSE" ; break ; case MSG_TURN_SEND_ERROR_RESPONSE: szRequest = "MSG_TURN_SEND_ERROR_RESPONSE" ; break ; case MSG_TURN_DATA_INDICATION: szRequest = "MSG_TURN_DATA_INDICATION" ; break ; case MSG_TURN_ACTIVE_DESTINATION_REQUEST: szRequest = "MSG_TURN_ACTIVE_DESTINATION_REQUEST" ; break ; case MSG_TURN_ACTIVE_DESTINATION_RESPONSE: szRequest = "MSG_TURN_ACTIVE_DESTINATION_RESPONSE" ; break ; case MSG_TURN_ACTIVE_DESTINATION_ERROR_RESPONSE: szRequest = "MSG_TURN_ACTIVE_DESTINATION_ERROR_RESPONSE" ; break ; case MSG_TURN_CONNECTION_STATUS_INDICATION: szRequest = "MSG_TURN_CONNECTION_STATUS_INDICATION" ; break ; case MSG_TURN_CLOSE_BINDING_REQUEST: szRequest = "MSG_TURN_CLOSE_BINDING_REQUEST" ; break ; case MSG_TURN_CLOSE_BINDING_RESPONSE: szRequest = "MSG_TURN_CLOSE_BINDING_RESPONSE" ; break ; case MSG_TURN_CLOSE_BINDING_ERROR_RESPONSE: szRequest = "MSG_TURN_CLOSE_BINDING_ERROR_RESPONSE" ; break ; } return szRequest ; } static const char* convertAttributeToString(unsigned short attribute) { const char* szAttribute = "Unknown" ; switch (attribute) { case ATTR_STUN_MAPPED_ADDRESS: szAttribute = "ATTR_STUN_MAPPED_ADDRESS" ; break ; case ATTR_STUN_RESPONSE_ADDRESS: szAttribute = "ATTR_STUN_RESPONSE_ADDRESS" ; break ; case ATTR_STUN_CHANGE_REQUEST: szAttribute = "ATTR_STUN_CHANGE_REQUEST" ; break ; case ATTR_STUN_SOURCE_ADDRESS: szAttribute = "ATTR_STUN_SOURCE_ADDRESS" ; break ; case ATTR_STUN_CHANGED_ADDRESS: szAttribute = "ATTR_STUN_CHANGED_ADDRESS" ; break ; case ATTR_STUN_USERNAME: szAttribute = "ATTR_STUN_USERNAME" ; break ; case ATTR_STUN_PASSWORD: szAttribute = "ATTR_STUN_PASSWORD" ; break ; case ATTR_STUN_MESSAGE_INTEGRITY: szAttribute = "ATTR_STUN_MESSAGE_INTEGRITY" ; break ; case ATTR_STUN_ERROR_CODE: szAttribute = "ATTR_STUN_ERROR_CODE" ; break ; case ATTR_STUN_UNKNOWN_ATTRIBUTE: szAttribute = "ATTR_STUN_UNKNOWN_ATTRIBUTE" ; break ; case ATTR_STUN_REFLECTED_FROM: szAttribute = "ATTR_STUN_REFLECTED_FROM" ; break ; case ATTR_STUN_ALTERNATE_SERVER: case ATTR_STUN_ALTERNATE_SERVER2: szAttribute = "ATTR_STUN_ALTERNATE_SERVER" ; break ; case ATTR_STUN_REALM: szAttribute = "ATTR_STUN_REALM" ; break ; case ATTR_STUN_NONCE: szAttribute = "ATTR_STUN_NONCE" ; break ; case ATTR_STUN_XOR_MAPPED_ADDRESS: case ATTR_STUN_XOR_MAPPED_ADDRESS2: szAttribute = "ATTR_STUN_XOR_MAPPED_ADDRESS" ; break ; case ATTR_STUN_XOR_ONLY: szAttribute = "ATTR_STUN_XOR_ONLY" ; break ; case ATTR_STUN_FINGERPRINT: szAttribute = "ATTR_STUN_FINGERPRINT" ; break ; case ATTR_STUN_SERVER: case ATTR_STUN_SERVER2: szAttribute = "ATTR_STUN_SERVER" ; break ; case ATTR_STUN_BINDING_LIFETIME: szAttribute = "ATTR_STUN_BINDING_LIFETIME" ; break ; case ATTR_TURN_LIFETIME: szAttribute = "ATTR_TURN_LIFETIME" ; break ; case ATTR_TURN_MAGIC_COOKIE: szAttribute = "ATTR_TURN_MAGIC_COOKIE" ; break ; case ATTR_TURN_BANDWIDTH: szAttribute = "ATTR_TURN_BANDWIDTH" ; break ; case ATTR_TURN_DESTINATION_ADDRESS: szAttribute = "ATTR_TURN_DESTINATION_ADDRESS" ; break ; case ATTR_TURN_REMOTE_ADDRESS: szAttribute = "ATTR_TURN_REMOTE_ADDRESS" ; break ; case ATTR_TURN_DATA: szAttribute = "ATTR_TURN_DATA" ; break ; case ATTR_TURN_RELAY_ADDRESS: szAttribute = "ATTR_TURN_RELAY_ADDRESS" ; break ; case ATTR_TURN_REQUESTED_TRANSPORT: szAttribute = "ATTR_TURN_REQUESTED_TRANSPORT" ; break ; } return szAttribute ; } void StunUtils::debugDump(char* pPacket, size_t nPacket, UtlString& output) { char cTemp[1024] ; output.remove(0) ; char* pTraverse = pPacket ; if ( StunMessage::isStunMessage(pPacket, nPacket) || TurnMessage::isTurnMessage(pPacket, nPacket)) { STUN_MESSAGE_HEADER msgHeader ; memcpy(&msgHeader, pPacket, sizeof(msgHeader)) ; pTraverse += sizeof(msgHeader) ; sprintf(cTemp, "Msg t=0x%04X/%s, l=%d, id=%08X/", ntohs(msgHeader.type), convertRequestToString(ntohs(msgHeader.type)), ntohs(msgHeader.length), ntohl(msgHeader.magicId.id)) ; output.append(cTemp) ; for (int i=0; i<12; i++) { sprintf(cTemp, "%02X", msgHeader.transactionId.id[i]) ; cTemp[2] = 0 ; output.append(cTemp) ; } output.append("\n") ; while (pTraverse < (pPacket + nPacket) ) { if (((pPacket + nPacket) - pTraverse) >= sizeof(STUN_ATTRIBUTE_HEADER)) { STUN_ATTRIBUTE_HEADER attrHeader ; memcpy(&attrHeader, pTraverse, sizeof(attrHeader)) ; pTraverse += sizeof(attrHeader) ; sprintf(cTemp, "attr t=0x%04X/%s, l=%d\n v=", ntohs(attrHeader.type), convertAttributeToString(ntohs(attrHeader.type)), ntohs(attrHeader.length)) ; output.append(cTemp) ; if (((pPacket + nPacket) - pTraverse) >= ntohs(attrHeader.length)) { for (int i=0; i #include #include #include #if defined(__pingtel_on_posix__) # include # include # include # include # include #endif // APPLICATION INCLUDES #include "os/OsSocket.h" #include "os/OsDatagramSocket.h" #include "os/TurnMessage.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* /////////////////////////s/// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor TurnMessage::TurnMessage(TurnMessage* pRequest, bool bLegacyMode) : StunMessage(pRequest, bLegacyMode) { mszTurnData = NULL ; mLifetime = 0 ; mbLifetimeValid = false ; mBandwidth = 0 ; mbBandwidthValid = false ; memset(&mDestinationAddress, 0, sizeof(STUN_ATTRIBUTE_ADDRESS)) ; mbDestinationAddressValid = false ; memset(&mTurnRemoteAddress, 0, sizeof(STUN_ATTRIBUTE_ADDRESS)) ; mbTurnRemoteAddressValid = false ; if (mszTurnData) { free(mszTurnData) ; } mszTurnData = NULL ; mnTurnData = 0 ; mbTurnDataValid = false ; memset(&mRelayAddress, 0, sizeof(STUN_ATTRIBUTE_ADDRESS)) ; mbRelayAddressValid = false ; mTransport = 0 ; mbTransportValid = false ; memset(&mRequestedIp, 0, sizeof(STUN_ATTRIBUTE_ADDRESS)) ; mbRequestedIpValid = false ; setIncludeMessageIntegrity(true) ; } // Destructor TurnMessage::~TurnMessage() { if (mszTurnData) { free(mszTurnData) ; } } /* ============================ MANIPULATORS ============================== */ void TurnMessage::reset() { StunMessage::reset() ; mLifetime = 0 ; mbLifetimeValid = false ; mBandwidth = 0 ; mbBandwidthValid = false ; memset(&mDestinationAddress, 0, sizeof(STUN_ATTRIBUTE_ADDRESS)) ; mbDestinationAddressValid = false ; memset(&mTurnRemoteAddress, 0, sizeof(STUN_ATTRIBUTE_ADDRESS)) ; mbTurnRemoteAddressValid = false ; if (mszTurnData) { free(mszTurnData) ; } mszTurnData = NULL ; mnTurnData = 0 ; mbTurnDataValid = false ; memset(&mRelayAddress, 0, sizeof(STUN_ATTRIBUTE_ADDRESS)) ; mbRelayAddressValid = false ; mTransport = 0 ; mbTransportValid = false ; memset(&mRequestedIp, 0, sizeof(STUN_ATTRIBUTE_ADDRESS)) ; mbRequestedIpValid = false ; setIncludeMessageIntegrity(true) ; } bool TurnMessage::encodeBody(char* pBuf, size_t nBufLength, size_t& nBytesUsed) { bool bError = false ; char* pTraverse = pBuf ; size_t nBytesLeft = nBufLength ; if (!bError) { bError = !encodeAttributeLong(ATTR_TURN_MAGIC_COOKIE, ATTR_MAGIC_COOKIE, pTraverse, nBytesLeft) ; } if ((!bError) && mbLifetimeValid) { bError = !encodeAttributeLong(ATTR_TURN_LIFETIME, mLifetime, pTraverse, nBytesLeft) ; } if ((!bError) && mbBandwidthValid) { bError = !encodeAttributeLong(ATTR_TURN_BANDWIDTH, mBandwidth, pTraverse, nBytesLeft) ; } if ((!bError) && mbDestinationAddressValid) { bError = !encodeAttributeAddress(ATTR_TURN_DESTINATION_ADDRESS, &mDestinationAddress, pTraverse, nBytesLeft) ; } if ((!bError) && mbTurnRemoteAddressValid) { bError = !encodeAttributeAddress(ATTR_TURN_REMOTE_ADDRESS, &mTurnRemoteAddress, pTraverse, nBytesLeft) ; } if ((!bError) && mbTurnDataValid) { bError = !encodeAttributeRaw(ATTR_TURN_DATA, mszTurnData, mnTurnData, pTraverse, nBytesLeft) ; } if ((!bError) && mbRelayAddressValid) { bError = !encodeAttributeAddress(ATTR_TURN_RELAY_ADDRESS, &mRelayAddress, pTraverse, nBytesLeft) ; } if ((!bError) && mbTransportValid) { bError = !encodeAttributeLong(ATTR_TURN_REQUESTED_TRANSPORT, mTransport, pTraverse, nBytesLeft) ; } if ((!bError) && mbRequestedIpValid) { bError = !encodeAttributeAddress(ATTR_TURN_REQUESTED_IP, &mRequestedIp, pTraverse, nBytesLeft) ; } // Stun attributes must be last (e.g. message-integrity). size_t nStunBytesUsed = 0 ; if (!bError) { bError = StunMessage::encodeBody(pTraverse, nBytesLeft, nStunBytesUsed) ; } nBytesUsed = (nBufLength - nBytesLeft) + nStunBytesUsed ; return bError ; } void TurnMessage::setLifetime(uint32_t secs) { mLifetime = secs ; mbLifetimeValid = true ; } void TurnMessage::setBandwidth(uint32_t rKBPS) { mBandwidth = rKBPS ; mbBandwidthValid = true ; } void TurnMessage::setDestinationAddress(const char* szIp, uint16_t port) { mDestinationAddress.family = ATTR_ADDRESS_FAMILY_IPV4 ; mDestinationAddress.address = ntohl(inet_addr(szIp)) ; mDestinationAddress.port = port ; mbDestinationAddressValid = true ; } void TurnMessage::setTurnRemoteAddress(const char* szIp, uint16_t port) { mTurnRemoteAddress.family = ATTR_ADDRESS_FAMILY_IPV4 ; mTurnRemoteAddress.address = ntohl(inet_addr(szIp)) ; mTurnRemoteAddress.port = port ; mbTurnRemoteAddressValid = true ; } void TurnMessage::setData(const char* pData, uint16_t nLength) { if (mszTurnData) { free(mszTurnData) ; } mszTurnData = (char*) malloc(nLength) ; memcpy(mszTurnData, pData, nLength) ; mnTurnData = nLength ; mbTurnDataValid = true ; } void TurnMessage::setRelayAddress(const char* szIp, uint16_t port) { mRelayAddress.family = ATTR_ADDRESS_FAMILY_IPV4 ; mRelayAddress.address = ntohl(inet_addr(szIp)) ; mRelayAddress.port = port ; mbRelayAddressValid = true ; } void TurnMessage::setRequestedTransport(TURN_TRANSPORT_TYPE transportType) { mTransport = (uint32_t) transportType ; mbTransportValid = true ; assert( (mTransport == 0) || (mTransport == 1) ) ; } void TurnMessage::setRequestedIp(const char* szIp, uint16_t port) { mRequestedIp.family = ATTR_ADDRESS_FAMILY_IPV4 ; mRequestedIp.address = ntohl(inet_addr(szIp)) ; mRequestedIp.port = port ; mbRequestedIpValid = true ; } /* ============================ ACCESSORS ================================= */ bool TurnMessage::getLifetime(uint32_t& rSecs) { if (mbLifetimeValid) { rSecs = mLifetime ; } return mbLifetimeValid ; } bool TurnMessage::getBandwidth(uint32_t& rKBPS) { if (mbBandwidthValid) { rKBPS = mBandwidth ; } return mbBandwidthValid ; } bool TurnMessage::getDestinationAddress(char* szIp, uint16_t& rPort) { if (mbDestinationAddressValid) { uint32_t address = htonl(mDestinationAddress.address) ; strcpy(szIp, inet_ntoa(*((in_addr*) &address))) ; rPort = mDestinationAddress.port ; } return mbDestinationAddressValid ; } bool TurnMessage::getTurnRemoteAddress(char* szIp, uint16_t& rPort) { if (mbTurnRemoteAddressValid) { uint32_t address = htonl(mTurnRemoteAddress.address) ; strcpy(szIp, inet_ntoa(*((in_addr*) &address))) ; rPort = mTurnRemoteAddress.port ; } return mbTurnRemoteAddressValid ; } bool TurnMessage::getData(char*& rpData, uint16_t& nLength) { if (mbTurnDataValid) { rpData = mszTurnData ; nLength = (uint16_t) mnTurnData ; } return mbTurnDataValid ; } bool TurnMessage::getRelayAddress(char* szIp, uint16_t& rPort) { if (mbRelayAddressValid) { uint32_t address = htonl(mRelayAddress.address) ; strcpy(szIp, inet_ntoa(*((in_addr*) &address))) ; rPort = mRelayAddress.port ; } return mbRelayAddressValid ; } bool TurnMessage::getRequestedTransport(TURN_TRANSPORT_TYPE& rTransportType) { if (mbTransportValid) { rTransportType = (TURN_TRANSPORT_TYPE) mTransport ; } return mbTransportValid ; } bool TurnMessage::getRequestedIp(char* szIp, uint16_t& rPort) { if (mbRequestedIpValid) { uint32_t address = htonl(mRequestedIp.address) ; strcpy(szIp, inet_ntoa(*((in_addr*) &address))) ; rPort = mRequestedIp.port ; } return mbRequestedIpValid ; } /* ============================ INQUIRY =================================== */ bool TurnMessage::validateMessageType(uint16_t type) { bool bValid = false ; switch (type) { case MSG_TURN_ALLOCATE_REQUEST: case MSG_TURN_ALLOCATE_RESPONSE: case MSG_TURN_ALLOCATE_ERROR_RESPONSE: case MSG_TURN_SEND_REQUEST: case MSG_TURN_SEND_RESPONSE: case MSG_TURN_SEND_ERROR_RESPONSE: case MSG_TURN_DATA_INDICATION: case MSG_TURN_ACTIVE_DESTINATION_REQUEST: case MSG_TURN_ACTIVE_DESTINATION_RESPONSE: case MSG_TURN_ACTIVE_DESTINATION_ERROR_RESPONSE: case MSG_TURN_CONNECTION_STATUS_INDICATION: case MSG_TURN_CLOSE_BINDING_REQUEST: case MSG_TURN_CLOSE_BINDING_RESPONSE: case MSG_TURN_CLOSE_BINDING_ERROR_RESPONSE: bValid = true ; break ; default: bValid = StunMessage::validateMessageType(type) ; break ; } return bValid ; } bool TurnMessage::isTurnMessage(const char* pBuf, uint16_t nBufLength, bool* pbDataIndication) { bool bValid = false ; if (nBufLength >= (sizeof(STUN_MESSAGE_HEADER) + sizeof(STUN_ATTRIBUTE_HEADER) + sizeof(uint32_t))) { STUN_MESSAGE_HEADER header ; char* pTraverse = (char*) pBuf ; // Copy header memcpy(&header, pTraverse, sizeof(STUN_MESSAGE_HEADER)) ; header.type = ntohs(header.type) ; header.length = ntohs(header.length) ; // Valid Length if (nBufLength == (sizeof(STUN_MESSAGE_HEADER) + header.length)) { switch (header.type) { case MSG_TURN_ALLOCATE_REQUEST: case MSG_TURN_ALLOCATE_RESPONSE: case MSG_TURN_ALLOCATE_ERROR_RESPONSE: case MSG_TURN_SEND_REQUEST: case MSG_TURN_SEND_RESPONSE: case MSG_TURN_SEND_ERROR_RESPONSE: case MSG_TURN_DATA_INDICATION: case MSG_TURN_ACTIVE_DESTINATION_REQUEST: case MSG_TURN_ACTIVE_DESTINATION_RESPONSE: case MSG_TURN_ACTIVE_DESTINATION_ERROR_RESPONSE: case MSG_TURN_CONNECTION_STATUS_INDICATION: case MSG_TURN_CLOSE_BINDING_REQUEST: case MSG_TURN_CLOSE_BINDING_RESPONSE: case MSG_TURN_CLOSE_BINDING_ERROR_RESPONSE: // Validate Magic Cookie /* STUN_ATTRIBUTE_HEADER attrHeader ; uint32_t magicCookie ; pTraverse += sizeof(STUN_MESSAGE_HEADER) ; memcpy(&attrHeader, pTraverse, sizeof(STUN_ATTRIBUTE_HEADER)) ; attrHeader.type = ntohs(attrHeader.type) ; attrHeader.length = ntohs(attrHeader.length) ; pTraverse += sizeof(STUN_ATTRIBUTE_HEADER) ; memcpy(&magicCookie, pTraverse, sizeof(uint32_t)) ; magicCookie = ntohl(magicCookie) ; if ( (attrHeader.type == ATTR_TURN_MAGIC_COOKIE) && (attrHeader.length == sizeof(uint32_t)) && (magicCookie == ATTR_MAGIC_COOKIE) ) { */ bValid = true ; if (pbDataIndication) *pbDataIndication = (header.type == MSG_TURN_DATA_INDICATION) ; /* } */ break ; default: break ; } } } return bValid ; } bool TurnMessage::isRequestOrNonErrorResponse() { bool bRequestOrNonErrorResponse ; switch (getType()) { case MSG_TURN_ALLOCATE_REQUEST: case MSG_TURN_ALLOCATE_RESPONSE: case MSG_TURN_SEND_REQUEST: case MSG_TURN_SEND_RESPONSE: case MSG_TURN_ACTIVE_DESTINATION_REQUEST: case MSG_TURN_ACTIVE_DESTINATION_RESPONSE: case MSG_TURN_CLOSE_BINDING_REQUEST: case MSG_TURN_CLOSE_BINDING_RESPONSE: bRequestOrNonErrorResponse = true ; break ; case MSG_TURN_ALLOCATE_ERROR_RESPONSE: case MSG_TURN_SEND_ERROR_RESPONSE: case MSG_TURN_DATA_INDICATION: case MSG_TURN_ACTIVE_DESTINATION_ERROR_RESPONSE: case MSG_TURN_CONNECTION_STATUS_INDICATION: case MSG_TURN_CLOSE_BINDING_ERROR_RESPONSE: bRequestOrNonErrorResponse = false ; break ; default: bRequestOrNonErrorResponse = StunMessage::isRequestOrNonErrorResponse() ; break ; } return bRequestOrNonErrorResponse ; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ bool TurnMessage::parseAttribute(STUN_ATTRIBUTE_HEADER* pHeader, char* pBuf) { uint32_t magicCookie ; bool bValid = false ; switch (pHeader->type) { case ATTR_TURN_LIFETIME: bValid = parseLongAttribute(pBuf, pHeader->length, &mLifetime) ; mbLifetimeValid = bValid ; break ; case ATTR_TURN_MAGIC_COOKIE: bValid = parseLongAttribute(pBuf, pHeader->length, &magicCookie) ; // Validate Cookie if (bValid) { bValid = (magicCookie == ATTR_MAGIC_COOKIE) ; } break ; case ATTR_TURN_BANDWIDTH: bValid = parseLongAttribute(pBuf, pHeader->length, &mBandwidth) ; mbBandwidthValid = bValid ; break ; case ATTR_TURN_DESTINATION_ADDRESS: bValid = parseAddressAttribute(pBuf, pHeader->length, &mDestinationAddress) ; mbDestinationAddressValid = bValid ; break ; case ATTR_TURN_REMOTE_ADDRESS: bValid = parseAddressAttribute(pBuf, pHeader->length, &mTurnRemoteAddress) ; mbTurnRemoteAddressValid = bValid ; break ; case ATTR_TURN_DATA: if (pHeader->length) { mszTurnData = (char*) malloc(pHeader->length) ; if (mszTurnData) { bValid = parseRawAttribute(pBuf, pHeader->length, mszTurnData, pHeader->length) ; mbTurnDataValid = (pHeader->length > 0); mnTurnData = pHeader->length ; if (!bValid) { free(mszTurnData) ; mszTurnData = NULL ; mnTurnData = 0 ; } } } break ; case ATTR_TURN_RELAY_ADDRESS: bValid = parseAddressAttribute(pBuf, pHeader->length, &mRelayAddress) ; mbRelayAddressValid = bValid ; break ; case ATTR_TURN_REQUESTED_PORT: bValid = true ; break ; case ATTR_TURN_REQUESTED_TRANSPORT: bValid = parseLongAttribute(pBuf, pHeader->length, &mTransport) ; mbTransportValid = bValid ; break ; case ATTR_TURN_REQUESTED_IP: bValid = parseAddressAttribute(pBuf, pHeader->length, &mRequestedIp) ; mbRequestedIpValid = bValid ; break ; default: bValid = StunMessage::parseAttribute(pHeader, pBuf) ; break ; } return bValid ; } bool TurnMessage::encodeAttributeLong(uint16_t type, uint32_t value, char*& pBuf, size_t& nBytesLeft) { bool bRC = false ; if ( (nBytesLeft >= (sizeof(uint32_t) + sizeof(STUN_ATTRIBUTE_HEADER))) && encodeAttributeHeader(type, sizeof(uint32_t), pBuf, nBytesLeft) && encodeLong(value, pBuf, nBytesLeft)) { bRC = true ; } return bRC ; } bool TurnMessage::encodeAttributeRaw(uint16_t type, const char* cBuf, size_t nBuf, char*& pBuf, size_t& nBytesLeft) { bool bRC = false; size_t nTotalLength = sizeof(STUN_ATTRIBUTE_HEADER) + nBuf ; if ( (nBytesLeft >= nTotalLength) && encodeAttributeHeader(type, (uint16_t) nBuf, pBuf, nBytesLeft) && encodeRaw(cBuf, nBuf, pBuf, nBytesLeft)) { bRC = true ; } return bRC ; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/0000755000175000017500000000000012321445023021244 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlLongLongInt.cpp0000644000175000017500000001322112205613256024634 0ustar00danieldaniel00000000000000// // // Copyright (C) 2005-2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #include // APPLICATION INCLUDES #include "utl/UtlLongLongInt.h" // DEFINES #if defined(_MSC_VER) && (_MSC_VER < 1300) // If < MSVC7(VS2003), _strtoi64 is not defined. // Come up with a suitable replacement. # include static inline int64_t strtoll(const char* cStr, char** strEndPos, int base) { assert(strEndPos == 0); assert(base == 10 || base == 0); return _atoi64(cStr); } #elif defined( WIN32 ) && !defined( WINCE ) // For all other windows variants except CE, // use more appropriate _strtoi64 # define strtoll _strtoi64 #endif // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS UtlContainableType UtlLongLongInt::TYPE = "UtlLongLongInt" ; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor accepting an optional default value. UtlLongLongInt::UtlLongLongInt(int64_t value) { mValue = value ; } // Copy constructor // Destructor UtlLongLongInt::~UtlLongLongInt() { } /* ============================ OPERATORS ============================== */ // Prefix increment operator UtlLongLongInt& UtlLongLongInt::operator++() { mValue++; return *this; } // Postfix increment operator UtlLongLongInt UtlLongLongInt::operator++(int) { UtlLongLongInt temp = *this; ++*this; return temp; } // Prefix decrement operator UtlLongLongInt& UtlLongLongInt::operator--() { mValue--; return *this; } // Postfix decrement operator UtlLongLongInt UtlLongLongInt::operator--(int) { UtlLongLongInt temp = *this; --*this; return temp; } /* ============================ MANIPULATORS ============================== */ int64_t UtlLongLongInt::setValue(int64_t iValue) { int64_t iOldValue = mValue ; mValue = iValue ; return iOldValue ; } int64_t UtlLongLongInt::stringToLongLong(const char* longLongString) { #if defined(_VXWORKS) int numDigits = strlen(longLongString); int64_t sum = -1; if(numDigits <= 9) { sum = strtol(longLongString, 0, 0); } else if(numDigits > 9) { int64_t billions = 0; int64_t first9digits = strtol(&longLongString[numDigits - 9], 0, 0); char digitBuffer[10]; if(numDigits <= 18) { // Billions digits memcpy(digitBuffer, longLongString, numDigits - 9); digitBuffer[numDigits - 9] = '\0'; billions = strtol(digitBuffer, 0, 0); if(billions >= 0) { sum = billions * 1000000 + first9digits; } else { sum = billions * 1000000 + first9digits * -1; } } else //(numDigits > 18) { int64_t gazillions = 0; // Billions digits memcpy(digitBuffer, &longLongString[numDigits - 18], 9); digitBuffer[9] = '\0'; billions = strtol(digitBuffer, 0, 0); // Gazillions digits (take a maximum of 5 digits and sign) int remainingDigits = numDigits > 23 ? 5 : numDigits - 18; memcpy(digitBuffer, longLongString, remainingDigits); digitBuffer[remainingDigits] = '\0'; gazillions = strtol(digitBuffer, 0, 0); if(gazillions > 0) { sum = gazillions * 1000000000000 + billions * 1000000 + first9digits; } else { sum = gazillions * 1000000000000 + billions * -1000000 + first9digits * -1; } } } return sum; #else // We could use "atoll" here but it is obsolete, "strtoll" is the recommended function // See http://www.delorie.com/gnu/docs/glibc/libc_423.html . return strtoll(longLongString, 0, 0); #endif } /* ============================ ACCESSORS ================================= */ int64_t UtlLongLongInt::getValue() const { return mValue ; } unsigned UtlLongLongInt::hash() const { return (unsigned)mValue ; } UtlContainableType UtlLongLongInt::getContainableType() const { return UtlLongLongInt::TYPE ; } /* ============================ INQUIRY =================================== */ int UtlLongLongInt::compareTo(UtlContainable const * inVal) const { int result ; if (inVal->isInstanceOf(UtlLongLongInt::TYPE)) { UtlLongLongInt* temp = (UtlLongLongInt*)inVal ; int64_t inIntll = temp -> getValue() ; if (mValue > inIntll) { result = 1 ; } else if (mValue == inIntll) { result = 0 ; } else { // mValue < inIntll result = -1 ; } } else { // The result for a non-like object is undefined except that we must // declare that the two objects are not equal result = INT_MAX ; } return result ; } UtlBoolean UtlLongLongInt::isEqual(UtlContainable const * inVal) const { return (compareTo(inVal) == 0); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlNameValueTokenizer.cpp0000644000175000017500000001640112205613256026215 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlNameValueTokenizer::UtlNameValueTokenizer(const char* multiLineText, int length) { if (multiLineText && length < 0) { length = strlen(multiLineText); } textPtr = multiLineText; bytesConsumed = 0; textLen = length; } // Destructor UtlNameValueTokenizer::~UtlNameValueTokenizer() { } /* ============================ MANIPULATORS ============================== */ int UtlNameValueTokenizer::findNextLineTerminator(const char* text, int length, int* nextLineIndex) { int byteIndex = 0; int terminatorIndex = -1; *nextLineIndex = -1; while (byteIndex < length) { if (text[byteIndex] == NEWLINE || text[byteIndex] == CARRIAGE_RETURN) { terminatorIndex = byteIndex; // Check for NL after CR if (byteIndex < length - 1 && text[byteIndex + 1] == NEWLINE && text[byteIndex] == CARRIAGE_RETURN) { *nextLineIndex = terminatorIndex + 2; } else { *nextLineIndex = terminatorIndex + 1; } break; } byteIndex++; } return(terminatorIndex); } UtlBoolean UtlNameValueTokenizer::getSubField(const char* textField, int textFieldLength, int subFieldIndex, const char* subFieldSeparators, const char*& subFieldPtr, int& subFieldLength, int* lastCharIndex) { UtlBoolean found = FALSE; if (textField) { int subFieldI = -1; int subFieldBegin = 0; int separatorIndex = -1; int numSeparators = strlen(subFieldSeparators); for (int charIndex = 0; subFieldI < subFieldIndex; charIndex++) { if ((textFieldLength >= 0 && charIndex >= textFieldLength) || textField[charIndex] == '\0') { subFieldI++; subFieldBegin = separatorIndex + 1; separatorIndex = charIndex; break; } // If we found a separator character else if (// 1 separator check it directly, it is much faster (numSeparators == 1 && subFieldSeparators[0] == textField[charIndex]) || // 2 separator characters, check both: (numSeparators == 2 && (subFieldSeparators[0] == textField[charIndex] || subFieldSeparators[1] == textField[charIndex])) || // 3 or more separator characters, do it the slow way: (numSeparators > 2 && strchr(subFieldSeparators, textField[charIndex]))) { subFieldBegin = separatorIndex + 1; separatorIndex = charIndex; // Ignore empty subfields (i.e. they do not count if (subFieldBegin != separatorIndex) { subFieldI++; } } } if (subFieldI == subFieldIndex) { found = TRUE; subFieldPtr = &(textField[subFieldBegin]); subFieldLength = separatorIndex - subFieldBegin; if (lastCharIndex) { *lastCharIndex = separatorIndex; } } } if (!found) { subFieldPtr = NULL; subFieldLength = 0; if (lastCharIndex) { *lastCharIndex = 0; } } return found; } UtlBoolean UtlNameValueTokenizer::getSubField(const char* textField, int subFieldIndex, const char* subFieldSeparators, UtlString* subFieldText, int* lastCharIndex) { int subFieldLength = 0; const char* subFieldPtr = NULL; UtlBoolean found = getSubField(textField, -1, // stop at null (i.e. '\0') subFieldIndex, subFieldSeparators, subFieldPtr, subFieldLength, lastCharIndex); if (subFieldPtr && subFieldLength > 0) { subFieldText->replace(0, subFieldLength, subFieldPtr, subFieldLength); subFieldText->remove(subFieldLength); } else { subFieldText->remove(0); } return found; } UtlBoolean UtlNameValueTokenizer::getNextPair(char separator, UtlString* name, UtlString* value) { UtlBoolean nameFound = 0; name->remove(0); value->remove(0); int nextLineOffset; // Find the end of the line and the begining of the next int lineLength = findNextLineTerminator(&textPtr[bytesConsumed], textLen - bytesConsumed, &nextLineOffset); // Did not find an end of line, assume the rest of the text is the line if (lineLength < 0) { lineLength = textLen - bytesConsumed; } // Add a header field if (lineLength > 0) { // Find the name value delimiter int nameEnd = 0; while (nameEnd < lineLength && textPtr[bytesConsumed + nameEnd] != separator) { nameEnd++; } if (nameEnd > 0) { name->append(&textPtr[bytesConsumed], nameEnd); nameFound = 1; } // Get rid of the white space while (nameEnd + 1 < lineLength && (textPtr[bytesConsumed + nameEnd + 1] == ' ' || textPtr[bytesConsumed + nameEnd + 1] == '\t')) { nameEnd++; } nameEnd++; if (nameEnd < lineLength) { value->append(&textPtr[bytesConsumed + nameEnd], lineLength - nameEnd); } } if (nextLineOffset > 0) { bytesConsumed += nextLineOffset; } else { bytesConsumed += lineLength; } return nameFound; } /* ============================ ACCESSORS ================================= */ int UtlNameValueTokenizer::getProcessedIndex() { return bytesConsumed; } /* ============================ INQUIRY =================================== */ UtlBoolean UtlNameValueTokenizer::isAtEnd() { return bytesConsumed >= textLen; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlBool.cpp0000644000175000017500000000466012205613256023344 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2011 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlBool.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS UtlContainableType UtlBool::TYPE = "UtlBool" ; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor accepting an optional default value. UtlBool::UtlBool(bool value) { mValue = value ; } // Copy constructor // Destructor UtlBool::~UtlBool() { } UtlCopyableContainable* UtlBool::clone() const { return(new UtlBool(*this)); } /* ============================ MANIPULATORS ============================== */ void UtlBool::setValue(bool value) { mValue = value ; } /* ============================ ACCESSORS ================================= */ bool UtlBool::getValue() const { return mValue ; } unsigned UtlBool::hash() const { return mValue ; } UtlContainableType UtlBool::getContainableType() const { return UtlBool::TYPE ; } /* ============================ INQUIRY =================================== */ int UtlBool::compareTo(UtlContainable const * inVal) const { int result ; if (inVal->isInstanceOf(UtlBool::TYPE)) { UtlBool* temp = (UtlBool*)inVal ; bool inBool = temp -> getValue() ; if (inBool == mValue) { result = 0 ; } else { result = 1 ; } } else { result = 1 ; } return result ; } UtlBoolean UtlBool::isInstanceOf(const UtlContainableType type) const { // Check if it is my type and the defer parent type comparisons to parent return(areSameTypes(type, UtlBool::TYPE) || UtlCopyableContainable::isInstanceOf(type)); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlCopyableContainable.cpp0000644000175000017500000000357612205613256026354 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2011 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlCopyableContainable.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS UtlContainableType UtlCopyableContainable::TYPE = "UtlCopyableContainable"; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlCopyableContainable::UtlCopyableContainable() { } // Destructor UtlCopyableContainable::~UtlCopyableContainable() { } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ UtlContainableType UtlCopyableContainable::getContainableType() const { return(UtlCopyableContainable::TYPE); } /* ============================ INQUIRY =================================== */ UtlBoolean UtlCopyableContainable::isInstanceOf(const UtlContainableType type) const { // Generally classes should check their own type and then deligate to // their parent class implementation of isInstanceOf. However this is // a slight optimization as UtlContainable will also compare with the base // class type again. return(areSameTypes(type, UtlCopyableContainable::TYPE) || areSameTypes(type, UtlContainable::TYPE)); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlCrc32.cpp0000644000175000017500000001301312205613256023315 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "utl/UtlCrc32.h" #include "utl/UtlString.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // The following CRC lookup table was generated automagically // by the Rocksoft^tm Model CRC Algorithm Table Generation // Program V1.0 using the following model parameters: // // Width : 4 bytes // Poly : 0x04C11DB7 // Reverse : TRUE // // For more information on the Rocksoft^tm Model CRC Algorithm, // see the document titled "A Painless Guide to CRC Error // Detection Algorithms" by Ross Williams // (ross@guest.adelaide.edu.au.). This document is likely to be // in the FTP archive "ftp.adelaide.edu.au/pub/rocksoft". static unsigned long sCrcTable[256] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D } ; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlCrc32::UtlCrc32() { reset() ; } /* ============================ MANIPULATORS ============================== */ void UtlCrc32::reset() { mCrc = 0xFFFFFFFF ; } void UtlCrc32::calc(unsigned char ch) { mCrc = sCrcTable[(mCrc ^ ch) & 0x000000FF] ^ (mCrc >> 8) ; } void UtlCrc32::calc(unsigned char* pData, size_t nData) { for (size_t i=0; i> 8) ; } } void UtlCrc32::calc(const UtlString& data) { calc((unsigned char*) data.data(), data.length()) ; } /* ============================ ACCESSORS ================================= */ unsigned long UtlCrc32::getValue() const { return mCrc ^ 0xFFFFFFFF ; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlCryptoData.cpp0000644000175000017500000000272012205613256024516 0ustar00danieldaniel00000000000000// // Copyright (C) 2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2008 Mutualink, Inc. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // Author: Sergey Kostanbaev // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlCryptoData.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // TYPEDEFS // DEFINES // MACROS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////////// PUBLIC //////////////////////////////// */ /* =============================== CREATORS =============================== */ UtlCryptoData::UtlCryptoData(int initSize) { mData = new unsigned char[initSize]; length = initSize; } UtlCryptoData::~UtlCryptoData() { delete mData; } /* ============================= MANIPULATORS ============================= */ /* ============================== ACCESSORS =============================== */ /* =============================== INQUIRY ================================ */ void UtlCryptoData::resize(int newSize) { assert (newSize <= length); length = newSize; } UtlString UtlCryptoData::dumpHex() const { UtlString str; for (int i=0; i #include "utl/UtlCryptoKey.h" #include #include #include #include #include #ifdef WIN32 # pragma comment (lib, "libeay32.lib") # pragma comment (lib, "ssleay32.lib") #endif // Static initialization const EVP_MD* UtlCryptoKey::spMdAlg = EVP_sha1(); UtlCryptoKey::UtlCryptoKey() : mKeyType(KEY_INVALID), mLastErr(0) { } UtlCryptoKey::~UtlCryptoKey() { clearKey(); } void UtlCryptoKey::clearKey() { mKeyType = KEY_INVALID; mLastErr = 0; } int UtlCryptoKey::importFromFile(const char* pFilename) { return -1; } int UtlCryptoKey::loadBinaryKey(const unsigned char* pSrc, int srcLen) { return -1; } UtlCryptoData* UtlCryptoKey::getBinaryKey() const { return 0; } UtlCryptoData* UtlCryptoKey::encrypt(const unsigned char* pSrc, int srcLen) const { // Allocate a destination buffer int destLen = getMaxEncryptedSize(srcLen); UtlCryptoData* pDest = new UtlCryptoData(destLen); if (!pDest) return 0; // Encrypt the data into the buffer if (encrypt(pSrc, srcLen, pDest->data(), &destLen) == 0) { delete pDest; return 0; } // Set the size of the destination buffer to the returned size pDest->resize(destLen); return pDest; } UtlCryptoData* UtlCryptoKey::decrypt(const unsigned char* pSrc, int srcLen) const { // Allocate a destination buffer int destLen = getMaxDecryptedSize(srcLen); UtlCryptoData* pDest = new UtlCryptoData(destLen); if (!pDest) return 0; // Decrypt the data into the buffer if (decrypt(pSrc, srcLen, pDest->data(), &destLen) == 0) { delete pDest; return 0; } // Set the size of the destination buffer to the returned size pDest->resize(destLen); return pDest; } UtlCryptoData* UtlCryptoKey::sign(const unsigned char* pSrc, int srcLen) const { // Allocate a destination buffer int destLen = getMaxSignatureSize(srcLen); UtlCryptoData* pDest = new UtlCryptoData(destLen); if (!pDest) return 0; // Sign the data & write signature into the buffer if (sign(pSrc, srcLen, pDest->data(), &destLen) == 0) { delete pDest; return 0; } // Set the size of the destination buffer to the returned size pDest->resize(destLen); return pDest; } int UtlCryptoKey::getMaxSignatureSize(int srcLen) const { return 0; } int UtlCryptoKey::sign(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const { if (pDestLen) *pDestLen = 0; return 0; } int UtlCryptoKey::verify(const unsigned char* pSrc, int srcLen, const unsigned char* pSig, int sigLen) const { return -1; } unsigned long UtlCryptoKey::setLastError(unsigned long err) const { // Allow mLastErr to be set by const methods as well // (technically a violation of the const principle, but mLastErr isn't // really part of the state of the key; it's more of a convenience thing) mLastErr = err; return err; } UtlString UtlCryptoKey::output() const { UtlString str; str.append("KeyType="); switch (mKeyType) { case UtlCryptoKey::KEY_INVALID: str.append("(invalid)"); break; case UtlCryptoKey::KEY_SYMMETRIC: str.append("Symmetric"); break; case UtlCryptoKey::KEY_PRIVATE: str.append("Private"); break; case UtlCryptoKey::KEY_PUBLIC: str.append("Public"); break; default: str.appendFormat("(unknown value %d!)", mKeyType); } return str; } int UtlCryptoKey::getDigestAlgType() { return EVP_MD_type(spMdAlg); } inline int UtlCryptoKey::getMaxDigestSize(int srcLen) { return EVP_MD_size(spMdAlg); } int UtlCryptoKey::computeDigest(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) { if (!pSrc || !srcLen || !pDest || !pDestLen || *pDestLen < getMaxDigestSize(srcLen)) return 0; *pDestLen = 0; EVP_MD_CTX mdctx; EVP_MD_CTX_init(&mdctx); OpenSSL_add_all_digests(); if (!EVP_DigestInit_ex(&mdctx, spMdAlg, NULL)) { osPrintf("*****EVP_DigestInit_ex failed"); EVP_MD_CTX_cleanup(&mdctx); return 0; } if (!EVP_DigestUpdate(&mdctx, pSrc, srcLen)) { osPrintf("*****EVP_DigestUpdate failed"); EVP_MD_CTX_cleanup(&mdctx); return 0; } if (!EVP_DigestFinal_ex(&mdctx, pDest, (unsigned*)pDestLen)) { osPrintf("*****EVP_DigestFinal_ex failed"); EVP_MD_CTX_cleanup(&mdctx); *pDestLen = 0; return 0; } EVP_MD_CTX_cleanup(&mdctx); return *pDestLen; } UtlCryptoData* UtlCryptoKey::computeDigest(const unsigned char* pSrc, int srcLen) { // Allocate a destination buffer int destLen = getMaxDigestSize(srcLen); UtlCryptoData* pDest = new UtlCryptoData(destLen); if (!pDest) return 0; // Compute digest and write it into the buffer if (computeDigest(pSrc, srcLen, pDest->data(), &destLen) == 0) { delete pDest; return 0; } // Set the size of the destination buffer to the returned size pDest->resize(destLen); return pDest; } inline int UtlCryptoKey::getMaxBase64EncodedSize(int srcLen) { int byteTriplets = srcLen/3 + (srcLen%3 ? 1 : 0); int padBytes = srcLen%3 ? (3 - srcLen%3) : 0; int encodedBytes = byteTriplets * 4 + padBytes; int crlfs = (encodedBytes / 76) + 1; return encodedBytes + crlfs; } const char UtlCryptoKey::sBase64Chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; int UtlCryptoKey::getBase64Idx(unsigned char c) { if (c >= 'A' && c <= 'Z') return c - 'A'; else if (c >= 'a' && c <= 'z') return c - 'a' + 26; else if (c >= '0' && c <= '9') return c - '0' + 52; else if (c == '+') return 62; else if (c == '/') return 63; return -1; } int UtlCryptoKey::base64Encode(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) { if (!pSrc || !srcLen || !pDest || !pDestLen || *pDestLen < getMaxBase64EncodedSize(srcLen)) return 0; *pDestLen = 0; const unsigned char* pSrcChar = pSrc; unsigned char* pDestTail = pDest; int srcLeft = srcLen; int tripCnt = 0; unsigned char triplet[3]; // Triplet of source binary chars unsigned char quadCode[4]; // Triplet encoded as four base64 chars // For every 3 source bytes (triplet), write 4 base64 chars (quadCode) while (srcLeft--) { triplet[tripCnt++] = *(pSrcChar++); if (tripCnt == 3) // If we have a full triplet { // For each group of 6 bits, produce one base64 char quadCode[0] = (triplet[0] & 0xfc) >> 2; quadCode[1] = ((triplet[0] & 0x03) << 4) + ((triplet[1] & 0xf0) >> 4); quadCode[2] = ((triplet[1] & 0x0f) << 2) + ((triplet[2] & 0xc0) >> 6); quadCode[3] = triplet[2] & 0x3f; for (int i = 0; i < 4; i++) *(pDestTail++) = sBase64Chars[quadCode[i]]; tripCnt = 0; } } // If the last triplet is partially filled, if (tripCnt) { // Pad remaining bytes with 0s for (int i = tripCnt; i < 3; i++) triplet[i] = '\0'; quadCode[0] = (triplet[0] & 0xfc) >> 2; quadCode[1] = ((triplet[0] & 0x03) << 4) + ((triplet[1] & 0xf0) >> 4); quadCode[2] = ((triplet[1] & 0x0f) << 2) + ((triplet[2] & 0xc0) >> 6); quadCode[3] = triplet[2] & 0x3f; // Write 2 b64 chars for triplet with 1 byte filled, or 3 for 2 bytes for (int i = 0; i < (tripCnt + 1); i++) *(pDestTail++) = sBase64Chars[quadCode[i]]; // Append one '=' for each 0 added as padding above to fill out quadCode while (tripCnt++ < 3) *(pDestTail++) = '='; } *pDestLen = pDestTail - pDest; return *pDestLen; } UtlString UtlCryptoKey::base64Encode(const unsigned char* pSrc, int srcLen) { // Allocate a destination string UtlString dest; int destLen = getMaxBase64EncodedSize(srcLen); dest.resize(destLen); // Make sure there's enough room in the string // Encode data into the string if (base64Encode(pSrc, srcLen, (unsigned char*)dest.data(), &destLen) == 0) return ""; // Set the size of the destination buffer to the returned size dest.resize(destLen); return dest; } int UtlCryptoKey::getMaxBase64DecodedSize(int srcLen) { int quadCodes = srcLen/4 + 1; int encodedBytes = quadCodes * 3; return encodedBytes; } bool UtlCryptoKey::isBase64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } int UtlCryptoKey::base64Decode(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) { if (!pSrc || !srcLen || !pDest || !pDestLen || *pDestLen < getMaxBase64DecodedSize(srcLen)) return 0; *pDestLen = 0; unsigned char* pDestTail = pDest; int quadCnt = 0; int padCnt = 0; unsigned char quadCode[4]; // Group of four source base64 chars unsigned char triplet[3]; // Triplet of decoded binary chars // From every 4 source bytes (quadCodes), decode 3 binary chars (triplet) const unsigned char* pSrcChar; const unsigned char* pSrcEnd = pSrc + srcLen; for (pSrcChar = pSrc; pSrcChar != pSrcEnd; pSrcChar++) { // Skip any whitespace inserted in the string for formatting if (*pSrcChar == '\r' || *pSrcChar == '\n' || *pSrcChar == ' ' || *pSrcChar == '\t') continue; // Count pad characters at end of string if (*pSrcChar == '=') { padCnt++; if (padCnt == 2) // Max of 2 pad chars allowed break; continue; } // Any other char (or valid char after a pad char is found) // is illegal and marks the end of the b64 string if (!isBase64(*pSrcChar) || padCnt) break; quadCode[quadCnt++] = *pSrcChar; if (quadCnt == 4) // If we have a full quadCode { // For each group of 4 b64 chars, produce 3 binary chars for (int i = 0; i < 4; i++) //quadCode[i] = sBase64Chars.find(quadCode[i]); quadCode[i] = getBase64Idx(quadCode[i]); triplet[0] = (quadCode[0] << 2) + ((quadCode[1] & 0x30) >> 4); triplet[1] = ((quadCode[1] & 0xf) << 4) + ((quadCode[2] & 0x3c) >> 2); triplet[2] = ((quadCode[2] & 0x3) << 6) + quadCode[3]; for (int i = 0; i < 3; i++) *(pDestTail++) = triplet[i]; quadCnt = 0; } } // If the last quadCode is partially filled, if (quadCnt) { if (quadCnt + padCnt != 4) osPrintf("***base64Decode: quadCnt=%d padCnt=%d after decode, total should be 4!", quadCnt, padCnt); // Pad rest of quad with 'A's (so will convert to 0s in next step) for (int i = quadCnt; i < 4; i++) quadCode[i] = 'A'; // Convert ASCII to indexes into b64 table for (int i = 0; i < 4; i++) //quadCode[i] = sBase64Chars.find(quadCode[i]); quadCode[i] = getBase64Idx(quadCode[i]); triplet[0] = (quadCode[0] << 2) + ((quadCode[1] & 0x30) >> 4); triplet[1] = ((quadCode[1] & 0xf) << 4) + ((quadCode[2] & 0x3c) >> 2); triplet[2] = ((quadCode[2] & 0x3) << 6) + quadCode[3]; for (int i = 0; i < (quadCnt - 1); i++) *(pDestTail++) = triplet[i]; } *pDestLen = pDestTail - pDest; return *pDestLen; } int UtlCryptoKey::base64Decode(const UtlString& pSrc, unsigned char* pDest, int* pDestLen) { if (!pSrc) return 0; return base64Decode((const unsigned char*)pSrc.data(), pSrc.length(), pDest, pDestLen); } UtlCryptoData* UtlCryptoKey::base64Decode(const unsigned char* pSrc, int srcLen) { // Allocate a destination buffer int destLen = getMaxBase64DecodedSize(srcLen); UtlCryptoData* pDest = new UtlCryptoData(destLen); if (!pDest) return 0; // Decode data into the buffer if (base64Decode(pSrc, srcLen, pDest->data(), &destLen) == 0) { delete pDest; return 0; } // Set the size of the destination buffer to the returned size pDest->resize(destLen); return pDest; } UtlCryptoData* UtlCryptoKey::base64Decode(const UtlString& pSrc) { // Allocate a destination buffer int destLen = getMaxBase64DecodedSize(pSrc.length()); UtlCryptoData* pDest = new UtlCryptoData(destLen); if (!pDest) return 0; // Decode data into the buffer if (base64Decode((const unsigned char*)pSrc.data(), pSrc.length(), pDest->data(), &destLen) == 0) { delete pDest; return 0; } // Set the size of the destination buffer to the returned size pDest->resize(destLen); return pDest; } #endifsipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlCryptoKeyRsa.cpp0000644000175000017500000001647012205613256025052 0ustar00danieldaniel00000000000000// // Copyright (C) 2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2008 Mutualink, Inc. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// #ifdef HAVE_SSL #include "utl/UtlCryptoKeyRsa.h" #include #include #include #include #include UtlCryptoKeyRsa::UtlCryptoKeyRsa() : mpRsa(0) { } UtlCryptoKeyRsa::~UtlCryptoKeyRsa() { clearKey(); } void UtlCryptoKeyRsa::clearKey() { if (mpRsa) { RSA_free(mpRsa); mpRsa = 0; } UtlCryptoKey::clearKey(); } int UtlCryptoKeyRsa::generateKey() { // Make sure we don't leave any previous keys hanging around clearKey(); int numKeyBits = 2048; unsigned long keyExponent = 65537; mpRsa = RSA_generate_key(numKeyBits, keyExponent, NULL, 0); if (mpRsa) { setKeyType(KEY_PRIVATE); return setLastError(0); } else { return setLastError(ERR_get_error()); } } int UtlCryptoKeyRsa::importFromFile(const char* pFilename) { // Make sure we don't leave any previous keys hanging around clearKey(); FILE *pFile = fopen(pFilename, "rt"); if (!pFile) return -1; // First try to read a public key mpRsa = PEM_read_RSA_PUBKEY(pFile, 0, 0, 0); if (mpRsa) setKeyType(KEY_PUBLIC); else { // If that failed, try to read a private key fseek(pFile, 0, SEEK_SET); mpRsa = PEM_read_RSAPrivateKey(pFile, 0, 0, 0); if (mpRsa) setKeyType(KEY_PRIVATE); } fclose(pFile); if (isValid()) return setLastError(0); else return -1; } inline int UtlCryptoKeyRsa::getMaxEncryptedSize(int srcLen) const { return RSA_size(mpRsa); } int UtlCryptoKeyRsa::encrypt(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const { if (isPrivate()) return encryptPrivate(pSrc, srcLen, pDest, pDestLen); else if (isPublic()) return encryptPublic(pSrc, srcLen, pDest, pDestLen); if (pDestLen) *pDestLen = 0; return 0; // TODO: Set lastError? } inline int UtlCryptoKeyRsa::getMaxDecryptedSize(int srcLen) const { return RSA_size(mpRsa); } int UtlCryptoKeyRsa::decrypt(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const { if (isPrivate()) return decryptPrivate(pSrc, srcLen, pDest, pDestLen); else if (isPublic()) return decryptPublic(pSrc, srcLen, pDest, pDestLen); if (pDestLen) *pDestLen = 0; return 0; // TODO: Set lastError? } int UtlCryptoKeyRsa::encryptPrivate(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const { if (!pSrc || !srcLen || !pDest || !pDestLen || *pDestLen < getMaxEncryptedSize(srcLen)) return 0; // Encrypt the data into the destination buffer int destLen = RSA_private_encrypt(srcLen, pSrc, pDest, mpRsa, RSA_PKCS1_PADDING); if (destLen == -1) { setLastError(ERR_get_error()); *pDestLen = 0; return 0; } setLastError(0); *pDestLen = destLen; return destLen; } int UtlCryptoKeyRsa::decryptPrivate(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const { if (!pSrc || !srcLen || !pDest || !pDestLen || *pDestLen < getMaxDecryptedSize(srcLen)) return 0; // Decrypt the data into the destination buffer int destLen = RSA_private_decrypt(srcLen, pSrc, pDest, mpRsa, RSA_PKCS1_PADDING); if (destLen == -1) { setLastError(ERR_get_error()); *pDestLen = 0; return 0; } setLastError(0); *pDestLen = destLen; return destLen; } int UtlCryptoKeyRsa::encryptPublic(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const { if (!pSrc || !srcLen || !pDest || !pDestLen || *pDestLen < getMaxEncryptedSize(srcLen)) return 0; // Encrypt the data into the destination buffer int destLen = RSA_public_encrypt(srcLen, pSrc, pDest, mpRsa, RSA_PKCS1_PADDING); if (destLen == -1) { setLastError(ERR_get_error()); *pDestLen = 0; return 0; } setLastError(0); *pDestLen = destLen; return destLen; } int UtlCryptoKeyRsa::decryptPublic(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const { if (!pSrc || !srcLen || !pDest || !pDestLen || *pDestLen < getMaxDecryptedSize(srcLen)) return 0; // Decrypt the data into the destination buffer int destLen = RSA_public_decrypt(srcLen, pSrc, pDest, mpRsa, RSA_PKCS1_PADDING); if (destLen == -1) { setLastError(ERR_get_error()); *pDestLen = 0; return 0; } setLastError(0); *pDestLen = destLen; return destLen; } int UtlCryptoKeyRsa::sign(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const { if (!pSrc || !srcLen || !pDest || !pDestLen || *pDestLen < getMaxSignatureSize(srcLen)) { if (pDestLen) *pDestLen = 0; return 0; } *pDestLen = 0; // First, compute the Message Digest (MD) of the source data int mdLen = EVP_MAX_MD_SIZE; unsigned char md[EVP_MAX_MD_SIZE]; if (computeDigest(pSrc, srcLen, &md[0], &mdLen) == 0) return 0; // Next, sign the Message Digest & return that if (!RSA_sign(getDigestAlgType(), &md[0], mdLen, pDest, (unsigned*)pDestLen, mpRsa)) { osPrintf("*****RSA_sign failed"); return 0; } setLastError(0); return *pDestLen; } int UtlCryptoKeyRsa::verify(const unsigned char* pSrc, int srcLen, const unsigned char* pSig, int sigLen) const { // First, compute the Message Digest (MD) of the source data int mdLen = EVP_MAX_MD_SIZE; unsigned char md[EVP_MAX_MD_SIZE]; if (computeDigest(pSrc, srcLen, &md[0], &mdLen) == 0) return -1; // Next, see if the signature matches the MD if (!RSA_verify(getDigestAlgType(), &md[0], mdLen, const_cast(pSig), sigLen, mpRsa)) { return -1; } return 0; } UtlString UtlCryptoKeyRsa::output() const { // Write any base class details first UtlString str = UtlCryptoKey::output(); BIO* pBio = BIO_new(BIO_s_mem()); RSA_print(pBio, mpRsa, 8 /*indent*/ ); BUF_MEM* pBufMem; BIO_get_mem_ptr(pBio, &pBufMem); pBufMem->data[pBufMem->length] = 0; str.append(pBufMem->data); BIO_free_all(pBio); return str; } int UtlCryptoKeyRsa::getMaxSignatureSize(int srcLen) const { return RSA_size(mpRsa); } #endif sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlCryptoKeySym.cpp0000644000175000017500000001471012205613256025070 0ustar00danieldaniel00000000000000// // Copyright (C) 2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2008 Mutualink, Inc. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// #ifdef HAVE_SSL #include "utl/UtlCryptoKeySym.h" #include "utl/UtlRandom.h" #include #include #include #include #include UtlCryptoKeySym::UtlCryptoKeySym() : mpCipher(EVP_des_cbc()) , mKeyLen(EVP_CIPHER_key_length(mpCipher)) , mIvLen(EVP_CIPHER_iv_length(mpCipher)) , mpKey(0) , mpIv(0) { } UtlCryptoKeySym::~UtlCryptoKeySym() { clearKey(); } void UtlCryptoKeySym::clearKey() { if (mpKey) { delete mpKey; mpKey = 0; } if (mpIv) { delete mpIv; mpIv = 0; } UtlCryptoKey::clearKey(); } int UtlCryptoKeySym::generateKey() { // Make sure we don't leave any previous keys hanging around clearKey(); // TODO: Need to do real keys & IVs here! UtlRandom r; mpKey = new UtlCryptoData(mKeyLen); for (int i=0; i < mKeyLen; i++) (*mpKey)[i] = r.rand(); if (mIvLen) { mpIv = new UtlCryptoData(mIvLen); for (int i=0; i < mIvLen; i++) (*mpIv)[i] = r.rand(); } setKeyType(KEY_SYMMETRIC); return 0; } int UtlCryptoKeySym::loadBinaryKey(const unsigned char* pSrc, int srcLen) { // Make sure we don't leave any previous keys hanging around clearKey(); if (!pSrc || srcLen < mKeyLen + mIvLen) return -1; // First load the Key mpKey = new UtlCryptoData(mKeyLen); for (int i=0; i < mKeyLen; i++) (*mpKey)[i] = *pSrc++; // Then load the IV if needed if (mIvLen) { mpIv = new UtlCryptoData(mIvLen); for (int i=0; i < mIvLen; i++) (*mpIv)[i] = *pSrc++; } setKeyType(KEY_SYMMETRIC); return 0; } UtlCryptoData* UtlCryptoKeySym::getBinaryKey() const { // Make sure we have a key (and IV if needed) before proceeding if (!mpKey || (!mpIv && mIvLen)) return 0; UtlCryptoData* pData = new UtlCryptoData(mKeyLen + mIvLen); unsigned char* pDest = pData->data(); // First write the key value for (int i=0; i < mKeyLen; i++) *pDest++ = (*mpKey)[i]; // Then write the IV if needed if (mIvLen) { for (int i=0; i < mIvLen; i++) *pDest++ = (*mpIv)[i]; } return pData; } int UtlCryptoKeySym::getMaxEncryptedSize(int srcLen) const { return srcLen + EVP_CIPHER_block_size(mpCipher); } int UtlCryptoKeySym::encrypt(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const { if (!pSrc || !srcLen || !pDest || !pDestLen || *pDestLen < getMaxEncryptedSize(srcLen)) return 0; *pDestLen = 0; // Make sure we have a key (and IV if needed) before proceeding if (!mpKey || (!mpIv && mIvLen)) { osPrintf("*****Need valid key before encrypting"); return 0; } EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); if (!EVP_EncryptInit_ex(&ctx, mpCipher, NULL, mpKey->data(), mpIv->data())) { osPrintf("*****EVP_EncryptInit_ex failed"); setLastError(ERR_get_error()); EVP_CIPHER_CTX_cleanup(&ctx); return 0; } // Go ahead and encrypt the src data into the dest buffer int bytesWritten = 0; unsigned char* pDestTail = pDest; if (!EVP_EncryptUpdate(&ctx, pDestTail, &bytesWritten, pSrc, srcLen)) { osPrintf("*****EVP_EncryptUpdate failed"); setLastError(ERR_get_error()); EVP_CIPHER_CTX_cleanup(&ctx); return 0; } pDestTail += bytesWritten; int bytesFinal = 0; if (!EVP_EncryptFinal_ex(&ctx, pDestTail, &bytesFinal)) { osPrintf("*****EVP_EncryptFinal_ex failed"); setLastError(ERR_get_error()); EVP_CIPHER_CTX_cleanup(&ctx); return 0; } // How many total bytes did we write to pDest? *pDestLen = bytesWritten + bytesFinal; EVP_CIPHER_CTX_cleanup(&ctx); setLastError(0); return *pDestLen; } int UtlCryptoKeySym::getMaxDecryptedSize(int srcLen) const { return srcLen; } int UtlCryptoKeySym::decrypt(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const { if (!pSrc || !srcLen || !pDest || !pDestLen || *pDestLen < getMaxDecryptedSize(srcLen)) return 0; *pDestLen = 0; // Make sure we have a key (and IV if needed) before proceeding if (!mpKey || (!mpIv && mIvLen)) { osPrintf("*****Need valid key before decrypting"); return 0; } EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX_init(&ctx); if (!EVP_DecryptInit_ex(&ctx, mpCipher, NULL, mpKey->data(), mpIv->data())) { osPrintf("*****EVP_DecryptInit_ex failed"); setLastError(ERR_get_error()); EVP_CIPHER_CTX_cleanup(&ctx); return 0; } // Go ahead and encrypt the src data into the dest buffer int bytesWritten = 0; unsigned char* pDestTail = pDest; if (!EVP_DecryptUpdate(&ctx, pDestTail, &bytesWritten, pSrc, srcLen)) { osPrintf("*****EVP_DecryptUpdate failed"); setLastError(ERR_get_error()); EVP_CIPHER_CTX_cleanup(&ctx); return 0; } pDestTail += bytesWritten; int bytesFinal = 0; if (!EVP_DecryptFinal_ex(&ctx, pDestTail, &bytesFinal)) { osPrintf("*****EVP_DecryptFinal_ex failed"); setLastError(ERR_get_error()); EVP_CIPHER_CTX_cleanup(&ctx); return 0; } // How many total bytes did we write to pDest? *pDestLen = bytesWritten + bytesFinal; EVP_CIPHER_CTX_cleanup(&ctx); setLastError(0); return *pDestLen; } int UtlCryptoKeySym::getTotalKeyLength() { return mKeyLen + mIvLen; } UtlBoolean UtlCryptoKeySym::getBinaryKey(char* buffer, int bufferLength) { if (bufferLength < getTotalKeyLength()) return FALSE; memcpy(buffer, mpKey, mKeyLen); memcpy(buffer + mKeyLen, mpIv, mIvLen); return TRUE; } UtlString UtlCryptoKeySym::output() const { // Write any base class details first UtlString str = UtlCryptoKey::output(); if (mpKey) { str.append("\n Key: "); str.append(mpKey->dumpHex()); } if (mpIv) { str.append("\n IV: "); str.append(mpIv->dumpHex()); } return str; } #endif sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlDateTime.cpp0000644000175000017500000000411512205613256024140 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDateTime.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS UtlContainableType UtlDateTime::TYPE = "UtlDateTime" ; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor accepting an optional default value. UtlDateTime::UtlDateTime(OsDateTime value) { mTime = value ; } // Copy constructor // Destructor UtlDateTime::~UtlDateTime() { } /* ============================ MANIPULATORS ============================== */ void UtlDateTime::setTime(const OsDateTime& value) { mTime = value ; } /* ============================ ACCESSORS ================================= */ void UtlDateTime::getTime(OsDateTime& value) const { value = mTime ; } unsigned UtlDateTime::hash() const { return mTime.getSecsSinceEpoch() ; } UtlContainableType UtlDateTime::getContainableType() const { return UtlDateTime::TYPE ; } /* ============================ INQUIRY =================================== */ int UtlDateTime::compareTo(UtlContainable const * inVal) const { int result ; if (inVal->isInstanceOf(UtlDateTime::TYPE)) { UtlDateTime* temp = (UtlDateTime*)inVal ; OsDateTime inTime; temp->getTime(inTime); int tempValue = inTime.getSecsSinceEpoch() ; result = tempValue - mTime.getSecsSinceEpoch() ; } else { result = 1 ; } return result ; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlLink.cpp0000644000175000017500000001474612205613256023354 0ustar00danieldaniel00000000000000// // Copyright (C) 2005 Pingtel Corp. // ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "assert.h" // APPLICATION INCLUDES /* * Include UtlInit so that static members are initialized. This ensures UtlLink will be * initialized whenever it is linked into program. If it is required to use UtlLink * or UtlPair in a constructor or destructor of a static object, the corresponding .cpp * file must also include UtlInit.h to safeguard proper constructor/destructor ordering. * UtlInit.h should be the first include. */ #include "utl/UtlInit.h" #include "os/OsDefs.h" #include "os/OsLock.h" #include "utl/UtlChainPool.h" #include "utl/UtlLink.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // The pool of available UtlLinks UtlChainPool* UtlLink::spLinkPool; // The pool of available UtlPairs UtlChainPool* UtlPair::spPairPool; // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /// Insert a new item into a list before an existing entry (before NULL == at the tail). void UtlChain::listBefore(UtlChain* list, UtlChain* existing ) { if (!existing) // before NULL means at the tail { // insert on the tail of the list if (list->prev) { // this list has at least one UtlLink on it, so just link this on the existing chain chainAfter(list->prev); list->prev = this; } else { list->next = this; list->prev = this; } } else { chainBefore(existing); if (list->next == existing) // existing was the head of the list { list->next = this; } } } /// Insert a new item into a list before an existing entry (after NULL == at the head). void UtlChain::listAfter(UtlChain* list, UtlChain* existing ) { if (!existing) // after NULL means at the head { // insert on the head of the list if (list->next) { // this list has at least one UtlLink on it, so just link this on the existing chain chainBefore(list->next); list->next = this; } else { list->next = this; list->prev = this; } } else { chainAfter(existing); if (list->prev == existing) // existing was the tail of the list { list->prev = this; } } } UtlChain* UtlChain::detachFromList(UtlChain* list) { if (this == list->next) { list->next = next; } if (this == list->prev) { list->prev = prev; } unchain(); return this; } UtlContainable* UtlLink::unlink() { // Take the link block out of its list, and return the data pointer unchain(); UtlContainable* theData = data; spLinkPool->release(this); // :NOTE: cannot reference any member after call to release... return theData; } UtlLink* UtlLink::before(UtlChain* existing, UtlContainable* newData) { UtlLink* newLink; newLink = get(); newLink->data = newData; newLink->hash = newData->hash(); newLink->chainBefore(existing); return newLink; } UtlLink* UtlLink::after(UtlChain* existing, UtlContainable* newData) { UtlLink* newLink; newLink = get(); newLink->data = newData; newLink->hash = newData->hash(); newLink->chainAfter(existing); return newLink; } /// Insert a new item into a list before an existing entry (before NULL == at the tail). UtlLink* UtlLink::listBefore(UtlChain* list, UtlChain* existing, UtlContainable* newData ) { UtlLink* newLink; newLink = get(); newLink->data = newData; newLink->hash = newData->hash(); newLink->UtlChain::listBefore(list, existing); return newLink; } /// Insert a new item into a list before an existing entry (after NULL == at the head). UtlLink* UtlLink::listAfter(UtlChain* list, UtlChain* existing, UtlContainable* newData ) { UtlLink* newLink; newLink = get(); newLink->data = newData; newLink->hash = newData->hash(); newLink->UtlChain::listAfter(list, existing); return newLink; } UtlContainable* UtlLink::detachFrom(UtlChain* list) { UtlContainable* theData; theData = data; data = NULL; hash = 0; detachFromList(list); release(); return theData; } /* * This is for use in UtlContainer only. * get a UtlLink for internal iterator list use. */ UtlLink* UtlLink::get() { return static_cast(spLinkPool->get()); } /// Return a UtlLink to the pool. void UtlLink::release() { spLinkPool->release(this); } /// Recalculate the hash for this item void UtlLink::rehash() { if (data) { hash = data->hash(); } } size_t UtlLink::totalAllocated() { return spLinkPool->totalAllocated(); } /* //////////////////////////// PRIVATE /////////////////////////////////// */ void UtlLink::allocate(size_t blocksize, ///< number of instances to allocate UtlChain* blockList, ///< list header for first instance UtlChain* pool ///< list header for others ) { UtlLink* newBlock = new UtlLink[blocksize]; assert(newBlock); // The first UtlChain is consumed to chain the list of blocks // so that the destructor can free them. newBlock->UtlChain::listBefore(blockList, NULL); // chain the rest of the new UtlLinks onto the mLinkPool for (size_t i = 1; i < blocksize; i++) { newBlock[i].UtlChain::listBefore(pool, NULL); } } void UtlPair::allocate(size_t blocksize, ///< number of instances to allocate UtlChain* blockList, ///< list header for first instance UtlChain* pool ///< list header for others ) { UtlPair* newBlock = new UtlPair[blocksize]; assert(newBlock); // The first UtlChain is consumed to chain the list of blocks // so that the destructor can free them. newBlock->UtlChain::listBefore(blockList, NULL); // chain the rest of the new UtlLinks onto the mLinkPool for (size_t i = 1; i < blocksize; i++) { newBlock[i].UtlChain::listBefore(pool, NULL); } } UtlPair* UtlPair::get() { return static_cast(spPairPool->get()); } void UtlPair::release() { spPairPool->release(this); } sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlVoidPtr.cpp0000644000175000017500000000401012205613256024025 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "utl/UtlInt.h" #include "utl/UtlVoidPtr.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS const UtlContainableType UtlVoidPtr::TYPE = "UtlVoidPtr" ; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlVoidPtr::UtlVoidPtr(void* pValue) { mpValue = pValue ; } // Copy constructor // Destructor UtlVoidPtr::~UtlVoidPtr() { } /* ============================ MANIPULATORS ============================== */ void* UtlVoidPtr::setValue(void* pValue) { void* pOldValue = mpValue ; mpValue = pValue ; return pOldValue ; } /* ============================ ACCESSORS ================================= */ void* UtlVoidPtr::getValue() const { return mpValue ; } unsigned UtlVoidPtr::hash() const { return (uintptr_t)mpValue; } UtlContainableType UtlVoidPtr::getContainableType() const { return UtlVoidPtr::TYPE ; } /* ============================ INQUIRY =================================== */ // Compare the this object to another like-object. int UtlVoidPtr::compareTo(UtlContainable const * inVal) const { int result ; if (inVal->isInstanceOf(UtlVoidPtr::TYPE)) { result = ((uintptr_t) mpValue) - ((uintptr_t) ((UtlVoidPtr*) inVal)->mpValue); } else { result = -1; } return result; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlHistogram.cpp0000644000175000017500000000777212205613256024415 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "utl/UtlHistogram.h" #include "os/OsTime.h" #include "os/OsDateTime.h" #include "os/OsSysLog.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlHistogram::UtlHistogram(unsigned int bins, int base, unsigned int size, const char* outputFormat, unsigned int outputWidth) { if (bins == 0) { OsSysLog::add(FAC_KERNEL, PRI_CRIT, "UtlHistogram::UtlHistogram bins must be at least 1"); bins = 1; } mNoOfBins = bins; mBase = base; if (size == 0) { OsSysLog::add(FAC_KERNEL, PRI_CRIT, "UtlHistogram::UtlHistogram size must be at least 1"); size = 1; } mBinSize = size; mpBins = new unsigned int[mNoOfBins + 2]; mCount = 0; mOutputFormat = outputFormat; mOutputWidth = outputWidth; } // Destructor UtlHistogram::~UtlHistogram() { delete[] mpBins; } /* ============================ MANIPULATORS ============================== */ unsigned int UtlHistogram::tally(int value) { // Calculate the bin number. unsigned int bin = (value - mBase) / mBinSize; // Increment the appropriate bin. ++mpBins[bin < 0 ? 0 : bin > mNoOfBins ? mNoOfBins + 1 : bin + 1]; // Increment the total count. mCount++; return mCount; } void UtlHistogram::clear() { // Clear the bins. // Remember that there are mNoOfBins + 2 bins. for (unsigned int i = 0; i < mNoOfBins + 2; i++) { mpBins[i] = 0; } // Clear the total count. mCount = 0; } /* ============================ ACCESSORS ================================= */ /** * Get the number of bins. */ unsigned int UtlHistogram::getNoOfBins() { return mNoOfBins; } /** * Get the lowest value for bin 0. */ unsigned int UtlHistogram::getBase() { return mBase; } /** * Get the size of each bin. */ unsigned int UtlHistogram::getBinSize() { return mBinSize; } /** * Get the total count. */ unsigned int UtlHistogram::getCount() { return mCount; } /** * Get the count in bin i. */ unsigned int UtlHistogram::operator[](unsigned int i) { // Normalize i to index mpBins[]. i++; return i >= 0 && i < mNoOfBins+2 ? mpBins[i] : 0; } /* ============================ INQUIRY =================================== */ /** * Get a string containing the formatted values from the bins. */ UtlString* UtlHistogram::show() { unsigned int width; // Buffer into which to sprintf the values. char* buffer = new char[(mNoOfBins+2) * mOutputWidth + 1]; // Translate the values. for (unsigned int i = 0, j = 0; i < mNoOfBins + 2; i++, j += width) { width = sprintf(&buffer[j], mOutputFormat, mpBins[i]); if (width > mOutputWidth) { OsSysLog::add(FAC_KERNEL, PRI_CRIT, "UtlHistogram::show output from format '%s' " "had width %d != declared width %d", mOutputFormat, width, mOutputWidth); } } // Since there is always at least one bin, sprintf was called at least // once and it ended the string with a NUL. // Construct the UtlString. UtlString* value = new UtlString(buffer); delete[] buffer; return value; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlInit.cpp0000644000175000017500000000417212205613256023352 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 Jaroslav Libak // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlInit.h" #include "utl/UtlLink.h" #include "utl/UtlChainPool.h" #include "utl/UtlContainer.h" #include "utl/UtlListIterator.h" // DEFINES // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS unsigned int UtlInit::msCount = 0; // MACROS // GLOBAL VARIABLES // GLOBAL FUNCTIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ UtlInit::UtlInit(void) { if (msCount++ == 0) { UtlContainer::spIteratorConnectionLock = new OsBSem(OsBSem::Q_PRIORITY, OsBSem::FULL); UtlLink::spLinkPool = new UtlChainPool(UtlLink::allocate, UTLLINK_BLOCK_SIZE); UtlPair::spPairPool = new UtlChainPool(UtlPair::allocate, UTLLINK_BLOCK_SIZE); UtlListIterator::OFF_LIST_END = new UtlLink(); } } UtlInit::~UtlInit(void) { if (--msCount == 0) { delete UtlListIterator::OFF_LIST_END; UtlListIterator::OFF_LIST_END = NULL; delete UtlPair::spPairPool; UtlPair::spPairPool = NULL; delete UtlLink::spLinkPool; UtlLink::spLinkPool = NULL; delete UtlContainer::spIteratorConnectionLock; UtlContainer::spIteratorConnectionLock = NULL; } } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlInt.cpp0000644000175000017500000000662512205613256023206 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2011 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include // APPLICATION INCLUDES #include "utl/UtlInt.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS UtlContainableType UtlInt::TYPE = "UtlInt" ; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor accepting an optional default value. UtlInt::UtlInt(int value) : mValue(value) { } // Copy constructor UtlInt::UtlInt(const UtlInt& rhs) : mValue(rhs.mValue) { } // Destructor UtlInt::~UtlInt() { } UtlCopyableContainable* UtlInt::clone() const { return new UtlInt(*this); } /* ============================ OPERATORS ============================== */ // Prefix increment operator UtlInt& UtlInt::operator++() { mValue++; return *this; } // Postfix increment operator UtlInt UtlInt::operator++(int) { UtlInt temp = *this; ++*this; return temp; } // Prefix decrement operator UtlInt& UtlInt::operator--() { mValue--; return *this; } // Postfix decrement operator UtlInt UtlInt::operator--(int) { UtlInt temp = *this; --*this; return temp; } UtlInt& UtlInt::operator=(const UtlInt& rhs) { if (this == &rhs) // handle the assignment to self case return *this; // Assign values mValue = rhs.mValue; return *this; } void UtlInt::toString(UtlString& stringInt, int valueToStringify) { char buf[20]; sprintf(buf, "%d", valueToStringify); stringInt = buf; } /* ============================ MANIPULATORS ============================== */ int UtlInt::setValue(int iValue) { int iOldValue = mValue ; mValue = iValue ; return iOldValue ; } /* ============================ ACCESSORS ================================= */ int UtlInt::getValue() const { return mValue ; } unsigned UtlInt::hash() const { return mValue ; } UtlContainableType UtlInt::getContainableType() const { return UtlInt::TYPE ; } /* ============================ INQUIRY =================================== */ int UtlInt::compareTo(UtlContainable const * inVal) const { int result ; if (inVal->isInstanceOf(UtlInt::TYPE)) { UtlInt* temp = (UtlInt*)inVal ; int inInt = temp -> getValue() ; result = mValue - inInt ; } else { result = INT_MAX ; } return result ; } UtlBoolean UtlInt::isEqual(UtlContainable const * inVal) const { return (compareTo(inVal) == 0) ; } UtlBoolean UtlInt::isInstanceOf(const UtlContainableType type) const { // Check if it is my type and the defer parent type comparisons to parent return(areSameTypes(type, UtlInt::TYPE) || UtlCopyableContainable::isInstanceOf(type)); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlIntPtr.cpp0000644000175000017500000000663012205613256023670 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2011 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include // APPLICATION INCLUDES #include "utl/UtlIntPtr.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS UtlContainableType UtlIntPtr::TYPE = "UtlIntPtr"; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor accepting an optional default value. UtlIntPtr::UtlIntPtr(intptr_t value) : mValue(value) { } // Copy constructor UtlIntPtr::UtlIntPtr(const UtlIntPtr& rhs) : mValue(rhs.mValue) { } // Destructor UtlIntPtr::~UtlIntPtr() { } UtlCopyableContainable* UtlIntPtr::clone() const { return new UtlIntPtr(*this); } /* ============================ OPERATORS ============================== */ // Prefix increment operator UtlIntPtr& UtlIntPtr::operator++() { mValue++; return *this; } // Postfix increment operator UtlIntPtr UtlIntPtr::operator++(int) { UtlIntPtr temp = *this; ++*this; return temp; } // Prefix decrement operator UtlIntPtr& UtlIntPtr::operator--() { mValue--; return *this; } // Postfix decrement operator UtlIntPtr UtlIntPtr::operator--(int) { UtlIntPtr temp = *this; --*this; return temp; } UtlIntPtr& UtlIntPtr::operator=(const UtlIntPtr& rhs) { if (this == &rhs) // handle the assignment to self case return *this; // Assign values mValue = rhs.mValue; return *this; } /* ============================ MANIPULATORS ============================== */ intptr_t UtlIntPtr::setValue(intptr_t iValue) { intptr_t iOldValue = mValue ; mValue = iValue ; return iOldValue ; } /* ============================ ACCESSORS ================================= */ intptr_t UtlIntPtr::getValue() const { return mValue ; } unsigned UtlIntPtr::hash() const { return (unsigned)mValue ; } UtlContainableType UtlIntPtr::getContainableType() const { return UtlIntPtr::TYPE ; } /* ============================ INQUIRY =================================== */ int UtlIntPtr::compareTo(UtlContainable const * inVal) const { int result ; if (inVal->isInstanceOf(UtlIntPtr::TYPE)) { UtlIntPtr* temp = (UtlIntPtr*)inVal ; intptr_t inInt = temp->getValue() ; result = (int)(mValue - inInt); } else { result = INT_MAX ; } return result ; } UtlBoolean UtlIntPtr::isEqual(UtlContainable const * inVal) const { return (compareTo(inVal) == 0) ; } UtlBoolean UtlIntPtr::isInstanceOf(const UtlContainableType type) const { // Check if it is my type and the defer parent type comparisons to parent return(areSameTypes(type, UtlIntPtr::TYPE) || UtlCopyableContainable::isInstanceOf(type)); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlString.cpp0000644000175000017500000007744712205613256023734 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2011 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #include // APPLICATION INCLUDES #include "utl/UtlString.h" #include "os/OsDefs.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define UTLSTRING_MIN_INCREMENT 100 ///< smallest additional memory to be allocated // STATIC VARIABLE INITIALIZATIONS const UtlContainableType UtlString::TYPE = "UtlString"; const char* UtlString::ssNull = ""; const size_t UtlString::UTLSTRING_NOT_FOUND = (size_t) (-1); const size_t UtlString::UTLSTRING_TO_END = (size_t) (-1); /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Default Constructor UtlString::UtlString() { mpData = mBuiltIn; mBuiltIn[0] = '\000'; mSize = 0; mCapacity = DEFAULT_UTLSTRING_CAPACITY; } // Copy constructor UtlString::UtlString(const char* szSource) { mpData = mBuiltIn; mBuiltIn[0] = '\000'; mSize = 0; mCapacity = DEFAULT_UTLSTRING_CAPACITY; append(szSource); } // Copy constructor UtlString::UtlString(const char* szSource, size_t length) { mpData = mBuiltIn; mBuiltIn[0] = '\000'; mSize = 0; mCapacity = DEFAULT_UTLSTRING_CAPACITY; append(szSource, length); } // Copy constructor UtlString::UtlString(const UtlString& source) { mpData = mBuiltIn; mBuiltIn[0] = '\000'; mSize = 0; mCapacity = DEFAULT_UTLSTRING_CAPACITY; capacity(source.mCapacity); append(source); } // Copy constructor UtlString::UtlString(const UtlString& source, size_t length) { mpData = mBuiltIn; mBuiltIn[0] = '\000'; mSize = 0; mCapacity = DEFAULT_UTLSTRING_CAPACITY; capacity(source.mCapacity); // Check that we do not copy beyond the end of source if(length > source.mSize) { length = source.mSize; } append(source.mpData, length); } UtlCopyableContainable* UtlString::clone() const { return new UtlString(*this); } // Destructor UtlString::~UtlString() { if(mpData && mpData != mBuiltIn) { delete[] mpData; } mpData = NULL; mCapacity = 0; mSize = 0; } /* ============================ MANIPULATORS ============================== */ // Assignment operator, use append(const char*). UtlString& UtlString::operator=(const char* szStr) { // check for self assignment if (mpData != szStr) { remove(0); if(szStr && *szStr) { append(szStr); } } return *this; } // Assignment operator, use append(const char* , size_t ). UtlString& UtlString::operator=(const UtlString& str) { if (this != &str) { remove(0); if(str.mCapacity > mCapacity) { capacity(str.mCapacity); } append(str.mpData, str.mSize); } return *this; } // Plus equals operator, use append(const char*). UtlString& UtlString::operator+=(const char* szStr) { return append(szStr); } // Plus equals operator, use append(const UtlString& ). UtlString& UtlString::operator+=(const UtlString& str) { return append(str); } // Plus equals operator, use append(const char). UtlString& UtlString::operator+=(const char c) { return append(c); } // Get the character at position N. char UtlString::operator()(size_t N) { char foundChar = '\0'; if (mpData && N >= 0 && N < mSize) { foundChar = mpData[N]; } return foundChar; } // prepend:prepend a copy of the null-terminated character string pointed // to by szStr to self.Returns a reference to self. // use append(). UtlString& UtlString::prepend(const char* szStr) { UtlString newUtlString; //FIX: should avoid allocation if capacity is big enough newUtlString.append(szStr); newUtlString.append(mpData); remove(0); append(newUtlString); return *this ; } // Append the designated string to the end of this string. // use append(const char* szStr, size_t N) UtlString& UtlString::append(const char* szStr) { if (szStr) { append(szStr, strlen(szStr)); } return *this; } // Append the designated string to the end of this string. // use append(const char* szStr, size_t N) UtlString& UtlString::append(const char c) { append(&c, 1); return *this; } // Append up to N bytes of the designated string to the end of this string. UtlString& UtlString::append(const char* szStr, size_t N) { // The N bytes to append may contain zero bytes. if(szStr && N>0) { // Calculate the total space needed, including room for a final // zero byte. size_t maxCap = mSize + N + 1; // If necessary, reallocate the data area to hold maxCap bytes. if (maxCap <= capacity(maxCap)) { if (mpData) { // Copy the N bytes after the existing mSize bytes in the string. memcpy(&mpData[mSize], szStr, N); // Update the size of the string. mSize += N; // Append a final zero byte. mpData[mSize] = '\0'; } } else { //allocate failure, do nothing; } } return *this; } UtlString& UtlString::appendFormat(const char* format, ...) { va_list args; va_start(args, format); int n; int extraSize = 0; for(;;) { size_t availableCap = capacity() - mSize; va_list tmp; /* Argument list must be copied, because we call vsnprintf in a loop * and first call will invalidate list, so on second iteration it * will contain junk. (this is not a problem for i386, but appears * as such on e.g. x86_64) */ va_copy(tmp, args); /* Try to print in the allocated space. */ n = vsnprintf (&mpData[mSize], availableCap, format, tmp); va_end(tmp); /* If that worked, return the string. */ if (n > -1 && n < (int)availableCap) { break; } /* Else try again with more space. */ if (n > -1) /* glibc 2.1 */ extraSize = n+1; /* precisely what is needed */ else /* glibc 2.0 */ if (extraSize == 0) extraSize = availableCap; else extraSize *= 2; /* twice the old size */ capacity(mSize + extraSize); } mSize += n; va_end(args); return *this; } // Append the designated string to the end of this string. // use append(const char* ). UtlString& UtlString::append(const UtlString& str) { append(str.mpData, str.mSize); return *this ; } // Append the designated string to the end of this string. // use append(const char* ). UtlString& UtlString::append(const UtlString& str, size_t position, size_t length) { if (position < str.mSize) { if ( (length == UTLSTRING_TO_END) || (position+length > str.mSize) ) { length = str.mSize - position; } append(str.mpData+position, length); } return *this; } UtlString& UtlString::insert(size_t position, const char* source) { if(source && position < mSize) { size_t len = strlen(source); insert(position, source, len); } else if (source && position == mSize) { append(source); } return(*this); } UtlString& UtlString::insert(size_t position, const char* source, size_t sourceLength) { if(position <= mSize) { if(mCapacity < mSize + sourceLength + 1) { capacity(mSize + sourceLength + 1); } if (mpData) { memmove(&mpData[position + sourceLength], &mpData[position], mSize - position); memcpy(&mpData[position], source, sourceLength); mSize+= sourceLength; mpData[mSize] = '\0'; } } // Else do nothing return(*this); } UtlString& UtlString::insert(size_t position, const char source) { return(insert(position, &source, 1)); } // Insert the designated string starting at character position start. UtlString& UtlString::insert(size_t start, const UtlString& str) { if(start >= 0 && start <= mSize && str.mpData && str.mSize > 0) { insert(start, str.mpData, str.mSize); } else { //do nothing. } return *this; } // Remove all characters after the specified position. UtlString& UtlString::remove(size_t pos) { if(mpData && pos >= 0 && pos < mSize) { mSize = pos; mpData[mSize] = '\0'; } else { //do nothing } return *this; } // Remove N characters from this string starting at designated position. UtlString& UtlString::remove(size_t pos, size_t N) { if(mpData && N > 0 && N <= mSize - pos && pos >= 0 && pos < mSize) { // Add one extra byte for the '\0' size_t bytesToShift = mSize - (pos + N) + 1; // memcpy() cannot be used here due to possible overlap of source // and destination areas! memmove(&mpData[pos], &mpData[pos + N], bytesToShift); mSize -= N; mpData[mSize] = '\0'; } else { //do nothing } return *this; } // Replace a single character at the designated position void UtlString::replaceAt(size_t pos, char newChar) { if (mpData && mSize > pos) { mpData[pos] = newChar; } } // Replace N characters starting at the designated position with the // designated replacement string. // use replace(size_t pos, size_t N, const char* replaceStr, size_t L). UtlString& UtlString::replace(size_t pos, size_t N, const char* replaceStr) { return replace(pos, N, replaceStr, strlen(replaceStr)); } // Replace N characters starting at the designated position with the // designated replacement string. UtlString& UtlString::replace(size_t pos, size_t N, const UtlString& replaceStr) { return replace(pos, N, replaceStr.mpData, replaceStr.mSize); } // Replace N characters starting at the designated position with a subset // of the designated replacement string. // use strncpy() to realize. UtlString& UtlString::replace(size_t pos, size_t N, const char* replaceStr, size_t L) { // FIX: need to avoid the allocation and extra copy if possible if ((replaceStr != NULL) && (pos >= 0) && (N >= 0) && (strlen(replaceStr) >= L) && (mpData) ) { UtlString newUtlString; newUtlString.append(mpData, pos); newUtlString.append(replaceStr, L); if(int(mSize - N - pos) > 0) //can not change to size_t { newUtlString.append(&mpData[pos + N], mSize - N - pos); } remove(0); append(newUtlString); } else { //do nothing; } return *this; } // Replace all instances of character src with character tgt UtlString& UtlString::replace(const char src, const char tgt) { if (mpData && (src!=0) && (tgt!=0)) { for (size_t i=0; i 0) { if(type == both) { strip(leading); //Here I use the method of recursion. strip(trailing); } else if(type == leading) { unsigned int removeLeading = 0; const char* leadingPtr = mpData; while(removeLeading < mSize && (*leadingPtr == '\t' || *leadingPtr == ' ' || *leadingPtr == '\n' || *leadingPtr == '\r')) { removeLeading++; leadingPtr++; } if(removeLeading > 0) { remove(0, removeLeading); } } else { unsigned int removeTrailing = 0; const char* trailingPtr = mpData + mSize - 1; while(removeTrailing < mSize && (*trailingPtr == '\t' || *trailingPtr == ' ' || *trailingPtr == '\n' || *trailingPtr == '\r')) { removeTrailing++; trailingPtr--; } if(removeTrailing > 0) { remove(mSize - removeTrailing); } } } return *this; } // Remove the designated character from the beginning of the string, // from the end of the string, or from both the beginning and end of // the string. // use remove(size_t pos, size_t N) UtlString UtlString::strip(StripType type , char toBeStriped) { if(mpData && mSize > 0) { if (type == leading || type == both) { unsigned int removeLeading = 0; while(mSize > removeLeading && mpData[removeLeading] == toBeStriped) { removeLeading++; } if(removeLeading > 0) { remove(0, removeLeading); } } if(type == trailing || type == both) { unsigned int removeTrailing = 0; while(mSize > removeTrailing && mpData[mSize - 1 - removeTrailing] == toBeStriped) { removeTrailing++; } if(removeTrailing > 0) { remove(mSize - removeTrailing); } } } return *this; } // Convert the string to all lower case characters. // use tolower(char*) of Standard C++ Library. void UtlString::toLower() { if(mpData) { char* charPtr; for(size_t i = 0; i < mSize; i++) { charPtr = &mpData[i]; *charPtr = tolower(*charPtr); } } } // Convert the string to all upper case characters. // use toUpper(char*) of Standard C++ Library void UtlString::toUpper() { if(mpData) { char* charPtr; for(size_t i = 0; i < mSize; i++) //waring point { charPtr = &mpData[i]; *charPtr = toupper(*charPtr); } } } // Resize the string to the specified size. // use capacity(size_t). void UtlString::resize(size_t N, UtlBoolean clearTail) { if(N > mSize) { if (mCapacity <= N) { capacity(N + 1); } if (clearTail) { if (mpData) { for (; mSize < N; mSize++) { mpData[mSize] = '\0'; } mpData[mSize] = '\0'; } } else { mSize = N; } } else { remove(N); } } // Set the string's storage capacity to the designated value. size_t UtlString::capacity(size_t N) { #ifdef _VXWORKS size_t maxFreeBlockSize = 0; #endif size_t newSize = 0; char* newData = 0; if(mCapacity < N && N > 0) { if(mCapacity + UTLSTRING_MIN_INCREMENT > N) { N = mCapacity + UTLSTRING_MIN_INCREMENT; } #ifdef _VXWORKS if (N > CHECK_BLOCK_THRESHOLD) { maxFreeBlockSize = FindMaxFreeBlock(); // We are not going over the largest block size then try to // allocate otherwise we will return NULL, and the size returned // will be zero! if (N < maxFreeBlockSize) { newData = new char[N]; } } else { newData = new char[N]; } #else //for all other OS's lets assume it really returns NULL and not crashes newData = new char[N]; #endif if (newData) { if(mSize > 0 && mpData) { memcpy(newData, mpData, mSize); } else { newData[0] = '\0'; } if(mpData && mpData != mBuiltIn) { delete[] mpData; } mpData = newData; newSize = mCapacity = N; } else { osPrintf("******** ERROR******* : UtlString::capacity failed (%"PRIuMAX"). Memory not allocated!\n", N); #ifdef _VXWORKS osPrintf("******** ERROR******* : Largest block = %"PRIuMAX", requested size = %"PRIuMAX"\n",maxFreeBlockSize, N); #endif newSize = 0; } } else { newSize = mCapacity; } return(newSize); } //Addition operator UtlString operator+(const UtlString& str1, const UtlString& str2) { UtlString NewS = str1; NewS.append(str2); return NewS; } //Addition operator UtlString operator+(const UtlString& str, const char* szStr) { UtlString NewS = str; NewS.append(szStr); return NewS; } //Addition operator UtlString operator+(const char* szStr, const UtlString& str) { UtlString newS(szStr); newS.append(str); return newS; } /* ============================ ACCESSORS ================================= */ // Returns the index of the first occurrence of the character searchChar in self. // Returns "-1" if there is no such character or if there is an embedded // null prior to finding c. // use index(). size_t UtlString::first(char searchChar) const { return index(searchChar) ; } // Find the first instance of the designated string or UTLSTRING_NOT_FOUND // if not found. size_t UtlString::first(const char * searchStr) const { return index(searchStr); } // Return the string length. size_t UtlString::length() const { return mSize; } // Return a read-only pointer to the underlying data. const char* UtlString::data() const { return(mpData ? mpData : ssNull); } // Return the index of the designated character or UTLSTRING_NOT_FOUND // if not found. size_t UtlString::index(char searchChar) const { return index(searchChar, 0); } // Return the index of the designated character starting at the // designated postion or UTLSTRING_NOT_FOUND if not found. size_t UtlString::index(char searchChar, size_t start) const { size_t foundPosition = UTLSTRING_NOT_FOUND; if(mpData) { size_t startIndex = start; for(size_t pos = startIndex; pos < mSize && foundPosition == UTLSTRING_NOT_FOUND; pos++) { if(mpData[pos] == searchChar) { foundPosition = pos; } } } return foundPosition; } // Optimization to avoid strlen call as well as the only // safe way to work with binary or opaque data size_t UtlString::index(const UtlString& searchString) const { return(index(searchString, 0)); } // Optimization to avoid strlen call as well as the only // safe way to work with binary or opaque data size_t UtlString::index(const UtlString& searchString, size_t start) const { size_t foundPosition = UTLSTRING_NOT_FOUND; // mpData may be null, so use data() which returns an // static empty string if mpData is null const char* dataPtr = data(); size_t searchStrSize = searchString.length(); size_t startIndex = start; if(searchStrSize <= mSize) { for (size_t pos = startIndex; pos <= (mSize - searchStrSize) && foundPosition == UTLSTRING_NOT_FOUND; pos++) { if (memcmp(dataPtr + pos, searchString.data(), searchStrSize) == 0) { foundPosition = pos; } } } return foundPosition; } // Return the index of the designated substring starting at the // designated position or UTLSTRING_NOT_FOUND if not found. // Optimization to avoid strlen call as well as the only // safe way to work with binary or opaque data size_t UtlString::index(const UtlString& searchString, size_t start, CompareCase type) const { size_t foundPosition = UTLSTRING_NOT_FOUND; size_t searchStrSize = searchString.length(); size_t startIndex = start; if (type == matchCase) { foundPosition = index(searchString, start); } else { // mpData may be null, so use data() which returns an // static empty string if mpData is null const char* dataPtr = data(); if (!dataPtr) assert(0); if(searchStrSize <= mSize) { for (size_t pos = startIndex; pos <= (mSize - searchStrSize) && foundPosition == UTLSTRING_NOT_FOUND; pos++) { if(strncasecmp(dataPtr + pos, searchString.data(), searchStrSize) == 0) { foundPosition = pos; } } } } return foundPosition; } // Return the index of the designated substring or UTLSTRING_NOT_FOUND if not found. // Pattern matching. I think the arithmetic should be optimized. // such as KMP: http://www.ics.uci.edu/~eppstein/161/960227.html size_t UtlString::index(const char* searchStr) const { return index(searchStr, 0); } // Return the index of the designated substring starting at the // designated position or UTLSTRING_NOT_FOUND if not found. size_t UtlString::index(const char* searchStr, size_t start) const { size_t foundPosition = UTLSTRING_NOT_FOUND; if(searchStr) { // mpData may be null, so use data() which returns an // static empty string if mpData is null const char* dataPtr = data(); // dataPtr better not be NULL if (!dataPtr) assert(0); size_t searchStrSize = strlen(searchStr); size_t startIndex = start; if(searchStrSize <= mSize) { for (size_t pos = startIndex; pos <= (mSize - searchStrSize) && foundPosition == UTLSTRING_NOT_FOUND; pos++) { if (memcmp(dataPtr + pos, searchStr, searchStrSize) == 0) { foundPosition = pos; } } } } return foundPosition; } // Return the index of the designated substring starting at the // designated position or UTLSTRING_NOT_FOUND if not found. size_t UtlString::index(const char* searchStr, size_t start, CompareCase type) const { size_t foundPosition = UTLSTRING_NOT_FOUND; if(searchStr) { size_t searchStrSize = strlen(searchStr); size_t startIndex = start; if (type == matchCase) { foundPosition = index(searchStr, start); } else { // mpData may be null, so use data() which returns an // static empty string if mpData is null const char* dataPtr = data(); if (!dataPtr) assert(0); for (int pos = startIndex; pos <= int(mSize - searchStrSize) && foundPosition == UTLSTRING_NOT_FOUND; pos++) { if(strncasecmp(dataPtr + pos, searchStr, searchStrSize) == 0) { foundPosition = pos; } } } } return foundPosition; } // Returns the index of the last occurrence in the string of the character s. size_t UtlString::last(char searchChar) const { size_t foundPosition = UTLSTRING_NOT_FOUND; if(mpData) { size_t startIndex = 0; for(size_t pos = startIndex; pos < mSize; pos++) { if(mpData[pos] == searchChar) { foundPosition = pos; } } } return foundPosition; } // Return the storage capacity allocated for this string. size_t UtlString::capacity() const { return mCapacity; } // Returns an UtlString of self with length len, starting at index. // Just return a copy. UtlString UtlString::operator() (size_t start, size_t len) const { UtlString newUtlString; // Note that since unsigned arithmetic can overflow, we have to test that // start + len >= start. if (mpData && start <= mSize && len == UTLSTRING_TO_END ) { // Get all of the string after start. newUtlString.append(&mpData[start], mSize - start); } else if (mpData && start <= start + len && start + len <= mSize) { // Get len characters. newUtlString.append(&mpData[start], len); } return newUtlString; } #if 0 UtlString UtlString::operator()(const RegEx& re) const { } #endif /* 0 */ // Cast this object to a const char* pointer. UtlString::operator const char*() const { return (data()); } // Returns a hash value. unsigned UtlString::hash() const { // Need to use data() in case mpData is null const char* pHashData = data(); size_t hashSize = mSize; unsigned hashValue = 0; while (hashSize > 0) { hashValue = (hashValue << 5) - hashValue + *pHashData; pHashData++; hashSize--; } return hashValue; } // Get the ContainableType for a UtlContainable derived class. UtlContainableType UtlString::getContainableType() const { return UtlString::TYPE; } /* ============================ INQUIRY =================================== */ // Not equals operator. // use compareTo(). UtlBoolean operator!=(const char* compareStr, const UtlString& compareUtlStr) { return compareUtlStr.compareTo(compareStr) != 0; } // Not equals operator. // compare the first byte of str and the char. UtlBoolean operator!=(const char compareChar, const UtlString& compareUtlStr) { UtlBoolean operatorFlag = TRUE; if (compareUtlStr.mpData && compareUtlStr.mSize == 1 && compareUtlStr.mpData[0] == compareChar) { operatorFlag = FALSE; } return operatorFlag; } // Equals operator. // compare the first byte of str and the char. UtlBoolean operator==(const char compareChar, const UtlString& compareUtlStr) { UtlBoolean operatorFlag = FALSE; if (compareUtlStr.mpData && compareUtlStr.mSize == 1 && compareUtlStr.mpData[0] == compareChar) { operatorFlag = TRUE; } return operatorFlag; } UtlBoolean operator==(const char* compareStr, const UtlString& compareUtlStr) { return compareUtlStr.compareTo(compareStr) == 0; } UtlBoolean UtlString::operator==(const char *compareStr) const { return compareTo(compareStr) == 0; } UtlBoolean UtlString::operator==(const UtlString& compareStr) const { return compareTo(compareStr) == 0; } UtlBoolean UtlString::operator!=(const char *compareStr) const { return compareTo(compareStr) != 0; } UtlBoolean UtlString::operator!=(const UtlString& compareStr) const { return compareTo(compareStr) != 0; } // Compare this object to another like-objects. int UtlString::compareTo(UtlContainable const * compareContainable) const { int compareFlag = -1; if (compareContainable && compareContainable->isInstanceOf(UtlString::TYPE) == TRUE ) { compareFlag = compareTo(((UtlString*) compareContainable)->data()); } return compareFlag; } // Test this object to another like-object for equality. UtlBoolean UtlString::isEqual(UtlContainable const * compareContainable) const { return (compareTo(compareContainable) == 0); } // Compare this object to the specified string (case sensitive). int UtlString::compareTo(const char * compareStr) const { int compareFlag; if (compareStr) { compareFlag = compareTo(compareStr, matchCase); } else { // compareStr == NULL means it represents the null string. compareFlag = mSize > 0 ? 1 : 0; } return(compareFlag); } // Compare this object to the specified string with option of forcing // either a case insensitive compare or a case sensitive compare. int UtlString::compareTo(UtlString const * compareStr, CompareCase type) const { int compareFlag = -1; if(compareStr->isInstanceOf(UtlString::TYPE) == TRUE) { if (mSize == 0 || compareStr->mSize == 0 ) { if (compareStr->mSize != mSize) { compareFlag = mSize > compareStr->mSize ? 1 : -1; } else { compareFlag = 0; } } else { if (type == matchCase) { // BUG: Need to use memcmp mpData may have null char before end compareFlag = strcmp(mpData ? mpData : "", compareStr->mpData); } else { compareFlag = strcasecmp(mpData ? mpData : "", compareStr->mpData); } } } return compareFlag; } // Compare this object to the specified string with option of forcing // either a case insensitive compare of a case sensitive compare. int UtlString::compareTo(const char* compareStr, CompareCase type) const { int compareFlag; if (type == matchCase) { // BUG: should use memcmp as compareStr may have null char before end compareFlag = strcmp(mpData ? mpData : "", compareStr ? compareStr : ""); } else { compareFlag = strcasecmp(mpData ? mpData : "", compareStr ? compareStr : ""); } return compareFlag; } // Returns TRUE if szStr occurs in self. // use index(const char * szStr). UtlBoolean UtlString::contains(const char* searchStr) const { UtlBoolean containFlag = TRUE; size_t containPosition = index(searchStr); if (containPosition == UTLSTRING_NOT_FOUND) { containFlag = FALSE; } return containFlag; } // Return true if this is a empty (or null) string. UtlBoolean UtlString::isNull() const { return(mSize == 0); } UtlBoolean UtlString::isInstanceOf(const UtlContainableType type) const { // Check if it is my type and the defer parent type comparisons to parent return(areSameTypes(type, UtlString::TYPE) || UtlCopyableContainable::isInstanceOf(type)); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ #if defined(_VXWORKS) /* * perform string compare not caring for case of the * characters. Compare only first N characters of the * string. */ int strncasecmp( const char *s1, const char *s2, int N ) { int i; char c1, c2; // check simple case if ((s1 == s2) || (0 == N)) { // match found return 0; } // if just one of them is NULL then there is a mistmatch if (!s1) { // NO match return -1; } else if (!s2) { // NO match return 1; } // loop thru all N entries for (i=0; idetachFromList(&mPool); } } // end of critical section return newChain; } void UtlChainPool::release( UtlChain* freeChain ) { OsLock poolLock(mLock); // put this freed object on the tail of the pool list freeChain->listBefore(&mPool, NULL); } /* //////////////////////////// PRIVATE /////////////////////////////////// */ UtlChainPool::~UtlChainPool() { OsLock poolLock(mLock); UtlChain* block; while (!mBlocks.isUnLinked()) // blocks still on block list { block = mBlocks.listHead()->detachFromList(&mBlocks); delete[] block; } } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlContainable.cpp0000644000175000017500000000560412205613256024667 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2011 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "utl/UtlContainable.h" #include "os/OsIntTypes.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS const UtlContainableType UtlContainable::TYPE = "UtlContainable" ; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor // Copy constructor // Destructor UtlContainable::~UtlContainable() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ // RTTI UtlBoolean UtlContainable::areSameTypes(const UtlContainableType type1, const UtlContainableType type2) { return(type1 != NULL && type2 != NULL && (type1 == type2 || (strcmp(type1, type2) == 0))); } UtlBoolean UtlContainable::isInstanceOf(const UtlContainableType type) const { return(areSameTypes(type, UtlContainable::TYPE) || // This is for upward compatablity as many sub-classes do not yet // implement isInstanceOf. This may be redundent in some cases. areSameTypes(type, getContainableType())); } // Test this object to another like-object for equality. UtlBoolean UtlContainable::isEqual(UtlContainable const * compareContainable) const { return ( compareTo(compareContainable) == 0 ); } /// Provides a hash function that uses the object pointer as the hash value. unsigned UtlContainable::directHash() const { return (uintptr_t) this; } /// Provides a hash function appropriate for null-terminated string values. unsigned UtlContainable::stringHash(char const* value) { /* * Adapted from * "Data Structures and Algorithms with Object-Oriented Design Patterns in C++" * by Bruno R. Preiss * http://www.brpreiss.com/books/opus4/html/page218.html#proghash3c */ unsigned const mask = 0x3f; unsigned const shift = 6; unsigned result = 0; while (!*value) { result = (result & mask) ^ (result << shift) ^ *value; } return result; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlContainer.cpp0000644000175000017500000001150212205613256024364 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES // Keep UtlInit.h as the first include! // See UtlInit class description for more information. #include "utl/UtlInit.h" #include "utl/UtlContainer.h" #include "utl/UtlLink.h" #include "utl/UtlIterator.h" #include "os/OsLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const UtlContainableType UtlContainer::TYPE = "UtlContainer"; // STATIC VARIABLE INITIALIZATIONS OsBSem* UtlContainer::spIteratorConnectionLock; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlContainer::UtlContainer() : mContainerLock(OsBSem::Q_PRIORITY, OsBSem::FULL) { } // Destructor UtlContainer::~UtlContainer() { } // invalidateIterators() isn't called by the UtlContainer destructor // (and need not be, since no iterators are defined for UtlContainer), // but it is used by the methods for various subclasses. void UtlContainer::invalidateIterators() { UtlLink* listNode; UtlIterator* foundIterator; // The caller is holding the sIteratorConnectionLock and mContainerLock. // Walk the list to notify the iterators. for (listNode = static_cast(mIteratorList.head()); listNode != NULL; listNode = listNode->next() ) { foundIterator = (UtlIterator*)listNode->data; foundIterator->invalidate(); } assert(mIteratorList.isUnLinked());// some iterator failed to call removeIterator } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ // These are here because every UtlContainer is also a UtlContainable /** * Calculate a unique hash code for this object. If the equals * operator returns true between two objects, then both objects * must have the same hash code. */ unsigned UtlContainer::hash() const { // default implementation return (uintptr_t) this; } /** * Get the ContainableType for a UtlContainable derived class. */ UtlContainableType UtlContainer::getContainableType() const { return UtlContainer::TYPE; } /* ============================ INQUIRY =================================== */ /** * Compare the this object to another like object. Results for * comparing with a non-like object are undefined. * * @returns 0 if equal, <0 if less than and >0 if greater. */ int UtlContainer::compareTo(const UtlContainable* otherObject) const { return ((uintptr_t) this) - ((uintptr_t) otherObject); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /// Lock the linkage between containers and iterators void UtlContainer::acquireIteratorConnectionLock() { spIteratorConnectionLock->acquire(); } /// Unlock the linkage between containers and iterators void UtlContainer::releaseIteratorConnectionLock() { spIteratorConnectionLock->release(); } void UtlContainer::addIterator(UtlIterator* newIterator) const { // Caller must be holding this->mContainerLock. // But it need not be holding newIterator->mpContainerRefLock, because // we do not set newIterator->mpMyContainer. // This method is declared const because it makes no change that // any other method can detect in the container, but it actually // does make a change, so we have to cast away the const. UtlContainer* my = const_cast(this); if(newIterator) { // :HACK: note that we are storing a UtlIterator* in the UtlContainer* pointer UtlLink* iteratorLink = UtlLink::get(); iteratorLink->data = (UtlContainer*)newIterator; iteratorLink->UtlChain::listBefore(&my->mIteratorList, NULL); } } void UtlContainer::removeIterator(UtlIterator *existingIterator) const { // Caller must be holding this->mContainerLock. // But it need not be holding newIterator->mpContainerRefLock, because // we do not set newIterator->mpMyContainer. // This method is declared const because it makes no change that // any other method can detect in the container, but it actually // does make a change, so we have to cast away the const. if(existingIterator) { UtlContainer *my = (UtlContainer*)this; UtlLink* iteratorLink; // :HACK: note that we are storing a UtlIterator* in the UtlContainer* pointer iteratorLink = UtlLink::findData(&my->mIteratorList, (UtlContainer*)existingIterator); if (iteratorLink) { iteratorLink->detachFrom(&my->mIteratorList); } } } sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlContainableAtomic.cpp0000644000175000017500000000257212205613256026025 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 Pingtel Corp. // // // $$ //////////////////////////////////////////////////////////////////////// ////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlContainableAtomic.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor // Copy constructor // Destructor /* ============================ MANIPULATORS ============================== */ // Assignment operator /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /// Get hash of object. unsigned UtlContainableAtomic::hash() const { return UtlContainable::directHash(); } /// Compare this object to another object. int UtlContainableAtomic::compareTo(UtlContainable const* other) const { // C++ permits the consistent comparison of all pointers. int r = this > other ? 1 : this < other ? -1 : 0; return r; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlContainablePair.cpp0000644000175000017500000000506412205613256025503 0ustar00danieldaniel00000000000000// // Copyright (C) 2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlInt.h" #include "utl/UtlContainablePair.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS const UtlContainableType UtlContainablePair::TYPE = "UtlContainablePair"; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ UtlContainablePair::UtlContainablePair(UtlContainable *pFirst, UtlContainable *pSecond) : mpFirst(pFirst) , mpSecond(pSecond) { } UtlContainablePair::~UtlContainablePair() { delete mpFirst; delete mpSecond; } /* ============================ MANIPULATORS ============================== */ UtlContainable* UtlContainablePair::setFirst(UtlContainable *val) { UtlContainable* pOldValue = mpFirst; mpFirst = val; return pOldValue; } UtlContainable* UtlContainablePair::setSecond(UtlContainable *val) { UtlContainable* pOldValue = mpSecond; mpSecond = val; return pOldValue; } /* ============================ ACCESSORS ================================= */ UtlContainable* UtlContainablePair::getFirst() const { return mpFirst; } UtlContainable* UtlContainablePair::getSecond() const { return mpSecond; } unsigned UtlContainablePair::hash() const { return mpFirst->hash() ^ mpSecond->hash(); } UtlContainableType UtlContainablePair::getContainableType() const { return UtlContainablePair::TYPE; } /* ============================ INQUIRY =================================== */ int UtlContainablePair::compareTo(UtlContainable const *inVal) const { int result; assert(mpFirst != NULL && mpSecond != NULL); if (inVal->isInstanceOf(UtlContainablePair::TYPE)) { UtlContainablePair *pOther = (UtlContainablePair*)inVal; assert(pOther->mpFirst != NULL && pOther->mpSecond != NULL); result = mpFirst->compareTo(pOther->mpFirst); if (result != 0) { result = mpSecond->compareTo(pOther->mpSecond); } } else { result = -1; } return result; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlIterator.cpp0000644000175000017500000000551312205613256024240 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlIterator.h" #include "utl/UtlContainer.h" #include "os/OsLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor // in this case, we don't need to acquire the sIteratorConnectionLock or take the // mContainerRefLock because this is constructor, // so no one has the pointer to this iterator yet. UtlIterator::UtlIterator(const UtlContainer& container) : mContainerRefLock(OsBSem::Q_PRIORITY, OsBSem::FULL), mpMyContainer(const_cast(&container)) { } // Copy constructor // Destructor UtlIterator::~UtlIterator() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /***************************************************************** * The following routines are here to provide (protected) access * to the mpIteratorList in the associated UtlContainer. These * operations are invoked here from the derived iterator class * constructors and destructors rather than in the UtlIterator * constructor and destructor so that the locks can be taken and * released in the correct order. (E.g., if invalidate() was called * from ~UtlContainer, then a subclass's data structure would be * released before the iterators were invalidated.) *****************************************************************/ void UtlIterator::addToContainer(const UtlContainer* container) { // caller is already holding the mContainerLock container->addIterator(this); } /** * invalidate is called by the UtlContainer from its destructor. * It disconnects the iterator from its container object (sets mpMyContainer to * NULL). * * Any subsequent invocation of this iterator (other than its * destructor) must not attempt to access *mpMyContainer. */ void UtlIterator::invalidate() { // Caller holds sIteratorConnectionLock. // The caller is holding the sIteratorConnectionLock, so it is OK to lock // this. OsLock takeContainer(mContainerRefLock); mpMyContainer = NULL; // it may be that more is needed in the subclasses, but this provides the failsafe } sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlList.cpp0000644000175000017500000001554212205613256023365 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlContainable.h" #include "utl/UtlListIterator.h" #include "utl/UtlList.h" #include "os/OsLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const UtlContainableType UtlList::TYPE = "UtlList"; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlList::UtlList() { } // Destructor UtlList::~UtlList() { UtlContainer::acquireIteratorConnectionLock(); OsLock take(mContainerLock); LIST_SANITY_CHECK; invalidateIterators(); UtlContainer::releaseIteratorConnectionLock(); UtlLink* node; while((node = head())) { removeLink(node); } } /* ============================ MANIPULATORS ============================== */ // Removes and returns the first item in the list (pop). UtlContainable* UtlList::get() { OsLock take(mContainerLock); LIST_SANITY_CHECK; UtlContainable* firstElement = NULL; UtlLink* firstNode = head(); if(firstNode) { firstElement = (UtlContainable*) firstNode->data; removeLink(firstNode); } return(firstElement); } // Removed the designated object by reference. UtlContainable* UtlList::removeReference(const UtlContainable* containableToMatch) { UtlContainable* foundElement = NULL; UtlLink* foundNode = NULL; UtlLink* listNode; OsLock take(mContainerLock); LIST_SANITY_CHECK; for(listNode = head(); listNode && !foundElement; listNode = listNode->next()) { if((UtlContainable*) listNode->data == containableToMatch) { foundNode = listNode; foundElement = (UtlContainable*) listNode->data; } } if (foundNode) { removeLink(foundNode); } return(foundElement); } void UtlList::removeLink(UtlLink* toBeRemoved) { // The caller already holds the mContainerLock. UtlLink* listNode = NULL; UtlListIterator* eachIterator; for (listNode = mIteratorList.head(); listNode; listNode = listNode->next()) { eachIterator = (UtlListIterator*)listNode->data; eachIterator->removing(toBeRemoved); } toBeRemoved->detachFrom(this); } // Removes and frees the designated objects. UtlBoolean UtlList::destroy(UtlContainable* obj) { UtlBoolean result = FALSE; // this does not take the mContainerLock, because all the container state changes // are made inside the remove method, which already takes it. UtlContainable* removed = remove(obj); if (removed) { result = TRUE; delete removed; } return result; } // Removes and delete all elements void UtlList::destroyAll() { UtlLink* node; OsLock take(mContainerLock); LIST_SANITY_CHECK; while((node = head())) { UtlContainable* theObject = (UtlContainable*)node->data; removeLink(node); if(theObject) { delete theObject; } } } // Remove the object at position index UtlContainable* UtlList::removeAt(const size_t N) { UtlContainable* removed = NULL; OsLock take(mContainerLock); UtlLink* link; size_t n; for (n = 0, link = head(); link && n < N; link = link->next(), n++) { } if (link) { removed = (UtlContainable*)link->data; removeLink(link); } return removed; } // Remove all elements, but do not free the objects void UtlList::removeAll() { UtlLink* node; OsLock take(mContainerLock); LIST_SANITY_CHECK; while((node = head())) { removeLink(node); } } // Re-calculates hashes for all items void UtlList::rehash() { OsLock take(mContainerLock); UtlLink* link; for (link = head(); link; link = link->next()) { link->rehash() ; } } /* ============================ ACCESSORS ================================= */ // Return the first element (head) of the list. UtlContainable* UtlList::first() const { OsLock take(const_cast(mContainerLock)); UtlLink* firstNode = head(); return firstNode ? (UtlContainable*) firstNode->data : NULL; } // Return the last element (tail) of the list. UtlContainable* UtlList::last() const { OsLock take(const_cast(mContainerLock)); UtlLink* lastNode = tail(); return lastNode ? (UtlContainable*) lastNode->data : NULL; } // Return the element at position N. UtlContainable* UtlList::at(size_t N) const { OsLock take(const_cast(mContainerLock)); size_t n; UtlLink* link; for (n = 0, link = head(); link && n < N; link = link->next(), n++) { } return link ? (UtlContainable*)link->data : NULL; } /* ============================ INQUIRY =================================== */ // Return the total number. size_t UtlList::entries() const { OsLock take(const_cast(mContainerLock)); size_t count; UtlLink* node; for (count = 0, node = head(); node; count++, node=node->next()) { } return count; } // Return true of the container is empty. UtlBoolean UtlList::isEmpty() const { return !head(); } // Return true if the container includes the designated object. UtlBoolean UtlList::contains(const UtlContainable* object) const { return(find(object) != NULL); } // Return true if the list contains the designated object reference . UtlBoolean UtlList::containsReference(const UtlContainable* containableToMatch) const { UtlLink* listNode; UtlBoolean isMatch = FALSE; OsLock take(const_cast(mContainerLock)); for(listNode = head(); listNode && !isMatch; listNode = listNode->next()) { if((UtlContainable*)listNode->data == containableToMatch) { isMatch = TRUE; } } return isMatch; } /** * Get the ContainableType for the list as a contained object. */ UtlContainableType UtlList::getContainableType() const { return UtlList::TYPE; } #ifdef GLIST_SANITY_TEST bool UtlList::sanityCheck() const { UtlLink* thisNode; UtlLink* prevNode; // The caller already holds the mContainerLock. for ( ( prevNode=NULL, thisNode=head() ); thisNode; ( prevNode=thisNode, thisNode=thisNode->next() ) ) { if (thisNode->prev() != prevNode) { return FALSE; } } return TRUE; } #endif /* GLIST_SANITY_TEST */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlListIterator.cpp0000644000175000017500000001246012205613256025073 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES // Keep UtlInit.h as the first include! // See UtlInit class description for more information. #include "utl/UtlInit.h" #include "utl/UtlListIterator.h" #include "utl/UtlList.h" #include "utl/UtlContainable.h" #include "os/OsLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS /* * The NOWHERE UtlLink is used when the iterator steps off the end * of the list [next() returns NULL]; mpCurrentNode is set to point * to this special stub empty list (using OFF_LIST_END for clarity). * If mpCurrentNode were left equal to NULL, then a subsequent call to * the iterator would return the first element on the list, because NULL * designates the state "before the first element". */ const UtlLink* UtlListIterator::OFF_LIST_END; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlListIterator::UtlListIterator(const UtlList& list) : UtlIterator(list), mpCurrentNode(NULL) { OsLock container(const_cast(list.mContainerLock)); addToContainer(&list); } // Destructor UtlListIterator::~UtlListIterator() { UtlContainer::acquireIteratorConnectionLock(); OsLock take(mContainerRefLock); UtlList* myList = static_cast(mpMyContainer); if (myList != NULL) { OsLock take(myList->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); // as soon as both object locks are taken myList->removeIterator(this); mpMyContainer = NULL; } else { UtlContainer::releaseIteratorConnectionLock(); } } /* ============================ MANIPULATORS ============================== */ // Assignment operator // Return the next element . UtlContainable* UtlListIterator::operator()() { UtlContainable* nextVal = NULL; UtlContainer::acquireIteratorConnectionLock(); OsLock take(mContainerRefLock); UtlList* myList = static_cast(mpMyContainer); OsLock container(myList->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); mpCurrentNode = (mpCurrentNode == NULL ? myList->head() : mpCurrentNode->next() ); if(mpCurrentNode) // not end of list { nextVal = (UtlContainable*) mpCurrentNode->data; } else { // reset position so that subsequent calls will also return end of list mpCurrentNode = const_cast(OFF_LIST_END); } return(nextVal); } // Reset the list iterator. void UtlListIterator::reset() { UtlContainer::acquireIteratorConnectionLock(); OsLock take(mContainerRefLock); UtlList* myList = static_cast(mpMyContainer); OsLock container(myList->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); mpCurrentNode = NULL; } UtlContainable* UtlListIterator::toLast() { UtlContainable* last = NULL; UtlContainer::acquireIteratorConnectionLock(); OsLock take(mContainerRefLock); UtlList* myList = static_cast(mpMyContainer); OsLock container(myList->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); mpCurrentNode = myList->tail(); last = static_cast(mpCurrentNode ? mpCurrentNode->data : NULL); return last; } /* ============================ ACCESSORS ================================= */ // return the current data UtlContainable* UtlListIterator::item() const { UtlContainable* currentItem = NULL; UtlContainer::acquireIteratorConnectionLock(); OsLock take(const_cast(mContainerRefLock)); UtlList* myList = static_cast(mpMyContainer); OsLock container(myList->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); currentItem = static_cast(mpCurrentNode->data); return currentItem; } /* ============================ INQUIRY =================================== */ // Is the iterator positioned at the last element? UtlBoolean UtlListIterator::atLast() const { UtlBoolean isAtLast = false; UtlContainer::acquireIteratorConnectionLock(); OsLock take(const_cast(mContainerRefLock)); UtlList* myList = static_cast(mpMyContainer); OsLock container(myList->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); isAtLast = (mpCurrentNode && mpCurrentNode == myList->tail()); return isAtLast; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /** * removing is called by the UtlList when an element is about to be * removed from the container. The iterator must ensure that the removed * element is not returned by any subsequent call. */ void UtlListIterator::removing(const UtlLink* node) { // The caller already holds the mContainerLock. if (mpCurrentNode == node) { mpCurrentNode = node->prev(); } } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlSList.cpp0000644000175000017500000001356612205613256023514 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlContainable.h" #include "utl/UtlSListIterator.h" #include "utl/UtlSList.h" #include "os/OsLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const UtlContainableType UtlSList::TYPE = "UtlSList"; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlSList::UtlSList() : UtlList() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator // Append containable object to the end. UtlContainable* UtlSList::append(UtlContainable* obj) { OsLock take(mContainerLock); if(obj != NULL) { LIST_SANITY_CHECK; UtlLink::listBefore(this, NULL, obj); LIST_SANITY_CHECK; } return(obj); } // Insert at the designated position. UtlContainable* UtlSList::insertAt(size_t N, UtlContainable* obj) { // :NOTE: this method is deliberately not the same as g_list_insert in that // the glib routine will accept a value of N > the length of the list // but this routine treats that as an error. UtlContainable* inserted = NULL; OsLock take(mContainerLock); LIST_SANITY_CHECK; size_t n; UtlLink* link; for (n = 0, link = head(); link && n < N; link = link->next(), n++) { } if (n == N) { UtlLink::listBefore(this, link, obj); inserted = obj; } LIST_SANITY_CHECK; return inserted; } UtlContainable* UtlSList::insertAfter(UtlLink* afterNode, UtlContainable* object) { OsLock take(mContainerLock); UtlLink::listAfter(this, afterNode, object); return object; } // Inserts at the end postion (tailer). UtlContainable* UtlSList::insert(UtlContainable* obj) { return append(obj); } // Remove the designated object by equality. UtlContainable* UtlSList::remove(const UtlContainable* object) { UtlLink* listNode; UtlLink* found; UtlContainable* foundObject = NULL; OsLock take(mContainerLock); LIST_SANITY_CHECK; for (listNode = head(), found = NULL; listNode && !found; listNode = listNode->next()) { UtlContainable* visitNode = (UtlContainable*) listNode->data; if(visitNode && visitNode->compareTo(object) == 0) { found = listNode; } } if (found) { foundObject = (UtlContainable*)found->data; removeLink(found); } LIST_SANITY_CHECK; return foundObject; } // Removes and frees the designated object. UtlBoolean UtlSList::destroy(UtlContainable* obj) { UtlBoolean result = FALSE; // this does not take the mContainerLock, because all the container state changes // are made inside the remove method, which already takes it. UtlContainable* removed = remove(obj); if (removed) { result = TRUE; delete removed; } return result; } /* ============================ ACCESSORS ================================= */ // Find the first occurrence of the designated object by equality. UtlContainable* UtlSList::find(const UtlContainable* containableToMatch) const { UtlLink* listNode; UtlContainable* matchElement = NULL; UtlContainable* visitNode; unsigned targetHash = containableToMatch->hash(); OsLock take(const_cast(mContainerLock)); LIST_SANITY_CHECK; for(listNode = head()->findNextHash(targetHash); listNode && matchElement == NULL; listNode = listNode->next()->findNextHash(targetHash) ) { visitNode = (UtlContainable*) listNode->data; if(visitNode && visitNode->compareTo(containableToMatch) == 0) { matchElement = visitNode; } } LIST_SANITY_CHECK; return(matchElement); } /* ============================ INQUIRY =================================== */ // Return the number of occurrences of the designated object. size_t UtlSList::occurrencesOf(const UtlContainable* containableToMatch) const { int count = 0; UtlLink* listNode; UtlContainable* visitNode = NULL; OsLock take(const_cast(mContainerLock)); LIST_SANITY_CHECK; for(listNode = head(); listNode; listNode = listNode->next()) { visitNode = (UtlContainable*)listNode->data; if(visitNode && visitNode->compareTo(containableToMatch) == 0) { count++; } } LIST_SANITY_CHECK; return(count); } // Return the list position of the designated object. size_t UtlSList::index(const UtlContainable* containableToMatch) const { size_t matchedIndex = UTL_NOT_FOUND; size_t currentIndex; UtlLink* listNode; UtlContainable* visitNode = NULL; OsLock take(const_cast(mContainerLock)); LIST_SANITY_CHECK; for(listNode = head(), currentIndex = 0; matchedIndex == UTL_NOT_FOUND && listNode; listNode = listNode->next() ) { visitNode = (UtlContainable*) listNode->data; if(visitNode && visitNode->compareTo(containableToMatch) == 0) { matchedIndex = currentIndex; } else { currentIndex++; } } LIST_SANITY_CHECK; return matchedIndex; } /** * Get the ContainableType for the list as a contained object. */ UtlContainableType UtlSList::getContainableType() const { return UtlSList::TYPE; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlCopyableSList.cpp0000644000175000017500000000477312205613256025173 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlCopyableSList.h" #include "utl/UtlSListIterator.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const UtlContainableType UtlCopyableSList::TYPE = "UtlCopyableSList"; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlCopyableSList::UtlCopyableSList() : UtlSList() { } // Copy constructor UtlCopyableSList::UtlCopyableSList(const UtlCopyableSList& rhs) { operator=(rhs); } // Destructor UtlCopyableSList::~UtlCopyableSList() { destroyAll(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator UtlCopyableSList& UtlCopyableSList::operator=(const UtlCopyableSList& rhs) { if (this == &rhs) // handle the assignment to self case return *this; destroyAll(); UtlSListIterator it(rhs); UtlCopyableContainable* item; while(item = static_cast(it())) { insert(item->clone()); } return *this; } UtlContainable* UtlCopyableSList::append(UtlCopyableContainable* obj) { return UtlSList::append(obj); } UtlContainable* UtlCopyableSList::insertAt(size_t N, ///< zero-based position obj should be UtlCopyableContainable* obj ///< object to insert at N ) { return UtlSList::insertAt(N, obj); } UtlContainable* UtlCopyableSList::insert(UtlCopyableContainable* obj) { return UtlSList::insert(obj); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /** * Get the ContainableType for the list as a contained object. */ UtlContainableType UtlCopyableSList::getContainableType() const { return UtlCopyableSList::TYPE; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlSListIterator.cpp0000644000175000017500000000527412205613256025223 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlSListIterator.h" #include "utl/UtlSList.h" #include "utl/UtlContainable.h" #include "os/OsLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlSListIterator::UtlSListIterator(const UtlSList& list) : UtlListIterator(list) { } /* ============================ MANIPULATORS ============================== */ // Find the next like-instance of the designated object . UtlContainable* UtlSListIterator::findNext(const UtlContainable* containableToMatch) { UtlContainable* match = NULL; UtlContainer::acquireIteratorConnectionLock(); OsLock takeContainer(mContainerRefLock); UtlSList* myList = static_cast(mpMyContainer); OsLock take(myList->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); // advance the iterator UtlLink* nextLink = (mpCurrentNode == NULL ? myList->head() : mpCurrentNode->next() ); // search for the next match forward while (nextLink && !match) { UtlContainable *candidate = (UtlContainable*)nextLink->data; if (candidate && candidate->compareTo(containableToMatch) == 0) { mpCurrentNode = nextLink; match = candidate; } else { nextLink = nextLink->next(); } } return match; } UtlContainable* UtlSListIterator::insertAfterPoint(UtlContainable* insertedObject) { UtlContainable* result = NULL; UtlContainer::acquireIteratorConnectionLock(); OsLock takeContainer(mContainerRefLock); UtlSList* myList = static_cast(mpMyContainer); OsLock take(myList->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); if (mpCurrentNode == UtlListIterator::OFF_LIST_END) { mpCurrentNode = UtlLink::listBefore(myList, NULL, insertedObject); /* append to tail */ } else { UtlLink::listAfter(myList, mpCurrentNode, insertedObject); } result = insertedObject; return result; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlDList.cpp0000644000175000017500000000270212205613256023463 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDList.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const UtlContainableType UtlDList::TYPE = "UtlDList"; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlDList::UtlDList() : UtlSList() { } // Copy constructor // Destructor UtlDList::~UtlDList() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /** * Get the ContainableType for the list as a contained object. */ UtlContainableType UtlDList::getContainableType() const { return UtlDList::TYPE; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlDListIterator.cpp0000644000175000017500000000252512205613256025200 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDListIterator.h" #include "utl/UtlDList.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor // Copy constructor UtlDListIterator::UtlDListIterator(const UtlDList & list) : UtlSListIterator(list) { } // Destructor UtlDListIterator::~UtlDListIterator() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlCopyableSortedList.cpp0000644000175000017500000000432312205613256026220 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlCopyableSortedList.h" #include "utl/UtlSortedListIterator.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const UtlContainableType UtlCopyableSortedList::TYPE = "UtlCopyableSortedList"; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlCopyableSortedList::UtlCopyableSortedList() : UtlSortedList() { } // Copy constructor UtlCopyableSortedList::UtlCopyableSortedList(const UtlCopyableSortedList& rhs) { operator=(rhs); } // Destructor UtlCopyableSortedList::~UtlCopyableSortedList() { destroyAll(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator UtlCopyableSortedList& UtlCopyableSortedList::operator=(const UtlCopyableSortedList& rhs) { if (this == &rhs) // handle the assignment to self case return *this; destroyAll(); UtlSortedListIterator it(rhs); UtlCopyableContainable* item; while(item = static_cast(it())) { insert(item->clone()); } return *this; } UtlContainable* UtlCopyableSortedList::insert(UtlCopyableContainable* obj) { return UtlSortedList::insert(obj); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /** * Get the ContainableType for the list as a contained object. */ UtlContainableType UtlCopyableSortedList::getContainableType() const { return UtlCopyableSortedList::TYPE; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlSortedList.cpp0000644000175000017500000001120412205613256024535 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlContainable.h" #include "utl/UtlSortedList.h" #include "os/OsLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const UtlContainableType UtlSortedList::TYPE = "UtlSortedList"; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlSortedList::UtlSortedList() : UtlList() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator // Sorted Insert according to the object comparison function UtlContainable* UtlSortedList::insert(UtlContainable* obj) { OsLock take(mContainerLock); UtlLink::listBefore(this, findNode(head(), POSITION, obj), obj); return obj; } // Remove the designated object by equality UtlContainable* UtlSortedList::remove(const UtlContainable* obj) { UtlLink* listNode; UtlContainable* removed = NULL; OsLock take(mContainerLock); listNode = findNode(head(), EXACTLY, obj); if (listNode) { removed = (UtlContainable*)listNode->data; removeLink(listNode); } return removed; } /* ============================ ACCESSORS ================================= */ // Find the first occurence of the designated object by equality. UtlContainable* UtlSortedList::find(const UtlContainable* obj) const { UtlLink* listNode; UtlContainable* matchNode = NULL; OsLock take(const_cast(mContainerLock)); listNode = findNode(head(), EXACTLY, obj); if (listNode != NULL) { matchNode = (UtlContainable*)listNode->data; } return matchNode; } /* ============================ INQUIRY =================================== */ // Return the list position of the designated object. size_t UtlSortedList::index(const UtlContainable* obj) const { size_t index = UTL_NOT_FOUND; size_t thisIndex; UtlLink* listNode; unsigned keyHash = obj->hash(); OsLock take(const_cast(mContainerLock)); for (listNode = head(), thisIndex = 0; listNode && index == UTL_NOT_FOUND; listNode = listNode->next(), thisIndex++) { if ( listNode->data // there is an object (for safety sake) && listNode->hash == keyHash // quick test for possible equality && listNode->data->compareTo(obj) == 0 // real (but slower) test for equality ) { index = thisIndex; } } return index; } // Return the number of occurrences of the designated object. size_t UtlSortedList::occurrencesOf(const UtlContainable* containableToMatch) const { int count = 0; UtlLink* listNode; UtlContainable* visitNode = NULL; int comparison; OsLock take(const_cast(mContainerLock)); for (listNode = head(), comparison = 0; comparison <= 0 && listNode; listNode = listNode->next() ) { visitNode = (UtlContainable*)listNode->data; if(visitNode && visitNode->compareTo(containableToMatch) == 0) { count++; } } return(count); } /** * Get the ContainableType for the list as a contained object. */ UtlContainableType UtlSortedList::getContainableType() const { return UtlSortedList::TYPE; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ // Return the first UtlLink node to find. UtlLink* UtlSortedList::findNode(UtlLink* start, MatchType match, const UtlContainable* obj) const { UtlLink* listNode; UtlLink* foundNode; UtlContainable* listElement; int comparison = 0; // the caller already holds the mContainerLock for (listNode = start, foundNode = NULL; !foundNode && listNode; listNode = listNode->next() ) { listElement = (UtlContainable*)listNode->data; if (listElement) { // we can't use the hash as a shortcut here because we need the order too comparison = listElement->compareTo(obj); if ( comparison >= 0 ) { foundNode = listNode; } } } if (foundNode && match == EXACTLY && comparison != 0) // match not exact { foundNode = NULL; } return foundNode; } sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlSortedListIterator.cpp0000644000175000017500000000505312205613256026254 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlContainable.h" #include "utl/UtlSortedList.h" #include "utl/UtlSortedListIterator.h" #include "os/OsLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ UtlSortedListIterator::UtlSortedListIterator(const UtlSortedList& list) : UtlListIterator(list) { } /* ============================ MANIPULATORS ============================== */ /** * Find the next object that isEqualTo objectToFind, and reset the iterator * so that it is the current position. * * @return The found element or NULL if no more elements are available. */ UtlContainable* UtlSortedListIterator::findNext(const UtlContainable* objectToFind) { UtlContainable* nextMatch = NULL; UtlContainer::acquireIteratorConnectionLock(); OsLock take(mContainerRefLock); const UtlSortedList* myList = static_cast(mpMyContainer); if (myList) { OsLock container(myList->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); if (mpCurrentNode != UtlListIterator::OFF_LIST_END) { UtlLink* start = (mpCurrentNode == NULL ? myList->head() : mpCurrentNode); UtlLink* nextNode = myList->findNode(start, UtlSortedList::EXACTLY, objectToFind); if (nextNode) { nextMatch = (UtlContainable*)nextNode->data; mpCurrentNode = nextNode; } } if (!nextMatch) // find a match? { // no - set current position so that next will return NULL mpCurrentNode = myList->tail(); } } else { UtlContainer::releaseIteratorConnectionLock(); } return(nextMatch); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlHashMap.cpp0000644000175000017500000003277312205613256024000 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2011 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "utl/UtlContainable.h" #include "utl/UtlLink.h" #include "utl/UtlInt.h" #include "utl/UtlHashMapIterator.h" #include "utl/UtlHashMap.h" #include "os/OsLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const UtlContainableType UtlHashMap::TYPE = "UtlHashMap"; #define HASHMAP_INITIAL_BUCKET_BITS 4 // STATIC VARIABLE INITIALIZATIONS const UtlInt INTERNAL_NULL_OBJECT(666); const UtlContainable* UtlHashMap::INTERNAL_NULL = &INTERNAL_NULL_OBJECT; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Default Constructor UtlHashMap::UtlHashMap() : mElements(0), mBucketBits(HASHMAP_INITIAL_BUCKET_BITS), mpBucket(new UtlChain[NUM_HASHMAP_BUCKETS(HASHMAP_INITIAL_BUCKET_BITS)]) { } // Destructor UtlHashMap::~UtlHashMap() { UtlContainer::acquireIteratorConnectionLock(); OsLock take(mContainerLock); invalidateIterators(); UtlContainer::releaseIteratorConnectionLock(); // still holding the mContainerLock // walk the buckets for (size_t i = 0; i < numberOfBuckets(); i++) { // empty each bucket and release each UtlPair back to the pool while (!mpBucket[i].isUnLinked()) { UtlPair* pair = static_cast(mpBucket[i].listHead()); pair->detachFromList(&mpBucket[i]); pair->release(); } } delete [] mpBucket; // free the bucket headers } /* * Allocate additional buckets and redistribute existing contents. * This should only be called through resizeIfNeededAndSafe. */ void UtlHashMap::resize() { // already holding the mContainerLock UtlChain* newBucket; size_t newBucketBits; // if an iterator had prevented resizing while many elements were added, // we might need to double more than once to restore the target ratio. for (newBucketBits = mBucketBits+1; mElements / NUM_HASHMAP_BUCKETS(newBucketBits) >= 3; newBucketBits++ ) { } // allocate the new buckets newBucket = new UtlChain[NUM_HASHMAP_BUCKETS(newBucketBits)]; if (newBucket) { // save the old buckets until we move the entries out of them UtlChain* oldBucket = mpBucket; size_t numOldBuckets = numberOfBuckets(); // put in the new buckets mBucketBits = newBucketBits; mpBucket = newBucket; // move all the entries to the new buckets size_t old; size_t toBeMoved; for (old = 0, toBeMoved = mElements; old < numOldBuckets && toBeMoved; old++ ) { while(!oldBucket[old].isUnLinked()) // old bucket is not empty yet { UtlPair* pair = static_cast(oldBucket[old].head()); pair->detachFromList(&oldBucket[old]); insert(pair, &mpBucket[bucketNumber(pair->hash)]); toBeMoved--; } } delete [] oldBucket; // finished with the old empty buckets } else { assert(newBucket); // failed to allocate new buckets } } /// Make an off the heap, deep copy of this object UtlHashMap* UtlHashMap::clone() const { UtlHashMap* copy = new UtlHashMap(); deepCopyInto(*copy); return(copy); } /* ============================ MANIPULATORS ============================== */ UtlContainable* UtlHashMap::remove(UtlContainable* key) { UtlContainable* unusedValue; return removeKeyAndValue(key, unusedValue); } UtlContainable* UtlHashMap::removeReference(const UtlContainable* key) { UtlContainable* unusedValue; // Locking is done by removeKeyAndValue(). return removeKeyAndValue(key, unusedValue); } UtlBoolean UtlHashMap::destroy(UtlContainable* key) { UtlBoolean wasRemoved = FALSE; UtlContainable* value; // Locking is done by removeKeyAndValue(). UtlContainable* removedKey = removeKeyAndValue(key, value); if(removedKey) { wasRemoved = TRUE; delete removedKey; if (value != INTERNAL_NULL) { delete value; } } return wasRemoved; } void UtlHashMap::removeAll() { OsLock take(mContainerLock); size_t i; size_t toBeRemoved; for (i = 0, toBeRemoved = mElements; i < numberOfBuckets() && toBeRemoved; i++ ) // for each bucket { while(!mpBucket[i].isUnLinked()) // bucket is not empty yet { UtlPair* pair = static_cast(mpBucket[i].head()); notifyIteratorsOfRemove(pair); pair->detachFromList(&mpBucket[i]); pair->release(); toBeRemoved--; } } mElements = 0; } void UtlHashMap::destroyAll() { OsLock take(mContainerLock); size_t i; size_t toBeDestroyed; for (i = 0, toBeDestroyed = mElements; i < numberOfBuckets() && toBeDestroyed; i++ ) // for each bucket { while(!mpBucket[i].isUnLinked()) // bucket is not empty yet { UtlPair* pair = static_cast(mpBucket[i].head()); notifyIteratorsOfRemove(pair); pair->detachFromList(&mpBucket[i]); delete pair->data; if (pair->value != INTERNAL_NULL) { delete pair->value; } pair->release(); toBeDestroyed--; } } mElements = 0; } // insert a key with a NULL value UtlContainable* UtlHashMap::insert(UtlContainable* obj) { // Locking will be done by insertKeyAndValue(). return insertKeyAndValue(obj, NULL); } UtlContainable* UtlHashMap::insertKeyAndValue(UtlContainable* key, UtlContainable* value) { UtlContainable* insertedKey = NULL; if (!value) { value = const_cast(INTERNAL_NULL); } if (key && value) // NULL keys and values are not allowed { OsLock take(mContainerLock); UtlPair* pair; UtlChain* bucket; if(!lookup(key, bucket, pair)) { pair = UtlPair::get(); pair->data = key; pair->hash = key->hash(); pair->value = value; mElements++; insert(pair, bucket); insertedKey = key; } else { // this key is already in the map, so this is an error - leave insertedKey == NULL } } return insertedKey; } UtlContainable* UtlHashMap::removeKeyAndValue(const UtlContainable* key, UtlContainable*& value) { UtlContainable* removed = NULL; value = NULL; if (key) { OsLock take(mContainerLock); UtlPair* pair; UtlChain* bucket; if ( lookup(key, bucket, pair) ) { removed = pair->data; value = (pair->value != INTERNAL_NULL) ? pair->value : NULL; notifyIteratorsOfRemove(pair); pair->detachFromList(bucket); removed = pair->data; value = pair->value; pair->release(); mElements--; } } return removed; } void UtlHashMap::copyInto(UtlHashMap& into) const { UtlHashMapIterator i(*this); while (i() != NULL) { into.insertKeyAndValue(i.key(), i.value()); } } OsStatus UtlHashMap::deepCopyInto(UtlHashMap& target) const { OsStatus status = OS_SUCCESS; UtlHashMapIterator iterator(*this); UtlContainable* keyPtr = NULL; UtlContainable* valuePtr = NULL; while ((keyPtr = (UtlContainable*) iterator())) { valuePtr = (UtlContainable*) iterator.value(); if(keyPtr->isInstanceOf(UtlCopyableContainable::TYPE) && (valuePtr == NULL || valuePtr->isInstanceOf(UtlCopyableContainable::TYPE))) { // Returns key if insert succeeds, NULL if key already exists if(target.insertKeyAndValue(((UtlCopyableContainable*)keyPtr)->clone(), valuePtr ? ((UtlCopyableContainable*)valuePtr)->clone() : NULL) == NULL) { status = OS_NAME_IN_USE; } } // Key or value are not clonable (i.e. derived from UtlCopyableContainable else { //assert(keyPtr->isInstanceOf(UtlCopyableContainable::TYPE)); //assert(valuePtr->isInstanceOf(UtlCopyableContainable::TYPE)); status = OS_NOT_SUPPORTED; } } return(status); } /* ============================ ACCESSORS ================================= */ UtlContainable* UtlHashMap::findValue(const UtlContainable* key) const { UtlContainable* foundValue = NULL; UtlPair* foundPair; UtlChain* unusedBucket; OsLock take(const_cast(mContainerLock)); if (lookup(key, unusedBucket, foundPair)) { foundValue = foundPair->value != INTERNAL_NULL ? foundPair->value : NULL; } return foundValue; } UtlContainable* UtlHashMap::find(const UtlContainable* key) const { UtlContainable* foundKey = NULL; UtlPair* foundPair; UtlChain* unusedBucket; OsLock take(const_cast(mContainerLock)); if (lookup(key, unusedBucket, foundPair)) { foundKey = foundPair->data; } return foundKey; } /* ============================ INQUIRY =================================== */ size_t UtlHashMap::entries() const { OsLock take(const_cast(mContainerLock)); return mElements; } UtlBoolean UtlHashMap::isEmpty() const { return entries() == 0; } UtlBoolean UtlHashMap::contains(const UtlContainable* key) const { return find(key) != NULL; } /** * Get the ContainableType for the hash map as a contained object. */ UtlContainableType UtlHashMap::getContainableType() const { return UtlHashMap::TYPE; } void UtlHashMap::notifyIteratorsOfRemove(const UtlPair* pair) { UtlLink* listNode; UtlHashMapIterator* foundIterator; for (listNode = mIteratorList.head(); listNode; listNode = listNode->next()) { foundIterator = (UtlHashMapIterator*)listNode->data; foundIterator->removing(pair); } } /* * Search for a given key value and return the bucket and UtlPair for it. * Return true if the key was found, and false if not. */ bool UtlHashMap::lookup(const UtlContainable* key, ///< The key to locate. UtlChain*& bucket, /**< The bucket list header in which it belongs. * This is set regardless of whether or not the * key was found in the table. */ UtlPair*& pair /**< If the key was found, the UtlPair for entry. * If the key was not found, this is NULL. */ ) const { UtlPair* check; size_t keyHash = key->hash(); bucket = &mpBucket[bucketNumber(keyHash)]; for (pair = NULL, check = static_cast(bucket->listHead()); ( !pair // not found && check // not end of list && keyHash <= check->hash // hash list is ordered, so if > then it's not in the list ); check = static_cast(check->UtlChain::next) ) { if (check->hash == keyHash && check->data->isEqual(key)) { pair = check; // found it } } return pair != NULL; } /* * Insert a pair into a bucket (the bucket list is ordered by hashcode). */ void UtlHashMap::insert(UtlPair* pair, ///< The UtlPair for the entry if it was found. UtlChain* bucket ///< The bucket list header where the entry belongs. ) { UtlPair* position; for (position = static_cast(bucket->listHead()); ( position // not end of list && pair->hash <= position->hash // hash list is ordered, so if > then we're done. ); position = static_cast(position->UtlChain::next) ) { } /* * At this point, position is either: * - NULL, in which case pair goes on the tail of the bucket * - non-NULL in which case pair goes before position * * NOTE - it is an unchecked error if pair->data->isEqual(position->data) * the caller must ensure this is not the case. */ pair->UtlChain::listBefore(bucket, position); resizeIfNeededAndSafe(); } size_t UtlHashMap::bucketNumber(unsigned hash) const { /* * We only use mBucketBits of the hash to index mpBucket, but we don't want to * loose the information in the higher bits of the hash code. So we 'fold' the * high order bits by XORing them mBucketBits at a time into the bits we'll * use until there are no non-zero high order bits left. */ size_t foldedHash; size_t highBits; size_t lowBitsMask = numberOfBuckets() - 1; for ( (foldedHash = hash & lowBitsMask, // get the low bits we want into the folded value highBits = hash // don't bother masking off the low bits ); (highBits = highBits >> mBucketBits); // shift out bits already used until zero foldedHash ^= highBits & lowBitsMask // incorporate non-zero ) { } return foldedHash; } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlHashMapIterator.cpp0000644000175000017500000001231312205613256025476 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "utl/UtlHashMapIterator.h" #include "utl/UtlSListIterator.h" #include "utl/UtlContainable.h" #include "os/OsLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlHashMapIterator::UtlHashMapIterator(const UtlHashMap& mapSource) : UtlIterator(mapSource) { OsLock container(const_cast(mapSource.mContainerLock)); addToContainer(&mapSource); init(); } // Destructor UtlHashMapIterator::~UtlHashMapIterator() { UtlContainer::acquireIteratorConnectionLock(); OsLock take(mContainerRefLock); UtlHashMap* myHashMap = static_cast(mpMyContainer); if (myHashMap) { OsLock container(myHashMap->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); myHashMap->removeIterator(this); /* * A UtlHashMap cannot be resized when there is an iterator associated with it, * so it's possible that it has grown while this iterator existed and that it * needs to be resized. Check for and do that now if needed. */ myHashMap->resizeIfNeededAndSafe(); mpMyContainer = NULL; } else { UtlContainer::releaseIteratorConnectionLock(); } } /* ============================ MANIPULATORS ============================== */ // Assignment operator UtlContainable* UtlHashMapIterator::operator()() { UtlContainable* foundKey = NULL; UtlContainer::acquireIteratorConnectionLock(); OsLock take(mContainerRefLock); UtlHashMap* myHashMap = static_cast(mpMyContainer); OsLock container(myHashMap->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); if (mPosition < myHashMap->numberOfBuckets()) { UtlPair* pair; for ( pair = ( mpCurrentPair ? static_cast(mpCurrentPair->UtlChain::next) : static_cast(myHashMap->mpBucket[mPosition].listHead()) ); !pair && ++mPosition < myHashMap->numberOfBuckets(); pair = static_cast(myHashMap->mpBucket[mPosition].listHead()) ) { } if(pair) { mpCurrentPair = pair; foundKey = pair->data; } } else { // mPosition >= myHashMap->numberOfBuckets(), so we've run off the end of the entries. mpCurrentPair = NULL; } return foundKey; } void UtlHashMapIterator::reset() { UtlContainer::acquireIteratorConnectionLock(); OsLock take(mContainerRefLock); UtlHashMap* myHashMap = static_cast(mpMyContainer); OsLock container(myHashMap->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); init(); } /* ============================ ACCESSORS ================================= */ UtlContainable* UtlHashMapIterator::key() const { UtlContainable* currentKey = NULL; UtlContainer::acquireIteratorConnectionLock(); OsLock take(const_cast(mContainerRefLock)); UtlHashMap* myHashMap = static_cast(mpMyContainer); OsLock container(myHashMap->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); if ( (mPosition < myHashMap->numberOfBuckets()) && (mpCurrentPair) && (mPairIsValid) ) { currentKey = mpCurrentPair->data; } return currentKey; } UtlContainable* UtlHashMapIterator::value() const { UtlContainable* currentValue = NULL; UtlContainer::acquireIteratorConnectionLock(); OsLock take(const_cast(mContainerRefLock)); UtlHashMap* myHashMap = static_cast(mpMyContainer); OsLock container(myHashMap->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); if ( (mPosition < myHashMap->numberOfBuckets()) && (mpCurrentPair) && (mPairIsValid) ) { currentValue = ( mpCurrentPair->value != UtlHashMap::INTERNAL_NULL ? mpCurrentPair->value : NULL ); } return currentValue; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ // Called by the HashMap before removing a key from the map void UtlHashMapIterator::removing(const UtlPair* key) { // the caller already holds the mContainerLock if (key = mpCurrentPair) { mPairIsValid = false; mpCurrentPair = static_cast(mpCurrentPair->UtlChain::prev); } } /* //////////////////////////// PRIVATE /////////////////////////////////// */ void UtlHashMapIterator::init() { mPosition = 0; mpCurrentPair = NULL; mPairIsValid = true; } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlHashBag.cpp0000644000175000017500000002726412205613256023753 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlContainable.h" #include "utl/UtlHashBag.h" #include "utl/UtlHashBagIterator.h" #include "os/OsLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const UtlContainableType UtlHashBag::TYPE = "UtlHashBag"; #define HASHBAG_INITIAL_BUCKET_BITS 4 #define NUM_HASHBAG_BUCKETS(bits) (1<(mpBucket[i].listHead()); link->detachFromList(&mpBucket[i]); link->release(); } } delete [] mpBucket; // free the bucket headers } /* * Allocate additional buckets and redistribute existing contents. * This should only be called through resizeIfNeededAndSafe. */ void UtlHashBag::resize() { // already holding the mContainerLock UtlChain* newBucket; size_t newBucketBits; // if an iterator had prevented resizing while many elements were added, // we might need to double more than once to restore the target ratio. for (newBucketBits = mBucketBits+1; mElements / NUM_HASHBAG_BUCKETS(newBucketBits) >= 3; newBucketBits++ ) { } // allocate the new buckets newBucket = new UtlChain[NUM_HASHBAG_BUCKETS(newBucketBits)]; if (newBucket) { // save the old buckets until we move the entries out of them UtlChain* oldBucket = mpBucket; size_t numOldBuckets = numberOfBuckets(); // put in the new buckets mBucketBits = newBucketBits; mpBucket = newBucket; // move all the entries to the new buckets size_t old; size_t toBeMoved; for (old = 0, toBeMoved = mElements; old < numOldBuckets && toBeMoved; old++ ) { while(!oldBucket[old].isUnLinked()) // old bucket is not empty yet { UtlLink* link = static_cast(oldBucket[old].head()); link->detachFromList(&oldBucket[old]); insert(link, &mpBucket[bucketNumber(link->hash)]); toBeMoved--; } } delete [] oldBucket; // finished with the old empty buckets } else { assert(newBucket); // failed to allocate new buckets } } /* ============================ MANIPULATORS ============================== */ UtlContainable* UtlHashBag::insert(UtlContainable* insertedContainable) { if (insertedContainable) // NULL keys are not allowed { OsLock take(mContainerLock); UtlLink* link; link = UtlLink::get(); link->data = insertedContainable; link->hash = insertedContainable->hash(); mElements++; insert(link, &mpBucket[bucketNumber(link->hash)]); } return insertedContainable; } /* * Insert a link into a bucket (the bucket list is ordered by hashcode). */ void UtlHashBag::insert(UtlLink* link, ///< The UtlLink for the entry if it was found. UtlChain* bucket ///< The bucket list header where the entry belongs. ) { UtlLink* inBucket; for (inBucket = static_cast(bucket->listHead()); ( inBucket // not end of list && link->hash > inBucket->hash // hash list is ordered, so if > then we're done. ); inBucket = static_cast(inBucket->UtlChain::next) ) { } link->UtlChain::listBefore(bucket, inBucket); resizeIfNeededAndSafe(); } UtlContainable* UtlHashBag::remove(UtlContainable* object) { UtlContainable* removed = NULL; if (object) { OsLock take(mContainerLock); UtlLink* link; UtlChain* bucket; if ( lookup(object, bucket, link) ) { removed = link->data; notifyIteratorsOfRemove(link); link->detachFromList(bucket); removed = link->data; link->release(); mElements--; } } return removed; } /** * Removed the designated object by reference * (as opposed to searching for an equality match). * * @return the object if successful, otherwise null */ UtlContainable* UtlHashBag::removeReference(const UtlContainable* object) { UtlContainable* removed = NULL; if (object) { size_t keyHash = object->hash(); OsLock take(mContainerLock); UtlLink* link; UtlChain* bucket; UtlLink* check; bucket = &mpBucket[bucketNumber(keyHash)]; for (link = NULL, check = static_cast(bucket->listHead()); ( !link // not found && check // not end of list && check->hash <= keyHash // hash list is ordered, so if > then it's not in the list ); check = check->next() ) { if (check->data == object) { link = check; // found it } } if (link) { notifyIteratorsOfRemove(link); link->detachFromList(bucket); removed = link->data; link->release(); mElements--; } } return removed; } UtlBoolean UtlHashBag::destroy(UtlContainable* object) { UtlBoolean deletedAnObject = FALSE; // no need to take locks... all the changes are inside remove UtlContainable* wasRemoved = remove(object); if(wasRemoved) { delete wasRemoved; deletedAnObject = TRUE; } return deletedAnObject; } void UtlHashBag::removeAll() { OsLock take(mContainerLock); size_t i; size_t toBeRemoved; for (i = 0, toBeRemoved = mElements; i < numberOfBuckets() && toBeRemoved; i++ ) // for each bucket { while(!mpBucket[i].isUnLinked()) // bucket is not empty yet { UtlLink* link = static_cast(mpBucket[i].head()); notifyIteratorsOfRemove(link); link->detachFromList(&mpBucket[i]); link->release(); toBeRemoved--; } } mElements = 0; } void UtlHashBag::destroyAll() { OsLock take(mContainerLock); size_t i; size_t toBeDestroyed; for (i = 0, toBeDestroyed = mElements; i < numberOfBuckets() && toBeDestroyed; i++ ) // for each bucket { while(!mpBucket[i].isUnLinked()) // bucket is not empty yet { UtlLink* link = static_cast(mpBucket[i].head()); notifyIteratorsOfRemove(link); link->detachFromList(&mpBucket[i]); delete link->data; link->release(); toBeDestroyed--; } } mElements = 0; } /* ============================ ACCESSORS ================================= */ UtlContainable* UtlHashBag::find(const UtlContainable* object) const { UtlContainable* foundObject = NULL; OsLock take(const_cast(mContainerLock)); UtlLink* link; UtlChain* bucket; if (lookup(object, bucket, link)) { foundObject = link->data; } return foundObject; } /* ============================ INQUIRY =================================== */ size_t UtlHashBag::entries() const { OsLock take(const_cast(mContainerLock)); return mElements; } UtlBoolean UtlHashBag::isEmpty() const { OsLock take(const_cast(mContainerLock)); return mElements == 0; } UtlBoolean UtlHashBag::contains(const UtlContainable* object) const { UtlLink* link; UtlChain* bucket; OsLock take(const_cast(mContainerLock)); return lookup(object, bucket, link); } /** * Get the ContainableType for the hash bag as a contained object. */ UtlContainableType UtlHashBag::getContainableType() const { return UtlHashBag::TYPE; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ void UtlHashBag::notifyIteratorsOfRemove(const UtlLink* link) { UtlLink* listNode; UtlHashBagIterator* foundIterator; for (listNode = mIteratorList.head(); listNode; listNode = listNode->next()) { foundIterator = (UtlHashBagIterator*)listNode->data; foundIterator->removing(link); } } /* * Search for a given key value and return the bucket and UtlLink for it. * Return true if the key was found, and false if not. */ bool UtlHashBag::lookup(const UtlContainable* key, ///< The key to locate. UtlChain*& bucket, /**< The bucket list header in which it belongs. * This is set regardless of whether or not the * key was found in the table. */ UtlLink*& link /**< If the key was found, the UtlLink for entry. * If the key was not found, this is NULL. */ ) const { UtlLink* check; size_t keyHash = key->hash(); bucket = &mpBucket[bucketNumber(keyHash)]; for (link = NULL, check = static_cast(bucket->listHead()); ( !link // not found && check // not end of list && check->hash <= keyHash // hash list is ordered, so if > then it's not in the list ); check = static_cast(check->UtlChain::next) ) { if (check->hash == keyHash && check->data->isEqual(key)) { link = check; // found it } } return link != NULL; } size_t UtlHashBag::bucketNumber(unsigned hash) const { /* * We only use mBucketBits of the hash to index mpBucket, but we don't want to * loose the information in the higher bits of the hash code. So we 'fold' the * high order bits by XORing them mBucketBits at a time into the bits we'll * use until there are no non-zero high order bits left. */ size_t foldedHash; size_t highBits; size_t lowBitsMask = numberOfBuckets() - 1; for ( (foldedHash = hash & lowBitsMask, // get the low bits we want into the folded value highBits = hash // don't bother masking off the low bits ); highBits = highBits >> mBucketBits; // shift out bits already used until zero foldedHash ^= highBits & lowBitsMask // incorporate non-zero ) { } return foldedHash; } sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlHashBagIterator.cpp0000644000175000017500000001677112205613256025466 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "utl/UtlHashBagIterator.h" #include "os/OsLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* * =========================== Design Notes ===================================== * * The following tables show the state of the position tracking member variables * for different iterator states. The states of a keyed iterator and an unkeyed * iterator are shown separately. (The state following a reset() is the same as * the Initial state) * * ================ Unkeyed iterator (created without passing a key object) * mPosition mpCurrentLink mLinkIsValid * Initial() 0 NULL true * on returned item 0..(numberOfBuckets-1) ->UtlLink->item true * on removed item 0..(numberOfBuckets-1) ->UtlLink->item false * after last item numberOfBuckets NULL true * * ================ Keyed iterator (created providing a key object) * mPosition mpCurrentLink mLinkIsValid * Initial(key) bucketNumber(mpSubsetHash) NULL true * on returned item bucketNumber(mpSubsetHash) ->UtlLink->item true * on removed item bucketNumber(mpSubsetHash) ->UtlLink->item false * after last item numberOfBuckets NULL true * */ /* ============================ CREATORS ================================== */ // Constructor UtlHashBagIterator::UtlHashBagIterator(const UtlHashBag& hashBag, UtlContainable* key) : UtlIterator(hashBag), mpSubsetMatch(key) { OsLock container(const_cast(hashBag.mContainerLock)); addToContainer(mpMyContainer); init(hashBag); } // Destructor UtlHashBagIterator::~UtlHashBagIterator() { UtlContainer::acquireIteratorConnectionLock(); OsLock take(mContainerRefLock); UtlHashBag* myHashBag = static_cast(mpMyContainer); if (myHashBag) { OsLock container(myHashBag->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); myHashBag->removeIterator(this); // in case the existence of this iterator has been preventing a resize myHashBag->resizeIfNeededAndSafe(); mpMyContainer = NULL; } else { UtlContainer::releaseIteratorConnectionLock(); } } /* ============================ MANIPULATORS ============================== */ UtlContainable* UtlHashBagIterator::operator()() { UtlContainable* foundObject = NULL; UtlContainer::acquireIteratorConnectionLock(); OsLock take(mContainerRefLock); UtlHashBag* myHashBag = static_cast(mpMyContainer); OsLock container(myHashBag->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); if (mPosition < myHashBag->numberOfBuckets()) { if (mpSubsetMatch) { /* * This iterator only returns elements matching mpSubsetMatch * so mPosition (the bucket index) never changes - all matches * are by definition in the same bucket. */ UtlLink* link; for ( link = ( mpCurrentLink ? static_cast(mpCurrentLink->UtlChain::next) : static_cast(myHashBag->mpBucket[mPosition].listHead()) ); ( !foundObject // no match found yet && link // but we have a link && link->hash <= mSubsetHash /* bucket list is sorted by hash code, * so when link->hash > mSubsetHash * there will be no more matches */ ); link = link->next() ) { if ( link->hash == mSubsetHash // save the call to isEqual && link->data->isEqual(mpSubsetMatch) // the real test of equality ) { mpCurrentLink = link; foundObject = link->data; } } if (!foundObject) { mPosition = myHashBag->numberOfBuckets(); // that's it - no more matches } } else { // this iterator has no subset to match - it walks all elements in the hash for ( mpCurrentLink = ( mpCurrentLink ? static_cast(mpCurrentLink->UtlChain::next) : static_cast( myHashBag->mpBucket[mPosition].listHead()) ); ( !mpCurrentLink // there was a next - this bucket has another item in it && ( ++mPosition // if not, bump the bucket < myHashBag->numberOfBuckets() // have we looked at the last bucket? ) ); mpCurrentLink = static_cast(myHashBag->mpBucket[mPosition].listHead()) ) { } if(mpCurrentLink) { foundObject = mpCurrentLink->data; } else { // this iterator is done - mPosition walked off the end. } } } else { // mPosition >= myHashMap->numberOfBuckets(), so we've run off the end of the entries. mpCurrentLink = NULL; } return foundObject; } void UtlHashBagIterator::reset() { UtlContainer::acquireIteratorConnectionLock(); OsLock take(mContainerRefLock); UtlHashBag* myHashBag = static_cast(mpMyContainer); OsLock container(myHashBag->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); init(*myHashBag); } /* ============================ ACCESSORS ================================= */ // Gets the key of the current element UtlContainable* UtlHashBagIterator::key() const { UtlContainable* current = NULL; UtlContainer::acquireIteratorConnectionLock(); OsLock take(const_cast(mContainerRefLock)); UtlHashBag* myHashBag = static_cast(mpMyContainer); OsLock container(myHashBag->mContainerLock); UtlContainer::releaseIteratorConnectionLock(); if (mLinkIsValid && mpCurrentLink) // current position is defined { current = mpCurrentLink->data; } return current; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ void UtlHashBagIterator::removing(const UtlLink* link) { // caller is holding the mContainerLock if (link = mpCurrentLink) { mLinkIsValid = false; mpCurrentLink = mpCurrentLink->prev(); } } /* //////////////////////////// PRIVATE /////////////////////////////////// */ void UtlHashBagIterator::init(const UtlHashBag& hashBag) { // caller is holding the mContainerLock mpCurrentLink = NULL; mLinkIsValid = true; if (mpSubsetMatch) { mSubsetHash = mpSubsetMatch->hash(); mPosition = hashBag.bucketNumber(mSubsetHash); } else { mPosition = 0; } } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlRscStore.cpp0000644000175000017500000001440212205613256024210 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include "utl/UtlRscTrace.h" #ifdef RSC_TEST // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "utl/UtlRscStore.h" #include "os/OsWriteLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // Database of active Rscs. // The UtlRscStore maintains a database of active Rscs (i.e., those Rscs // that have been started by the low level OsSysRsc class). Since the // OsRscTask is the only task that should be accessing the Rsc database // there is no need to serialize access (and no locking). // // Each entry in the database is a key/value pair where the key corresponds // to a Rsc ID and the value is the pointer to the corresponding OsRsc // object. Duplicate keys are not allowed. /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlRscStore::UtlRscStore(int initialStoreSize) : mDict(initialStoreSize), mNumInserts(0), mNumRemoves(0), mDictRWLock(OsRWMutex::Q_PRIORITY) { // since we plan to store OsRsc pointers in the // database, we make sure the sizes are compatible assert(sizeof(char*) <= sizeof(int)); // no other work required } // Destructor UtlRscStore::~UtlRscStore() { cleanUp(); } /* ============================ MANIPULATORS ============================== */ // Insert the indicated Rsc into the database of active Rscs. // Return OS_SUCCESS if successful, OS_NAME_IN_USE if the key is // already in the database. OsStatus UtlRscStore::insert(int RscId, char* pRsc) { UtlInt* pDictKey; UtlString* pDictValue; UtlInt* pInsertedKey; int removed = 0; { OsWriteLock lock(mDictRWLock); pDictKey = new UtlInt(RscId); pDictValue = new UtlString(pRsc); pInsertedKey = (UtlInt*) mDict.insertKeyAndValue(pDictKey, pDictValue); if (pInsertedKey == NULL) { osPrintf("\nUtlRscStore::insert failed: try to remove 0x%08x\n",RscId); UtlInt* pLookupKey; UtlInt* pRemKey; UtlString* pRemValue; pLookupKey = new UtlInt(RscId); pRemKey = (UtlInt*) mDict.removeKeyAndValue(pLookupKey, (UtlContainable*&) pRemValue); delete pLookupKey; if (pRemKey != NULL) { osPrintf("\nUtlRscStore::insert failed: 0x%08x removed\n", RscId); mNumRemoves++; delete pRemKey; // before returning we need to destroy the delete pRemValue; // objects that were used to maintain the removed = 1; } delete pDictKey; // clean up the key and value objects delete pDictValue; } else { mNumInserts++; return OS_SUCCESS; } } if (removed) return insert(RscId, pRsc); else { osPrintf("\nUtlRscStore::insert 0x%08x failed: mNumInserts = %d\n", RscId, mNumInserts); // insert failed return OS_NAME_IN_USE; } } // Remove the indicated Rsc from the database of active Rscs. // Return OS_SUCCESS if the indicated RscId is found, return // OS_NOT_FOUND if there is no match for the specified key. OsStatus UtlRscStore::remove(int RscId) { UtlInt* pLookupKey; UtlInt* pDictKey; UtlString* pDictValue; OsWriteLock lock(mDictRWLock); pLookupKey = new UtlInt(RscId); pDictKey = (UtlInt*) mDict.removeKeyAndValue(pLookupKey, (UtlContainable*&) pDictValue); delete pLookupKey; if (pDictKey == NULL) { osPrintf("\nUtlRscStore::remove: 0x%08x not found: \n" " mNumInserts = %d mNumRemoves = %d\n", RscId, mNumInserts, mNumRemoves); return OS_NOT_FOUND; // did not find the specified key } else mNumRemoves++; delete pDictKey; // before returning we need to destroy the delete pDictValue; // objects that were used to maintain the // dictionary entry return OS_SUCCESS; } void UtlRscStore::cleanUp() { UtlHashMapIterator iter(mDict); UtlContainable* next; UtlInt* key; UtlInt* value; iter.reset(); while (next = iter()) { key = (UtlInt*) iter.key(); value = (UtlInt*) iter.value(); iter.remove(); delete key; delete value; iter.reset(); } mNumInserts = 0; mNumRemoves = 0; } /* ============================ ACCESSORS ================================= */ // Get an array of pointers to the Rscs that are currently active. // The caller provides an array that can hold up to "size" OsRsc // pointers. This method will fill in the "activeRscs" array with // up to "size" pointers. The method returns the number of pointers // in the array that were actually filled in. int UtlRscStore::getActiveRscs(char* activeRscs[], int size) { UtlHashMapIterator iter(mDict); UtlContainable* next; UtlInt* value; int i; iter.reset(); i = 0; while (next = iter()) { if (i >= size) break; value = (UtlInt*) iter.value(); activeRscs[i] = (char*) value->value(); i++; } return i; } // Get the number of insertions and removals for the Rsc database. void UtlRscStore::getStoreStats(unsigned& nInserts, unsigned& nRemoves) const { nInserts = mNumInserts; nRemoves = mNumRemoves; } // Return the number of key-value pairs in the Rsc database. int UtlRscStore::numEntries(void) const { return mDict.entries(); } /* ============================ INQUIRY =================================== */ // Return TRUE if the Rsc database is empty. UtlBoolean UtlRscStore::isEmpty(void) const { return (numEntries() == 0); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ #endif // RSC_TEST sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlRegex.cpp0000644000175000017500000003024212205613256023516 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // Derived from regex.hpp, the original copyright and license notice from regex.cpp: // ---------------- // regex.hpp 1.0 Copyright (c) 2003 Peter Petersen (pp@on-time.de) // Simple C++ wrapper for PCRE // // This source file is freeware. You may use it for any purpose without // restriction except that the copyright notice as the top of this file as // well as this paragraph may not be removed or altered. // ---------------- // #include "assert.h" #include "utl/UtlRegex.h" #ifndef SIPX_MAX_REGEX_RECURSION # define SIPX_MAX_REGEX_RECURSION 800 #endif const unsigned long int RegEx::MAX_RECURSION = SIPX_MAX_REGEX_RECURSION; // Some versions do not separately define a limit for stack recursion; // for those, we must just limit the number of matches. #ifndef PCRE_EXTRA_MATCH_LIMIT_RECURSION # define PCRE_EXTRA_MATCH_LIMIT_RECURSION PCRE_EXTRA_MATCH_LIMIT # define match_limit_recursion match_limit #endif ///////////////////////////////// RegEx::RegEx(const char * regex, int options, unsigned long int maxDepth) { const char* pcre_error; int erroffset; // compile and study the expression re = pcre_compile(regex, options, &pcre_error, &erroffset, NULL); if (re == NULL) { assert(!"Regular expression failed to compile!"); abort(); } pe = pcre_study(re, 0, &pcre_error); if ( pcre_error == NULL ) { // save the compilation block sizes for the copy constructor. pcre_fullinfo(re, pe, PCRE_INFO_SIZE, &re_size); pcre_fullinfo(re, pe, PCRE_INFO_STUDYSIZE, &study_size); allocated_study = false; } else { re_size = 0; study_size = 0; } if (!pe) { // pcre_study didn't return any study data, // but we need the pcre_extra block anyway for the recursion limit, // so get one pe = (pcre_extra*)pcre_malloc(sizeof(pcre_extra)); memset(pe, 0, sizeof(pcre_extra)); } // set the maximum recursion depth option in the pcre_extra (pe) block pe->flags |= PCRE_EXTRA_MATCH_LIMIT_RECURSION; pe->match_limit_recursion = maxDepth; // allocate space for match results based on how many substrings // there are in the expression (+1 for the entire match) pcre_fullinfo(re, pe, PCRE_INFO_CAPTURECOUNT, &substrcount); substrcount++; ovector = new int[3*substrcount]; matchlist = NULL; }; ///////////////////////////////// RegEx::RegEx(const RegEx& regex) { // allocate memory for the compiled regular expression information re = (pcre*)pcre_malloc(regex.re_size); if (re) { // copy the compiled regular expression information memcpy(re, regex.re, regex.re_size); re_size = regex.re_size; pe = NULL; study_size = 0; allocated_study = false; if (regex.pe) // should always be true, because constructor allocates it { // allocate memory for the extra study information and recursion limit pe = (pcre_extra*)pcre_malloc(sizeof(pcre_extra)); if (pe) { // copy the extra information memcpy(pe, regex.pe, sizeof(pcre_extra)) ; // copy any study information if (regex.study_size > 0) { void* copied_study_data = pcre_malloc(regex.study_size); if (copied_study_data) { pe->study_data = copied_study_data; memcpy(pe->study_data, regex.pe->study_data, regex.study_size) ; study_size = regex.study_size; allocated_study = true; } } } } else { // no extra or study data to copy // this should not happen because we always want the recursion limit } substrcount = regex.substrcount; ovector = new int[3*substrcount]; matchlist = NULL; } else { assert(!"Cannot malloc regular expression!"); abort(); } }; ///////////////////////////////// RegEx::~RegEx() { ClearMatchList(); if (ovector != NULL) { delete [] ovector; } if (pe) { if (allocated_study && study_size) { pcre_free(pe->study_data); } pcre_free(pe); } pcre_free(re); } ///////////////////////////////// int RegEx::SubStrings(void) const { return substrcount; } ///////////////////////////////// bool RegEx::Search(const char * subject, int len, int options) { ClearMatchList(); subjectStr = subject; lastStart = 0; subjectLen = (len >= 0) ? len : strlen(subject); lastMatches = pcre_exec(re, pe, subjectStr, subjectLen, 0, options, ovector, 3*substrcount); return lastMatches > 0; } ///////////////////////////////// bool RegEx::SearchAt(const char* subject, ///< the string to be searched for a match int offset, ///< offset to begin search in subject string int len, ///< offset to begin search in subject string int options ///< sum of any PCRE options flags ) { /* * Search the subject string for matches to this regular expression * @returns true if a match is found. */ ClearMatchList(); subjectStr = subject; lastStart = 0; subjectLen = (len >= 0) ? len : strlen(subject); lastMatches = pcre_exec(re, pe, subject, subjectLen, offset, options, ovector, 3*substrcount); return lastMatches > 0; } ///////////////////////////////// bool RegEx::SearchAgain(int options) { ClearMatchList(); bool matched; lastStart = ovector[1]; if (lastStart < subjectLen) { lastMatches = pcre_exec(re, pe, subjectStr, subjectLen, lastStart, options, ovector, 3*substrcount); matched = lastMatches > 0; } else { // The last search matched the entire subject string // If the pattern allows a null string to match, then another call to pcre_exec // would return that match, so don't do that. // Instead, return no match to prevent an infinite loop. matched = false; } return matched; } ///////////////////////////////// int RegEx::Matches() { /* * Get the maximum number of substrings matched by a previous Search or SearchAgain call. * May only be called after a successful * call to Search() or SearchAgain() and applies to the results of * that call. * - any negative return indicates a caller error - the preceeding search call did not match * - a return value of 1 indicates that the entire pattern matched, but no substrings * within it matched. * - a return value of N > 1 indicates that the full string and N-1 substrings are available * * @note * If the expression has internal optional matches, they may not be matched; for example the * expression "foo(bar)?(bing)" matches subject "foobingo", and Matches would return 2 * because substring 2 "bing" was matched, but substring 1 would be the null string for * that match. * @endnote */ return lastMatches; } //////////////////////////////////////////////////////////////// bool RegEx::BeforeMatchString(UtlString* before) { bool hadBefore = false; // assume no match if (lastMatches) // any matches in the last search? { int startOffset = ovector[0]; // start of all of most recent match if (lastStart < startOffset) // anything before the last match? { int length = startOffset - lastStart; if (NULL!=before) { before->append(subjectStr+lastStart, length); } hadBefore = true; } } return hadBefore; } //////////////// int RegEx::AfterMatch(int i ///< the substring specifier ) { /* * Get the offset of the first character past the matched value * * May only be called after a successful call to Search() or SearchAgain() and applies to * the results of that call. */ return ( i < lastMatches ? ovector[(2*i)+1] : -1 ); } bool RegEx::AfterMatchString(UtlString* after) { bool hadAfter = false; // assume no match if (lastMatches) // any matches in the last search? { int endOffset = ovector[1]; // end of all of most recent match if (endOffset < subjectLen) // anything after the last match? { int length = subjectLen - endOffset; if (NULL!=after) { after->append(subjectStr+endOffset, length); } hadAfter = true; } } return hadAfter; } bool RegEx::MatchString(UtlString* matched, int i) { bool hadMatch = false; // assume no match if (i < lastMatches) // enough matches in the last search? { if (-1 == i) // return entire subject string { if (NULL!=matched) { matched->append(subjectStr, subjectLen); } hadMatch = true; } else { int startOffset = ovector[i*2]; if (0 <= startOffset) // did ith string match? { int length = ovector[(i*2)+1] - startOffset; if (0append(subjectStr+startOffset, length); } } else { // the matched substring was a null string - can happen } hadMatch = true; } } } return hadMatch; } ///////////////////////////////// bool RegEx::Match(const int i, ///< input - must be < SubStrings() */ int& offset, ///< output - offset in last subject of the n'th match int& length ///< output - length in last subject of the n'th match ) { bool i_matched; /* * Get a string matched by a previous Search or SearchAgain call. * May only be called after a successful * call to Search() or SearchAgain() and applies to the results of * that call. Parameter i must be less than * SubStrings(). * - Match(-1) returns the last searched subject. * - Match(0) returns the match of the complete regular expression. * - Match(1) returns $1, etc. * @returns true if the last search had an n'th match, false if not */ assert(i < lastMatches); if (i <= lastMatches) { offset = ovector[(2*i)]; length = ovector[(2*i)+1] - ovector[(2*i)]; i_matched = offset != -1; } else { i_matched = false; } return i_matched; } /// Get the position of a match in the subject int RegEx::MatchStart(const int i ///< input - must be < SubStrings() */ ) { assert(i < lastMatches); return ( (i <= lastMatches) ? ovector[(2*i)] : -1 ); } ///////////////////////////////// const char * RegEx::Match(int i) { // use of this routine is discouraged for efficiency reasons - use MatchString instead if (i >= 0) { if (matchlist == NULL) { pcre_get_substring_list(subjectStr, ovector, substrcount, &matchlist); } return matchlist[i]; } else { return subjectStr; } } // PRIVATE METHODS void RegEx::ClearMatchList(void) { if (matchlist) { pcre_free_substring_list(matchlist); matchlist = NULL; } } // Below is a little demo/test program using class RegEx #ifdef REGEX_DEMO #include #include "regex.hpp" /////////////////////////////////////// int main(int argc, char * argv[]) { if (argc != 2) { fprintf(stderr, "Usage: grep pattern\n\n" "Reads stdin, searches 'pattern', writes to stdout\n"); return 2; } try { RegEx Pattern(argv[1]); int count = 0; char buffer[1024]; while (fgets(buffer, sizeof(buffer), stdin)) if (Pattern.Search(buffer)) fputs(buffer, stdout), count++; return count == 0; } catch (const char * ErrorMsg) { fprintf(stderr, "error in regex '%s': %s\n", argv[1], ErrorMsg); return 2; } } #endif // REGEX_DEMO sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlTokenizer.cpp0000644000175000017500000000616512205613256024425 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS #if defined(_VXWORKS) extern "C" char* strdup(const char*); #endif /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlTokenizer::UtlTokenizer(const UtlString& tokens) { m_tokens = (char *)strdup(tokens.data()); m_tokenPosition = 0; } // Destructor UtlTokenizer::~UtlTokenizer() { free(m_tokens); } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /** * Tokenize a string into a series of smaller strings based on a set * of single character delimiters. Delimitters are not returned and * can vary with each call to this method. * * Sample token strings and token counts where delimitters = "X" * * | string | count | * +-------------+-------+ * ---X---X--- 3 * X--X-- 2 * --- 1 * ---X 1 * ---X 1 * ---XXX--- 2 * XXXX 0 */ UtlBoolean UtlTokenizer::next(UtlString &token, const char *delim) { size_t len = strlen(m_tokens); UtlBoolean done = FALSE; token.remove(0) ; for (size_t i = m_tokenPosition; i < len && !done; i++) { // token starts at first non-delimiter if (!isDelim(m_tokens[i], delim)) { int end = nextDelim(m_tokens, i, len, delim); token.append(m_tokens + i, end - i); m_tokenPosition = end; done = TRUE; } } return !token.isNull() ; } int UtlTokenizer::nextDelim(const char *tokens, const int start, const int len, const char *delim) { int end = start; for (; end < len && !isDelim(tokens[end], delim); end++); return end; } UtlBoolean UtlTokenizer::isDelim(const char c, const char *delim) { UtlBoolean match = FALSE; size_t delimLen = strlen(delim); for (size_t i = 0; i < delimLen && !match; i++) { match = (delim[i] == c); } return match; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ // Copy constructor UtlTokenizer::UtlTokenizer(const UtlTokenizer& rUtlTokenizer) { } // Assignment operator UtlTokenizer& UtlTokenizer::operator=(const UtlTokenizer& rhs) { if (this != &rhs) { // ... handle assignment from another... } return *this; } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/XmlContent.cpp0000644000175000017500000002201612205613256024052 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "assert.h" // APPLICATION INCLUDES #include "utl/XmlContent.h" #include "utl/UtlRegex.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * XmlContent provides conversion functions for escaping and unescaping UtlStrings * as appropriate for use in XML attribute and element content. * * At present, this makes no accomodation for character set differences; input is assumed * to be 8 bits. The following characters are encoded using the mandatory character * entities: * - < => &lt; * - & => &amp; * - > => &gt; * - ' => &apos; * - " => &quot; * * Other character values outside the range of valid 8-bit characters in XML: * - \#x09 | \#x0A | \#x0D | [\#x20-\#FF] * are encoded using the numeric entity encoding (&\#x??;). * * While this is not strictly XML conformant (in that it does not explicitly deal with * larger-size character encodings), it is symmetric (esaping and unescaping any 8 bit string * using these routines will always produce the original string), and will interoperate correctly * for any 8 bit encoding. */ #define QUOTE """ /* " \x22 */ #define AMPERSAND "&" /* & \x26 */ #define APOSTROPHE "'" /* ' \x27 */ #define LESS_THAN "<" /* < \x3c */ #define GREATER_THAN ">" /* > \x3e */ #define XML_CHARS "[\\x09\\x0a\\x0d\\x20\\x21\\x23-\\x25\\x28-\\x3b\\x3d\\x3f-\\xff]" #define ESC_CHARS "[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x22\\x26\\x27\\x3c\\x3e]" const RegEx CopyChars( "(" XML_CHARS "*)(" ESC_CHARS ")?" ); /// Append escaped source string onto destination string /** * The contents of the source string are appended to the destination string, with all * characters escaped as described above. * @returns true for success, false if an error was returned from any UtlString operation. */ bool XmlEscape(UtlString& destination, const UtlString& source) { bool resultOk = false; size_t srcLen = source.length(); if (srcLen > 0) { // make sure that the destination is at least large enough to add the source size_t minDstLen = destination.length() + srcLen; if (destination.capacity(minDstLen) >= minDstLen) { RegEx copyChars(CopyChars); UtlString escapeChar; bool matched; // each iteration picks up leading n valid chars (n may be zero) and one that needs to be escaped. for (matched = copyChars.Search(source.data(), srcLen); matched; matched = copyChars.SearchAgain() ) { // copy any leading characters that don't need to be escaped copyChars.MatchString(&destination,1); if (copyChars.MatchString(&escapeChar,2)) // was there an escaped character? { switch(*escapeChar.data()) { case '\x22' /* " */: destination.append(QUOTE); break; case '\x26' /* & */: destination.append(AMPERSAND); break; case '\x27' /* ' */: destination.append(APOSTROPHE); break; case '\x3c' /* < */: destination.append(LESS_THAN); break; case '\x3e' /* > */: destination.append(GREATER_THAN); break; default: { // outside the valid range; escape as numeric entity char hexval[7]; sprintf(hexval, "&#x%02x;", *escapeChar.data()); destination.append(hexval); } break; } escapeChar.remove(0); // clear for next iteration } } resultOk = true; } else { // UtlString capacity failed assert(false); } } else { resultOk = true; // empty source - easy } return resultOk; } static const RegEx Entity("&(?:(quot)|(amp)|(apos)|(lt)|(gt)|#(?:([0-9]{1,3})|x([0-9a-fA-F]{1,2})));([^&]*)"); /* substring indicies 1 2 3 4 5 6 7 8 */ /// Append unescaped source string onto destination string /** * The contents of the source string are appended to the destination string, with all * characters unescaped as described above. * @returns true for success, false if an error was returned from any UtlString operation. */ bool XmlUnEscape(UtlString& destination, const UtlString& source) { bool resultOk = false; size_t srcLen = source.length(); if (srcLen > 0) { // make sure that the destination is large enough to add the source (which cannot grow) size_t minDstLen = destination.length() + srcLen; if (destination.capacity(minDstLen) >= minDstLen) { RegEx entity(Entity); UtlString number; bool matched; bool matchedOnce; bool firstMatch = true; // each iteration picks up leading n valid chars (n may be zero) and one that needs to be escaped. for (matchedOnce = matched = entity.Search(source.data(), srcLen); matched; matched = entity.SearchAgain() ) { if (firstMatch) { // copy any leading characters that don't need to be escaped entity.BeforeMatchString(&destination); firstMatch = false; } if (entity.MatchString(NULL,1)) { destination.append('"'); } else if (entity.MatchString(NULL,2)) { destination.append('&'); } else if (entity.MatchString(NULL,3)) { destination.append("'"); } else if (entity.MatchString(NULL,4)) { destination.append('<'); } else if (entity.MatchString(NULL,5)) { destination.append('>'); } else if (entity.MatchString(&number,6)) { char* unconverted; int decimalNum = strtol(number.data(), &unconverted, /* base */ 10); if ('\000'==*unconverted && decimalNum >= 0 && decimalNum < 256) { destination.append(decimalNum); } else { // invalid decimal numeric entity - transcribe it untranslated destination.append(number); } number.remove(0); // clear for next iteration } else if (entity.MatchString(&number,7)) { char* unconverted; int decimalNum = strtol(number.data(), &unconverted, /* base */ 16); if ('\000'==*unconverted && decimalNum >= 0 && decimalNum < 256) { destination.append(decimalNum); } else { // invalid decimal numeric entity - transcribe it untranslated destination.append(number); } number.remove(0); // clear for next iteration } else { assert(false); // the Entity expression should have matched one of the above } // copy any leading characters that don't need to be escaped entity.MatchString(&destination,8); } if (!matchedOnce) { // there were no entities, so just copy the content. destination.append(source); } resultOk = true; } else { // UtlString capacity failed assert(false); } } else { resultOk = true; // empty source - easy } return resultOk; } /// Append decimal string onto destination string /** * The source value is converted into a decimal string according to * "format". The decimal string is appended to the destination string. * "format" defaults to "%d", and must generate no more than 20 characters * (excluding the ending NUL). * @returns true for success, false if an error was returned from any UtlString operation. */ bool XmlDecimal(UtlString& destination, int source, const char* format) { // Buffer in which to build the decimal string. char buffer[20 + 1]; // Build the decimal string. sprintf(buffer, format != NULL ? format : "%d", source); // Append it to the destination. destination.append(buffer); return TRUE; } sipxtapi-3.3.0~test17/sipXportLib/src/utl/UtlRandom.cpp0000644000175000017500000000343112205617431023663 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "utl/UtlRandom.h" #include "os/OsTime.h" #include "os/OsDateTime.h" #include "os/OsTask.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor UtlRandom::UtlRandom() { static int siCounter = 0 ; OsTaskId_t iTaskId = 0 ; OsTime now ; unsigned int seed ; OsTask::getCurrentTaskId(iTaskId) ; OsDateTime::getCurTime(now) ; seed = (now.cvtToMsecs() ^ (now.usecs() + (now.usecs() << 16)) ^ iTaskId) + siCounter++ ; srand(seed) ; } // Constructor UtlRandom::UtlRandom(int seed) { srand(seed) ; } // Destructor UtlRandom::~UtlRandom() { } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ int UtlRandom::rand() { return ::rand() ; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXportLib/src/utl/PluginHooks.cpp0000644000175000017500000001745012205613256024227 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsIntTypes.h" #include "os/OsSysLog.h" #include "os/OsConfigDb.h" #include "os/OsSharedLibMgr.h" #include "utl/UtlString.h" #include "utl/UtlSList.h" #include "utl/Plugin.h" #include "utl/PluginHooks.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define HOOK_LIB_PREFIX "_HOOK_LIBRARY." // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS // GLOBAL VARIABLES /// ConfiguredHook is the container used to hold each Plugin. /** * ConfiguredHook inherits from UtlString so that it will be a * UtlContainable and will be identifiable by its configured prefix name. */ class ConfiguredHook : public UtlString { public: // Load the library for a hook and use its factory to get a new instance. ConfiguredHook(const UtlString& hookPrefix, const UtlString& hookFactoryName, const UtlString& libName ) : UtlString(hookPrefix) , hook(NULL) { OsSharedLibMgrBase* sharedLibMgr = OsSharedLibMgr::getOsSharedLibMgr(); if (sharedLibMgr) { Plugin::Factory factory; if (OS_SUCCESS == sharedLibMgr->getSharedLibSymbol(libName.data(), hookFactoryName, (void*&)factory )) { // Use the factory to get an instance of the hook // and tell the new instance its own name. hook = factory(hookPrefix); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "PluginHooks ConfiguredHook:: created instance '%s' from '%s'", data(), libName.data() ); } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "PluginHooks ConfiguredHook:: factory '%s' not found in library '%s' for instance '%s'", hookFactoryName.data(), libName.data(), data() ); } } else { OsSysLog::add(FAC_KERNEL, PRI_CRIT, "PluginHooks ConfiguredHook:: failed to getOsSharedLibMgr" ); } } ~ConfiguredHook() { // Don't try to unload any libraries. // It does not worth the complexity of reference counting if // the same library could be configured more than once with // different hook names and parameters. } /// Get the name of this hook. void name(UtlString* hookName) const { if (hookName) { hookName->remove(0); hookName->append(*this); } } /// Get the actual hook object. Plugin* plugin() const { return hook; } /// Construct the subhash for the hook and configure it. void readConfig(const UtlString& prefix, OsConfigDb& configDb) { if (hook) { OsConfigDb myConfig; UtlString myConfigName; // build up ".." key for configuration subhash myConfigName.append(prefix); myConfigName.append('.'); myConfigName.append(*this); myConfigName.append('.'); if (OS_SUCCESS == configDb.getSubHash(myConfigName, myConfig)) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "ConfiguredHook:: configuring instance '%s' using prefix '%s'", data(), myConfigName.data() ); hook->readConfig(myConfig); } else { OsSysLog::add(FAC_KERNEL, PRI_CRIT, "ConfiguredHook:: no configuration found for instance '%s'", data() ); } } }; private: Plugin* hook; ///< the actual hook instance }; PluginHooks::PluginHooks(const char* hookFactoryName, const char* hookPrefix ) : mFactory(hookFactoryName) , mPrefix(hookPrefix) { } PluginHooks::~PluginHooks() { mConfiguredHooks.destroyAll(); } void PluginHooks::readConfig(OsConfigDb& configDb) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "PluginHooks::readConfig mFactory = '%s', mPrefix = '%s'", mFactory.data(), mPrefix.data()); // Move any existing hooks from the current configured list to // a temporary holding list. UtlSList existingHooks; UtlContainable* existingHook; UtlSortedListIterator nextHook(mConfiguredHooks); while ((existingHook = nextHook())) { existingHooks.append(mConfiguredHooks.removeReference(existingHook)); } // the mConfiguredHooks list is now empty // Walk the current configuration, // any existing hook is moved back to the mConfiguredHooks list, // newly configured hooks are added, // each configured hook is called to read its own configuration. UtlString hookPrefix(mPrefix); hookPrefix.append(HOOK_LIB_PREFIX); OsConfigDb allHooks; OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "PluginHooks::readConfig looking up hooks '%s'", hookPrefix.data() ); if (OS_SUCCESS == configDb.getSubHash(hookPrefix, allHooks)) // any hooks configured for prefix? { UtlString lastHook; UtlString hookName; UtlString hookLibrary; // walk each hook and attempt to load and configure it for ( lastHook = ""; OS_SUCCESS == allHooks.getNext(lastHook, hookName, hookLibrary); lastHook = hookName ) { ConfiguredHook* thisHook; if (NULL == (thisHook = static_cast(existingHooks.remove(&hookName)))) { // not an existing hook, so create a new one OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "PluginHooks: loading instance '%s'", hookName.data() ); thisHook = new ConfiguredHook(hookName, mFactory, hookLibrary); } // put the hook onto the list of active hooks mConfiguredHooks.insert(thisHook); // (re)configure the hook thisHook->readConfig(mPrefix, configDb); } } else { OsSysLog::add(FAC_KERNEL, PRI_INFO, "PluginHooks: no '%s' hooks configured", mPrefix.data() ); } // discard any hooks that are no longer in the configuration existingHooks.destroyAll(); } size_t PluginHooks::entries() const { return mConfiguredHooks.entries(); } PluginIterator::PluginIterator(const PluginHooks& pluginHooks) : mConfiguredHooksIterator(pluginHooks.mConfiguredHooks) { } PluginIterator::~PluginIterator() { } Plugin* PluginIterator::next(UtlString* name) { Plugin* nextPlugin = NULL; // make sure that name is cleared if passed in case this is the last hook if (name) { name->remove(0); } // step the parent iterator on the mConfiguredHooks list ConfiguredHook* nextHook = static_cast(mConfiguredHooksIterator()); if (nextHook) { nextHook->name(name); // return the name, if it's been asked for nextPlugin = nextHook->plugin(); } return nextPlugin; } sipxtapi-3.3.0~test17/sipXportLib/src/xmlparser/0000755000175000017500000000000012321445024022456 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/src/xmlparser/tinystr.cpp0000644000175000017500000001722612205613256024713 0ustar00danieldaniel00000000000000/* www.sourceforge.net/projects/tinyxml Original file by Yves Berquin. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "xmlparser/tinyxml.h" #ifndef TIXML_USE_STL #include #include #include #include "xmlparser/tinystr.h" // TiXmlString constructor, based on a C string TiXmlString::TiXmlString (const char* instring) { size_t newlen; char * newstring; if (!instring) { allocated = 0; cstring = NULL; current_length = 0; return; } newlen = strlen (instring) + 1; newstring = new char [newlen]; memcpy (newstring, instring, newlen); // strcpy (newstring, instring); allocated = newlen; cstring = newstring; current_length = newlen - 1; } // TiXmlString copy constructor TiXmlString::TiXmlString (const TiXmlString& copy) { size_t newlen; char * newstring; // Prevent copy to self! if ( © == this ) return; if (! copy . allocated) { allocated = 0; cstring = NULL; current_length = 0; return; } newlen = copy . length () + 1; newstring = new char [newlen]; // strcpy (newstring, copy . cstring); memcpy (newstring, copy . cstring, newlen); allocated = newlen; cstring = newstring; current_length = newlen - 1; } // TiXmlString = operator. Safe when assign own content void TiXmlString ::operator = (const char * content) { size_t newlen; char * newstring; if (! content) { empty_it (); return; } newlen = strlen (content) + 1; newstring = new char [newlen]; // strcpy (newstring, content); memcpy (newstring, content, newlen); empty_it (); allocated = newlen; cstring = newstring; current_length = newlen - 1; } // = operator. Safe when assign own content void TiXmlString ::operator = (const TiXmlString & copy) { size_t newlen; char * newstring; if (! copy . length ()) { empty_it (); return; } newlen = copy . length () + 1; newstring = new char [newlen]; // strcpy (newstring, copy . c_str ()); memcpy (newstring, copy . c_str (), newlen); empty_it (); allocated = newlen; cstring = newstring; current_length = newlen - 1; } // append a const char * to an existing TiXmlString void TiXmlString::append( const char* str, size_t len ) { char * new_string; size_t new_alloc, new_size, size_suffix; // don't use strlen - it can overrun the len passed in! const char* p = str; size_suffix = 0; while ( *p && size_suffix < (unsigned)len ) { ++p; ++size_suffix; } if ( !size_suffix) return; new_size = length () + size_suffix + 1; // check if we need to expand if (new_size > allocated) { // compute new size new_alloc = assign_new_size (new_size); // allocate new buffer new_string = new char [new_alloc]; new_string [0] = 0; // copy the previous allocated buffer into this one if (allocated && cstring) // strcpy (new_string, cstring); memcpy (new_string, cstring, length ()); // append the suffix. It does exist, otherwize we wouldn't be expanding // strncat (new_string, str, len); memcpy (new_string + length (), str, size_suffix); // return previsously allocated buffer if any if (allocated && cstring) delete [] cstring; // update member variables cstring = new_string; allocated = new_alloc; } else { // we know we can safely append the new string // strncat (cstring, str, len); memcpy (cstring + length (), str, size_suffix); } current_length = new_size - 1; cstring [current_length] = 0; } // append a const char * to an existing TiXmlString void TiXmlString::append( const char * suffix ) { char * new_string; size_t new_alloc, new_size; new_size = length () + strlen (suffix) + 1; // check if we need to expand if (new_size > allocated) { // compute new size new_alloc = assign_new_size (new_size); // allocate new buffer new_string = new char [new_alloc]; new_string [0] = 0; // copy the previous allocated buffer into this one if (allocated && cstring) memcpy (new_string, cstring, 1 + length ()); // strcpy (new_string, cstring); // append the suffix. It does exist, otherwize we wouldn't be expanding // strcat (new_string, suffix); memcpy (new_string + length (), suffix, strlen (suffix) + 1); // return previsously allocated buffer if any if (allocated && cstring) delete [] cstring; // update member variables cstring = new_string; allocated = new_alloc; } else { // we know we can safely append the new string // strcat (cstring, suffix); memcpy (cstring + length (), suffix, strlen (suffix) + 1); } current_length = new_size - 1; } // Check for TiXmlString equuivalence //bool TiXmlString::operator == (const TiXmlString & compare) const //{ // return (! strcmp (c_str (), compare . c_str ())); //} //unsigned TiXmlString::length () const //{ // if (allocated) // // return strlen (cstring); // return current_length; // return 0; //} unsigned TiXmlString::find (char tofind, unsigned offset) const { char * lookup; if (offset >= length ()) return (unsigned) notfound; for (lookup = cstring + offset; * lookup; lookup++) if (* lookup == tofind) return (unsigned)(lookup - cstring); return (unsigned) notfound; } bool TiXmlString::operator == (const TiXmlString & compare) const { if ( allocated && compare.allocated ) { assert( cstring ); assert( compare.cstring ); return ( strcmp( cstring, compare.cstring ) == 0 ); } else if ( length() == 0 && compare.length() == 0 ) { return true; } return false; } bool TiXmlString::operator == (const char* compare) const { if ( allocated && compare && *compare ) { assert( cstring ); return ( strcmp( cstring, compare ) == 0 ); } else if ( length() == 0 && (!compare || !*compare ) ) // this is a little dubious, but try to duplicate behavior in other operator== { return true; } return false; } bool TiXmlString::operator < (const TiXmlString & compare) const { if ( allocated && compare.allocated ) { assert( cstring ); assert( compare.cstring ); return ( strcmp( cstring, compare.cstring ) > 0 ); } return false; } bool TiXmlString::operator > (const TiXmlString & compare) const { if ( allocated && compare.allocated ) { assert( cstring ); assert( compare.cstring ); return ( strcmp( cstring, compare.cstring ) < 0 ); } return false; } #endif // TIXML_USE_STL sipxtapi-3.3.0~test17/sipXportLib/src/xmlparser/tinyxml.cpp0000644000175000017500000007452612205613256024711 0ustar00danieldaniel00000000000000/* www.sourceforge.net/projects/tinyxml Original code (2.0 and earlier )copyright (c) 2000-2002 Lee Thomason (www.grinninglizard.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include #ifdef _WIN32 # ifndef WINCE # include # endif #else # include #endif #include "xmlparser/tinyxml.h" #ifdef TIXML_USE_STL #include #endif #include bool TiXmlBase::condenseWhiteSpace = true; void TiXmlBase::PutString( const TIXML_STRING& str, TIXML_OSTREAM* stream ) { TIXML_STRING buffer; PutString( str, &buffer ); (*stream) << buffer; } void TiXmlBase::PutString( const TIXML_STRING& str, TIXML_STRING* outString ) { int i=0; while( i<(int)str.length() ) { unsigned char c = (unsigned char) str[i]; if ( c == '&' && i < ( (int)str.length() - 2 ) && str[i+1] == '#' && str[i+2] == 'x' ) { // Hexadecimal character reference. // Pass through unchanged. // © -- copyright symbol, for example. // // The -1 is a bug fix from Rob Laveaux. It keeps // an overflow from happening if there is no ';'. // There are actually 2 ways to exit this loop - // while fails (error case) and break (semicolon found). // However, there is no mechanism (currently) for // this function to return an error. while ( i<(int)str.length()-1 ) { outString->append( str.c_str() + i, 1 ); ++i; if ( str[i] == ';' ) break; } } else if ( c == '&' ) { outString->append( entity[0].str, entity[0].strLength ); ++i; } else if ( c == '<' ) { outString->append( entity[1].str, entity[1].strLength ); ++i; } else if ( c == '>' ) { outString->append( entity[2].str, entity[2].strLength ); ++i; } else if ( c == '\"' ) { outString->append( entity[3].str, entity[3].strLength ); ++i; } else if ( c == '\'' ) { outString->append( entity[4].str, entity[4].strLength ); ++i; } else if ( c < 32 ) { // Easy pass at non-alpha/numeric/symbol // Below 32 is symbolic. char buf[ 32 ]; sprintf( buf, "&#x%02X;", (unsigned) ( c & 0xff ) ); //*ME: warning C4267: convert 'size_t' to 'int' //*ME: Int-Cast to make compiler happy ... outString->append( buf, (int)strlen( buf ) ); ++i; } else { //char realc = (char) c; //outString->append( &realc, 1 ); *outString += (char) c; // somewhat more efficient function call. ++i; } } } // <-- Strange class for a bug fix. Search for STL_STRING_BUG TiXmlBase::StringToBuffer::StringToBuffer( const TIXML_STRING& str ) { buffer = new char[ str.length()+1 ]; if ( buffer ) { strcpy( buffer, str.c_str() ); } } TiXmlBase::StringToBuffer::~StringToBuffer() { delete [] buffer; } // End strange bug fix. --> TiXmlNode::TiXmlNode( NodeType _type ) : TiXmlBase() { parent = 0; type = _type; firstChild = 0; lastChild = 0; prev = 0; next = 0; } TiXmlNode::~TiXmlNode() { TiXmlNode* node = firstChild; TiXmlNode* temp = 0; while ( node ) { temp = node; node = node->next; delete temp; } } void TiXmlNode::CopyTo( TiXmlNode* target ) const { target->SetValue (value.c_str() ); target->userData = userData; } void TiXmlNode::Clear() { TiXmlNode* node = firstChild; TiXmlNode* temp = 0; while ( node ) { temp = node; node = node->next; delete temp; } firstChild = 0; lastChild = 0; } TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node ) { node->parent = this; node->prev = lastChild; node->next = 0; if ( lastChild ) lastChild->next = node; else firstChild = node; // it was an empty list. lastChild = node; return node; } TiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis ) { TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; return LinkEndChild( node ); } TiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ) { if ( !beforeThis || beforeThis->parent != this ) return 0; TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; node->parent = this; node->next = beforeThis; node->prev = beforeThis->prev; if ( beforeThis->prev ) { beforeThis->prev->next = node; } else { assert( firstChild == beforeThis ); firstChild = node; } beforeThis->prev = node; return node; } TiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ) { if ( !afterThis || afterThis->parent != this ) return 0; TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; node->parent = this; node->prev = afterThis; node->next = afterThis->next; if ( afterThis->next ) { afterThis->next->prev = node; } else { assert( lastChild == afterThis ); lastChild = node; } afterThis->next = node; return node; } TiXmlNode* TiXmlNode::ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ) { if ( replaceThis->parent != this ) return 0; TiXmlNode* node = withThis.Clone(); if ( !node ) return 0; node->next = replaceThis->next; node->prev = replaceThis->prev; if ( replaceThis->next ) replaceThis->next->prev = node; else lastChild = node; if ( replaceThis->prev ) replaceThis->prev->next = node; else firstChild = node; delete replaceThis; node->parent = this; return node; } bool TiXmlNode::RemoveChild( TiXmlNode* removeThis ) { if ( removeThis->parent != this ) { assert( 0 ); return false; } if ( removeThis->next ) removeThis->next->prev = removeThis->prev; else lastChild = removeThis->prev; if ( removeThis->prev ) removeThis->prev->next = removeThis->next; else firstChild = removeThis->next; delete removeThis; return true; } const TiXmlNode* TiXmlNode::FirstChild( const char * _value ) const { const TiXmlNode* node; for ( node = firstChild; node; node = node->next ) { if ( node->SValue() == _value ) return node; } return 0; } TiXmlNode* TiXmlNode::FirstChild( const char * _value ) { TiXmlNode* node; for ( node = firstChild; node; node = node->next ) { if ( node->SValue() == _value ) return node; } return 0; } const TiXmlNode* TiXmlNode::LastChild( const char * _value ) const { const TiXmlNode* node; for ( node = lastChild; node; node = node->prev ) { if ( node->SValue() == _value ) return node; } return 0; } TiXmlNode* TiXmlNode::LastChild( const char * _value ) { TiXmlNode* node; for ( node = lastChild; node; node = node->prev ) { if ( node->SValue() == _value ) return node; } return 0; } const TiXmlNode* TiXmlNode::IterateChildren( const TiXmlNode* previous ) const { if ( !previous ) { return FirstChild(); } else { assert( previous->parent == this ); return previous->NextSibling(); } } TiXmlNode* TiXmlNode::IterateChildren( TiXmlNode* previous ) { if ( !previous ) { return FirstChild(); } else { assert( previous->parent == this ); return previous->NextSibling(); } } const TiXmlNode* TiXmlNode::IterateChildren( const char * val, const TiXmlNode* previous ) const { if ( !previous ) { return FirstChild( val ); } else { assert( previous->parent == this ); return previous->NextSibling( val ); } } TiXmlNode* TiXmlNode::IterateChildren( const char * val, TiXmlNode* previous ) { if ( !previous ) { return FirstChild( val ); } else { assert( previous->parent == this ); return previous->NextSibling( val ); } } const TiXmlNode* TiXmlNode::NextSibling( const char * _value ) const { const TiXmlNode* node; for ( node = next; node; node = node->next ) { if ( node->SValue() == _value ) return node; } return 0; } TiXmlNode* TiXmlNode::NextSibling( const char * _value ) { TiXmlNode* node; for ( node = next; node; node = node->next ) { if ( node->SValue() == _value ) return node; } return 0; } const TiXmlNode* TiXmlNode::PreviousSibling( const char * _value ) const { const TiXmlNode* node; for ( node = prev; node; node = node->prev ) { if ( node->SValue() == _value ) return node; } return 0; } TiXmlNode* TiXmlNode::PreviousSibling( const char * _value ) { TiXmlNode* node; for ( node = prev; node; node = node->prev ) { if ( node->SValue() == _value ) return node; } return 0; } void TiXmlElement::RemoveAttribute( const char * name ) { TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) { attributeSet.Remove( node ); delete node; } } const TiXmlElement* TiXmlNode::FirstChildElement() const { const TiXmlNode* node; for ( node = FirstChild(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } TiXmlElement* TiXmlNode::FirstChildElement() { TiXmlNode* node; for ( node = FirstChild(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlElement* TiXmlNode::FirstChildElement( const char * _value ) const { const TiXmlNode* node; for ( node = FirstChild( _value ); node; node = node->NextSibling( _value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } TiXmlElement* TiXmlNode::FirstChildElement( const char * _value ) { TiXmlNode* node; for ( node = FirstChild( _value ); node; node = node->NextSibling( _value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlElement* TiXmlNode::NextSiblingElement() const { const TiXmlNode* node; for ( node = NextSibling(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } TiXmlElement* TiXmlNode::NextSiblingElement() { TiXmlNode* node; for ( node = NextSibling(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlElement* TiXmlNode::NextSiblingElement( const char * _value ) const { const TiXmlNode* node; for ( node = NextSibling( _value ); node; node = node->NextSibling( _value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } TiXmlElement* TiXmlNode::NextSiblingElement( const char * _value ) { TiXmlNode* node; for ( node = NextSibling( _value ); node; node = node->NextSibling( _value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlDocument* TiXmlNode::GetDocument() const { const TiXmlNode* node; for( node = this; node; node = node->parent ) { if ( node->ToDocument() ) return node->ToDocument(); } return 0; } TiXmlDocument* TiXmlNode::GetDocument() { TiXmlNode* node; for( node = this; node; node = node->parent ) { if ( node->ToDocument() ) return node->ToDocument(); } return 0; } TiXmlElement::TiXmlElement (const char * _value) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; value = _value; } #ifdef TIXML_USE_STL TiXmlElement::TiXmlElement( const std::string& _value ) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; value = _value; } #endif TiXmlElement::TiXmlElement( const TiXmlElement& copy) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; copy.CopyTo( this ); } void TiXmlElement::operator=( const TiXmlElement& base ) { ClearThis(); base.CopyTo( this ); } TiXmlElement::~TiXmlElement() { ClearThis(); } void TiXmlElement::ClearThis() { Clear(); while( attributeSet.First() ) { TiXmlAttribute* node = attributeSet.First(); attributeSet.Remove( node ); delete node; } } const char * TiXmlElement::Attribute( const char * name ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) return node->Value(); return 0; } const char * TiXmlElement::Attribute( const char * name, int* i ) const { const char * s = Attribute( name ); if ( i ) { if ( s ) *i = atoi( s ); else *i = 0; } return s; } const char * TiXmlElement::Attribute( const char * name, double* d ) const { const char * s = Attribute( name ); if ( d ) { if ( s ) *d = atof( s ); else *d = 0; } return s; } int TiXmlElement::QueryIntAttribute( const char* name, int* ival ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryIntValue( ival ); } int TiXmlElement::QueryDoubleAttribute( const char* name, double* dval ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryDoubleValue( dval ); } void TiXmlElement::SetAttribute( const char * name, int val ) { char buf[64]; sprintf( buf, "%d", val ); SetAttribute( name, buf ); } void TiXmlElement::SetDoubleAttribute( const char * name, double val ) { char buf[256]; sprintf( buf, "%f", val ); SetAttribute( name, buf ); } void TiXmlElement::SetAttribute( const char * name, const char * _value ) { TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) { node->SetValue( _value ); return; } TiXmlAttribute* attrib = new TiXmlAttribute( name, _value ); if ( attrib ) { attributeSet.Add( attrib ); } else { TiXmlDocument* document = GetDocument(); if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, TIXML_ENCODING_UNKNOWN ); } } void TiXmlElement::Print( FILE* cfile, int depth ) const { int i; for ( i=0; iNext() ) { fprintf( cfile, " " ); attrib->Print( cfile, depth ); } // There are 3 different formatting approaches: // 1) An element without children is printed as a node // 2) An element with only a text child is printed as text // 3) An element with children is printed on multiple lines. TiXmlNode* node; if ( !firstChild ) { fprintf( cfile, " />" ); } else if ( firstChild == lastChild && firstChild->ToText() ) { fprintf( cfile, ">" ); firstChild->Print( cfile, depth + 1 ); fprintf( cfile, "", value.c_str() ); } else { fprintf( cfile, ">" ); for ( node = firstChild; node; node=node->NextSibling() ) { if ( !node->ToText() ) { fprintf( cfile, "\n" ); } node->Print( cfile, depth+1 ); } fprintf( cfile, "\n" ); for( i=0; i", value.c_str() ); } } void TiXmlElement::StreamOut( TIXML_OSTREAM * stream ) const { (*stream) << "<" << value; const TiXmlAttribute* attrib; for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() ) { (*stream) << " "; attrib->StreamOut( stream ); } // If this node has children, give it a closing tag. Else // make it an empty tag. TiXmlNode* node; if ( firstChild ) { (*stream) << ">"; for ( node = firstChild; node; node=node->NextSibling() ) { node->StreamOut( stream ); } (*stream) << ""; } else { (*stream) << " />"; } } void TiXmlElement::CopyTo( TiXmlElement* target ) const { // superclass: TiXmlNode::CopyTo( target ); // Element class: // Clone the attributes, then clone the children. const TiXmlAttribute* attribute = 0; for( attribute = attributeSet.First(); attribute; attribute = attribute->Next() ) { target->SetAttribute( attribute->Name(), attribute->Value() ); } TiXmlNode* node = 0; for ( node = firstChild; node; node = node->NextSibling() ) { target->LinkEndChild( node->Clone() ); } } TiXmlNode* TiXmlElement::Clone() const { TiXmlElement* clone = new TiXmlElement( Value() ); if ( !clone ) return 0; CopyTo( clone ); return clone; } TiXmlDocument::TiXmlDocument() : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; ClearError(); } TiXmlDocument::TiXmlDocument( const char * documentName ) : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; value = documentName; ClearError(); } #ifdef TIXML_USE_STL TiXmlDocument::TiXmlDocument( const std::string& documentName ) : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; value = documentName; ClearError(); } #endif TiXmlDocument::TiXmlDocument( const TiXmlDocument& copy ) : TiXmlNode( TiXmlNode::DOCUMENT ) { copy.CopyTo( this ); } void TiXmlDocument::operator=( const TiXmlDocument& copy ) { Clear(); copy.CopyTo( this ); } bool TiXmlDocument::LoadFile( TiXmlEncoding encoding ) { // See STL_STRING_BUG below. StringToBuffer buf( value ); if ( buf.buffer && LoadFile( buf.buffer, encoding ) ) return true; return false; } bool TiXmlDocument::SaveFile() const { // See STL_STRING_BUG below. StringToBuffer buf( value ); if ( buf.buffer && SaveFile( buf.buffer ) ) return true; return false; } bool TiXmlDocument::LoadFile( const char* filename, TiXmlEncoding encoding ) { // Delete the existing data: Clear(); location.Clear(); // There was a really terrifying little bug here. The code: // value = filename // in the STL case, cause the assignment method of the std::string to // be called. What is strange, is that the std::string had the same // address as it's c_str() method, and so bad things happen. Looks // like a bug in the Microsoft STL implementation. // See STL_STRING_BUG above. // Fixed with the StringToBuffer class. value = filename; FILE* file = fopen( value.c_str (), "r" ); if ( file ) { // Get the file size, so we can pre-allocate the string. HUGE speed impact. long length = 0; fseek( file, 0, SEEK_END ); length = ftell( file ); fseek( file, 0, SEEK_SET ); // Strange case, but good to handle up front. if ( length == 0 ) { fclose( file ); return false; } // If we have a file, assume it is all one big XML file, and read it in. // The document parser may decide the document ends sooner than the entire file, however. TIXML_STRING data; data.reserve( length ); const int BUF_SIZE = 2048; char buf[BUF_SIZE]; while( fgets( buf, BUF_SIZE, file ) ) { data += buf; } fclose( file ); Parse( data.c_str(), 0, encoding ); if ( Error() ) return false; else return true; } SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); return false; } bool TiXmlDocument::SaveFile( const char * filename ) const { bool result = false; // the filename is what we want to write, but if we crash or are restarted // when it is only partially written, then the resulting file will not be // well-formed, so we first write to a .new file and then only when that is // done do we change the name to the real filename const char* newsuffix = ".new"; char* newfilename = new char[strlen(filename) + strlen(newsuffix) + 1]; if (newfilename) { strcpy(newfilename,filename); strcat(newfilename,newsuffix); // The old c stuff lives on... FILE* fp = fopen( newfilename, "w" ); if ( fp ) { Print( fp, 0 ); fflush( fp ); // flush user space buffers fflush(fp); // sync kernel buffers to disk fclose( fp ); // file is safe on disk - rename atomically changes it to filename, // ensuring that at all times there is a well-formed file on disk.xo OsFile tempFile(newfilename); tempFile.rename(filename); result = true; } delete [] newfilename; } return result; } void TiXmlDocument::CopyTo( TiXmlDocument* target ) const { TiXmlNode::CopyTo( target ); target->error = error; target->errorDesc = errorDesc.c_str (); TiXmlNode* node = 0; for ( node = firstChild; node; node = node->NextSibling() ) { target->LinkEndChild( node->Clone() ); } } TiXmlNode* TiXmlDocument::Clone() const { TiXmlDocument* clone = new TiXmlDocument(); if ( !clone ) return 0; CopyTo( clone ); return clone; } void TiXmlDocument::Print( FILE* cfile, int depth ) const { const TiXmlNode* node; for ( node=FirstChild(); node; node=node->NextSibling() ) { node->Print( cfile, depth ); fprintf( cfile, "\n" ); } } void TiXmlDocument::StreamOut( TIXML_OSTREAM * out ) const { const TiXmlNode* node; for ( node=FirstChild(); node; node=node->NextSibling() ) { node->StreamOut( out ); // Special rule for streams: stop after the root element. // The stream in code will only read one element, so don't // write more than one. if ( node->ToElement() ) break; } } const TiXmlAttribute* TiXmlAttribute::Next() const { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( next->value.empty() && next->name.empty() ) return 0; return next; } TiXmlAttribute* TiXmlAttribute::Next() { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( next->value.empty() && next->name.empty() ) return 0; return next; } const TiXmlAttribute* TiXmlAttribute::Previous() const { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( prev->value.empty() && prev->name.empty() ) return 0; return prev; } TiXmlAttribute* TiXmlAttribute::Previous() { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( prev->value.empty() && prev->name.empty() ) return 0; return prev; } void TiXmlAttribute::Print( FILE* cfile, int /*depth*/ ) const { TIXML_STRING n, v; PutString( name, &n ); PutString( value, &v ); if (value.find ('\"') == TIXML_STRING::npos) fprintf (cfile, "%s=\"%s\"", n.c_str(), v.c_str() ); else fprintf (cfile, "%s='%s'", n.c_str(), v.c_str() ); } void TiXmlAttribute::StreamOut( TIXML_OSTREAM * stream ) const { if (value.find( '\"' ) != TIXML_STRING::npos) { PutString( name, stream ); (*stream) << "=" << "'"; PutString( value, stream ); (*stream) << "'"; } else { PutString( name, stream ); (*stream) << "=" << "\""; PutString( value, stream ); (*stream) << "\""; } } int TiXmlAttribute::QueryIntValue( int* ival ) const { if ( sscanf( value.c_str(), "%d", ival ) == 1 ) return TIXML_SUCCESS; return TIXML_WRONG_TYPE; } int TiXmlAttribute::QueryDoubleValue( double* dval ) const { if ( sscanf( value.c_str(), "%lf", dval ) == 1 ) return TIXML_SUCCESS; return TIXML_WRONG_TYPE; } void TiXmlAttribute::SetIntValue( int _value ) { char buf [64]; sprintf (buf, "%d", _value); SetValue (buf); } void TiXmlAttribute::SetDoubleValue( double _value ) { char buf [256]; sprintf (buf, "%lf", _value); SetValue (buf); } const int TiXmlAttribute::IntValue() const { return atoi (value.c_str ()); } const double TiXmlAttribute::DoubleValue() const { return atof (value.c_str ()); } TiXmlComment::TiXmlComment( const TiXmlComment& copy ) : TiXmlNode( TiXmlNode::COMMENT ) { copy.CopyTo( this ); } void TiXmlComment::operator=( const TiXmlComment& base ) { Clear(); base.CopyTo( this ); } void TiXmlComment::Print( FILE* cfile, int depth ) const { for ( int i=0; i", value.c_str() ); } void TiXmlComment::StreamOut( TIXML_OSTREAM * stream ) const { (*stream) << ""; } void TiXmlComment::CopyTo( TiXmlComment* target ) const { TiXmlNode::CopyTo( target ); } TiXmlNode* TiXmlComment::Clone() const { TiXmlComment* clone = new TiXmlComment(); if ( !clone ) return 0; CopyTo( clone ); return clone; } void TiXmlText::Print( FILE* cfile, int /*depth*/ ) const { TIXML_STRING buffer; PutString( value, &buffer ); fprintf( cfile, "%s", buffer.c_str() ); } void TiXmlText::StreamOut( TIXML_OSTREAM * stream ) const { PutString( value, stream ); } void TiXmlText::CopyTo( TiXmlText* target ) const { TiXmlNode::CopyTo( target ); } TiXmlNode* TiXmlText::Clone() const { TiXmlText* clone = 0; clone = new TiXmlText( "" ); if ( !clone ) return 0; CopyTo( clone ); return clone; } TiXmlDeclaration::TiXmlDeclaration( const char * _version, const char * _encoding, const char * _standalone ) : TiXmlNode( TiXmlNode::DECLARATION ) { version = _version; encoding = _encoding; standalone = _standalone; } #ifdef TIXML_USE_STL TiXmlDeclaration::TiXmlDeclaration( const std::string& _version, const std::string& _encoding, const std::string& _standalone ) : TiXmlNode( TiXmlNode::DECLARATION ) { version = _version; encoding = _encoding; standalone = _standalone; } #endif TiXmlDeclaration::TiXmlDeclaration( const TiXmlDeclaration& copy ) : TiXmlNode( TiXmlNode::DECLARATION ) { copy.CopyTo( this ); } void TiXmlDeclaration::operator=( const TiXmlDeclaration& copy ) { Clear(); copy.CopyTo( this ); } void TiXmlDeclaration::Print( FILE* cfile, int /*depth*/ ) const { fprintf (cfile, ""); } void TiXmlDeclaration::StreamOut( TIXML_OSTREAM * stream ) const { (*stream) << ""; } void TiXmlDeclaration::CopyTo( TiXmlDeclaration* target ) const { TiXmlNode::CopyTo( target ); target->version = version; target->encoding = encoding; target->standalone = standalone; } TiXmlNode* TiXmlDeclaration::Clone() const { TiXmlDeclaration* clone = new TiXmlDeclaration(); if ( !clone ) return 0; CopyTo( clone ); return clone; } void TiXmlUnknown::Print( FILE* cfile, int depth ) const { for ( int i=0; i", value.c_str() ); } void TiXmlUnknown::StreamOut( TIXML_OSTREAM * stream ) const { (*stream) << "<" << value << ">"; // Don't use entities here! It is unknown. } void TiXmlUnknown::CopyTo( TiXmlUnknown* target ) const { TiXmlNode::CopyTo( target ); } TiXmlNode* TiXmlUnknown::Clone() const { TiXmlUnknown* clone = new TiXmlUnknown(); if ( !clone ) return 0; CopyTo( clone ); return clone; } TiXmlAttributeSet::TiXmlAttributeSet() { sentinel.next = &sentinel; sentinel.prev = &sentinel; } TiXmlAttributeSet::~TiXmlAttributeSet() { assert( sentinel.next == &sentinel ); assert( sentinel.prev == &sentinel ); } void TiXmlAttributeSet::Add( TiXmlAttribute* addMe ) { assert( !Find( addMe->Name() ) ); // Shouldn't be multiply adding to the set. addMe->next = &sentinel; addMe->prev = sentinel.prev; sentinel.prev->next = addMe; sentinel.prev = addMe; } void TiXmlAttributeSet::Remove( TiXmlAttribute* removeMe ) { TiXmlAttribute* node; for( node = sentinel.next; node != &sentinel; node = node->next ) { if ( node == removeMe ) { node->prev->next = node->next; node->next->prev = node->prev; node->next = 0; node->prev = 0; return; } } assert( 0 ); // we tried to remove a non-linked attribute. } const TiXmlAttribute* TiXmlAttributeSet::Find( const char * name ) const { const TiXmlAttribute* node; for( node = sentinel.next; node != &sentinel; node = node->next ) { if ( node->name == name ) return node; } return 0; } TiXmlAttribute* TiXmlAttributeSet::Find( const char * name ) { TiXmlAttribute* node; for( node = sentinel.next; node != &sentinel; node = node->next ) { if ( node->name == name ) return node; } return 0; } #ifdef TIXML_USE_STL TIXML_ISTREAM & operator >> (TIXML_ISTREAM & in, TiXmlNode & base) { TIXML_STRING tag; tag.reserve( 8 * 1000 ); base.StreamIn( &in, &tag ); base.Parse( tag.c_str(), 0, TIXML_DEFAULT_ENCODING ); return in; } #endif TIXML_OSTREAM & operator<< (TIXML_OSTREAM & out, const TiXmlNode & base) { base.StreamOut (& out); return out; } #ifdef TIXML_USE_STL std::string & operator<< (std::string& out, const TiXmlNode& base ) { std::ostringstream os_stream( std::ostringstream::out ); base.StreamOut( &os_stream ); out.append( os_stream.str() ); return out; } #endif TiXmlHandle TiXmlHandle::FirstChild() const { if ( node ) { TiXmlNode* child = node->FirstChild(); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChild( const char * value ) const { if ( node ) { TiXmlNode* child = node->FirstChild( value ); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChildElement() const { if ( node ) { TiXmlElement* child = node->FirstChildElement(); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChildElement( const char * value ) const { if ( node ) { TiXmlElement* child = node->FirstChildElement( value ); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::Child( int count ) const { if ( node ) { int i; TiXmlNode* child = node->FirstChild(); for ( i=0; child && iNextSibling(), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::Child( const char* value, int count ) const { if ( node ) { int i; TiXmlNode* child = node->FirstChild( value ); for ( i=0; child && iNextSibling( value ), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::ChildElement( int count ) const { if ( node ) { int i; TiXmlElement* child = node->FirstChildElement(); for ( i=0; child && iNextSiblingElement(), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::ChildElement( const char* value, int count ) const { if ( node ) { int i; TiXmlElement* child = node->FirstChildElement( value ); for ( i=0; child && iNextSiblingElement( value ), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } sipxtapi-3.3.0~test17/sipXportLib/src/xmlparser/tinyxmlerror.cpp0000644000175000017500000000325412205613256025751 0ustar00danieldaniel00000000000000/* www.sourceforge.net/projects/tinyxml Original code (2.0 and earlier )copyright (c) 2000-2002 Lee Thomason (www.grinninglizard.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "xmlparser/tinyxml.h" // The goal of the seperate error file is to make the first // step towards localization. tinyxml (currently) only supports // latin-1, but at least the error messages could now be translated. // // It also cleans up the code a bit. // const char* TiXmlBase::errorString[ TIXML_ERROR_STRING_COUNT ] = { "No error", "Error", "Failed to open file", "Memory allocation failed.", "Error parsing Element.", "Failed to read Element name", "Error reading Element value.", "Error reading Attributes.", "Error: empty tag.", "Error reading end tag.", "Error parsing Unknown.", "Error parsing Comment.", "Error parsing Declaration.", "Error document empty.", "Error null (0) or unexpected EOF found in input stream." }; sipxtapi-3.3.0~test17/sipXportLib/src/xmlparser/tinyxmlparser.cpp0000644000175000017500000010157312205613256026117 0ustar00danieldaniel00000000000000/* www.sourceforge.net/projects/tinyxml Original code (2.0 and earlier )copyright (c) 2000-2002 Lee Thomason (www.grinninglizard.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "xmlparser/tinyxml.h" #include #include //#define DEBUG_PARSER // Note tha "PutString" hardcodes the same list. This // is less flexible than it appears. Changing the entries // or order will break putstring. TiXmlBase::Entity TiXmlBase::entity[ NUM_ENTITY ] = { { "&", 5, '&' }, { "<", 4, '<' }, { ">", 4, '>' }, { """, 6, '\"' }, { "'", 6, '\'' } }; // Bunch of unicode info at: // http://www.unicode.org/faq/utf_bom.html // Including the basic of this table, which determines the #bytes in the // sequence from the lead byte. 1 placed for invalid sequences -- // although the result will be junk, pass it through as much as possible. // Beware of the non-characters in UTF-8: // ef bb bf (Microsoft "lead bytes") // ef bf be // ef bf bf const unsigned char TIXML_UTF_LEAD_0 = 0xefU; const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; const int TiXmlBase::utf8ByteTable[256] = { // 0 1 2 3 4 5 6 7 8 9 a b c d e f 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x10 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x20 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x30 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x40 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x50 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x60 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x70 End of ASCII range 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x80 0x80 to 0xc1 invalid 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x90 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xa0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xb0 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xc0 0xc2 to 0xdf 2 byte 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xd0 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xe0 0xe0 to 0xef 3 byte 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // 0xf0 0xf0 to 0xf4 4 byte, 0xf5 and higher invalid }; void TiXmlBase::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ) { const unsigned long BYTE_MASK = 0xBF; const unsigned long BYTE_MARK = 0x80; const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; if (input < 0x80) *length = 1; else if ( input < 0x800 ) *length = 2; else if ( input < 0x10000 ) *length = 3; else if ( input < 0x200000 ) *length = 4; else { *length = 0; return; } // This code won't covert this correctly anyway. output += *length; // Scary scary fall throughs. switch (*length) { case 4: --output; *output = (char)((input | BYTE_MARK) & BYTE_MASK); input >>= 6; case 3: --output; *output = (char)((input | BYTE_MARK) & BYTE_MASK); input >>= 6; case 2: --output; *output = (char)((input | BYTE_MARK) & BYTE_MASK); input >>= 6; case 1: --output; *output = (char)(input | FIRST_BYTE_MARK[*length]); } } /*static*/ int TiXmlBase::IsAlpha( unsigned char anyByte, TiXmlEncoding /*encoding*/ ) { // This will only work for low-ascii, everything else is assumed to be a valid // letter. I'm not sure this is the best approach, but it is quite tricky trying // to figure out alhabetical vs. not across encoding. So take a very // conservative approach. // if ( encoding == TIXML_ENCODING_UTF8 ) // { if ( anyByte < 127 ) return isalpha( anyByte ); else return 1; // What else to do? The unicode set is huge...get the english ones right. // } // else // { // return isalpha( anyByte ); // } } /*static*/ int TiXmlBase::IsAlphaNum( unsigned char anyByte, TiXmlEncoding /*encoding*/ ) { // This will only work for low-ascii, everything else is assumed to be a valid // letter. I'm not sure this is the best approach, but it is quite tricky trying // to figure out alhabetical vs. not across encoding. So take a very // conservative approach. // if ( encoding == TIXML_ENCODING_UTF8 ) // { if ( anyByte < 127 ) return isalnum( anyByte ); else return 1; // What else to do? The unicode set is huge...get the english ones right. // } // else // { // return isalnum( anyByte ); // } } class TiXmlParsingData { friend class TiXmlDocument; public: void Stamp( const char* now, TiXmlEncoding encoding ); const TiXmlCursor& Cursor() { return cursor; } private: // Only used by the document! TiXmlParsingData( const char* start, int _tabsize, int row, int col ) { assert( start ); stamp = start; tabsize = _tabsize; cursor.row = row; cursor.col = col; } TiXmlCursor cursor; const char* stamp; int tabsize; }; void TiXmlParsingData::Stamp( const char* now, TiXmlEncoding encoding ) { assert( now ); // Do nothing if the tabsize is 0. if ( tabsize < 1 ) { return; } // Get the current row, column. int row = cursor.row; int col = cursor.col; const char* p = stamp; assert( p ); while ( p < now ) { // Treat p as unsigned, so we have a happy compiler. const unsigned char* pU = (const unsigned char*)p; // Code contributed by Fletcher Dunn: (modified by lee) switch (*pU) { case 0: // We *should* never get here, but in case we do, don't // advance past the terminating null character, ever return; case '\r': // bump down to the next line ++row; col = 0; // Eat the character ++p; // Check for \r\n sequence, and treat this as a single character if (*p == '\n') { ++p; } break; case '\n': // bump down to the next line ++row; col = 0; // Eat the character ++p; // Check for \n\r sequence, and treat this as a single // character. (Yes, this bizarre thing does occur still // on some arcane platforms...) if (*p == '\r') { ++p; } break; case '\t': // Eat the character ++p; // Skip to next tab stop col = (col / tabsize + 1) * tabsize; break; case TIXML_UTF_LEAD_0: if ( encoding == TIXML_ENCODING_UTF8 ) { if ( *(p+1) && *(p+2) ) { // In these cases, don't advance the column. These are // 0-width spaces. if ( *(pU+1)==TIXML_UTF_LEAD_1 && *(pU+2)==TIXML_UTF_LEAD_2 ) p += 3; else if ( *(pU+1)==0xbfU && *(pU+2)==0xbeU ) p += 3; else if ( *(pU+1)==0xbfU && *(pU+2)==0xbfU ) p += 3; else { p +=3; ++col; } // A normal character. } } else { ++p; ++col; } break; default: if ( encoding == TIXML_ENCODING_UTF8 ) { // Eat the 1 to 4 byte utf8 character. int step = TiXmlBase::utf8ByteTable[*((unsigned char*)p)]; if ( step == 0 ) step = 1; // Error case from bad encoding, but handle gracefully. p += step; // Just advance one column, of course. ++col; } else { ++p; ++col; } break; } } cursor.row = row; cursor.col = col; assert( cursor.row >= -1 ); assert( cursor.col >= -1 ); stamp = p; assert( stamp ); } const char* TiXmlBase::SkipWhiteSpace( const char* p, TiXmlEncoding encoding ) { // *p == '\0' is legitimate, and will cause the code below to return // p. if ( !p ) { return 0; } if ( encoding == TIXML_ENCODING_UTF8 ) { while ( *p ) { const unsigned char* pU = (const unsigned char*)p; // Skip the stupid Microsoft UTF-8 Byte order marks if ( *(pU+0)==TIXML_UTF_LEAD_0 && *(pU+1)==TIXML_UTF_LEAD_1 && *(pU+2)==TIXML_UTF_LEAD_2 ) { p += 3; continue; } else if(*(pU+0)==TIXML_UTF_LEAD_0 && *(pU+1)==0xbfU && *(pU+2)==0xbeU ) { p += 3; continue; } else if(*(pU+0)==TIXML_UTF_LEAD_0 && *(pU+1)==0xbfU && *(pU+2)==0xbfU ) { p += 3; continue; } if ( IsWhiteSpace( *p ) || *p == '\n' || *p =='\r' ) // Still using old rules for white space. ++p; else break; } } else { while ( *p && IsWhiteSpace( *p ) || *p == '\n' || *p =='\r' ) ++p; } return p; } #ifdef TIXML_USE_STL /*static*/ bool TiXmlBase::StreamWhiteSpace( TIXML_ISTREAM * in, TIXML_STRING * tag ) { for( ;; ) { if ( !in->good() ) return false; int c = in->peek(); // At this scope, we can't get to a document. So fail silently. if ( !IsWhiteSpace( c ) || c <= 0 ) return true; *tag += (char) in->get(); } } /*static*/ bool TiXmlBase::StreamTo( TIXML_ISTREAM * in, int character, TIXML_STRING * tag ) { //assert( character > 0 && character < 128 ); // else it won't work in utf-8 while ( in->good() ) { int c = in->peek(); if ( c == character ) return true; if ( c <= 0 ) // Silent failure: can't get document at this scope return false; in->get(); *tag += (char) c; } return false; } #endif const char* TiXmlBase::ReadName( const char* p, TIXML_STRING * name, TiXmlEncoding encoding ) { *name = ""; assert( p ); // Names start with letters or underscores. // Of course, in unicode, tinyxml has no idea what a letter *is*. The // algorithm is generous. // // After that, they can be letters, underscores, numbers, // hyphens, or colons. (Colons are valid ony for namespaces, // but tinyxml can't tell namespaces from names.) if ( p && *p && ( IsAlpha( (unsigned char) *p, encoding ) || *p == '_' ) ) { while( p && *p && ( IsAlphaNum( (unsigned char ) *p, encoding ) || *p == '_' || *p == '-' || *p == '.' || *p == ':' ) ) { (*name) += *p; ++p; } return p; } return 0; } const char* TiXmlBase::GetEntity( const char* p, char* value, int* length, TiXmlEncoding encoding ) { // Presume an entity, and pull it out. TIXML_STRING ent; int i; *length = 0; if ( *(p+1) && *(p+1) == '#' && *(p+2) ) { unsigned long ucs = 0; ptrdiff_t delta = 0; unsigned mult = 1; if ( *(p+2) == 'x' ) { // Hexadecimal. if ( !*(p+3) ) return 0; const char* q = p+3; q = strchr( q, ';' ); if ( !q || !*q ) return 0; delta = q-p; --q; while ( *q != 'x' ) { if ( *q >= '0' && *q <= '9' ) ucs += mult * (*q - '0'); else if ( *q >= 'a' && *q <= 'f' ) ucs += mult * (*q - 'a' + 10); else if ( *q >= 'A' && *q <= 'F' ) ucs += mult * (*q - 'A' + 10 ); else return 0; mult *= 16; --q; } } else { // Decimal. if ( !*(p+2) ) return 0; const char* q = p+2; q = strchr( q, ';' ); if ( !q || !*q ) return 0; delta = q-p; --q; while ( *q != '#' ) { if ( *q >= '0' && *q <= '9' ) ucs += mult * (*q - '0'); else return 0; mult *= 10; --q; } } if ( encoding == TIXML_ENCODING_UTF8 ) { // convert the UCS to UTF-8 ConvertUTF32ToUTF8( ucs, value, length ); } else { *value = (char)ucs; *length = 1; } return p + delta + 1; } // Now try to match it. for( i=0; iappend( cArr, len ); } } else { bool whitespace = false; // Remove leading white space: p = SkipWhiteSpace( p, encoding ); while ( p && *p && !StringEqual( p, endTag, caseInsensitive, encoding ) ) { if ( *p == '\r' || *p == '\n' ) { whitespace = true; ++p; } else if ( IsWhiteSpace( *p ) ) { whitespace = true; ++p; } else { // If we've found whitespace, add it before the // new character. Any whitespace just becomes a space. if ( whitespace ) { (*text) += ' '; whitespace = false; } int len; char cArr[4] = { 0, 0, 0, 0 }; p = GetChar( p, cArr, &len, encoding ); if ( len == 1 ) (*text) += cArr[0]; // more efficient else text->append( cArr, len ); } } } return p + strlen( endTag ); } #ifdef TIXML_USE_STL void TiXmlDocument::StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ) { // The basic issue with a document is that we don't know what we're // streaming. Read something presumed to be a tag (and hope), then // identify it, and call the appropriate stream method on the tag. // // This "pre-streaming" will never read the closing ">" so the // sub-tag can orient itself. if ( !StreamTo( in, '<', tag ) ) { SetError( TIXML_ERROR_PARSING_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); return; } while ( in->good() ) { int tagIndex = (int) tag->length(); while ( in->good() && in->peek() != '>' ) { int c = in->get(); if ( c <= 0 ) { SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); break; } (*tag) += (char) c; } if ( in->good() ) { // We now have something we presume to be a node of // some sort. Identify it, and call the node to // continue streaming. TiXmlNode* node = Identify( tag->c_str() + tagIndex, TIXML_DEFAULT_ENCODING ); if ( node ) { node->StreamIn( in, tag ); bool isElement = node->ToElement() != 0; delete node; node = 0; // If this is the root element, we're done. Parsing will be // done by the >> operator. if ( isElement ) { return; } } else { SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); return; } } } // We should have returned sooner. SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); } #endif const char* TiXmlDocument::Parse( const char* p, TiXmlParsingData* prevData, TiXmlEncoding encoding ) { ClearError(); // Parse away, at the document level. Since a document // contains nothing but other tags, most of what happens // here is skipping white space. if ( !p || !*p ) { SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); return 0; } // Note that, for a document, this needs to come // before the while space skip, so that parsing // starts from the pointer we are given. location.Clear(); if ( prevData ) { location.row = prevData->cursor.row; location.col = prevData->cursor.col; } else { location.row = 0; location.col = 0; } TiXmlParsingData data( p, TabSize(), location.row, location.col ); location = data.Cursor(); if ( encoding == TIXML_ENCODING_UNKNOWN ) { // Check for the Microsoft UTF-8 lead bytes. const unsigned char* pU = (const unsigned char*)p; if ( *(pU+0) && *(pU+0) == TIXML_UTF_LEAD_0 && *(pU+1) && *(pU+1) == TIXML_UTF_LEAD_1 && *(pU+2) && *(pU+2) == TIXML_UTF_LEAD_2 ) { encoding = TIXML_ENCODING_UTF8; } } p = SkipWhiteSpace( p, encoding ); if ( !p ) { SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); return 0; } while ( p && *p ) { TiXmlNode* node = Identify( p, encoding ); if ( node ) { p = node->Parse( p, &data, encoding ); LinkEndChild( node ); } else { break; } // Did we get encoding info? if ( encoding == TIXML_ENCODING_UNKNOWN && node->ToDeclaration() ) { TiXmlDeclaration* dec = node->ToDeclaration(); const char* enc = dec->Encoding(); assert( enc ); if ( *enc == 0 ) encoding = TIXML_ENCODING_UTF8; else if ( StringEqual( enc, "UTF-8", true, TIXML_ENCODING_UNKNOWN ) ) encoding = TIXML_ENCODING_UTF8; else if ( StringEqual( enc, "UTF8", true, TIXML_ENCODING_UNKNOWN ) ) encoding = TIXML_ENCODING_UTF8; // incorrect, but be nice else encoding = TIXML_ENCODING_LEGACY; } p = SkipWhiteSpace( p, encoding ); } // Was this empty? if ( !firstChild ) { SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, encoding ); return 0; } // All is well. return p; } void TiXmlDocument::SetError( int err, const char* pError, TiXmlParsingData* data, TiXmlEncoding encoding ) { // The first error in a chain is more accurate - don't set again! if ( error ) return; assert( err > 0 && err < TIXML_ERROR_STRING_COUNT ); error = true; errorId = err; errorDesc = errorString[ errorId ]; errorLocation.Clear(); if ( pError && data ) { //TiXmlParsingData data( pError, prevData ); data->Stamp( pError, encoding ); errorLocation = data->Cursor(); } } TiXmlNode* TiXmlNode::Identify( const char* p, TiXmlEncoding encoding ) { TiXmlNode* returnNode = 0; p = SkipWhiteSpace( p, encoding ); if( !p || !*p || *p != '<' ) { return 0; } TiXmlDocument* doc = GetDocument(); p = SkipWhiteSpace( p, encoding ); if ( !p || !*p ) { return 0; } // What is this thing? // - Elements start with a letter or underscore, but xml is reserved. // - Comments: "; if ( !StringEqual( p, startTag, false, encoding ) ) { document->SetError( TIXML_ERROR_PARSING_COMMENT, p, data, encoding ); return 0; } p += strlen( startTag ); p = ReadText( p, &value, false, endTag, false, encoding ); return p; } const char* TiXmlAttribute::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ) { p = SkipWhiteSpace( p, encoding ); if ( !p || !*p ) return 0; int tabsize = 4; if ( document ) tabsize = document->TabSize(); // TiXmlParsingData data( p, prevData ); if ( data ) { data->Stamp( p, encoding ); location = data->Cursor(); } // Read the name, the '=' and the value. const char* pErr = p; p = ReadName( p, &name, encoding ); if ( !p || !*p ) { if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data, encoding ); return 0; } p = SkipWhiteSpace( p, encoding ); if ( !p || !*p || *p != '=' ) { if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); return 0; } ++p; // skip '=' p = SkipWhiteSpace( p, encoding ); if ( !p || !*p ) { if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); return 0; } const char* end; if ( *p == '\'' ) { ++p; end = "\'"; p = ReadText( p, &value, false, end, false, encoding ); } else if ( *p == '"' ) { ++p; end = "\""; p = ReadText( p, &value, false, end, false, encoding ); } else { // All attribute values should be in single or double quotes. // But this is such a common error that the parser will try // its best, even without them. value = ""; while ( p && *p // existence && !IsWhiteSpace( *p ) && *p != '\n' && *p != '\r' // whitespace && *p != '/' && *p != '>' ) // tag end { value += *p; ++p; } } return p; } #ifdef TIXML_USE_STL void TiXmlText::StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ) { while ( in->good() ) { int c = in->peek(); if ( c == '<' ) return; if ( c <= 0 ) { TiXmlDocument* document = GetDocument(); if ( document ) document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); return; } (*tag) += (char) c; in->get(); } } #endif const char* TiXmlText::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ) { value = ""; // TiXmlParsingData data( p, prevData ); if ( data ) { data->Stamp( p, encoding ); location = data->Cursor(); } bool ignoreWhite = true; const char* end = "<"; p = ReadText( p, &value, ignoreWhite, end, false, encoding ); if ( p ) return p-1; // don't truncate the '<' return 0; } #ifdef TIXML_USE_STL void TiXmlDeclaration::StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ) { while ( in->good() ) { int c = in->get(); if ( c <= 0 ) { TiXmlDocument* document = GetDocument(); if ( document ) document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); return; } (*tag) += (char) c; if ( c == '>' ) { // All is well. return; } } } #endif const char* TiXmlDeclaration::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding _encoding ) { p = SkipWhiteSpace( p, _encoding ); // Find the beginning, find the end, and look for // the stuff in-between. TiXmlDocument* document = GetDocument(); if ( !p || !*p || !StringEqual( p, "SetError( TIXML_ERROR_PARSING_DECLARATION, 0, 0, _encoding ); return 0; } // TiXmlParsingData data( p, prevData ); if ( data ) { data->Stamp( p, _encoding ); location = data->Cursor(); } p += 5; version = ""; encoding = ""; standalone = ""; while ( p && *p ) { if ( *p == '>' ) { ++p; return p; } p = SkipWhiteSpace( p, _encoding ); if ( StringEqual( p, "version", true, _encoding ) ) { TiXmlAttribute attrib; p = attrib.Parse( p, data, _encoding ); version = attrib.Value(); } else if ( StringEqual( p, "encoding", true, _encoding ) ) { TiXmlAttribute attrib; p = attrib.Parse( p, data, _encoding ); encoding = attrib.Value(); } else if ( StringEqual( p, "standalone", true, _encoding ) ) { TiXmlAttribute attrib; p = attrib.Parse( p, data, _encoding ); standalone = attrib.Value(); } else { // Read over whatever it is. while( p && *p && *p != '>' && !IsWhiteSpace( *p ) ) ++p; } } return 0; } bool TiXmlText::Blank() const { for ( unsigned i=0; iFirstChild(); child; child = child->NextSibling()) { // Examine the text nodes. if (child->Type() == TiXmlNode::TEXT) { // Append the content to the string. string.append(child->Value()); } } } void textContentDeep(UtlString& string, TiXmlElement *element) { // Clear the string. string.remove(0); // Recurse into the XML. textContentDeepRecursive(string, element); } void textContentDeepRecursive(UtlString& string, TiXmlElement *element) { // Iterate through all the children. for (TiXmlNode* child = element->FirstChild(); child; child = child->NextSibling()) { // Examine the text nodes. if (child->Type() == TiXmlNode::TEXT) { // Append the content to the string. string.append(child->Value()); } else if (child->Type() == TiXmlNode::ELEMENT) { // Recurse on this element. textContentDeepRecursive(string, child->ToElement()); } } } sipxtapi-3.3.0~test17/sipXportLib/src/Makefile.am0000644000175000017500000001323312205613305022477 0ustar00danieldaniel00000000000000## Process this file with automake to produce Makefile.in include $(top_srcdir)/config/sipXcommon.am.inc SUBDIRS = . test lib_LTLIBRARIES = libsipXport.la INCLUDES = -I$(top_srcdir)/sipXportLib/include -I$(top_srcdir)/sipXcallLib/include ## Libtool version info - update only immediately before a release # Current - increment if any interfaces are added, removed, or changed version_Current=2 # Revision - set to 0 if Current was incremented # increment if any implementation has changed version_Revision=0 # Age - set to 0 of any interfaces have been removed # increment if any interfaces have been added version_Age=0 libsipXport_la_LDFLAGS = \ -version-info ${version_Current}:${version_Revision}:${version_Age} libsipXport_la_LIBADD = \ -lssl -lcrypto \ -lpcre \ -ldl \ -lpthread \ -lstdc++ # this is helpful if you're debugging something with lots of inlines (like the UtlLink code) # -fno-gcse -O0 -fno-implement-inlines -fno-default-inline libsipXport_la_CXXFLAGS = \ -DSIPX_TMPDIR=\"@SIPX_TMPDIR@\" \ -DSIPX_CONFDIR=\"@SIPX_CONFDIR@\" nodist_libsipXport_la_SOURCES = \ $(top_srcdir)/config/@PACKAGE@-buildstamp.h \ $(top_srcdir)/config/@PACKAGE@-buildstamp.cpp libsipXport_la_SOURCES = \ utl/UtlLongLongInt.cpp \ utl/UtlNameValueTokenizer.cpp \ utl/UtlBool.cpp \ utl/UtlCopyableContainable.cpp \ utl/UtlCrc32.cpp \ utl/UtlCryptoData.cpp \ utl/UtlCryptoKey.cpp \ utl/UtlCryptoKeyRsa.cpp \ utl/UtlCryptoKeySym.cpp \ utl/UtlDateTime.cpp \ utl/UtlLink.cpp \ utl/UtlVoidPtr.cpp \ utl/UtlHistogram.cpp \ utl/UtlInit.cpp \ utl/UtlInt.cpp \ utl/UtlIntPtr.cpp \ utl/UtlString.cpp \ utl/UtlChainPool.cpp \ utl/UtlContainable.cpp \ utl/UtlContainer.cpp \ utl/UtlContainableAtomic.cpp \ utl/UtlContainablePair.cpp \ utl/UtlIterator.cpp \ utl/UtlList.cpp \ utl/UtlListIterator.cpp \ utl/UtlSList.cpp \ utl/UtlCopyableSList.cpp \ utl/UtlSListIterator.cpp \ utl/UtlDList.cpp \ utl/UtlDListIterator.cpp \ utl/UtlCopyableSortedList.cpp \ utl/UtlSortedList.cpp \ utl/UtlSortedListIterator.cpp \ utl/UtlHashMap.cpp \ utl/UtlHashMapIterator.cpp \ utl/UtlHashBag.cpp \ utl/UtlHashBagIterator.cpp \ utl/UtlRscStore.cpp \ utl/UtlRegex.cpp \ utl/UtlTokenizer.cpp \ utl/XmlContent.cpp \ utl/UtlRandom.cpp \ utl/PluginHooks.cpp \ os/NatMsg.cpp \ os/OsAssert.c \ os/OsCallback.cpp \ os/OsConfigDb.cpp \ os/OsContact.cpp \ os/OsContactList.cpp \ os/OsConnectionSocket.cpp \ os/OsCSemBase.cpp \ os/OsDatagramSocket.cpp \ os/OsDateTime.cpp \ os/OsDirBase.cpp \ os/OsEncryption.cpp \ os/OsEvent.cpp \ os/OsEventMsg.cpp \ os/OsExcept.cpp \ os/OsFileBase.cpp \ os/OsFileInfoBase.cpp \ os/OsFileIteratorBase.cpp \ os/OsFileSystem.cpp \ os/OsLockingList.cpp \ os/OsIntPtrMsg.cpp \ os/OsMsg.cpp \ os/OsMsgPool.cpp \ os/OsMsgQ.cpp \ os/OsMsgDispatcher.cpp \ os/OsMulticastSocket.cpp \ os/OsNameDb.cpp \ os/OsNameDbInit.cpp \ os/OsNatAgentTask.cpp \ os/OsNatDatagramSocket.cpp \ os/OsNatConnectionSocket.cpp \ os/OsNatSocketBaseImpl.cpp \ os/OsPathBase.cpp \ os/osPrintf.cpp \ os/OsProcessBase.cpp \ os/OsProcessIteratorBase.cpp \ os/OsProcessMgr.cpp \ os/OsProtectEvent.cpp \ os/OsProtectEventMgr.cpp \ os/OsProtectEventMgrInit.cpp \ os/OsPtrMsg.cpp \ os/OsQueuedEvent.cpp \ os/OsRpcMsg.cpp \ os/OsServerSocket.cpp \ os/OsServerTask.cpp \ os/OsSharedLibMgr.cpp \ os/OsSocket.cpp \ os/OsSocketCrypto.cpp \ os/OsSSL.cpp \ os/OsSSLConnectionSocket.cpp \ os/OsSSLServerSocket.cpp \ os/OsSysLog.cpp \ os/OsSysLogFacilities.cpp \ os/OsSysLogMsg.cpp \ os/OsSysLogTask.cpp \ os/OsTask.cpp \ os/OsTime.cpp \ os/OsTimeLog.cpp \ os/OsTimer.cpp \ os/OsTimerMsg.cpp \ os/OsTimerTask.cpp \ os/OsTLSServerSocket.cpp \ os/OsTLSConnectionSocket.cpp \ os/OsTLSClientConnectionSocket.cpp \ os/OsTokenizer.cpp \ os/OsUtil.cpp \ os/StunMessage.cpp \ os/StunUtils.cpp \ os/TurnMessage.cpp \ os/shared/OsMsgQShared.cpp \ os/shared/OsTimerMessage.cpp \ os/linux/clock_gettime.c \ os/linux/host_address.c \ os/linux/AdapterInfo.cpp \ os/linux/OsBSemLinux.cpp \ os/linux/OsCSemLinux.cpp \ os/linux/OsDateTimeLinux.cpp \ os/linux/OsDirLinux.cpp \ os/linux/OsFileInfoLinux.cpp \ os/linux/OsFileIteratorLinux.cpp \ os/linux/OsFileLinux.cpp \ os/linux/OsMutexLinux.cpp \ os/linux/OsPathLinux.cpp \ os/linux/OsProcessIteratorLinux.cpp \ os/linux/OsProcessLinux.cpp \ os/linux/OsRWMutexLinux.cpp \ os/linux/OsSharedLibMgrLinux.cpp \ os/linux/OsTaskLinux.cpp \ os/linux/OsUtilLinux.cpp \ os/linux/pt_csem.c \ os/linux/pt_mutex.c \ xmlparser/tinystr.cpp \ xmlparser/tinyxml.cpp \ xmlparser/tinyxmlerror.cpp \ xmlparser/tinyxmlparser.cpp \ xmlparser/TiXmlIterator.cpp \ xmlparser/ExtractContent.cpp \ hmac-sha1/hmac-sha1.c \ hmac-sha1/sha1.c \ hmac-sha1/sha1.h EXTRA_DIST= \ os/Wnt/getWindowsDNSServers.cpp \ os/Wnt/OsBSemWnt.cpp \ os/Wnt/OsCSemWnt.cpp \ os/Wnt/OsDateTimeWnt.cpp \ os/Wnt/OsDirWnt.cpp \ os/Wnt/OsFileInfoWnt.cpp \ os/Wnt/OsFileIteratorWnt.cpp \ os/Wnt/OsFileSystemWnt.cpp \ os/Wnt/OsFileWnt.cpp \ os/Wnt/OsMutexWnt.cpp \ os/Wnt/OsPathWnt.cpp \ os/Wnt/OsProcessIteratorWnt.cpp \ os/Wnt/OsProcessWnt.cpp \ os/Wnt/OsSharedLibMgrWnt.cpp \ os/Wnt/OsTaskWnt.cpp \ os/Wnt/OsTimerMessage.cpp \ os/Wnt/OsUtilWnt.cpp \ os/Wnt/WindowsAdapterInfo.cpp sipxtapi-3.3.0~test17/sipXportLib/src/Makefile.in0000644000175000017500000064355612321445001022524 0ustar00danieldaniel00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # -*-makefile-*- VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ $(top_srcdir)/config/sipXcommon.am.inc subdir = sipXportLib/src ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/general.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/sipXlib.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" LTLIBRARIES = $(lib_LTLIBRARIES) libsipXport_la_DEPENDENCIES = am_libsipXport_la_OBJECTS = libsipXport_la-UtlLongLongInt.lo \ libsipXport_la-UtlNameValueTokenizer.lo \ libsipXport_la-UtlBool.lo \ libsipXport_la-UtlCopyableContainable.lo \ libsipXport_la-UtlCrc32.lo libsipXport_la-UtlCryptoData.lo \ libsipXport_la-UtlCryptoKey.lo \ libsipXport_la-UtlCryptoKeyRsa.lo \ libsipXport_la-UtlCryptoKeySym.lo \ libsipXport_la-UtlDateTime.lo libsipXport_la-UtlLink.lo \ libsipXport_la-UtlVoidPtr.lo libsipXport_la-UtlHistogram.lo \ libsipXport_la-UtlInit.lo libsipXport_la-UtlInt.lo \ libsipXport_la-UtlIntPtr.lo libsipXport_la-UtlString.lo \ libsipXport_la-UtlChainPool.lo \ libsipXport_la-UtlContainable.lo \ libsipXport_la-UtlContainer.lo \ libsipXport_la-UtlContainableAtomic.lo \ libsipXport_la-UtlContainablePair.lo \ libsipXport_la-UtlIterator.lo libsipXport_la-UtlList.lo \ libsipXport_la-UtlListIterator.lo libsipXport_la-UtlSList.lo \ libsipXport_la-UtlCopyableSList.lo \ libsipXport_la-UtlSListIterator.lo libsipXport_la-UtlDList.lo \ libsipXport_la-UtlDListIterator.lo \ libsipXport_la-UtlCopyableSortedList.lo \ libsipXport_la-UtlSortedList.lo \ libsipXport_la-UtlSortedListIterator.lo \ libsipXport_la-UtlHashMap.lo \ libsipXport_la-UtlHashMapIterator.lo \ libsipXport_la-UtlHashBag.lo \ libsipXport_la-UtlHashBagIterator.lo \ libsipXport_la-UtlRscStore.lo libsipXport_la-UtlRegex.lo \ libsipXport_la-UtlTokenizer.lo libsipXport_la-XmlContent.lo \ libsipXport_la-UtlRandom.lo libsipXport_la-PluginHooks.lo \ libsipXport_la-NatMsg.lo OsAssert.lo \ libsipXport_la-OsCallback.lo libsipXport_la-OsConfigDb.lo \ libsipXport_la-OsContact.lo libsipXport_la-OsContactList.lo \ libsipXport_la-OsConnectionSocket.lo \ libsipXport_la-OsCSemBase.lo \ libsipXport_la-OsDatagramSocket.lo \ libsipXport_la-OsDateTime.lo libsipXport_la-OsDirBase.lo \ libsipXport_la-OsEncryption.lo libsipXport_la-OsEvent.lo \ libsipXport_la-OsEventMsg.lo libsipXport_la-OsExcept.lo \ libsipXport_la-OsFileBase.lo libsipXport_la-OsFileInfoBase.lo \ libsipXport_la-OsFileIteratorBase.lo \ libsipXport_la-OsFileSystem.lo libsipXport_la-OsLockingList.lo \ libsipXport_la-OsIntPtrMsg.lo libsipXport_la-OsMsg.lo \ libsipXport_la-OsMsgPool.lo libsipXport_la-OsMsgQ.lo \ libsipXport_la-OsMsgDispatcher.lo \ libsipXport_la-OsMulticastSocket.lo libsipXport_la-OsNameDb.lo \ libsipXport_la-OsNameDbInit.lo \ libsipXport_la-OsNatAgentTask.lo \ libsipXport_la-OsNatDatagramSocket.lo \ libsipXport_la-OsNatConnectionSocket.lo \ libsipXport_la-OsNatSocketBaseImpl.lo \ libsipXport_la-OsPathBase.lo libsipXport_la-osPrintf.lo \ libsipXport_la-OsProcessBase.lo \ libsipXport_la-OsProcessIteratorBase.lo \ libsipXport_la-OsProcessMgr.lo \ libsipXport_la-OsProtectEvent.lo \ libsipXport_la-OsProtectEventMgr.lo \ libsipXport_la-OsProtectEventMgrInit.lo \ libsipXport_la-OsPtrMsg.lo libsipXport_la-OsQueuedEvent.lo \ libsipXport_la-OsRpcMsg.lo libsipXport_la-OsServerSocket.lo \ libsipXport_la-OsServerTask.lo \ libsipXport_la-OsSharedLibMgr.lo libsipXport_la-OsSocket.lo \ libsipXport_la-OsSocketCrypto.lo libsipXport_la-OsSSL.lo \ libsipXport_la-OsSSLConnectionSocket.lo \ libsipXport_la-OsSSLServerSocket.lo libsipXport_la-OsSysLog.lo \ libsipXport_la-OsSysLogFacilities.lo \ libsipXport_la-OsSysLogMsg.lo libsipXport_la-OsSysLogTask.lo \ libsipXport_la-OsTask.lo libsipXport_la-OsTime.lo \ libsipXport_la-OsTimeLog.lo libsipXport_la-OsTimer.lo \ libsipXport_la-OsTimerMsg.lo libsipXport_la-OsTimerTask.lo \ libsipXport_la-OsTLSServerSocket.lo \ libsipXport_la-OsTLSConnectionSocket.lo \ libsipXport_la-OsTLSClientConnectionSocket.lo \ libsipXport_la-OsTokenizer.lo libsipXport_la-OsUtil.lo \ libsipXport_la-StunMessage.lo libsipXport_la-StunUtils.lo \ libsipXport_la-TurnMessage.lo libsipXport_la-OsMsgQShared.lo \ libsipXport_la-OsTimerMessage.lo clock_gettime.lo \ host_address.lo libsipXport_la-AdapterInfo.lo \ libsipXport_la-OsBSemLinux.lo libsipXport_la-OsCSemLinux.lo \ libsipXport_la-OsDateTimeLinux.lo libsipXport_la-OsDirLinux.lo \ libsipXport_la-OsFileInfoLinux.lo \ libsipXport_la-OsFileIteratorLinux.lo \ libsipXport_la-OsFileLinux.lo libsipXport_la-OsMutexLinux.lo \ libsipXport_la-OsPathLinux.lo \ libsipXport_la-OsProcessIteratorLinux.lo \ libsipXport_la-OsProcessLinux.lo \ libsipXport_la-OsRWMutexLinux.lo \ libsipXport_la-OsSharedLibMgrLinux.lo \ libsipXport_la-OsTaskLinux.lo libsipXport_la-OsUtilLinux.lo \ pt_csem.lo pt_mutex.lo libsipXport_la-tinystr.lo \ libsipXport_la-tinyxml.lo libsipXport_la-tinyxmlerror.lo \ libsipXport_la-tinyxmlparser.lo \ libsipXport_la-TiXmlIterator.lo \ libsipXport_la-ExtractContent.lo hmac-sha1.lo sha1.lo nodist_libsipXport_la_OBJECTS = \ libsipXport_la-@PACKAGE@-buildstamp.lo libsipXport_la_OBJECTS = $(am_libsipXport_la_OBJECTS) \ $(nodist_libsipXport_la_OBJECTS) libsipXport_la_LINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) \ $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) \ $(libsipXport_la_LDFLAGS) $(LDFLAGS) -o $@ DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) CCLD = $(CC) LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) CXXLD = $(CXX) CXXLINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ SOURCES = $(libsipXport_la_SOURCES) $(nodist_libsipXport_la_SOURCES) DIST_SOURCES = $(libsipXport_la_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ html-recursive info-recursive install-data-recursive \ install-dvi-recursive install-exec-recursive \ install-html-recursive install-info-recursive \ install-pdf-recursive install-ps-recursive install-recursive \ installcheck-recursive installdirs-recursive pdf-recursive \ ps-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ distdir ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMRNB_INCLUDE = @AMRNB_INCLUDE@ AMRNB_LIB_ROOT = @AMRNB_LIB_ROOT@ AMRWB_INCLUDE = @AMRWB_INCLUDE@ AMRWB_LIB_ROOT = @AMRWB_LIB_ROOT@ AMRWB_TARGET = @AMRWB_TARGET@ AMR_TARGET = @AMR_TARGET@ AMTAR = @AMTAR@ ANT = @ANT@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CARBON_LIBS = @CARBON_LIBS@ CA_LIBS = @CA_LIBS@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPUNIT_CFLAGS = @CPPUNIT_CFLAGS@ CPPUNIT_CONFIG = @CPPUNIT_CONFIG@ CPPUNIT_LIBS = @CPPUNIT_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPS_PCRE_CFLAGS = @DEPS_PCRE_CFLAGS@ DEPS_PCRE_LIBS = @DEPS_PCRE_LIBS@ DLLTOOL = @DLLTOOL@ DOT = @DOT@ DOXYGEN = @DOXYGEN@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DYNEXT = @DYNEXT@ EAGC_LDFLAGS = @EAGC_LDFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EJBE_LDFLAGS = @EJBE_LDFLAGS@ EPLC_LDFLAGS = @EPLC_LDFLAGS@ EVAD_LDFLAGS = @EVAD_LDFLAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ G722_TARGET = @G722_TARGET@ G726_TARGET = @G726_TARGET@ GIPSINC = @GIPSINC@ GIPS_CE_OBJS = @GIPS_CE_OBJS@ GIPS_CPPFLAGS = @GIPS_CPPFLAGS@ GIPS_NEQ_OBJS = @GIPS_NEQ_OBJS@ GIPS_VE_OBJS = @GIPS_VE_OBJS@ GREP = @GREP@ GSM_CFLAGS = @GSM_CFLAGS@ GSM_CXXFLAGS = @GSM_CXXFLAGS@ GSM_LDFLAGS = @GSM_LDFLAGS@ GSM_LIBS = @GSM_LIBS@ GSM_TARGET = @GSM_TARGET@ ILBC_INCLUDE = @ILBC_INCLUDE@ ILBC_LIB_ROOT = @ILBC_LIB_ROOT@ ILBC_LIB_TARGET = @ILBC_LIB_TARGET@ ILBC_TARGET = @ILBC_TARGET@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTERFACE_FLAGS = @INTERFACE_FLAGS@ JAVA = @JAVA@ JAVAC_DEBUG = @JAVAC_DEBUG@ JAVAC_OPTIMIZED = @JAVAC_OPTIMIZED@ JAVA_HOME = @JAVA_HOME@ L16_TARGET = @L16_TARGET@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NAMED_PROGRAM = @NAMED_PROGRAM@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPUS_CFLAGS = @OPUS_CFLAGS@ OPUS_LIBS = @OPUS_LIBS@ OPUS_TARGET = @OPUS_TARGET@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PCMAPCMU_TARGET = @PCMAPCMU_TARGET@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ RTL_CXXFLAGS = @RTL_CXXFLAGS@ RTL_LDFLAGS = @RTL_LDFLAGS@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SIPXMEDIA_CE_LIBS = @SIPXMEDIA_CE_LIBS@ SIPXMEDIA_VE_LIBS = @SIPXMEDIA_VE_LIBS@ SIPXMEDIA_VE_STATIC_LIBS = @SIPXMEDIA_VE_STATIC_LIBS@ SIPXPBXUSER = @SIPXPBXUSER@ SIPXPHONECONF = @SIPXPHONECONF@ SIPXPHONEDATA = @SIPXPHONEDATA@ SIPXPHONELIB = @SIPXPHONELIB@ SIPX_BACKUPDIR = @SIPX_BACKUPDIR@ SIPX_BINDIR = @SIPX_BINDIR@ SIPX_CONFDIR = @SIPX_CONFDIR@ SIPX_CONFIGPHONEDIR = @SIPX_CONFIGPHONEDIR@ SIPX_DATADIR = @SIPX_DATADIR@ SIPX_DBDIR = @SIPX_DBDIR@ SIPX_DOCDIR = @SIPX_DOCDIR@ SIPX_INCDIR = @SIPX_INCDIR@ SIPX_LIBDIR = @SIPX_LIBDIR@ SIPX_LOGDIR = @SIPX_LOGDIR@ SIPX_PARKMUSICDIR = @SIPX_PARKMUSICDIR@ SIPX_RUNDIR = @SIPX_RUNDIR@ SIPX_SCHEMADIR = @SIPX_SCHEMADIR@ SIPX_TMPDIR = @SIPX_TMPDIR@ SIPX_UNIT_TARGET = @SIPX_UNIT_TARGET@ SIPX_VXMLDATADIR = @SIPX_VXMLDATADIR@ SPANDSP_CFLAGS = @SPANDSP_CFLAGS@ SPANDSP_CXXFLAGS = @SPANDSP_CXXFLAGS@ SPANDSP_LDFLAGS = @SPANDSP_LDFLAGS@ SPANDSP_LIBS = @SPANDSP_LIBS@ SPEEXDSP_CFLAGS = @SPEEXDSP_CFLAGS@ SPEEXDSP_LIBS = @SPEEXDSP_LIBS@ SPEEXDSP_STATIC_LIB = @SPEEXDSP_STATIC_LIB@ SPEEX_CFLAGS = @SPEEX_CFLAGS@ SPEEX_LIBS = @SPEEX_LIBS@ SPEEX_ROOT = @SPEEX_ROOT@ SPEEX_STATIC_LIB = @SPEEX_STATIC_LIB@ SPEEX_TARGET = @SPEEX_TARGET@ SS_LDFLAGS = @SS_LDFLAGS@ STATIC_CODEC_LIBS = @STATIC_CODEC_LIBS@ STRIP = @STRIP@ TONES_TARGET = @TONES_TARGET@ VERSION = @VERSION@ VIDEO_DEFINE = @VIDEO_DEFINE@ WXWIDGETS_CFLAGS = @WXWIDGETS_CFLAGS@ WXWIDGETS_CONFIG = @WXWIDGETS_CONFIG@ WXWIDGETS_CXXFLAGS = @WXWIDGETS_CXXFLAGS@ WXWIDGETS_LIBS = @WXWIDGETS_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ codeclibdir = @codeclibdir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ enable_dot = @enable_dot@ enable_html_docs = @enable_html_docs@ enable_latex_docs = @enable_latex_docs@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ jar = @jar@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ sipx_abs_srcdir = @sipx_abs_srcdir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ wwwdir = @wwwdir@ ConfigureArgs = $(shell sed \ -e '/^ *\$$ .*\/configure/!d' \ -e 's/^ *\$$ .*\/configure *//' \ $(top_builddir)/config.log \ ) LocalizeSipXconfig = sed \ -e 's,@PACKAGE\@,@PACKAGE@,g' \ -e 's,@VERSION\@,@VERSION@,g' \ -e 's,@abs_builddir\@,@abs_builddir@,g' \ -e 's,@abs_srcdir\@,@abs_srcdir@,g' \ -e 's,@abs_top_srcdir\@,@abs_top_srcdir@,g' \ -e 's,@sipx_abs_srcdir\@,@sipx_abs_srcdir@,g' \ -e 's!@CONFIGURE_OPTIONS@!$(ConfigureArgs)!g' \ -e 's,@bindir\@,$(bindir),g' \ -e 's,@datadir\@,$(datadir),g' \ -e 's,@htmldir\@,@htmldir@,g' \ -e 's,@INSTALL\@,@INSTALL@,g' \ -e 's,@install_sh\@,@install_sh@,g' \ -e 's,@libdir\@,$(libdir),g' \ -e 's,@localstatedir\@,$(localstatedir),g' \ -e 's,@pkgdatadir\@,@pkgdatadir@,g' \ -e 's,@prefix\@,$(prefix),g' \ -e 's,@profiledir\@,@profiledir@,g' \ -e 's,@wwwdir\@,@wwwdir@,g' \ -e 's,@host\@,@host@,g' \ -e 's,@PERL\@,@PERL@,g' \ -e 's,@APACHE2_HTTPD\@,@APACHE2_HTTPD@,g' \ -e 's,@APACHE2_MOD\@,@APACHE2_MOD@,g' \ -e 's,@CLOVER_HOME\@,@CLOVER_HOME@,g' \ -e 's,@JAVAC_DEBUG\@,@JAVAC_DEBUG@,g' \ -e 's,@JAVAC_OPTIMIZED\@,@JAVAC_OPTIMIZED@,g' \ -e 's,@JAVA\@,@JAVA@,g' \ -e 's,@JAVA_HOME\@,@JAVA_HOME@,g' \ -e 's,@JBOSS_HOME\@,@JBOSS_HOME@,g' \ -e 's,@JBOSS_SERVER_CONF\@,@JBOSS_SERVER_CONF@,g' \ -e 's,@SIPFOUNDRY_ORG\@,@SIPFOUNDRY_ORG@,g' \ -e 's,@SIPXCONFIG_LIBDIR\@,@SIPXCONFIG_LIBDIR@,g' \ -e 's,@SIPXPBXUSER\@,@SIPXPBXUSER@,g' \ -e 's,@SIPX_BINDIR\@,@SIPX_BINDIR@,g' \ -e 's,@SIPX_CONFDIR\@,@SIPX_CONFDIR@,g' \ -e 's,@SIPX_CONFIGPHONEDIR\@,@SIPX_CONFIGPHONEDIR@,g' \ -e 's,@SIPX_BACKUPDIR\@,@SIPX_BACKUPDIR@,g' \ -e 's,@SIPX_DATADIR\@,@SIPX_DATADIR@,g' \ -e 's,@SIPX_DBDIR\@,@SIPX_DBDIR@,g' \ -e 's,@SIPX_DOCDIR\@,@SIPX_DOCDIR@,g' \ -e 's,@SIPX_LOGDIR\@,@SIPX_LOGDIR@,g' \ -e 's,@SIPX_RUNDIR\@,@SIPX_RUNDIR@,g' \ -e 's,@SIPX_TMPDIR\@,@SIPX_TMPDIR@,g' \ -e 's,@SIPX_INCDIR\@,@SIPX_INCDIR@,g' \ -e 's,@SIPX_LIBDIR\@,@SIPX_LIBDIR@,g' \ -e 's,@SIPX_SCHEMADIR\@,@SIPX_SCHEMADIR@,g' \ -e 's,@SIPX_VXMLDATADIR\@,@SIPX_VXMLDATADIR@,g' \ -e 's,@SIPX_PARKMUSICDIR\@,@SIPX_PARKMUSICDIR@,g' \ -e 's,@SPRING_HOME\@,@SPRING_HOME@,g' \ -e 's,@XPRESSA_BUILD_NUMBER\@,@XPRESSA_BUILD_NUMBER@,g' \ -e 's,@XPRESSA_BUILD_COMMENT\@,@XPRESSA_BUILD_COMMENT@,g' \ -e 's,@SIPXPHONELIB\@,@SIPXPHONELIB@,g' \ -e 's,@SIPXPHONEDATA\@,@SIPXPHONEDATA@,g' \ -e 's,@SIPXPHONECONF\@,@SIPXPHONECONF@,g' \ -e 's,@NAMED_PROGRAM\@,@NAMED_PROGRAM@,g' SUBDIRS = . test lib_LTLIBRARIES = libsipXport.la INCLUDES = -I$(top_srcdir)/sipXportLib/include -I$(top_srcdir)/sipXcallLib/include # Current - increment if any interfaces are added, removed, or changed version_Current = 2 # Revision - set to 0 if Current was incremented # increment if any implementation has changed version_Revision = 0 # Age - set to 0 of any interfaces have been removed # increment if any interfaces have been added version_Age = 0 libsipXport_la_LDFLAGS = \ -version-info ${version_Current}:${version_Revision}:${version_Age} libsipXport_la_LIBADD = \ -lssl -lcrypto \ -lpcre \ -ldl \ -lpthread \ -lstdc++ # this is helpful if you're debugging something with lots of inlines (like the UtlLink code) # -fno-gcse -O0 -fno-implement-inlines -fno-default-inline libsipXport_la_CXXFLAGS = \ -DSIPX_TMPDIR=\"@SIPX_TMPDIR@\" \ -DSIPX_CONFDIR=\"@SIPX_CONFDIR@\" nodist_libsipXport_la_SOURCES = \ $(top_srcdir)/config/@PACKAGE@-buildstamp.h \ $(top_srcdir)/config/@PACKAGE@-buildstamp.cpp libsipXport_la_SOURCES = \ utl/UtlLongLongInt.cpp \ utl/UtlNameValueTokenizer.cpp \ utl/UtlBool.cpp \ utl/UtlCopyableContainable.cpp \ utl/UtlCrc32.cpp \ utl/UtlCryptoData.cpp \ utl/UtlCryptoKey.cpp \ utl/UtlCryptoKeyRsa.cpp \ utl/UtlCryptoKeySym.cpp \ utl/UtlDateTime.cpp \ utl/UtlLink.cpp \ utl/UtlVoidPtr.cpp \ utl/UtlHistogram.cpp \ utl/UtlInit.cpp \ utl/UtlInt.cpp \ utl/UtlIntPtr.cpp \ utl/UtlString.cpp \ utl/UtlChainPool.cpp \ utl/UtlContainable.cpp \ utl/UtlContainer.cpp \ utl/UtlContainableAtomic.cpp \ utl/UtlContainablePair.cpp \ utl/UtlIterator.cpp \ utl/UtlList.cpp \ utl/UtlListIterator.cpp \ utl/UtlSList.cpp \ utl/UtlCopyableSList.cpp \ utl/UtlSListIterator.cpp \ utl/UtlDList.cpp \ utl/UtlDListIterator.cpp \ utl/UtlCopyableSortedList.cpp \ utl/UtlSortedList.cpp \ utl/UtlSortedListIterator.cpp \ utl/UtlHashMap.cpp \ utl/UtlHashMapIterator.cpp \ utl/UtlHashBag.cpp \ utl/UtlHashBagIterator.cpp \ utl/UtlRscStore.cpp \ utl/UtlRegex.cpp \ utl/UtlTokenizer.cpp \ utl/XmlContent.cpp \ utl/UtlRandom.cpp \ utl/PluginHooks.cpp \ os/NatMsg.cpp \ os/OsAssert.c \ os/OsCallback.cpp \ os/OsConfigDb.cpp \ os/OsContact.cpp \ os/OsContactList.cpp \ os/OsConnectionSocket.cpp \ os/OsCSemBase.cpp \ os/OsDatagramSocket.cpp \ os/OsDateTime.cpp \ os/OsDirBase.cpp \ os/OsEncryption.cpp \ os/OsEvent.cpp \ os/OsEventMsg.cpp \ os/OsExcept.cpp \ os/OsFileBase.cpp \ os/OsFileInfoBase.cpp \ os/OsFileIteratorBase.cpp \ os/OsFileSystem.cpp \ os/OsLockingList.cpp \ os/OsIntPtrMsg.cpp \ os/OsMsg.cpp \ os/OsMsgPool.cpp \ os/OsMsgQ.cpp \ os/OsMsgDispatcher.cpp \ os/OsMulticastSocket.cpp \ os/OsNameDb.cpp \ os/OsNameDbInit.cpp \ os/OsNatAgentTask.cpp \ os/OsNatDatagramSocket.cpp \ os/OsNatConnectionSocket.cpp \ os/OsNatSocketBaseImpl.cpp \ os/OsPathBase.cpp \ os/osPrintf.cpp \ os/OsProcessBase.cpp \ os/OsProcessIteratorBase.cpp \ os/OsProcessMgr.cpp \ os/OsProtectEvent.cpp \ os/OsProtectEventMgr.cpp \ os/OsProtectEventMgrInit.cpp \ os/OsPtrMsg.cpp \ os/OsQueuedEvent.cpp \ os/OsRpcMsg.cpp \ os/OsServerSocket.cpp \ os/OsServerTask.cpp \ os/OsSharedLibMgr.cpp \ os/OsSocket.cpp \ os/OsSocketCrypto.cpp \ os/OsSSL.cpp \ os/OsSSLConnectionSocket.cpp \ os/OsSSLServerSocket.cpp \ os/OsSysLog.cpp \ os/OsSysLogFacilities.cpp \ os/OsSysLogMsg.cpp \ os/OsSysLogTask.cpp \ os/OsTask.cpp \ os/OsTime.cpp \ os/OsTimeLog.cpp \ os/OsTimer.cpp \ os/OsTimerMsg.cpp \ os/OsTimerTask.cpp \ os/OsTLSServerSocket.cpp \ os/OsTLSConnectionSocket.cpp \ os/OsTLSClientConnectionSocket.cpp \ os/OsTokenizer.cpp \ os/OsUtil.cpp \ os/StunMessage.cpp \ os/StunUtils.cpp \ os/TurnMessage.cpp \ os/shared/OsMsgQShared.cpp \ os/shared/OsTimerMessage.cpp \ os/linux/clock_gettime.c \ os/linux/host_address.c \ os/linux/AdapterInfo.cpp \ os/linux/OsBSemLinux.cpp \ os/linux/OsCSemLinux.cpp \ os/linux/OsDateTimeLinux.cpp \ os/linux/OsDirLinux.cpp \ os/linux/OsFileInfoLinux.cpp \ os/linux/OsFileIteratorLinux.cpp \ os/linux/OsFileLinux.cpp \ os/linux/OsMutexLinux.cpp \ os/linux/OsPathLinux.cpp \ os/linux/OsProcessIteratorLinux.cpp \ os/linux/OsProcessLinux.cpp \ os/linux/OsRWMutexLinux.cpp \ os/linux/OsSharedLibMgrLinux.cpp \ os/linux/OsTaskLinux.cpp \ os/linux/OsUtilLinux.cpp \ os/linux/pt_csem.c \ os/linux/pt_mutex.c \ xmlparser/tinystr.cpp \ xmlparser/tinyxml.cpp \ xmlparser/tinyxmlerror.cpp \ xmlparser/tinyxmlparser.cpp \ xmlparser/TiXmlIterator.cpp \ xmlparser/ExtractContent.cpp \ hmac-sha1/hmac-sha1.c \ hmac-sha1/sha1.c \ hmac-sha1/sha1.h EXTRA_DIST = \ os/Wnt/getWindowsDNSServers.cpp \ os/Wnt/OsBSemWnt.cpp \ os/Wnt/OsCSemWnt.cpp \ os/Wnt/OsDateTimeWnt.cpp \ os/Wnt/OsDirWnt.cpp \ os/Wnt/OsFileInfoWnt.cpp \ os/Wnt/OsFileIteratorWnt.cpp \ os/Wnt/OsFileSystemWnt.cpp \ os/Wnt/OsFileWnt.cpp \ os/Wnt/OsMutexWnt.cpp \ os/Wnt/OsPathWnt.cpp \ os/Wnt/OsProcessIteratorWnt.cpp \ os/Wnt/OsProcessWnt.cpp \ os/Wnt/OsSharedLibMgrWnt.cpp \ os/Wnt/OsTaskWnt.cpp \ os/Wnt/OsTimerMessage.cpp \ os/Wnt/OsUtilWnt.cpp \ os/Wnt/WindowsAdapterInfo.cpp all: all-recursive .SUFFIXES: .SUFFIXES: .c .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(top_srcdir)/config/sipXcommon.am.inc $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu sipXportLib/src/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu sipXportLib/src/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/config/sipXcommon.am.inc: $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ test "$$dir" != "$$p" || dir=.; \ echo "rm -f \"$${dir}/so_locations\""; \ rm -f "$${dir}/so_locations"; \ done libsipXport.la: $(libsipXport_la_OBJECTS) $(libsipXport_la_DEPENDENCIES) $(EXTRA_libsipXport_la_DEPENDENCIES) $(libsipXport_la_LINK) -rpath $(libdir) $(libsipXport_la_OBJECTS) $(libsipXport_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OsAssert.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/clock_gettime.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hmac-sha1.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/host_address.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-@PACKAGE@-buildstamp.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-AdapterInfo.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-ExtractContent.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-NatMsg.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsBSemLinux.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsCSemBase.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsCSemLinux.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsCallback.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsConfigDb.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsConnectionSocket.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsContact.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsContactList.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsDatagramSocket.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsDateTime.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsDateTimeLinux.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsDirBase.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsDirLinux.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsEncryption.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsEvent.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsEventMsg.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsExcept.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsFileBase.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsFileInfoBase.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsFileInfoLinux.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsFileIteratorBase.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsFileIteratorLinux.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsFileLinux.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsFileSystem.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsIntPtrMsg.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsLockingList.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsMsg.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsMsgDispatcher.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsMsgPool.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsMsgQ.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsMsgQShared.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsMulticastSocket.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsMutexLinux.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsNameDb.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsNameDbInit.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsNatAgentTask.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsNatConnectionSocket.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsNatDatagramSocket.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsNatSocketBaseImpl.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsPathBase.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsPathLinux.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsProcessBase.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsProcessIteratorBase.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsProcessIteratorLinux.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsProcessLinux.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsProcessMgr.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsProtectEvent.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsProtectEventMgr.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsProtectEventMgrInit.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsPtrMsg.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsQueuedEvent.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsRWMutexLinux.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsRpcMsg.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsSSL.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsSSLConnectionSocket.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsSSLServerSocket.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsServerSocket.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsServerTask.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsSharedLibMgr.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsSharedLibMgrLinux.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsSocket.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsSocketCrypto.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsSysLog.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsSysLogFacilities.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsSysLogMsg.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsSysLogTask.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsTLSClientConnectionSocket.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsTLSConnectionSocket.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsTLSServerSocket.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsTask.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsTaskLinux.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsTime.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsTimeLog.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsTimer.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsTimerMessage.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsTimerMsg.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsTimerTask.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsTokenizer.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsUtil.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-OsUtilLinux.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-PluginHooks.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-StunMessage.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-StunUtils.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-TiXmlIterator.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-TurnMessage.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlBool.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlChainPool.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlContainable.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlContainableAtomic.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlContainablePair.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlContainer.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlCopyableContainable.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlCopyableSList.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlCopyableSortedList.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlCrc32.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlCryptoData.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlCryptoKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlCryptoKeyRsa.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlCryptoKeySym.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlDList.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlDListIterator.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlDateTime.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlHashBag.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlHashBagIterator.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlHashMap.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlHashMapIterator.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlHistogram.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlInit.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlInt.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlIntPtr.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlIterator.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlLink.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlList.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlListIterator.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlLongLongInt.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlNameValueTokenizer.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlRandom.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlRegex.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlRscStore.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlSList.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlSListIterator.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlSortedList.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlSortedListIterator.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlString.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlTokenizer.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-UtlVoidPtr.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-XmlContent.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-osPrintf.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-tinystr.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-tinyxml.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-tinyxmlerror.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXport_la-tinyxmlparser.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pt_csem.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pt_mutex.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sha1.Plo@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(COMPILE) -c $< .c.obj: @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< OsAssert.lo: os/OsAssert.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT OsAssert.lo -MD -MP -MF $(DEPDIR)/OsAssert.Tpo -c -o OsAssert.lo `test -f 'os/OsAssert.c' || echo '$(srcdir)/'`os/OsAssert.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/OsAssert.Tpo $(DEPDIR)/OsAssert.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='os/OsAssert.c' object='OsAssert.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o OsAssert.lo `test -f 'os/OsAssert.c' || echo '$(srcdir)/'`os/OsAssert.c clock_gettime.lo: os/linux/clock_gettime.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT clock_gettime.lo -MD -MP -MF $(DEPDIR)/clock_gettime.Tpo -c -o clock_gettime.lo `test -f 'os/linux/clock_gettime.c' || echo '$(srcdir)/'`os/linux/clock_gettime.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/clock_gettime.Tpo $(DEPDIR)/clock_gettime.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='os/linux/clock_gettime.c' object='clock_gettime.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o clock_gettime.lo `test -f 'os/linux/clock_gettime.c' || echo '$(srcdir)/'`os/linux/clock_gettime.c host_address.lo: os/linux/host_address.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT host_address.lo -MD -MP -MF $(DEPDIR)/host_address.Tpo -c -o host_address.lo `test -f 'os/linux/host_address.c' || echo '$(srcdir)/'`os/linux/host_address.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/host_address.Tpo $(DEPDIR)/host_address.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='os/linux/host_address.c' object='host_address.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o host_address.lo `test -f 'os/linux/host_address.c' || echo '$(srcdir)/'`os/linux/host_address.c pt_csem.lo: os/linux/pt_csem.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT pt_csem.lo -MD -MP -MF $(DEPDIR)/pt_csem.Tpo -c -o pt_csem.lo `test -f 'os/linux/pt_csem.c' || echo '$(srcdir)/'`os/linux/pt_csem.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/pt_csem.Tpo $(DEPDIR)/pt_csem.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='os/linux/pt_csem.c' object='pt_csem.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o pt_csem.lo `test -f 'os/linux/pt_csem.c' || echo '$(srcdir)/'`os/linux/pt_csem.c pt_mutex.lo: os/linux/pt_mutex.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT pt_mutex.lo -MD -MP -MF $(DEPDIR)/pt_mutex.Tpo -c -o pt_mutex.lo `test -f 'os/linux/pt_mutex.c' || echo '$(srcdir)/'`os/linux/pt_mutex.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/pt_mutex.Tpo $(DEPDIR)/pt_mutex.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='os/linux/pt_mutex.c' object='pt_mutex.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o pt_mutex.lo `test -f 'os/linux/pt_mutex.c' || echo '$(srcdir)/'`os/linux/pt_mutex.c hmac-sha1.lo: hmac-sha1/hmac-sha1.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT hmac-sha1.lo -MD -MP -MF $(DEPDIR)/hmac-sha1.Tpo -c -o hmac-sha1.lo `test -f 'hmac-sha1/hmac-sha1.c' || echo '$(srcdir)/'`hmac-sha1/hmac-sha1.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/hmac-sha1.Tpo $(DEPDIR)/hmac-sha1.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='hmac-sha1/hmac-sha1.c' object='hmac-sha1.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o hmac-sha1.lo `test -f 'hmac-sha1/hmac-sha1.c' || echo '$(srcdir)/'`hmac-sha1/hmac-sha1.c sha1.lo: hmac-sha1/sha1.c @am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT sha1.lo -MD -MP -MF $(DEPDIR)/sha1.Tpo -c -o sha1.lo `test -f 'hmac-sha1/sha1.c' || echo '$(srcdir)/'`hmac-sha1/sha1.c @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/sha1.Tpo $(DEPDIR)/sha1.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='hmac-sha1/sha1.c' object='sha1.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o sha1.lo `test -f 'hmac-sha1/sha1.c' || echo '$(srcdir)/'`hmac-sha1/sha1.c .cpp.o: @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< libsipXport_la-UtlLongLongInt.lo: utl/UtlLongLongInt.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlLongLongInt.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlLongLongInt.Tpo -c -o libsipXport_la-UtlLongLongInt.lo `test -f 'utl/UtlLongLongInt.cpp' || echo '$(srcdir)/'`utl/UtlLongLongInt.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlLongLongInt.Tpo $(DEPDIR)/libsipXport_la-UtlLongLongInt.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlLongLongInt.cpp' object='libsipXport_la-UtlLongLongInt.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlLongLongInt.lo `test -f 'utl/UtlLongLongInt.cpp' || echo '$(srcdir)/'`utl/UtlLongLongInt.cpp libsipXport_la-UtlNameValueTokenizer.lo: utl/UtlNameValueTokenizer.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlNameValueTokenizer.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlNameValueTokenizer.Tpo -c -o libsipXport_la-UtlNameValueTokenizer.lo `test -f 'utl/UtlNameValueTokenizer.cpp' || echo '$(srcdir)/'`utl/UtlNameValueTokenizer.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlNameValueTokenizer.Tpo $(DEPDIR)/libsipXport_la-UtlNameValueTokenizer.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlNameValueTokenizer.cpp' object='libsipXport_la-UtlNameValueTokenizer.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlNameValueTokenizer.lo `test -f 'utl/UtlNameValueTokenizer.cpp' || echo '$(srcdir)/'`utl/UtlNameValueTokenizer.cpp libsipXport_la-UtlBool.lo: utl/UtlBool.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlBool.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlBool.Tpo -c -o libsipXport_la-UtlBool.lo `test -f 'utl/UtlBool.cpp' || echo '$(srcdir)/'`utl/UtlBool.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlBool.Tpo $(DEPDIR)/libsipXport_la-UtlBool.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlBool.cpp' object='libsipXport_la-UtlBool.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlBool.lo `test -f 'utl/UtlBool.cpp' || echo '$(srcdir)/'`utl/UtlBool.cpp libsipXport_la-UtlCopyableContainable.lo: utl/UtlCopyableContainable.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlCopyableContainable.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlCopyableContainable.Tpo -c -o libsipXport_la-UtlCopyableContainable.lo `test -f 'utl/UtlCopyableContainable.cpp' || echo '$(srcdir)/'`utl/UtlCopyableContainable.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlCopyableContainable.Tpo $(DEPDIR)/libsipXport_la-UtlCopyableContainable.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlCopyableContainable.cpp' object='libsipXport_la-UtlCopyableContainable.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlCopyableContainable.lo `test -f 'utl/UtlCopyableContainable.cpp' || echo '$(srcdir)/'`utl/UtlCopyableContainable.cpp libsipXport_la-UtlCrc32.lo: utl/UtlCrc32.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlCrc32.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlCrc32.Tpo -c -o libsipXport_la-UtlCrc32.lo `test -f 'utl/UtlCrc32.cpp' || echo '$(srcdir)/'`utl/UtlCrc32.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlCrc32.Tpo $(DEPDIR)/libsipXport_la-UtlCrc32.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlCrc32.cpp' object='libsipXport_la-UtlCrc32.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlCrc32.lo `test -f 'utl/UtlCrc32.cpp' || echo '$(srcdir)/'`utl/UtlCrc32.cpp libsipXport_la-UtlCryptoData.lo: utl/UtlCryptoData.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlCryptoData.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlCryptoData.Tpo -c -o libsipXport_la-UtlCryptoData.lo `test -f 'utl/UtlCryptoData.cpp' || echo '$(srcdir)/'`utl/UtlCryptoData.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlCryptoData.Tpo $(DEPDIR)/libsipXport_la-UtlCryptoData.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlCryptoData.cpp' object='libsipXport_la-UtlCryptoData.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlCryptoData.lo `test -f 'utl/UtlCryptoData.cpp' || echo '$(srcdir)/'`utl/UtlCryptoData.cpp libsipXport_la-UtlCryptoKey.lo: utl/UtlCryptoKey.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlCryptoKey.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlCryptoKey.Tpo -c -o libsipXport_la-UtlCryptoKey.lo `test -f 'utl/UtlCryptoKey.cpp' || echo '$(srcdir)/'`utl/UtlCryptoKey.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlCryptoKey.Tpo $(DEPDIR)/libsipXport_la-UtlCryptoKey.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlCryptoKey.cpp' object='libsipXport_la-UtlCryptoKey.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlCryptoKey.lo `test -f 'utl/UtlCryptoKey.cpp' || echo '$(srcdir)/'`utl/UtlCryptoKey.cpp libsipXport_la-UtlCryptoKeyRsa.lo: utl/UtlCryptoKeyRsa.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlCryptoKeyRsa.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlCryptoKeyRsa.Tpo -c -o libsipXport_la-UtlCryptoKeyRsa.lo `test -f 'utl/UtlCryptoKeyRsa.cpp' || echo '$(srcdir)/'`utl/UtlCryptoKeyRsa.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlCryptoKeyRsa.Tpo $(DEPDIR)/libsipXport_la-UtlCryptoKeyRsa.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlCryptoKeyRsa.cpp' object='libsipXport_la-UtlCryptoKeyRsa.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlCryptoKeyRsa.lo `test -f 'utl/UtlCryptoKeyRsa.cpp' || echo '$(srcdir)/'`utl/UtlCryptoKeyRsa.cpp libsipXport_la-UtlCryptoKeySym.lo: utl/UtlCryptoKeySym.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlCryptoKeySym.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlCryptoKeySym.Tpo -c -o libsipXport_la-UtlCryptoKeySym.lo `test -f 'utl/UtlCryptoKeySym.cpp' || echo '$(srcdir)/'`utl/UtlCryptoKeySym.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlCryptoKeySym.Tpo $(DEPDIR)/libsipXport_la-UtlCryptoKeySym.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlCryptoKeySym.cpp' object='libsipXport_la-UtlCryptoKeySym.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlCryptoKeySym.lo `test -f 'utl/UtlCryptoKeySym.cpp' || echo '$(srcdir)/'`utl/UtlCryptoKeySym.cpp libsipXport_la-UtlDateTime.lo: utl/UtlDateTime.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlDateTime.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlDateTime.Tpo -c -o libsipXport_la-UtlDateTime.lo `test -f 'utl/UtlDateTime.cpp' || echo '$(srcdir)/'`utl/UtlDateTime.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlDateTime.Tpo $(DEPDIR)/libsipXport_la-UtlDateTime.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlDateTime.cpp' object='libsipXport_la-UtlDateTime.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlDateTime.lo `test -f 'utl/UtlDateTime.cpp' || echo '$(srcdir)/'`utl/UtlDateTime.cpp libsipXport_la-UtlLink.lo: utl/UtlLink.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlLink.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlLink.Tpo -c -o libsipXport_la-UtlLink.lo `test -f 'utl/UtlLink.cpp' || echo '$(srcdir)/'`utl/UtlLink.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlLink.Tpo $(DEPDIR)/libsipXport_la-UtlLink.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlLink.cpp' object='libsipXport_la-UtlLink.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlLink.lo `test -f 'utl/UtlLink.cpp' || echo '$(srcdir)/'`utl/UtlLink.cpp libsipXport_la-UtlVoidPtr.lo: utl/UtlVoidPtr.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlVoidPtr.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlVoidPtr.Tpo -c -o libsipXport_la-UtlVoidPtr.lo `test -f 'utl/UtlVoidPtr.cpp' || echo '$(srcdir)/'`utl/UtlVoidPtr.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlVoidPtr.Tpo $(DEPDIR)/libsipXport_la-UtlVoidPtr.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlVoidPtr.cpp' object='libsipXport_la-UtlVoidPtr.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlVoidPtr.lo `test -f 'utl/UtlVoidPtr.cpp' || echo '$(srcdir)/'`utl/UtlVoidPtr.cpp libsipXport_la-UtlHistogram.lo: utl/UtlHistogram.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlHistogram.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlHistogram.Tpo -c -o libsipXport_la-UtlHistogram.lo `test -f 'utl/UtlHistogram.cpp' || echo '$(srcdir)/'`utl/UtlHistogram.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlHistogram.Tpo $(DEPDIR)/libsipXport_la-UtlHistogram.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlHistogram.cpp' object='libsipXport_la-UtlHistogram.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlHistogram.lo `test -f 'utl/UtlHistogram.cpp' || echo '$(srcdir)/'`utl/UtlHistogram.cpp libsipXport_la-UtlInit.lo: utl/UtlInit.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlInit.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlInit.Tpo -c -o libsipXport_la-UtlInit.lo `test -f 'utl/UtlInit.cpp' || echo '$(srcdir)/'`utl/UtlInit.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlInit.Tpo $(DEPDIR)/libsipXport_la-UtlInit.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlInit.cpp' object='libsipXport_la-UtlInit.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlInit.lo `test -f 'utl/UtlInit.cpp' || echo '$(srcdir)/'`utl/UtlInit.cpp libsipXport_la-UtlInt.lo: utl/UtlInt.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlInt.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlInt.Tpo -c -o libsipXport_la-UtlInt.lo `test -f 'utl/UtlInt.cpp' || echo '$(srcdir)/'`utl/UtlInt.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlInt.Tpo $(DEPDIR)/libsipXport_la-UtlInt.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlInt.cpp' object='libsipXport_la-UtlInt.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlInt.lo `test -f 'utl/UtlInt.cpp' || echo '$(srcdir)/'`utl/UtlInt.cpp libsipXport_la-UtlIntPtr.lo: utl/UtlIntPtr.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlIntPtr.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlIntPtr.Tpo -c -o libsipXport_la-UtlIntPtr.lo `test -f 'utl/UtlIntPtr.cpp' || echo '$(srcdir)/'`utl/UtlIntPtr.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlIntPtr.Tpo $(DEPDIR)/libsipXport_la-UtlIntPtr.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlIntPtr.cpp' object='libsipXport_la-UtlIntPtr.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlIntPtr.lo `test -f 'utl/UtlIntPtr.cpp' || echo '$(srcdir)/'`utl/UtlIntPtr.cpp libsipXport_la-UtlString.lo: utl/UtlString.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlString.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlString.Tpo -c -o libsipXport_la-UtlString.lo `test -f 'utl/UtlString.cpp' || echo '$(srcdir)/'`utl/UtlString.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlString.Tpo $(DEPDIR)/libsipXport_la-UtlString.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlString.cpp' object='libsipXport_la-UtlString.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlString.lo `test -f 'utl/UtlString.cpp' || echo '$(srcdir)/'`utl/UtlString.cpp libsipXport_la-UtlChainPool.lo: utl/UtlChainPool.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlChainPool.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlChainPool.Tpo -c -o libsipXport_la-UtlChainPool.lo `test -f 'utl/UtlChainPool.cpp' || echo '$(srcdir)/'`utl/UtlChainPool.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlChainPool.Tpo $(DEPDIR)/libsipXport_la-UtlChainPool.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlChainPool.cpp' object='libsipXport_la-UtlChainPool.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlChainPool.lo `test -f 'utl/UtlChainPool.cpp' || echo '$(srcdir)/'`utl/UtlChainPool.cpp libsipXport_la-UtlContainable.lo: utl/UtlContainable.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlContainable.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlContainable.Tpo -c -o libsipXport_la-UtlContainable.lo `test -f 'utl/UtlContainable.cpp' || echo '$(srcdir)/'`utl/UtlContainable.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlContainable.Tpo $(DEPDIR)/libsipXport_la-UtlContainable.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlContainable.cpp' object='libsipXport_la-UtlContainable.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlContainable.lo `test -f 'utl/UtlContainable.cpp' || echo '$(srcdir)/'`utl/UtlContainable.cpp libsipXport_la-UtlContainer.lo: utl/UtlContainer.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlContainer.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlContainer.Tpo -c -o libsipXport_la-UtlContainer.lo `test -f 'utl/UtlContainer.cpp' || echo '$(srcdir)/'`utl/UtlContainer.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlContainer.Tpo $(DEPDIR)/libsipXport_la-UtlContainer.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlContainer.cpp' object='libsipXport_la-UtlContainer.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlContainer.lo `test -f 'utl/UtlContainer.cpp' || echo '$(srcdir)/'`utl/UtlContainer.cpp libsipXport_la-UtlContainableAtomic.lo: utl/UtlContainableAtomic.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlContainableAtomic.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlContainableAtomic.Tpo -c -o libsipXport_la-UtlContainableAtomic.lo `test -f 'utl/UtlContainableAtomic.cpp' || echo '$(srcdir)/'`utl/UtlContainableAtomic.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlContainableAtomic.Tpo $(DEPDIR)/libsipXport_la-UtlContainableAtomic.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlContainableAtomic.cpp' object='libsipXport_la-UtlContainableAtomic.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlContainableAtomic.lo `test -f 'utl/UtlContainableAtomic.cpp' || echo '$(srcdir)/'`utl/UtlContainableAtomic.cpp libsipXport_la-UtlContainablePair.lo: utl/UtlContainablePair.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlContainablePair.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlContainablePair.Tpo -c -o libsipXport_la-UtlContainablePair.lo `test -f 'utl/UtlContainablePair.cpp' || echo '$(srcdir)/'`utl/UtlContainablePair.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlContainablePair.Tpo $(DEPDIR)/libsipXport_la-UtlContainablePair.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlContainablePair.cpp' object='libsipXport_la-UtlContainablePair.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlContainablePair.lo `test -f 'utl/UtlContainablePair.cpp' || echo '$(srcdir)/'`utl/UtlContainablePair.cpp libsipXport_la-UtlIterator.lo: utl/UtlIterator.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlIterator.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlIterator.Tpo -c -o libsipXport_la-UtlIterator.lo `test -f 'utl/UtlIterator.cpp' || echo '$(srcdir)/'`utl/UtlIterator.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlIterator.Tpo $(DEPDIR)/libsipXport_la-UtlIterator.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlIterator.cpp' object='libsipXport_la-UtlIterator.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlIterator.lo `test -f 'utl/UtlIterator.cpp' || echo '$(srcdir)/'`utl/UtlIterator.cpp libsipXport_la-UtlList.lo: utl/UtlList.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlList.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlList.Tpo -c -o libsipXport_la-UtlList.lo `test -f 'utl/UtlList.cpp' || echo '$(srcdir)/'`utl/UtlList.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlList.Tpo $(DEPDIR)/libsipXport_la-UtlList.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlList.cpp' object='libsipXport_la-UtlList.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlList.lo `test -f 'utl/UtlList.cpp' || echo '$(srcdir)/'`utl/UtlList.cpp libsipXport_la-UtlListIterator.lo: utl/UtlListIterator.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlListIterator.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlListIterator.Tpo -c -o libsipXport_la-UtlListIterator.lo `test -f 'utl/UtlListIterator.cpp' || echo '$(srcdir)/'`utl/UtlListIterator.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlListIterator.Tpo $(DEPDIR)/libsipXport_la-UtlListIterator.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlListIterator.cpp' object='libsipXport_la-UtlListIterator.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlListIterator.lo `test -f 'utl/UtlListIterator.cpp' || echo '$(srcdir)/'`utl/UtlListIterator.cpp libsipXport_la-UtlSList.lo: utl/UtlSList.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlSList.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlSList.Tpo -c -o libsipXport_la-UtlSList.lo `test -f 'utl/UtlSList.cpp' || echo '$(srcdir)/'`utl/UtlSList.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlSList.Tpo $(DEPDIR)/libsipXport_la-UtlSList.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlSList.cpp' object='libsipXport_la-UtlSList.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlSList.lo `test -f 'utl/UtlSList.cpp' || echo '$(srcdir)/'`utl/UtlSList.cpp libsipXport_la-UtlCopyableSList.lo: utl/UtlCopyableSList.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlCopyableSList.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlCopyableSList.Tpo -c -o libsipXport_la-UtlCopyableSList.lo `test -f 'utl/UtlCopyableSList.cpp' || echo '$(srcdir)/'`utl/UtlCopyableSList.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlCopyableSList.Tpo $(DEPDIR)/libsipXport_la-UtlCopyableSList.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlCopyableSList.cpp' object='libsipXport_la-UtlCopyableSList.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlCopyableSList.lo `test -f 'utl/UtlCopyableSList.cpp' || echo '$(srcdir)/'`utl/UtlCopyableSList.cpp libsipXport_la-UtlSListIterator.lo: utl/UtlSListIterator.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlSListIterator.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlSListIterator.Tpo -c -o libsipXport_la-UtlSListIterator.lo `test -f 'utl/UtlSListIterator.cpp' || echo '$(srcdir)/'`utl/UtlSListIterator.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlSListIterator.Tpo $(DEPDIR)/libsipXport_la-UtlSListIterator.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlSListIterator.cpp' object='libsipXport_la-UtlSListIterator.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlSListIterator.lo `test -f 'utl/UtlSListIterator.cpp' || echo '$(srcdir)/'`utl/UtlSListIterator.cpp libsipXport_la-UtlDList.lo: utl/UtlDList.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlDList.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlDList.Tpo -c -o libsipXport_la-UtlDList.lo `test -f 'utl/UtlDList.cpp' || echo '$(srcdir)/'`utl/UtlDList.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlDList.Tpo $(DEPDIR)/libsipXport_la-UtlDList.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlDList.cpp' object='libsipXport_la-UtlDList.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlDList.lo `test -f 'utl/UtlDList.cpp' || echo '$(srcdir)/'`utl/UtlDList.cpp libsipXport_la-UtlDListIterator.lo: utl/UtlDListIterator.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlDListIterator.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlDListIterator.Tpo -c -o libsipXport_la-UtlDListIterator.lo `test -f 'utl/UtlDListIterator.cpp' || echo '$(srcdir)/'`utl/UtlDListIterator.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlDListIterator.Tpo $(DEPDIR)/libsipXport_la-UtlDListIterator.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlDListIterator.cpp' object='libsipXport_la-UtlDListIterator.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlDListIterator.lo `test -f 'utl/UtlDListIterator.cpp' || echo '$(srcdir)/'`utl/UtlDListIterator.cpp libsipXport_la-UtlCopyableSortedList.lo: utl/UtlCopyableSortedList.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlCopyableSortedList.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlCopyableSortedList.Tpo -c -o libsipXport_la-UtlCopyableSortedList.lo `test -f 'utl/UtlCopyableSortedList.cpp' || echo '$(srcdir)/'`utl/UtlCopyableSortedList.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlCopyableSortedList.Tpo $(DEPDIR)/libsipXport_la-UtlCopyableSortedList.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlCopyableSortedList.cpp' object='libsipXport_la-UtlCopyableSortedList.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlCopyableSortedList.lo `test -f 'utl/UtlCopyableSortedList.cpp' || echo '$(srcdir)/'`utl/UtlCopyableSortedList.cpp libsipXport_la-UtlSortedList.lo: utl/UtlSortedList.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlSortedList.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlSortedList.Tpo -c -o libsipXport_la-UtlSortedList.lo `test -f 'utl/UtlSortedList.cpp' || echo '$(srcdir)/'`utl/UtlSortedList.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlSortedList.Tpo $(DEPDIR)/libsipXport_la-UtlSortedList.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlSortedList.cpp' object='libsipXport_la-UtlSortedList.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlSortedList.lo `test -f 'utl/UtlSortedList.cpp' || echo '$(srcdir)/'`utl/UtlSortedList.cpp libsipXport_la-UtlSortedListIterator.lo: utl/UtlSortedListIterator.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlSortedListIterator.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlSortedListIterator.Tpo -c -o libsipXport_la-UtlSortedListIterator.lo `test -f 'utl/UtlSortedListIterator.cpp' || echo '$(srcdir)/'`utl/UtlSortedListIterator.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlSortedListIterator.Tpo $(DEPDIR)/libsipXport_la-UtlSortedListIterator.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlSortedListIterator.cpp' object='libsipXport_la-UtlSortedListIterator.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlSortedListIterator.lo `test -f 'utl/UtlSortedListIterator.cpp' || echo '$(srcdir)/'`utl/UtlSortedListIterator.cpp libsipXport_la-UtlHashMap.lo: utl/UtlHashMap.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlHashMap.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlHashMap.Tpo -c -o libsipXport_la-UtlHashMap.lo `test -f 'utl/UtlHashMap.cpp' || echo '$(srcdir)/'`utl/UtlHashMap.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlHashMap.Tpo $(DEPDIR)/libsipXport_la-UtlHashMap.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlHashMap.cpp' object='libsipXport_la-UtlHashMap.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlHashMap.lo `test -f 'utl/UtlHashMap.cpp' || echo '$(srcdir)/'`utl/UtlHashMap.cpp libsipXport_la-UtlHashMapIterator.lo: utl/UtlHashMapIterator.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlHashMapIterator.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlHashMapIterator.Tpo -c -o libsipXport_la-UtlHashMapIterator.lo `test -f 'utl/UtlHashMapIterator.cpp' || echo '$(srcdir)/'`utl/UtlHashMapIterator.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlHashMapIterator.Tpo $(DEPDIR)/libsipXport_la-UtlHashMapIterator.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlHashMapIterator.cpp' object='libsipXport_la-UtlHashMapIterator.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlHashMapIterator.lo `test -f 'utl/UtlHashMapIterator.cpp' || echo '$(srcdir)/'`utl/UtlHashMapIterator.cpp libsipXport_la-UtlHashBag.lo: utl/UtlHashBag.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlHashBag.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlHashBag.Tpo -c -o libsipXport_la-UtlHashBag.lo `test -f 'utl/UtlHashBag.cpp' || echo '$(srcdir)/'`utl/UtlHashBag.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlHashBag.Tpo $(DEPDIR)/libsipXport_la-UtlHashBag.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlHashBag.cpp' object='libsipXport_la-UtlHashBag.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlHashBag.lo `test -f 'utl/UtlHashBag.cpp' || echo '$(srcdir)/'`utl/UtlHashBag.cpp libsipXport_la-UtlHashBagIterator.lo: utl/UtlHashBagIterator.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlHashBagIterator.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlHashBagIterator.Tpo -c -o libsipXport_la-UtlHashBagIterator.lo `test -f 'utl/UtlHashBagIterator.cpp' || echo '$(srcdir)/'`utl/UtlHashBagIterator.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlHashBagIterator.Tpo $(DEPDIR)/libsipXport_la-UtlHashBagIterator.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlHashBagIterator.cpp' object='libsipXport_la-UtlHashBagIterator.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlHashBagIterator.lo `test -f 'utl/UtlHashBagIterator.cpp' || echo '$(srcdir)/'`utl/UtlHashBagIterator.cpp libsipXport_la-UtlRscStore.lo: utl/UtlRscStore.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlRscStore.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlRscStore.Tpo -c -o libsipXport_la-UtlRscStore.lo `test -f 'utl/UtlRscStore.cpp' || echo '$(srcdir)/'`utl/UtlRscStore.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlRscStore.Tpo $(DEPDIR)/libsipXport_la-UtlRscStore.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlRscStore.cpp' object='libsipXport_la-UtlRscStore.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlRscStore.lo `test -f 'utl/UtlRscStore.cpp' || echo '$(srcdir)/'`utl/UtlRscStore.cpp libsipXport_la-UtlRegex.lo: utl/UtlRegex.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlRegex.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlRegex.Tpo -c -o libsipXport_la-UtlRegex.lo `test -f 'utl/UtlRegex.cpp' || echo '$(srcdir)/'`utl/UtlRegex.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlRegex.Tpo $(DEPDIR)/libsipXport_la-UtlRegex.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlRegex.cpp' object='libsipXport_la-UtlRegex.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlRegex.lo `test -f 'utl/UtlRegex.cpp' || echo '$(srcdir)/'`utl/UtlRegex.cpp libsipXport_la-UtlTokenizer.lo: utl/UtlTokenizer.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlTokenizer.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlTokenizer.Tpo -c -o libsipXport_la-UtlTokenizer.lo `test -f 'utl/UtlTokenizer.cpp' || echo '$(srcdir)/'`utl/UtlTokenizer.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlTokenizer.Tpo $(DEPDIR)/libsipXport_la-UtlTokenizer.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlTokenizer.cpp' object='libsipXport_la-UtlTokenizer.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlTokenizer.lo `test -f 'utl/UtlTokenizer.cpp' || echo '$(srcdir)/'`utl/UtlTokenizer.cpp libsipXport_la-XmlContent.lo: utl/XmlContent.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-XmlContent.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-XmlContent.Tpo -c -o libsipXport_la-XmlContent.lo `test -f 'utl/XmlContent.cpp' || echo '$(srcdir)/'`utl/XmlContent.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-XmlContent.Tpo $(DEPDIR)/libsipXport_la-XmlContent.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/XmlContent.cpp' object='libsipXport_la-XmlContent.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-XmlContent.lo `test -f 'utl/XmlContent.cpp' || echo '$(srcdir)/'`utl/XmlContent.cpp libsipXport_la-UtlRandom.lo: utl/UtlRandom.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-UtlRandom.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-UtlRandom.Tpo -c -o libsipXport_la-UtlRandom.lo `test -f 'utl/UtlRandom.cpp' || echo '$(srcdir)/'`utl/UtlRandom.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-UtlRandom.Tpo $(DEPDIR)/libsipXport_la-UtlRandom.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlRandom.cpp' object='libsipXport_la-UtlRandom.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-UtlRandom.lo `test -f 'utl/UtlRandom.cpp' || echo '$(srcdir)/'`utl/UtlRandom.cpp libsipXport_la-PluginHooks.lo: utl/PluginHooks.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-PluginHooks.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-PluginHooks.Tpo -c -o libsipXport_la-PluginHooks.lo `test -f 'utl/PluginHooks.cpp' || echo '$(srcdir)/'`utl/PluginHooks.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-PluginHooks.Tpo $(DEPDIR)/libsipXport_la-PluginHooks.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/PluginHooks.cpp' object='libsipXport_la-PluginHooks.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-PluginHooks.lo `test -f 'utl/PluginHooks.cpp' || echo '$(srcdir)/'`utl/PluginHooks.cpp libsipXport_la-NatMsg.lo: os/NatMsg.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-NatMsg.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-NatMsg.Tpo -c -o libsipXport_la-NatMsg.lo `test -f 'os/NatMsg.cpp' || echo '$(srcdir)/'`os/NatMsg.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-NatMsg.Tpo $(DEPDIR)/libsipXport_la-NatMsg.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/NatMsg.cpp' object='libsipXport_la-NatMsg.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-NatMsg.lo `test -f 'os/NatMsg.cpp' || echo '$(srcdir)/'`os/NatMsg.cpp libsipXport_la-OsCallback.lo: os/OsCallback.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsCallback.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsCallback.Tpo -c -o libsipXport_la-OsCallback.lo `test -f 'os/OsCallback.cpp' || echo '$(srcdir)/'`os/OsCallback.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsCallback.Tpo $(DEPDIR)/libsipXport_la-OsCallback.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsCallback.cpp' object='libsipXport_la-OsCallback.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsCallback.lo `test -f 'os/OsCallback.cpp' || echo '$(srcdir)/'`os/OsCallback.cpp libsipXport_la-OsConfigDb.lo: os/OsConfigDb.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsConfigDb.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsConfigDb.Tpo -c -o libsipXport_la-OsConfigDb.lo `test -f 'os/OsConfigDb.cpp' || echo '$(srcdir)/'`os/OsConfigDb.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsConfigDb.Tpo $(DEPDIR)/libsipXport_la-OsConfigDb.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsConfigDb.cpp' object='libsipXport_la-OsConfigDb.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsConfigDb.lo `test -f 'os/OsConfigDb.cpp' || echo '$(srcdir)/'`os/OsConfigDb.cpp libsipXport_la-OsContact.lo: os/OsContact.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsContact.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsContact.Tpo -c -o libsipXport_la-OsContact.lo `test -f 'os/OsContact.cpp' || echo '$(srcdir)/'`os/OsContact.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsContact.Tpo $(DEPDIR)/libsipXport_la-OsContact.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsContact.cpp' object='libsipXport_la-OsContact.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsContact.lo `test -f 'os/OsContact.cpp' || echo '$(srcdir)/'`os/OsContact.cpp libsipXport_la-OsContactList.lo: os/OsContactList.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsContactList.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsContactList.Tpo -c -o libsipXport_la-OsContactList.lo `test -f 'os/OsContactList.cpp' || echo '$(srcdir)/'`os/OsContactList.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsContactList.Tpo $(DEPDIR)/libsipXport_la-OsContactList.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsContactList.cpp' object='libsipXport_la-OsContactList.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsContactList.lo `test -f 'os/OsContactList.cpp' || echo '$(srcdir)/'`os/OsContactList.cpp libsipXport_la-OsConnectionSocket.lo: os/OsConnectionSocket.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsConnectionSocket.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsConnectionSocket.Tpo -c -o libsipXport_la-OsConnectionSocket.lo `test -f 'os/OsConnectionSocket.cpp' || echo '$(srcdir)/'`os/OsConnectionSocket.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsConnectionSocket.Tpo $(DEPDIR)/libsipXport_la-OsConnectionSocket.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsConnectionSocket.cpp' object='libsipXport_la-OsConnectionSocket.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsConnectionSocket.lo `test -f 'os/OsConnectionSocket.cpp' || echo '$(srcdir)/'`os/OsConnectionSocket.cpp libsipXport_la-OsCSemBase.lo: os/OsCSemBase.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsCSemBase.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsCSemBase.Tpo -c -o libsipXport_la-OsCSemBase.lo `test -f 'os/OsCSemBase.cpp' || echo '$(srcdir)/'`os/OsCSemBase.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsCSemBase.Tpo $(DEPDIR)/libsipXport_la-OsCSemBase.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsCSemBase.cpp' object='libsipXport_la-OsCSemBase.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsCSemBase.lo `test -f 'os/OsCSemBase.cpp' || echo '$(srcdir)/'`os/OsCSemBase.cpp libsipXport_la-OsDatagramSocket.lo: os/OsDatagramSocket.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsDatagramSocket.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsDatagramSocket.Tpo -c -o libsipXport_la-OsDatagramSocket.lo `test -f 'os/OsDatagramSocket.cpp' || echo '$(srcdir)/'`os/OsDatagramSocket.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsDatagramSocket.Tpo $(DEPDIR)/libsipXport_la-OsDatagramSocket.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsDatagramSocket.cpp' object='libsipXport_la-OsDatagramSocket.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsDatagramSocket.lo `test -f 'os/OsDatagramSocket.cpp' || echo '$(srcdir)/'`os/OsDatagramSocket.cpp libsipXport_la-OsDateTime.lo: os/OsDateTime.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsDateTime.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsDateTime.Tpo -c -o libsipXport_la-OsDateTime.lo `test -f 'os/OsDateTime.cpp' || echo '$(srcdir)/'`os/OsDateTime.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsDateTime.Tpo $(DEPDIR)/libsipXport_la-OsDateTime.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsDateTime.cpp' object='libsipXport_la-OsDateTime.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsDateTime.lo `test -f 'os/OsDateTime.cpp' || echo '$(srcdir)/'`os/OsDateTime.cpp libsipXport_la-OsDirBase.lo: os/OsDirBase.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsDirBase.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsDirBase.Tpo -c -o libsipXport_la-OsDirBase.lo `test -f 'os/OsDirBase.cpp' || echo '$(srcdir)/'`os/OsDirBase.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsDirBase.Tpo $(DEPDIR)/libsipXport_la-OsDirBase.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsDirBase.cpp' object='libsipXport_la-OsDirBase.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsDirBase.lo `test -f 'os/OsDirBase.cpp' || echo '$(srcdir)/'`os/OsDirBase.cpp libsipXport_la-OsEncryption.lo: os/OsEncryption.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsEncryption.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsEncryption.Tpo -c -o libsipXport_la-OsEncryption.lo `test -f 'os/OsEncryption.cpp' || echo '$(srcdir)/'`os/OsEncryption.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsEncryption.Tpo $(DEPDIR)/libsipXport_la-OsEncryption.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsEncryption.cpp' object='libsipXport_la-OsEncryption.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsEncryption.lo `test -f 'os/OsEncryption.cpp' || echo '$(srcdir)/'`os/OsEncryption.cpp libsipXport_la-OsEvent.lo: os/OsEvent.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsEvent.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsEvent.Tpo -c -o libsipXport_la-OsEvent.lo `test -f 'os/OsEvent.cpp' || echo '$(srcdir)/'`os/OsEvent.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsEvent.Tpo $(DEPDIR)/libsipXport_la-OsEvent.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsEvent.cpp' object='libsipXport_la-OsEvent.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsEvent.lo `test -f 'os/OsEvent.cpp' || echo '$(srcdir)/'`os/OsEvent.cpp libsipXport_la-OsEventMsg.lo: os/OsEventMsg.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsEventMsg.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsEventMsg.Tpo -c -o libsipXport_la-OsEventMsg.lo `test -f 'os/OsEventMsg.cpp' || echo '$(srcdir)/'`os/OsEventMsg.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsEventMsg.Tpo $(DEPDIR)/libsipXport_la-OsEventMsg.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsEventMsg.cpp' object='libsipXport_la-OsEventMsg.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsEventMsg.lo `test -f 'os/OsEventMsg.cpp' || echo '$(srcdir)/'`os/OsEventMsg.cpp libsipXport_la-OsExcept.lo: os/OsExcept.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsExcept.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsExcept.Tpo -c -o libsipXport_la-OsExcept.lo `test -f 'os/OsExcept.cpp' || echo '$(srcdir)/'`os/OsExcept.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsExcept.Tpo $(DEPDIR)/libsipXport_la-OsExcept.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsExcept.cpp' object='libsipXport_la-OsExcept.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsExcept.lo `test -f 'os/OsExcept.cpp' || echo '$(srcdir)/'`os/OsExcept.cpp libsipXport_la-OsFileBase.lo: os/OsFileBase.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsFileBase.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsFileBase.Tpo -c -o libsipXport_la-OsFileBase.lo `test -f 'os/OsFileBase.cpp' || echo '$(srcdir)/'`os/OsFileBase.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsFileBase.Tpo $(DEPDIR)/libsipXport_la-OsFileBase.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsFileBase.cpp' object='libsipXport_la-OsFileBase.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsFileBase.lo `test -f 'os/OsFileBase.cpp' || echo '$(srcdir)/'`os/OsFileBase.cpp libsipXport_la-OsFileInfoBase.lo: os/OsFileInfoBase.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsFileInfoBase.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsFileInfoBase.Tpo -c -o libsipXport_la-OsFileInfoBase.lo `test -f 'os/OsFileInfoBase.cpp' || echo '$(srcdir)/'`os/OsFileInfoBase.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsFileInfoBase.Tpo $(DEPDIR)/libsipXport_la-OsFileInfoBase.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsFileInfoBase.cpp' object='libsipXport_la-OsFileInfoBase.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsFileInfoBase.lo `test -f 'os/OsFileInfoBase.cpp' || echo '$(srcdir)/'`os/OsFileInfoBase.cpp libsipXport_la-OsFileIteratorBase.lo: os/OsFileIteratorBase.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsFileIteratorBase.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsFileIteratorBase.Tpo -c -o libsipXport_la-OsFileIteratorBase.lo `test -f 'os/OsFileIteratorBase.cpp' || echo '$(srcdir)/'`os/OsFileIteratorBase.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsFileIteratorBase.Tpo $(DEPDIR)/libsipXport_la-OsFileIteratorBase.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsFileIteratorBase.cpp' object='libsipXport_la-OsFileIteratorBase.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsFileIteratorBase.lo `test -f 'os/OsFileIteratorBase.cpp' || echo '$(srcdir)/'`os/OsFileIteratorBase.cpp libsipXport_la-OsFileSystem.lo: os/OsFileSystem.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsFileSystem.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsFileSystem.Tpo -c -o libsipXport_la-OsFileSystem.lo `test -f 'os/OsFileSystem.cpp' || echo '$(srcdir)/'`os/OsFileSystem.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsFileSystem.Tpo $(DEPDIR)/libsipXport_la-OsFileSystem.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsFileSystem.cpp' object='libsipXport_la-OsFileSystem.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsFileSystem.lo `test -f 'os/OsFileSystem.cpp' || echo '$(srcdir)/'`os/OsFileSystem.cpp libsipXport_la-OsLockingList.lo: os/OsLockingList.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsLockingList.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsLockingList.Tpo -c -o libsipXport_la-OsLockingList.lo `test -f 'os/OsLockingList.cpp' || echo '$(srcdir)/'`os/OsLockingList.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsLockingList.Tpo $(DEPDIR)/libsipXport_la-OsLockingList.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsLockingList.cpp' object='libsipXport_la-OsLockingList.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsLockingList.lo `test -f 'os/OsLockingList.cpp' || echo '$(srcdir)/'`os/OsLockingList.cpp libsipXport_la-OsIntPtrMsg.lo: os/OsIntPtrMsg.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsIntPtrMsg.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsIntPtrMsg.Tpo -c -o libsipXport_la-OsIntPtrMsg.lo `test -f 'os/OsIntPtrMsg.cpp' || echo '$(srcdir)/'`os/OsIntPtrMsg.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsIntPtrMsg.Tpo $(DEPDIR)/libsipXport_la-OsIntPtrMsg.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsIntPtrMsg.cpp' object='libsipXport_la-OsIntPtrMsg.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsIntPtrMsg.lo `test -f 'os/OsIntPtrMsg.cpp' || echo '$(srcdir)/'`os/OsIntPtrMsg.cpp libsipXport_la-OsMsg.lo: os/OsMsg.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsMsg.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsMsg.Tpo -c -o libsipXport_la-OsMsg.lo `test -f 'os/OsMsg.cpp' || echo '$(srcdir)/'`os/OsMsg.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsMsg.Tpo $(DEPDIR)/libsipXport_la-OsMsg.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsMsg.cpp' object='libsipXport_la-OsMsg.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsMsg.lo `test -f 'os/OsMsg.cpp' || echo '$(srcdir)/'`os/OsMsg.cpp libsipXport_la-OsMsgPool.lo: os/OsMsgPool.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsMsgPool.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsMsgPool.Tpo -c -o libsipXport_la-OsMsgPool.lo `test -f 'os/OsMsgPool.cpp' || echo '$(srcdir)/'`os/OsMsgPool.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsMsgPool.Tpo $(DEPDIR)/libsipXport_la-OsMsgPool.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsMsgPool.cpp' object='libsipXport_la-OsMsgPool.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsMsgPool.lo `test -f 'os/OsMsgPool.cpp' || echo '$(srcdir)/'`os/OsMsgPool.cpp libsipXport_la-OsMsgQ.lo: os/OsMsgQ.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsMsgQ.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsMsgQ.Tpo -c -o libsipXport_la-OsMsgQ.lo `test -f 'os/OsMsgQ.cpp' || echo '$(srcdir)/'`os/OsMsgQ.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsMsgQ.Tpo $(DEPDIR)/libsipXport_la-OsMsgQ.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsMsgQ.cpp' object='libsipXport_la-OsMsgQ.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsMsgQ.lo `test -f 'os/OsMsgQ.cpp' || echo '$(srcdir)/'`os/OsMsgQ.cpp libsipXport_la-OsMsgDispatcher.lo: os/OsMsgDispatcher.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsMsgDispatcher.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsMsgDispatcher.Tpo -c -o libsipXport_la-OsMsgDispatcher.lo `test -f 'os/OsMsgDispatcher.cpp' || echo '$(srcdir)/'`os/OsMsgDispatcher.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsMsgDispatcher.Tpo $(DEPDIR)/libsipXport_la-OsMsgDispatcher.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsMsgDispatcher.cpp' object='libsipXport_la-OsMsgDispatcher.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsMsgDispatcher.lo `test -f 'os/OsMsgDispatcher.cpp' || echo '$(srcdir)/'`os/OsMsgDispatcher.cpp libsipXport_la-OsMulticastSocket.lo: os/OsMulticastSocket.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsMulticastSocket.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsMulticastSocket.Tpo -c -o libsipXport_la-OsMulticastSocket.lo `test -f 'os/OsMulticastSocket.cpp' || echo '$(srcdir)/'`os/OsMulticastSocket.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsMulticastSocket.Tpo $(DEPDIR)/libsipXport_la-OsMulticastSocket.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsMulticastSocket.cpp' object='libsipXport_la-OsMulticastSocket.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsMulticastSocket.lo `test -f 'os/OsMulticastSocket.cpp' || echo '$(srcdir)/'`os/OsMulticastSocket.cpp libsipXport_la-OsNameDb.lo: os/OsNameDb.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsNameDb.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsNameDb.Tpo -c -o libsipXport_la-OsNameDb.lo `test -f 'os/OsNameDb.cpp' || echo '$(srcdir)/'`os/OsNameDb.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsNameDb.Tpo $(DEPDIR)/libsipXport_la-OsNameDb.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsNameDb.cpp' object='libsipXport_la-OsNameDb.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsNameDb.lo `test -f 'os/OsNameDb.cpp' || echo '$(srcdir)/'`os/OsNameDb.cpp libsipXport_la-OsNameDbInit.lo: os/OsNameDbInit.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsNameDbInit.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsNameDbInit.Tpo -c -o libsipXport_la-OsNameDbInit.lo `test -f 'os/OsNameDbInit.cpp' || echo '$(srcdir)/'`os/OsNameDbInit.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsNameDbInit.Tpo $(DEPDIR)/libsipXport_la-OsNameDbInit.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsNameDbInit.cpp' object='libsipXport_la-OsNameDbInit.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsNameDbInit.lo `test -f 'os/OsNameDbInit.cpp' || echo '$(srcdir)/'`os/OsNameDbInit.cpp libsipXport_la-OsNatAgentTask.lo: os/OsNatAgentTask.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsNatAgentTask.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsNatAgentTask.Tpo -c -o libsipXport_la-OsNatAgentTask.lo `test -f 'os/OsNatAgentTask.cpp' || echo '$(srcdir)/'`os/OsNatAgentTask.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsNatAgentTask.Tpo $(DEPDIR)/libsipXport_la-OsNatAgentTask.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsNatAgentTask.cpp' object='libsipXport_la-OsNatAgentTask.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsNatAgentTask.lo `test -f 'os/OsNatAgentTask.cpp' || echo '$(srcdir)/'`os/OsNatAgentTask.cpp libsipXport_la-OsNatDatagramSocket.lo: os/OsNatDatagramSocket.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsNatDatagramSocket.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsNatDatagramSocket.Tpo -c -o libsipXport_la-OsNatDatagramSocket.lo `test -f 'os/OsNatDatagramSocket.cpp' || echo '$(srcdir)/'`os/OsNatDatagramSocket.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsNatDatagramSocket.Tpo $(DEPDIR)/libsipXport_la-OsNatDatagramSocket.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsNatDatagramSocket.cpp' object='libsipXport_la-OsNatDatagramSocket.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsNatDatagramSocket.lo `test -f 'os/OsNatDatagramSocket.cpp' || echo '$(srcdir)/'`os/OsNatDatagramSocket.cpp libsipXport_la-OsNatConnectionSocket.lo: os/OsNatConnectionSocket.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsNatConnectionSocket.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsNatConnectionSocket.Tpo -c -o libsipXport_la-OsNatConnectionSocket.lo `test -f 'os/OsNatConnectionSocket.cpp' || echo '$(srcdir)/'`os/OsNatConnectionSocket.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsNatConnectionSocket.Tpo $(DEPDIR)/libsipXport_la-OsNatConnectionSocket.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsNatConnectionSocket.cpp' object='libsipXport_la-OsNatConnectionSocket.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsNatConnectionSocket.lo `test -f 'os/OsNatConnectionSocket.cpp' || echo '$(srcdir)/'`os/OsNatConnectionSocket.cpp libsipXport_la-OsNatSocketBaseImpl.lo: os/OsNatSocketBaseImpl.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsNatSocketBaseImpl.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsNatSocketBaseImpl.Tpo -c -o libsipXport_la-OsNatSocketBaseImpl.lo `test -f 'os/OsNatSocketBaseImpl.cpp' || echo '$(srcdir)/'`os/OsNatSocketBaseImpl.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsNatSocketBaseImpl.Tpo $(DEPDIR)/libsipXport_la-OsNatSocketBaseImpl.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsNatSocketBaseImpl.cpp' object='libsipXport_la-OsNatSocketBaseImpl.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsNatSocketBaseImpl.lo `test -f 'os/OsNatSocketBaseImpl.cpp' || echo '$(srcdir)/'`os/OsNatSocketBaseImpl.cpp libsipXport_la-OsPathBase.lo: os/OsPathBase.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsPathBase.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsPathBase.Tpo -c -o libsipXport_la-OsPathBase.lo `test -f 'os/OsPathBase.cpp' || echo '$(srcdir)/'`os/OsPathBase.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsPathBase.Tpo $(DEPDIR)/libsipXport_la-OsPathBase.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsPathBase.cpp' object='libsipXport_la-OsPathBase.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsPathBase.lo `test -f 'os/OsPathBase.cpp' || echo '$(srcdir)/'`os/OsPathBase.cpp libsipXport_la-osPrintf.lo: os/osPrintf.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-osPrintf.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-osPrintf.Tpo -c -o libsipXport_la-osPrintf.lo `test -f 'os/osPrintf.cpp' || echo '$(srcdir)/'`os/osPrintf.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-osPrintf.Tpo $(DEPDIR)/libsipXport_la-osPrintf.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/osPrintf.cpp' object='libsipXport_la-osPrintf.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-osPrintf.lo `test -f 'os/osPrintf.cpp' || echo '$(srcdir)/'`os/osPrintf.cpp libsipXport_la-OsProcessBase.lo: os/OsProcessBase.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsProcessBase.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsProcessBase.Tpo -c -o libsipXport_la-OsProcessBase.lo `test -f 'os/OsProcessBase.cpp' || echo '$(srcdir)/'`os/OsProcessBase.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsProcessBase.Tpo $(DEPDIR)/libsipXport_la-OsProcessBase.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsProcessBase.cpp' object='libsipXport_la-OsProcessBase.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsProcessBase.lo `test -f 'os/OsProcessBase.cpp' || echo '$(srcdir)/'`os/OsProcessBase.cpp libsipXport_la-OsProcessIteratorBase.lo: os/OsProcessIteratorBase.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsProcessIteratorBase.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsProcessIteratorBase.Tpo -c -o libsipXport_la-OsProcessIteratorBase.lo `test -f 'os/OsProcessIteratorBase.cpp' || echo '$(srcdir)/'`os/OsProcessIteratorBase.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsProcessIteratorBase.Tpo $(DEPDIR)/libsipXport_la-OsProcessIteratorBase.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsProcessIteratorBase.cpp' object='libsipXport_la-OsProcessIteratorBase.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsProcessIteratorBase.lo `test -f 'os/OsProcessIteratorBase.cpp' || echo '$(srcdir)/'`os/OsProcessIteratorBase.cpp libsipXport_la-OsProcessMgr.lo: os/OsProcessMgr.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsProcessMgr.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsProcessMgr.Tpo -c -o libsipXport_la-OsProcessMgr.lo `test -f 'os/OsProcessMgr.cpp' || echo '$(srcdir)/'`os/OsProcessMgr.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsProcessMgr.Tpo $(DEPDIR)/libsipXport_la-OsProcessMgr.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsProcessMgr.cpp' object='libsipXport_la-OsProcessMgr.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsProcessMgr.lo `test -f 'os/OsProcessMgr.cpp' || echo '$(srcdir)/'`os/OsProcessMgr.cpp libsipXport_la-OsProtectEvent.lo: os/OsProtectEvent.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsProtectEvent.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsProtectEvent.Tpo -c -o libsipXport_la-OsProtectEvent.lo `test -f 'os/OsProtectEvent.cpp' || echo '$(srcdir)/'`os/OsProtectEvent.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsProtectEvent.Tpo $(DEPDIR)/libsipXport_la-OsProtectEvent.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsProtectEvent.cpp' object='libsipXport_la-OsProtectEvent.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsProtectEvent.lo `test -f 'os/OsProtectEvent.cpp' || echo '$(srcdir)/'`os/OsProtectEvent.cpp libsipXport_la-OsProtectEventMgr.lo: os/OsProtectEventMgr.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsProtectEventMgr.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsProtectEventMgr.Tpo -c -o libsipXport_la-OsProtectEventMgr.lo `test -f 'os/OsProtectEventMgr.cpp' || echo '$(srcdir)/'`os/OsProtectEventMgr.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsProtectEventMgr.Tpo $(DEPDIR)/libsipXport_la-OsProtectEventMgr.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsProtectEventMgr.cpp' object='libsipXport_la-OsProtectEventMgr.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsProtectEventMgr.lo `test -f 'os/OsProtectEventMgr.cpp' || echo '$(srcdir)/'`os/OsProtectEventMgr.cpp libsipXport_la-OsProtectEventMgrInit.lo: os/OsProtectEventMgrInit.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsProtectEventMgrInit.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsProtectEventMgrInit.Tpo -c -o libsipXport_la-OsProtectEventMgrInit.lo `test -f 'os/OsProtectEventMgrInit.cpp' || echo '$(srcdir)/'`os/OsProtectEventMgrInit.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsProtectEventMgrInit.Tpo $(DEPDIR)/libsipXport_la-OsProtectEventMgrInit.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsProtectEventMgrInit.cpp' object='libsipXport_la-OsProtectEventMgrInit.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsProtectEventMgrInit.lo `test -f 'os/OsProtectEventMgrInit.cpp' || echo '$(srcdir)/'`os/OsProtectEventMgrInit.cpp libsipXport_la-OsPtrMsg.lo: os/OsPtrMsg.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsPtrMsg.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsPtrMsg.Tpo -c -o libsipXport_la-OsPtrMsg.lo `test -f 'os/OsPtrMsg.cpp' || echo '$(srcdir)/'`os/OsPtrMsg.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsPtrMsg.Tpo $(DEPDIR)/libsipXport_la-OsPtrMsg.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsPtrMsg.cpp' object='libsipXport_la-OsPtrMsg.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsPtrMsg.lo `test -f 'os/OsPtrMsg.cpp' || echo '$(srcdir)/'`os/OsPtrMsg.cpp libsipXport_la-OsQueuedEvent.lo: os/OsQueuedEvent.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsQueuedEvent.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsQueuedEvent.Tpo -c -o libsipXport_la-OsQueuedEvent.lo `test -f 'os/OsQueuedEvent.cpp' || echo '$(srcdir)/'`os/OsQueuedEvent.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsQueuedEvent.Tpo $(DEPDIR)/libsipXport_la-OsQueuedEvent.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsQueuedEvent.cpp' object='libsipXport_la-OsQueuedEvent.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsQueuedEvent.lo `test -f 'os/OsQueuedEvent.cpp' || echo '$(srcdir)/'`os/OsQueuedEvent.cpp libsipXport_la-OsRpcMsg.lo: os/OsRpcMsg.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsRpcMsg.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsRpcMsg.Tpo -c -o libsipXport_la-OsRpcMsg.lo `test -f 'os/OsRpcMsg.cpp' || echo '$(srcdir)/'`os/OsRpcMsg.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsRpcMsg.Tpo $(DEPDIR)/libsipXport_la-OsRpcMsg.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsRpcMsg.cpp' object='libsipXport_la-OsRpcMsg.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsRpcMsg.lo `test -f 'os/OsRpcMsg.cpp' || echo '$(srcdir)/'`os/OsRpcMsg.cpp libsipXport_la-OsServerSocket.lo: os/OsServerSocket.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsServerSocket.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsServerSocket.Tpo -c -o libsipXport_la-OsServerSocket.lo `test -f 'os/OsServerSocket.cpp' || echo '$(srcdir)/'`os/OsServerSocket.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsServerSocket.Tpo $(DEPDIR)/libsipXport_la-OsServerSocket.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsServerSocket.cpp' object='libsipXport_la-OsServerSocket.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsServerSocket.lo `test -f 'os/OsServerSocket.cpp' || echo '$(srcdir)/'`os/OsServerSocket.cpp libsipXport_la-OsServerTask.lo: os/OsServerTask.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsServerTask.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsServerTask.Tpo -c -o libsipXport_la-OsServerTask.lo `test -f 'os/OsServerTask.cpp' || echo '$(srcdir)/'`os/OsServerTask.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsServerTask.Tpo $(DEPDIR)/libsipXport_la-OsServerTask.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsServerTask.cpp' object='libsipXport_la-OsServerTask.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsServerTask.lo `test -f 'os/OsServerTask.cpp' || echo '$(srcdir)/'`os/OsServerTask.cpp libsipXport_la-OsSharedLibMgr.lo: os/OsSharedLibMgr.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsSharedLibMgr.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsSharedLibMgr.Tpo -c -o libsipXport_la-OsSharedLibMgr.lo `test -f 'os/OsSharedLibMgr.cpp' || echo '$(srcdir)/'`os/OsSharedLibMgr.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsSharedLibMgr.Tpo $(DEPDIR)/libsipXport_la-OsSharedLibMgr.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsSharedLibMgr.cpp' object='libsipXport_la-OsSharedLibMgr.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsSharedLibMgr.lo `test -f 'os/OsSharedLibMgr.cpp' || echo '$(srcdir)/'`os/OsSharedLibMgr.cpp libsipXport_la-OsSocket.lo: os/OsSocket.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsSocket.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsSocket.Tpo -c -o libsipXport_la-OsSocket.lo `test -f 'os/OsSocket.cpp' || echo '$(srcdir)/'`os/OsSocket.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsSocket.Tpo $(DEPDIR)/libsipXport_la-OsSocket.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsSocket.cpp' object='libsipXport_la-OsSocket.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsSocket.lo `test -f 'os/OsSocket.cpp' || echo '$(srcdir)/'`os/OsSocket.cpp libsipXport_la-OsSocketCrypto.lo: os/OsSocketCrypto.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsSocketCrypto.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsSocketCrypto.Tpo -c -o libsipXport_la-OsSocketCrypto.lo `test -f 'os/OsSocketCrypto.cpp' || echo '$(srcdir)/'`os/OsSocketCrypto.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsSocketCrypto.Tpo $(DEPDIR)/libsipXport_la-OsSocketCrypto.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsSocketCrypto.cpp' object='libsipXport_la-OsSocketCrypto.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsSocketCrypto.lo `test -f 'os/OsSocketCrypto.cpp' || echo '$(srcdir)/'`os/OsSocketCrypto.cpp libsipXport_la-OsSSL.lo: os/OsSSL.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsSSL.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsSSL.Tpo -c -o libsipXport_la-OsSSL.lo `test -f 'os/OsSSL.cpp' || echo '$(srcdir)/'`os/OsSSL.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsSSL.Tpo $(DEPDIR)/libsipXport_la-OsSSL.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsSSL.cpp' object='libsipXport_la-OsSSL.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsSSL.lo `test -f 'os/OsSSL.cpp' || echo '$(srcdir)/'`os/OsSSL.cpp libsipXport_la-OsSSLConnectionSocket.lo: os/OsSSLConnectionSocket.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsSSLConnectionSocket.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsSSLConnectionSocket.Tpo -c -o libsipXport_la-OsSSLConnectionSocket.lo `test -f 'os/OsSSLConnectionSocket.cpp' || echo '$(srcdir)/'`os/OsSSLConnectionSocket.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsSSLConnectionSocket.Tpo $(DEPDIR)/libsipXport_la-OsSSLConnectionSocket.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsSSLConnectionSocket.cpp' object='libsipXport_la-OsSSLConnectionSocket.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsSSLConnectionSocket.lo `test -f 'os/OsSSLConnectionSocket.cpp' || echo '$(srcdir)/'`os/OsSSLConnectionSocket.cpp libsipXport_la-OsSSLServerSocket.lo: os/OsSSLServerSocket.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsSSLServerSocket.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsSSLServerSocket.Tpo -c -o libsipXport_la-OsSSLServerSocket.lo `test -f 'os/OsSSLServerSocket.cpp' || echo '$(srcdir)/'`os/OsSSLServerSocket.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsSSLServerSocket.Tpo $(DEPDIR)/libsipXport_la-OsSSLServerSocket.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsSSLServerSocket.cpp' object='libsipXport_la-OsSSLServerSocket.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsSSLServerSocket.lo `test -f 'os/OsSSLServerSocket.cpp' || echo '$(srcdir)/'`os/OsSSLServerSocket.cpp libsipXport_la-OsSysLog.lo: os/OsSysLog.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsSysLog.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsSysLog.Tpo -c -o libsipXport_la-OsSysLog.lo `test -f 'os/OsSysLog.cpp' || echo '$(srcdir)/'`os/OsSysLog.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsSysLog.Tpo $(DEPDIR)/libsipXport_la-OsSysLog.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsSysLog.cpp' object='libsipXport_la-OsSysLog.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsSysLog.lo `test -f 'os/OsSysLog.cpp' || echo '$(srcdir)/'`os/OsSysLog.cpp libsipXport_la-OsSysLogFacilities.lo: os/OsSysLogFacilities.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsSysLogFacilities.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsSysLogFacilities.Tpo -c -o libsipXport_la-OsSysLogFacilities.lo `test -f 'os/OsSysLogFacilities.cpp' || echo '$(srcdir)/'`os/OsSysLogFacilities.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsSysLogFacilities.Tpo $(DEPDIR)/libsipXport_la-OsSysLogFacilities.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsSysLogFacilities.cpp' object='libsipXport_la-OsSysLogFacilities.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsSysLogFacilities.lo `test -f 'os/OsSysLogFacilities.cpp' || echo '$(srcdir)/'`os/OsSysLogFacilities.cpp libsipXport_la-OsSysLogMsg.lo: os/OsSysLogMsg.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsSysLogMsg.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsSysLogMsg.Tpo -c -o libsipXport_la-OsSysLogMsg.lo `test -f 'os/OsSysLogMsg.cpp' || echo '$(srcdir)/'`os/OsSysLogMsg.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsSysLogMsg.Tpo $(DEPDIR)/libsipXport_la-OsSysLogMsg.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsSysLogMsg.cpp' object='libsipXport_la-OsSysLogMsg.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsSysLogMsg.lo `test -f 'os/OsSysLogMsg.cpp' || echo '$(srcdir)/'`os/OsSysLogMsg.cpp libsipXport_la-OsSysLogTask.lo: os/OsSysLogTask.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsSysLogTask.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsSysLogTask.Tpo -c -o libsipXport_la-OsSysLogTask.lo `test -f 'os/OsSysLogTask.cpp' || echo '$(srcdir)/'`os/OsSysLogTask.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsSysLogTask.Tpo $(DEPDIR)/libsipXport_la-OsSysLogTask.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsSysLogTask.cpp' object='libsipXport_la-OsSysLogTask.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsSysLogTask.lo `test -f 'os/OsSysLogTask.cpp' || echo '$(srcdir)/'`os/OsSysLogTask.cpp libsipXport_la-OsTask.lo: os/OsTask.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsTask.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsTask.Tpo -c -o libsipXport_la-OsTask.lo `test -f 'os/OsTask.cpp' || echo '$(srcdir)/'`os/OsTask.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsTask.Tpo $(DEPDIR)/libsipXport_la-OsTask.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTask.cpp' object='libsipXport_la-OsTask.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsTask.lo `test -f 'os/OsTask.cpp' || echo '$(srcdir)/'`os/OsTask.cpp libsipXport_la-OsTime.lo: os/OsTime.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsTime.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsTime.Tpo -c -o libsipXport_la-OsTime.lo `test -f 'os/OsTime.cpp' || echo '$(srcdir)/'`os/OsTime.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsTime.Tpo $(DEPDIR)/libsipXport_la-OsTime.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTime.cpp' object='libsipXport_la-OsTime.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsTime.lo `test -f 'os/OsTime.cpp' || echo '$(srcdir)/'`os/OsTime.cpp libsipXport_la-OsTimeLog.lo: os/OsTimeLog.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsTimeLog.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsTimeLog.Tpo -c -o libsipXport_la-OsTimeLog.lo `test -f 'os/OsTimeLog.cpp' || echo '$(srcdir)/'`os/OsTimeLog.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsTimeLog.Tpo $(DEPDIR)/libsipXport_la-OsTimeLog.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTimeLog.cpp' object='libsipXport_la-OsTimeLog.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsTimeLog.lo `test -f 'os/OsTimeLog.cpp' || echo '$(srcdir)/'`os/OsTimeLog.cpp libsipXport_la-OsTimer.lo: os/OsTimer.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsTimer.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsTimer.Tpo -c -o libsipXport_la-OsTimer.lo `test -f 'os/OsTimer.cpp' || echo '$(srcdir)/'`os/OsTimer.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsTimer.Tpo $(DEPDIR)/libsipXport_la-OsTimer.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTimer.cpp' object='libsipXport_la-OsTimer.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsTimer.lo `test -f 'os/OsTimer.cpp' || echo '$(srcdir)/'`os/OsTimer.cpp libsipXport_la-OsTimerMsg.lo: os/OsTimerMsg.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsTimerMsg.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsTimerMsg.Tpo -c -o libsipXport_la-OsTimerMsg.lo `test -f 'os/OsTimerMsg.cpp' || echo '$(srcdir)/'`os/OsTimerMsg.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsTimerMsg.Tpo $(DEPDIR)/libsipXport_la-OsTimerMsg.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTimerMsg.cpp' object='libsipXport_la-OsTimerMsg.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsTimerMsg.lo `test -f 'os/OsTimerMsg.cpp' || echo '$(srcdir)/'`os/OsTimerMsg.cpp libsipXport_la-OsTimerTask.lo: os/OsTimerTask.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsTimerTask.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsTimerTask.Tpo -c -o libsipXport_la-OsTimerTask.lo `test -f 'os/OsTimerTask.cpp' || echo '$(srcdir)/'`os/OsTimerTask.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsTimerTask.Tpo $(DEPDIR)/libsipXport_la-OsTimerTask.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTimerTask.cpp' object='libsipXport_la-OsTimerTask.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsTimerTask.lo `test -f 'os/OsTimerTask.cpp' || echo '$(srcdir)/'`os/OsTimerTask.cpp libsipXport_la-OsTLSServerSocket.lo: os/OsTLSServerSocket.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsTLSServerSocket.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsTLSServerSocket.Tpo -c -o libsipXport_la-OsTLSServerSocket.lo `test -f 'os/OsTLSServerSocket.cpp' || echo '$(srcdir)/'`os/OsTLSServerSocket.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsTLSServerSocket.Tpo $(DEPDIR)/libsipXport_la-OsTLSServerSocket.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTLSServerSocket.cpp' object='libsipXport_la-OsTLSServerSocket.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsTLSServerSocket.lo `test -f 'os/OsTLSServerSocket.cpp' || echo '$(srcdir)/'`os/OsTLSServerSocket.cpp libsipXport_la-OsTLSConnectionSocket.lo: os/OsTLSConnectionSocket.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsTLSConnectionSocket.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsTLSConnectionSocket.Tpo -c -o libsipXport_la-OsTLSConnectionSocket.lo `test -f 'os/OsTLSConnectionSocket.cpp' || echo '$(srcdir)/'`os/OsTLSConnectionSocket.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsTLSConnectionSocket.Tpo $(DEPDIR)/libsipXport_la-OsTLSConnectionSocket.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTLSConnectionSocket.cpp' object='libsipXport_la-OsTLSConnectionSocket.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsTLSConnectionSocket.lo `test -f 'os/OsTLSConnectionSocket.cpp' || echo '$(srcdir)/'`os/OsTLSConnectionSocket.cpp libsipXport_la-OsTLSClientConnectionSocket.lo: os/OsTLSClientConnectionSocket.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsTLSClientConnectionSocket.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsTLSClientConnectionSocket.Tpo -c -o libsipXport_la-OsTLSClientConnectionSocket.lo `test -f 'os/OsTLSClientConnectionSocket.cpp' || echo '$(srcdir)/'`os/OsTLSClientConnectionSocket.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsTLSClientConnectionSocket.Tpo $(DEPDIR)/libsipXport_la-OsTLSClientConnectionSocket.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTLSClientConnectionSocket.cpp' object='libsipXport_la-OsTLSClientConnectionSocket.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsTLSClientConnectionSocket.lo `test -f 'os/OsTLSClientConnectionSocket.cpp' || echo '$(srcdir)/'`os/OsTLSClientConnectionSocket.cpp libsipXport_la-OsTokenizer.lo: os/OsTokenizer.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsTokenizer.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsTokenizer.Tpo -c -o libsipXport_la-OsTokenizer.lo `test -f 'os/OsTokenizer.cpp' || echo '$(srcdir)/'`os/OsTokenizer.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsTokenizer.Tpo $(DEPDIR)/libsipXport_la-OsTokenizer.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTokenizer.cpp' object='libsipXport_la-OsTokenizer.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsTokenizer.lo `test -f 'os/OsTokenizer.cpp' || echo '$(srcdir)/'`os/OsTokenizer.cpp libsipXport_la-OsUtil.lo: os/OsUtil.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsUtil.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsUtil.Tpo -c -o libsipXport_la-OsUtil.lo `test -f 'os/OsUtil.cpp' || echo '$(srcdir)/'`os/OsUtil.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsUtil.Tpo $(DEPDIR)/libsipXport_la-OsUtil.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsUtil.cpp' object='libsipXport_la-OsUtil.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsUtil.lo `test -f 'os/OsUtil.cpp' || echo '$(srcdir)/'`os/OsUtil.cpp libsipXport_la-StunMessage.lo: os/StunMessage.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-StunMessage.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-StunMessage.Tpo -c -o libsipXport_la-StunMessage.lo `test -f 'os/StunMessage.cpp' || echo '$(srcdir)/'`os/StunMessage.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-StunMessage.Tpo $(DEPDIR)/libsipXport_la-StunMessage.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/StunMessage.cpp' object='libsipXport_la-StunMessage.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-StunMessage.lo `test -f 'os/StunMessage.cpp' || echo '$(srcdir)/'`os/StunMessage.cpp libsipXport_la-StunUtils.lo: os/StunUtils.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-StunUtils.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-StunUtils.Tpo -c -o libsipXport_la-StunUtils.lo `test -f 'os/StunUtils.cpp' || echo '$(srcdir)/'`os/StunUtils.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-StunUtils.Tpo $(DEPDIR)/libsipXport_la-StunUtils.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/StunUtils.cpp' object='libsipXport_la-StunUtils.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-StunUtils.lo `test -f 'os/StunUtils.cpp' || echo '$(srcdir)/'`os/StunUtils.cpp libsipXport_la-TurnMessage.lo: os/TurnMessage.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-TurnMessage.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-TurnMessage.Tpo -c -o libsipXport_la-TurnMessage.lo `test -f 'os/TurnMessage.cpp' || echo '$(srcdir)/'`os/TurnMessage.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-TurnMessage.Tpo $(DEPDIR)/libsipXport_la-TurnMessage.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/TurnMessage.cpp' object='libsipXport_la-TurnMessage.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-TurnMessage.lo `test -f 'os/TurnMessage.cpp' || echo '$(srcdir)/'`os/TurnMessage.cpp libsipXport_la-OsMsgQShared.lo: os/shared/OsMsgQShared.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsMsgQShared.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsMsgQShared.Tpo -c -o libsipXport_la-OsMsgQShared.lo `test -f 'os/shared/OsMsgQShared.cpp' || echo '$(srcdir)/'`os/shared/OsMsgQShared.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsMsgQShared.Tpo $(DEPDIR)/libsipXport_la-OsMsgQShared.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/shared/OsMsgQShared.cpp' object='libsipXport_la-OsMsgQShared.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsMsgQShared.lo `test -f 'os/shared/OsMsgQShared.cpp' || echo '$(srcdir)/'`os/shared/OsMsgQShared.cpp libsipXport_la-OsTimerMessage.lo: os/shared/OsTimerMessage.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsTimerMessage.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsTimerMessage.Tpo -c -o libsipXport_la-OsTimerMessage.lo `test -f 'os/shared/OsTimerMessage.cpp' || echo '$(srcdir)/'`os/shared/OsTimerMessage.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsTimerMessage.Tpo $(DEPDIR)/libsipXport_la-OsTimerMessage.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/shared/OsTimerMessage.cpp' object='libsipXport_la-OsTimerMessage.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsTimerMessage.lo `test -f 'os/shared/OsTimerMessage.cpp' || echo '$(srcdir)/'`os/shared/OsTimerMessage.cpp libsipXport_la-AdapterInfo.lo: os/linux/AdapterInfo.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-AdapterInfo.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-AdapterInfo.Tpo -c -o libsipXport_la-AdapterInfo.lo `test -f 'os/linux/AdapterInfo.cpp' || echo '$(srcdir)/'`os/linux/AdapterInfo.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-AdapterInfo.Tpo $(DEPDIR)/libsipXport_la-AdapterInfo.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/linux/AdapterInfo.cpp' object='libsipXport_la-AdapterInfo.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-AdapterInfo.lo `test -f 'os/linux/AdapterInfo.cpp' || echo '$(srcdir)/'`os/linux/AdapterInfo.cpp libsipXport_la-OsBSemLinux.lo: os/linux/OsBSemLinux.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsBSemLinux.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsBSemLinux.Tpo -c -o libsipXport_la-OsBSemLinux.lo `test -f 'os/linux/OsBSemLinux.cpp' || echo '$(srcdir)/'`os/linux/OsBSemLinux.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsBSemLinux.Tpo $(DEPDIR)/libsipXport_la-OsBSemLinux.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/linux/OsBSemLinux.cpp' object='libsipXport_la-OsBSemLinux.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsBSemLinux.lo `test -f 'os/linux/OsBSemLinux.cpp' || echo '$(srcdir)/'`os/linux/OsBSemLinux.cpp libsipXport_la-OsCSemLinux.lo: os/linux/OsCSemLinux.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsCSemLinux.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsCSemLinux.Tpo -c -o libsipXport_la-OsCSemLinux.lo `test -f 'os/linux/OsCSemLinux.cpp' || echo '$(srcdir)/'`os/linux/OsCSemLinux.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsCSemLinux.Tpo $(DEPDIR)/libsipXport_la-OsCSemLinux.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/linux/OsCSemLinux.cpp' object='libsipXport_la-OsCSemLinux.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsCSemLinux.lo `test -f 'os/linux/OsCSemLinux.cpp' || echo '$(srcdir)/'`os/linux/OsCSemLinux.cpp libsipXport_la-OsDateTimeLinux.lo: os/linux/OsDateTimeLinux.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsDateTimeLinux.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsDateTimeLinux.Tpo -c -o libsipXport_la-OsDateTimeLinux.lo `test -f 'os/linux/OsDateTimeLinux.cpp' || echo '$(srcdir)/'`os/linux/OsDateTimeLinux.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsDateTimeLinux.Tpo $(DEPDIR)/libsipXport_la-OsDateTimeLinux.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/linux/OsDateTimeLinux.cpp' object='libsipXport_la-OsDateTimeLinux.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsDateTimeLinux.lo `test -f 'os/linux/OsDateTimeLinux.cpp' || echo '$(srcdir)/'`os/linux/OsDateTimeLinux.cpp libsipXport_la-OsDirLinux.lo: os/linux/OsDirLinux.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsDirLinux.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsDirLinux.Tpo -c -o libsipXport_la-OsDirLinux.lo `test -f 'os/linux/OsDirLinux.cpp' || echo '$(srcdir)/'`os/linux/OsDirLinux.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsDirLinux.Tpo $(DEPDIR)/libsipXport_la-OsDirLinux.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/linux/OsDirLinux.cpp' object='libsipXport_la-OsDirLinux.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsDirLinux.lo `test -f 'os/linux/OsDirLinux.cpp' || echo '$(srcdir)/'`os/linux/OsDirLinux.cpp libsipXport_la-OsFileInfoLinux.lo: os/linux/OsFileInfoLinux.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsFileInfoLinux.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsFileInfoLinux.Tpo -c -o libsipXport_la-OsFileInfoLinux.lo `test -f 'os/linux/OsFileInfoLinux.cpp' || echo '$(srcdir)/'`os/linux/OsFileInfoLinux.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsFileInfoLinux.Tpo $(DEPDIR)/libsipXport_la-OsFileInfoLinux.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/linux/OsFileInfoLinux.cpp' object='libsipXport_la-OsFileInfoLinux.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsFileInfoLinux.lo `test -f 'os/linux/OsFileInfoLinux.cpp' || echo '$(srcdir)/'`os/linux/OsFileInfoLinux.cpp libsipXport_la-OsFileIteratorLinux.lo: os/linux/OsFileIteratorLinux.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsFileIteratorLinux.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsFileIteratorLinux.Tpo -c -o libsipXport_la-OsFileIteratorLinux.lo `test -f 'os/linux/OsFileIteratorLinux.cpp' || echo '$(srcdir)/'`os/linux/OsFileIteratorLinux.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsFileIteratorLinux.Tpo $(DEPDIR)/libsipXport_la-OsFileIteratorLinux.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/linux/OsFileIteratorLinux.cpp' object='libsipXport_la-OsFileIteratorLinux.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsFileIteratorLinux.lo `test -f 'os/linux/OsFileIteratorLinux.cpp' || echo '$(srcdir)/'`os/linux/OsFileIteratorLinux.cpp libsipXport_la-OsFileLinux.lo: os/linux/OsFileLinux.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsFileLinux.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsFileLinux.Tpo -c -o libsipXport_la-OsFileLinux.lo `test -f 'os/linux/OsFileLinux.cpp' || echo '$(srcdir)/'`os/linux/OsFileLinux.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsFileLinux.Tpo $(DEPDIR)/libsipXport_la-OsFileLinux.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/linux/OsFileLinux.cpp' object='libsipXport_la-OsFileLinux.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsFileLinux.lo `test -f 'os/linux/OsFileLinux.cpp' || echo '$(srcdir)/'`os/linux/OsFileLinux.cpp libsipXport_la-OsMutexLinux.lo: os/linux/OsMutexLinux.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsMutexLinux.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsMutexLinux.Tpo -c -o libsipXport_la-OsMutexLinux.lo `test -f 'os/linux/OsMutexLinux.cpp' || echo '$(srcdir)/'`os/linux/OsMutexLinux.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsMutexLinux.Tpo $(DEPDIR)/libsipXport_la-OsMutexLinux.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/linux/OsMutexLinux.cpp' object='libsipXport_la-OsMutexLinux.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsMutexLinux.lo `test -f 'os/linux/OsMutexLinux.cpp' || echo '$(srcdir)/'`os/linux/OsMutexLinux.cpp libsipXport_la-OsPathLinux.lo: os/linux/OsPathLinux.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsPathLinux.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsPathLinux.Tpo -c -o libsipXport_la-OsPathLinux.lo `test -f 'os/linux/OsPathLinux.cpp' || echo '$(srcdir)/'`os/linux/OsPathLinux.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsPathLinux.Tpo $(DEPDIR)/libsipXport_la-OsPathLinux.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/linux/OsPathLinux.cpp' object='libsipXport_la-OsPathLinux.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsPathLinux.lo `test -f 'os/linux/OsPathLinux.cpp' || echo '$(srcdir)/'`os/linux/OsPathLinux.cpp libsipXport_la-OsProcessIteratorLinux.lo: os/linux/OsProcessIteratorLinux.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsProcessIteratorLinux.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsProcessIteratorLinux.Tpo -c -o libsipXport_la-OsProcessIteratorLinux.lo `test -f 'os/linux/OsProcessIteratorLinux.cpp' || echo '$(srcdir)/'`os/linux/OsProcessIteratorLinux.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsProcessIteratorLinux.Tpo $(DEPDIR)/libsipXport_la-OsProcessIteratorLinux.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/linux/OsProcessIteratorLinux.cpp' object='libsipXport_la-OsProcessIteratorLinux.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsProcessIteratorLinux.lo `test -f 'os/linux/OsProcessIteratorLinux.cpp' || echo '$(srcdir)/'`os/linux/OsProcessIteratorLinux.cpp libsipXport_la-OsProcessLinux.lo: os/linux/OsProcessLinux.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsProcessLinux.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsProcessLinux.Tpo -c -o libsipXport_la-OsProcessLinux.lo `test -f 'os/linux/OsProcessLinux.cpp' || echo '$(srcdir)/'`os/linux/OsProcessLinux.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsProcessLinux.Tpo $(DEPDIR)/libsipXport_la-OsProcessLinux.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/linux/OsProcessLinux.cpp' object='libsipXport_la-OsProcessLinux.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsProcessLinux.lo `test -f 'os/linux/OsProcessLinux.cpp' || echo '$(srcdir)/'`os/linux/OsProcessLinux.cpp libsipXport_la-OsRWMutexLinux.lo: os/linux/OsRWMutexLinux.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsRWMutexLinux.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsRWMutexLinux.Tpo -c -o libsipXport_la-OsRWMutexLinux.lo `test -f 'os/linux/OsRWMutexLinux.cpp' || echo '$(srcdir)/'`os/linux/OsRWMutexLinux.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsRWMutexLinux.Tpo $(DEPDIR)/libsipXport_la-OsRWMutexLinux.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/linux/OsRWMutexLinux.cpp' object='libsipXport_la-OsRWMutexLinux.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsRWMutexLinux.lo `test -f 'os/linux/OsRWMutexLinux.cpp' || echo '$(srcdir)/'`os/linux/OsRWMutexLinux.cpp libsipXport_la-OsSharedLibMgrLinux.lo: os/linux/OsSharedLibMgrLinux.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsSharedLibMgrLinux.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsSharedLibMgrLinux.Tpo -c -o libsipXport_la-OsSharedLibMgrLinux.lo `test -f 'os/linux/OsSharedLibMgrLinux.cpp' || echo '$(srcdir)/'`os/linux/OsSharedLibMgrLinux.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsSharedLibMgrLinux.Tpo $(DEPDIR)/libsipXport_la-OsSharedLibMgrLinux.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/linux/OsSharedLibMgrLinux.cpp' object='libsipXport_la-OsSharedLibMgrLinux.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsSharedLibMgrLinux.lo `test -f 'os/linux/OsSharedLibMgrLinux.cpp' || echo '$(srcdir)/'`os/linux/OsSharedLibMgrLinux.cpp libsipXport_la-OsTaskLinux.lo: os/linux/OsTaskLinux.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsTaskLinux.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsTaskLinux.Tpo -c -o libsipXport_la-OsTaskLinux.lo `test -f 'os/linux/OsTaskLinux.cpp' || echo '$(srcdir)/'`os/linux/OsTaskLinux.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsTaskLinux.Tpo $(DEPDIR)/libsipXport_la-OsTaskLinux.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/linux/OsTaskLinux.cpp' object='libsipXport_la-OsTaskLinux.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsTaskLinux.lo `test -f 'os/linux/OsTaskLinux.cpp' || echo '$(srcdir)/'`os/linux/OsTaskLinux.cpp libsipXport_la-OsUtilLinux.lo: os/linux/OsUtilLinux.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-OsUtilLinux.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-OsUtilLinux.Tpo -c -o libsipXport_la-OsUtilLinux.lo `test -f 'os/linux/OsUtilLinux.cpp' || echo '$(srcdir)/'`os/linux/OsUtilLinux.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-OsUtilLinux.Tpo $(DEPDIR)/libsipXport_la-OsUtilLinux.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/linux/OsUtilLinux.cpp' object='libsipXport_la-OsUtilLinux.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-OsUtilLinux.lo `test -f 'os/linux/OsUtilLinux.cpp' || echo '$(srcdir)/'`os/linux/OsUtilLinux.cpp libsipXport_la-tinystr.lo: xmlparser/tinystr.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-tinystr.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-tinystr.Tpo -c -o libsipXport_la-tinystr.lo `test -f 'xmlparser/tinystr.cpp' || echo '$(srcdir)/'`xmlparser/tinystr.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-tinystr.Tpo $(DEPDIR)/libsipXport_la-tinystr.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='xmlparser/tinystr.cpp' object='libsipXport_la-tinystr.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-tinystr.lo `test -f 'xmlparser/tinystr.cpp' || echo '$(srcdir)/'`xmlparser/tinystr.cpp libsipXport_la-tinyxml.lo: xmlparser/tinyxml.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-tinyxml.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-tinyxml.Tpo -c -o libsipXport_la-tinyxml.lo `test -f 'xmlparser/tinyxml.cpp' || echo '$(srcdir)/'`xmlparser/tinyxml.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-tinyxml.Tpo $(DEPDIR)/libsipXport_la-tinyxml.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='xmlparser/tinyxml.cpp' object='libsipXport_la-tinyxml.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-tinyxml.lo `test -f 'xmlparser/tinyxml.cpp' || echo '$(srcdir)/'`xmlparser/tinyxml.cpp libsipXport_la-tinyxmlerror.lo: xmlparser/tinyxmlerror.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-tinyxmlerror.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-tinyxmlerror.Tpo -c -o libsipXport_la-tinyxmlerror.lo `test -f 'xmlparser/tinyxmlerror.cpp' || echo '$(srcdir)/'`xmlparser/tinyxmlerror.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-tinyxmlerror.Tpo $(DEPDIR)/libsipXport_la-tinyxmlerror.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='xmlparser/tinyxmlerror.cpp' object='libsipXport_la-tinyxmlerror.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-tinyxmlerror.lo `test -f 'xmlparser/tinyxmlerror.cpp' || echo '$(srcdir)/'`xmlparser/tinyxmlerror.cpp libsipXport_la-tinyxmlparser.lo: xmlparser/tinyxmlparser.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-tinyxmlparser.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-tinyxmlparser.Tpo -c -o libsipXport_la-tinyxmlparser.lo `test -f 'xmlparser/tinyxmlparser.cpp' || echo '$(srcdir)/'`xmlparser/tinyxmlparser.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-tinyxmlparser.Tpo $(DEPDIR)/libsipXport_la-tinyxmlparser.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='xmlparser/tinyxmlparser.cpp' object='libsipXport_la-tinyxmlparser.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-tinyxmlparser.lo `test -f 'xmlparser/tinyxmlparser.cpp' || echo '$(srcdir)/'`xmlparser/tinyxmlparser.cpp libsipXport_la-TiXmlIterator.lo: xmlparser/TiXmlIterator.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-TiXmlIterator.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-TiXmlIterator.Tpo -c -o libsipXport_la-TiXmlIterator.lo `test -f 'xmlparser/TiXmlIterator.cpp' || echo '$(srcdir)/'`xmlparser/TiXmlIterator.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-TiXmlIterator.Tpo $(DEPDIR)/libsipXport_la-TiXmlIterator.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='xmlparser/TiXmlIterator.cpp' object='libsipXport_la-TiXmlIterator.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-TiXmlIterator.lo `test -f 'xmlparser/TiXmlIterator.cpp' || echo '$(srcdir)/'`xmlparser/TiXmlIterator.cpp libsipXport_la-ExtractContent.lo: xmlparser/ExtractContent.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-ExtractContent.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-ExtractContent.Tpo -c -o libsipXport_la-ExtractContent.lo `test -f 'xmlparser/ExtractContent.cpp' || echo '$(srcdir)/'`xmlparser/ExtractContent.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-ExtractContent.Tpo $(DEPDIR)/libsipXport_la-ExtractContent.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='xmlparser/ExtractContent.cpp' object='libsipXport_la-ExtractContent.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-ExtractContent.lo `test -f 'xmlparser/ExtractContent.cpp' || echo '$(srcdir)/'`xmlparser/ExtractContent.cpp libsipXport_la-@PACKAGE@-buildstamp.lo: $(top_srcdir)/config/@PACKAGE@-buildstamp.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -MT libsipXport_la-@PACKAGE@-buildstamp.lo -MD -MP -MF $(DEPDIR)/libsipXport_la-@PACKAGE@-buildstamp.Tpo -c -o libsipXport_la-@PACKAGE@-buildstamp.lo `test -f '$(top_srcdir)/config/@PACKAGE@-buildstamp.cpp' || echo '$(srcdir)/'`$(top_srcdir)/config/@PACKAGE@-buildstamp.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXport_la-@PACKAGE@-buildstamp.Tpo $(DEPDIR)/libsipXport_la-@PACKAGE@-buildstamp.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$(top_srcdir)/config/@PACKAGE@-buildstamp.cpp' object='libsipXport_la-@PACKAGE@-buildstamp.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libsipXport_la_CXXFLAGS) $(CXXFLAGS) -c -o libsipXport_la-@PACKAGE@-buildstamp.lo `test -f '$(top_srcdir)/config/@PACKAGE@-buildstamp.cpp' || echo '$(srcdir)/'`$(top_srcdir)/config/@PACKAGE@-buildstamp.cpp mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run `make' without going through this Makefile. # To change the values of `make' variables: instead of editing Makefiles, # (1) if the variable is set in `config.status', edit `config.status' # (which will cause the Makefiles to be regenerated when you run `make'); # (2) otherwise, pass the desired values on the `make' command line. $(RECURSIVE_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ list='$(SUBDIRS)'; for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" $(RECURSIVE_CLEAN_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ rev=''; for subdir in $$list; do \ if test "$$subdir" = "."; then :; else \ rev="$$subdir $$rev"; \ fi; \ done; \ rev="$$rev ."; \ target=`echo $@ | sed s/-recursive//`; \ for subdir in $$rev; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done && test -z "$$fail" tags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ done ctags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ done ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(LTLIBRARIES) installdirs: installdirs-recursive installdirs-am: for dir in "$(DESTDIR)$(libdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ mostlyclean-am distclean: distclean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-libLTLIBRARIES install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: uninstall-libLTLIBRARIES .MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \ install-am install-strip tags-recursive .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ all all-am check check-am clean clean-generic \ clean-libLTLIBRARIES clean-libtool ctags ctags-recursive \ distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-libLTLIBRARIES install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs installdirs-am \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags tags-recursive uninstall uninstall-am \ uninstall-libLTLIBRARIES # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: sipxtapi-3.3.0~test17/sipXportLib/src/test/0000755000175000017500000000000012321445024021420 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/src/test/os/0000755000175000017500000000000012321445024022041 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsConfigDbTest.cpp0000644000175000017500000002415212205613256025373 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2012 SIPez LLC All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #define CONFIG_WITH_COMMENTS_DUPLICATES \ "# \n\ \n\ # Line 3\n\ # Line 4\n\ PARAM1 : 1\n\ PARAM2 : A\n\ \n\ # Duplicate param below should get removed\n\ PARAM1 : 2\n\ \n\ \n\ # Last line comment \n" #define CONFIG_WITH_COMMENTS_DUPLICATES_AFTER_UPDATE \ "# \n\ \n\ # Line 3\n\ # Line 4\n\ PARAM1 : 2\n\ PARAM2 : B\n\ \n\ # Duplicate param below should get removed\n\ \n\ \n\ # Last line comment \n\ PARAM3 : NEW\n" /** * Test OsConfigDb API */ class OsConfigDbTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsConfigDbTest); CPPUNIT_TEST(testCreators); CPPUNIT_TEST(testManipulators); CPPUNIT_TEST(testUpdate); CPPUNIT_TEST(testAccessors); CPPUNIT_TEST_SUITE_END(); public: void testCreators() { OsConfigDb *pDb = new OsConfigDb(); // create an empty database CPPUNIT_ASSERT_MESSAGE("verify that it looks empty", pDb->isEmpty()); CPPUNIT_ASSERT_MESSAGE("has zero entries", pDb->numEntries()==0); delete pDb; } void testManipulators() { OsConfigDb *pDb = new OsConfigDb(); pDb->set("Key1", "Value1"); CPPUNIT_ASSERT_MESSAGE("verify that the database is not empty", !pDb->isEmpty()); CPPUNIT_ASSERT_MESSAGE("has one entry", pDb->numEntries()==1); // test the remove() method // // We put the following block in its own scope so that the UtlString // reference (stored in "value") is released as a side effect of going // out of scope. Otherwise, it will look like a memory leak. { UtlString value; pDb->remove("Key1"); CPPUNIT_ASSERT_MESSAGE("verify that it looks empty", pDb->isEmpty()); CPPUNIT_ASSERT_MESSAGE("has zero entries", pDb->numEntries()==0); pDb->set("Key1", "Value1"); // add the entry back pDb->set("Key1", "Value1b"); // change the value for an existing entry CPPUNIT_ASSERT_MESSAGE("verify that the database is not empty", !pDb->isEmpty()); CPPUNIT_ASSERT_EQUAL_MESSAGE("has one entry", 1, pDb->numEntries()); OsStatus res = pDb->get("Key1", value); CPPUNIT_ASSERT(res == OS_SUCCESS); CPPUNIT_ASSERT_MESSAGE("that contains the revised value", value.compareTo("Value1b") == 0); pDb->set("Key2", "Value2"); pDb->set("Key3", "Value3"); pDb->set("Key4", "Value4"); CPPUNIT_ASSERT_MESSAGE("check the number of entries", pDb->numEntries()==4); value.remove(0); } // test the storeToFile() method pDb->storeToFile("tmpdb"); // store the config db to the file delete pDb; // delete the database // test the loadFromFile() method // // We put the following block in its own scope so that the UtlString // reference (stored in "value") is released as a side effect of going // out of scope. Otherwise, it will look like a memory leak. { UtlString value; pDb = new OsConfigDb(); // create an empty database pDb->loadFromFile("tmpdb"); // load the data from a file } CPPUNIT_ASSERT_MESSAGE("verify the database is not empty", !pDb->isEmpty()); CPPUNIT_ASSERT_MESSAGE("has four entries", pDb->numEntries()==4); UtlString value; OsStatus res = pDb->get("Key1", value); CPPUNIT_ASSERT_MESSAGE("contains correct data", res == OS_SUCCESS && value.compareTo("Value1b") == 0); res = pDb->get("Key2", value); CPPUNIT_ASSERT_MESSAGE("contains correct data", res == OS_SUCCESS && value.compareTo("Value2") == 0); res = pDb->get("Key3", value); CPPUNIT_ASSERT_MESSAGE("contains correct data", res == OS_SUCCESS && value.compareTo("Value3") == 0); res = pDb->get("Key4", value); CPPUNIT_ASSERT_MESSAGE("contains correct data", res == OS_SUCCESS && value.compareTo("Value4") == 0); delete pDb; // delete the database value.remove(0); } void testUpdate() { // Create reference config files UtlString refConfigFile("testConfig.conf"); UtlString refConfigContents(CONFIG_WITH_COMMENTS_DUPLICATES); long fileLength = OsFile::openAndWrite(refConfigFile, refConfigContents); CPPUNIT_ASSERT_MESSAGE("failed to write ref config file", fileLength > 0); OsConfigDb configDb; configDb.loadFromFile(refConfigFile); CPPUNIT_ASSERT_EQUAL(configDb.numEntries(), 2); UtlString value; configDb.get("PARAM2", value); CPPUNIT_ASSERT_EQUAL(value, "A"); configDb.set("PARAM2", "B"); configDb.set("PARAM3", "NEW"); configDb.updateFile(refConfigFile); UtlString actualModifiedConfigContent; fileLength = OsFile::openAndRead(refConfigFile, actualModifiedConfigContent); UtlString expectedModifiedConfigContent(CONFIG_WITH_COMMENTS_DUPLICATES_AFTER_UPDATE); CPPUNIT_ASSERT_EQUAL(expectedModifiedConfigContent, actualModifiedConfigContent); } void testAccessors() { #ifdef ANDROID CPPUNIT_ASSERT_MESSAGE("ANDROID_HANG", 0); return; #endif OsConfigDb *pDb = new OsConfigDb(); // the get() method is tested by testManipulators() // test the getNext() method // // We put the following block in its own scope so that the UtlString // references (stored in "name" and "value") are released as a side effect // of going out of scope. Otherwise, it will look like a memory leak. { UtlString name; UtlString value; pDb->set("Key3", "Value3"); // add several entries (not in pDb->set("Key2", "Value2"); // alphabetical or reverse alphabetical pDb->set("Key4", "Value4"); // order pDb->set("Key1", "Value1"); CPPUNIT_ASSERT_MESSAGE("verify that the database is not empty", !pDb->isEmpty()); CPPUNIT_ASSERT_MESSAGE("has four entries", pDb->numEntries()==4); OsStatus res = pDb->getNext("", name, value); // call getNext("", ...) CPPUNIT_ASSERT_MESSAGE("verify that Key1/Value1", res == OS_SUCCESS && name.compareTo("Key1") == 0 && // is returned value.compareTo("Value1") == 0); res = pDb->getNext("Key1", name, value); CPPUNIT_ASSERT_MESSAGE("call getNext(\"Key1\", ...)", res == OS_SUCCESS && // verify that Key2/Value2 name.compareTo("Key2") == 0 && // is returned value.compareTo("Value2") == 0); res = pDb->getNext("Key2", name, value); CPPUNIT_ASSERT_MESSAGE("call getNext(\"Key2\", ...)", res == OS_SUCCESS && // verify that Key3/Value3 name.compareTo("Key3") == 0 && // is returned value.compareTo("Value3") == 0); res = pDb->getNext("Key3", name, value); CPPUNIT_ASSERT_MESSAGE("call getNext(\"Key3\", ...)", res == OS_SUCCESS && name.compareTo("Key4") == 0 && value.compareTo("Value4") == 0); res = pDb->getNext("Key4", name, value); CPPUNIT_ASSERT_MESSAGE("call getNext(\"Key4\", ...)", res == OS_NO_MORE_DATA && name.compareTo("") == 0 && value.compareTo("") == 0); res = pDb->getNext("XXX", name, value); CPPUNIT_ASSERT_MESSAGE("call getNext with a key not in the database and verify", res == OS_NOT_FOUND && name.compareTo("") == 0 && // that empty strings are value.compareTo("") == 0); // returned for the next name // and value pair. delete pDb; // delete the database name.remove(0); value.remove(0); } } }; #ifdef WINCE #pragma message( "OsConfigDbTest disabled undef Win CE" ) #else CPPUNIT_TEST_SUITE_REGISTRATION(OsConfigDbTest); #endif sipxtapi-3.3.0~test17/sipXportLib/src/test/os/UnitTestLogHooks.cpp0000644000175000017500000000176512205613256026010 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2012 SIPez LLC All rights reserved. // // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #define LOG_DIR "./" void beginLogHook(const char* testClassName) { UtlString testLogFilename(LOG_DIR); testLogFilename.append(testClassName); testLogFilename.append(".log"); OsSysLog::initialize(0, "UnitTest"); OsSysLog::setLoggingPriority(PRI_DEBUG); // Remove old log before starting test OsFileSystem::remove(testLogFilename, FALSE, TRUE); OsSysLog::setOutputFile(0, testLogFilename); } void endLogHook(const char* testClassName) { OsSysLog::flush(); OsSysLog::shutdown(); } static int initLogHooks() { SipxPortUnitTestEnvironment::setLogHookBegin(beginLogHook); SipxPortUnitTestEnvironment::setLogHookEnd(endLogHook); return(0); } int sLogHookFoo = initLogHooks(); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsAdapterInfoTest.cpp0000644000175000017500000000225212205613256026111 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2009 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2009 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #define MAX_A 64 class OsAdapterInfoTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsAdapterInfoTest); CPPUNIT_TEST(testCount); CPPUNIT_TEST_SUITE_END(); public: void testCount() { const HostAdapterAddress *adapters[MAX_A]; int numAddrs = MAX_A; bool ret = getAllLocalHostIps(adapters, numAddrs); CPPUNIT_ASSERT(ret == true); CPPUNIT_ASSERT(numAddrs > 0); printf ("Found %d interface(s)\n", numAddrs); int i; for (int i = 0; i < numAddrs; i++) { printf("[%d] %s: %s\n", i, adapters[i]->mAdapter.data(), adapters[i]->mAddress.data()); } } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsAdapterInfoTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsCallbackTest.cpp0000644000175000017500000000222212205613256025406 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include /** Flag that callback function was called */ UtlBoolean gCallbackCalled; void setCallbackFlag(const intptr_t userData, const intptr_t eventData) { gCallbackCalled = TRUE; } class OsCallbackTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsCallbackTest); CPPUNIT_TEST(testCallback); CPPUNIT_TEST_SUITE_END(); public: void testCallback() { OsCallback* pCallback; pCallback = new OsCallback(12345, setCallbackFlag); gCallbackCalled = FALSE; pCallback->signal(67890); CPPUNIT_ASSERT(gCallbackCalled); delete pCallback; } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsCallbackTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsContactListTest.cpp0000644000175000017500000000674512205613256026157 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2010 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include /** This class is used to test the OsContact class. * * PLEASE READ THE README FILE THAT CAN FOUND IN THE SAME DIRECTORY AS * THIS FILE. The Readme describes the organization / flow of tests and * without reading this file, the following class (and all unit tests) * may not make a lot of sense and might be difficult to comprehend. */ class OsContactListTests : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsContactListTests); CPPUNIT_TEST(test) ; CPPUNIT_TEST_SUITE_END(); private: public: OsContactListTests() { } void setUp() { } void tearDown() { } ~OsContactListTests() { } /** Sandbox method for experimenting with the API Under Test. * This method MUST be empty when the test drivers are being * checked in (final checkin) to the repository. */ void DynaTest() { } /** Test an OsContactList class instance. */ void test() { OsContact contact1("192.168.0.1", 4141, OsSocket::TCP, IP4); OsContact contact2("192.168.0.1", 4242, OsSocket::UDP, IP6) ; OsContact contact3("192.168.0.2", 4242, OsSocket::UDP, IP6) ; OsContactList contactList; // insert the first one contactList.insert(&contact2); const OsContact* pContact = NULL; // no primary is set, so the first in the list is returned. pContact = contactList.getPrimary(); CPPUNIT_ASSERT(pContact != NULL); // verify equality CPPUNIT_ASSERT(pContact->isEqual(&contact2)); // verify number of records in list CPPUNIT_ASSERT(contactList.entries() == 1); // insert the second one at the end of the list contactList.insert(&contact1); // no primary is set, so the first in the list is returned. pContact = contactList.getPrimary(); CPPUNIT_ASSERT(pContact != NULL); // verify equality CPPUNIT_ASSERT(pContact->isEqual(&contact2)); // call setPrimary contactList.setPrimary(contact1); // get the primary contact pContact = contactList.getPrimary(); CPPUNIT_ASSERT(pContact != NULL); // verify equality CPPUNIT_ASSERT(pContact->isEqual(&contact1)); // verify number of records in list CPPUNIT_ASSERT(contactList.entries() == 2); // call setPrimary on a contact that is not already in the list contactList.setPrimary(contact3); // get the primary contact pContact = contactList.getPrimary(); CPPUNIT_ASSERT(pContact != NULL); // verify equality CPPUNIT_ASSERT(pContact->isEqual(&contact3)); // verify number of records in list CPPUNIT_ASSERT(contactList.entries() == 3); } }; // ------------------- Static constant initializers ------------------------- CPPUNIT_TEST_SUITE_REGISTRATION(OsContactListTests); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsContactTest.cpp0000644000175000017500000001254412205613256025315 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2010 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include /** This class is used to test the OsContact class. * * PLEASE READ THE README FILE THAT CAN FOUND IN THE SAME DIRECTORY AS * THIS FILE. The Readme describes the organization / flow of tests and * without reading this file, the following class (and all unit tests) * may not make a lot of sense and might be difficult to comprehend. */ class OsContactTests : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsContactTests); CPPUNIT_TEST(testConstructor) ; CPPUNIT_TEST(testCompareTo) ; CPPUNIT_TEST(testCompareTo_NonContact) ; CPPUNIT_TEST(testEquals) ; CPPUNIT_TEST(testEquals_NonContact) ; CPPUNIT_TEST(testGetContainableType) ; CPPUNIT_TEST_SUITE_END(); private: public: OsContactTests() { } void setUp() { } void tearDown() { } ~OsContactTests() { } /** Sandbox method for experimenting with the API Under Test. * This method MUST be empty when the test drivers are being * checked in (final checkin) to the repository. */ void DynaTest() { } /** Test the constructor * Checks that the object's values are set. */ void testConstructor() { // First test the default constructor OsContact testContact("192.168.0.1", 4242, OsSocket::UDP, IP6) ; const char* msg0 = "Test the constructor" ; UtlString address; testContact.getAddress(address); CPPUNIT_ASSERT(address.compareTo("192.168.0.1") == 0); CPPUNIT_ASSERT(testContact.getPort() == 4242); CPPUNIT_ASSERT(testContact.getProtocol() == OsSocket::UDP); CPPUNIT_ASSERT(testContact.getAddressType() == IP6); } /** Test the compareTo method * Data members are varied and compared to the match contact. * Then the match contact is compared to itself. */ void testCompareTo() { OsContact matchContact("192.168.0.1", 4242, OsSocket::UDP, IP6) ; OsContact testContact1("192.168.0.2", 4242, OsSocket::UDP, IP6) ; CPPUNIT_ASSERT(testContact1.compareTo(&matchContact) != 0); OsContact testContact2("192.168.0.1", 4243, OsSocket::UDP, IP6) ; CPPUNIT_ASSERT(testContact2.compareTo(&matchContact) != 0); OsContact testContact3("192.168.0.1", 4242, OsSocket::TCP, IP6) ; CPPUNIT_ASSERT(testContact3.compareTo(&matchContact) != 0); OsContact testContact4("192.168.0.1", 4242, OsSocket::UDP, IP4) ; CPPUNIT_ASSERT(testContact4.compareTo(&matchContact) != 0); OsContact testContact5("192.168.0.1", 4242, OsSocket::UDP, IP6) ; CPPUNIT_ASSERT(testContact5.compareTo(&matchContact) == 0); CPPUNIT_ASSERT(matchContact.compareTo(&matchContact) == 0); } /** Test the isEqual(UtlContainable*) method. * * The test data for this test is the same as the compareTo method. */ void testEquals() { OsContact matchContact("192.168.0.1", 4242, OsSocket::UDP, IP6) ; OsContact testContact1("192.168.0.2", 4242, OsSocket::UDP, IP6) ; CPPUNIT_ASSERT(testContact1.isEqual(&matchContact) == false); OsContact testContact2("192.168.0.1", 4243, OsSocket::UDP, IP6) ; CPPUNIT_ASSERT(testContact2.isEqual(&matchContact) == false); OsContact testContact3("192.168.0.1", 4242, OsSocket::TCP, IP6) ; CPPUNIT_ASSERT(testContact3.isEqual(&matchContact) == false); OsContact testContact4("192.168.0.1", 4242, OsSocket::UDP, IP4) ; CPPUNIT_ASSERT(testContact4.isEqual(&matchContact) == false); OsContact testContact5("192.168.0.1", 4242, OsSocket::UDP, IP6) ; CPPUNIT_ASSERT(testContact5.isEqual(&matchContact) == TRUE); CPPUNIT_ASSERT(matchContact.isEqual(&matchContact) == TRUE); } /*!a Test the compareTo method when a non-UtlInt is passed. * */ void testCompareTo_NonContact() { OsContact matchContact("192.168.0.1", 4242, OsSocket::UDP, IP6) ; UtlString foo("boo"); CPPUNIT_ASSERT(matchContact.compareTo(&foo) != 0); } /*!a Test the Equals Method when the argument passed is not a UtlInt * */ void testEquals_NonContact() { OsContact matchContact("192.168.0.1", 4242, OsSocket::UDP, IP6) ; UtlString foo("boo"); CPPUNIT_ASSERT(matchContact.isEqual(&foo) == false); } //testEquals_NonInteger /*!a Test the getContainableType method * * Test data = common test data set */ void testGetContainableType() { OsContact matchContact("192.168.0.1", 4242, OsSocket::UDP, IP6) ; CPPUNIT_ASSERT(matchContact.isInstanceOf(OsContact::TYPE)); } //testGetContainableType }; // ------------------- Static constant initializers ------------------------- CPPUNIT_TEST_SUITE_REGISTRATION(OsContactTests); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsDirTest.cpp0000644000175000017500000000534412205613256024440 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include /** * Directory testing. There are missing tests, however overlapping * tests are located in OsFileSytemTest. There is redundancy in API * because OsFileSystem is a convience wrapper to OsDir, and other * file related operations. Longterm we select 1 API and 1 set of * tests to maintain. */ class OsDirTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsDirTest); CPPUNIT_TEST(testCreateDir); CPPUNIT_TEST(testRemoveDir); CPPUNIT_TEST(testRenameDir); CPPUNIT_TEST_SUITE_END(); /** where all tests should r/w data */ OsPath mRootPath; public: void setUp() { OsTestUtilities::createTestDir(mRootPath); } void tearDown() { OsTestUtilities::removeTestDir(mRootPath); } void testCreateDir() { OsStatus stat; OsPath testPath = mRootPath + OsPath::separator + "testCreateDir"; OsDir testDir(testPath); stat = testDir.create(); CPPUNIT_ASSERT_MESSAGE("Create directory ok", stat == OS_SUCCESS); CPPUNIT_ASSERT_MESSAGE("Created dir actually exists", testDir.exists()); } void testRemoveDir() { OsStatus stat; OsPath testPath = mRootPath + OsPath::separator + "testRemoveDir"; OsDir testDir(testPath); stat = testDir.create(); CPPUNIT_ASSERT(stat == OS_SUCCESS); CPPUNIT_ASSERT(testDir.exists()); stat = testDir.remove(FALSE, TRUE); CPPUNIT_ASSERT_MESSAGE("Delete ok", stat == OS_SUCCESS); CPPUNIT_ASSERT_MESSAGE("Deleted dir !exist", !testDir.exists()); } void testRenameDir() { OsStatus stat; OsPath fromPath = mRootPath + OsPath::separator + "testRenameDirFrom"; OsPath toPath = mRootPath + OsPath::separator + "testRenameDirTo"; OsDir fromDir(fromPath); stat = fromDir.create(); CPPUNIT_ASSERT(stat == OS_SUCCESS); CPPUNIT_ASSERT(fromDir.exists()); stat = fromDir.rename(toPath); OsDir toDir(toPath); CPPUNIT_ASSERT_MESSAGE("Rename dir ok", stat == OS_SUCCESS); CPPUNIT_ASSERT_MESSAGE("Rename dir exists", toDir.exists()); } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsDirTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsEventTest.cpp0000644000175000017500000001432512205613256025002 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include class RightEventThread : public OsServerTask { public: int mNumEvents; int mMaxEvents; int* mpDeletedEvent; RightEventThread(int* eventOutcome, int eventsSize) { mNumEvents = -1; mMaxEvents = eventsSize; mpDeletedEvent = eventOutcome; } UtlBoolean handleMessage(OsMsg& rMsg) { int waitMsec = rand(); delay((waitMsec % 3 ) * 50); OsEvent* event = ((OsRpcMsg&)rMsg).getEvent(); CPPUNIT_ASSERT(event); mNumEvents++; intptr_t eventIndex =-1; event->getUserData(eventIndex); //CPPUNIT_ASSERT(mNumEvents == eventIndex); CPPUNIT_ASSERT(mNumEvents < mMaxEvents); OsStatus eventStat = event->signal(mNumEvents); if(eventStat == OS_ALREADY_SIGNALED) { // The Right side lost, the Left side is done // we delete on this side delete event; event = NULL; mpDeletedEvent[mNumEvents] = TRUE; } else { // This/Right side won. we do nothing mpDeletedEvent[mNumEvents] = FALSE; //osPrintf("Right: %d\n", eventStat); } return(TRUE); } }; /// This thread begin firing passed notification with specified delay. class MultipleFireThread : public OsTask { public: /** * @param delay - (in) - delay between fires. Pass -1 to get no-delay firing. * @param notification - (in) Notification to fire */ MultipleFireThread(int delay, OsNotification *notification) : OsTask("MultipleFireThread") , mDelay(delay) , mpNotification(notification) { CPPUNIT_ASSERT(mpNotification != NULL); } int run(void* pArg) { OsStatus status; while(!isShuttingDown()) { if (mDelay > 0) { delay(mDelay); } status = mpNotification->signal(0); } return 0; } protected: int mDelay; OsNotification *mpNotification; }; class OsEventTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsEventTest); CPPUNIT_TEST(testTimedEvent); CPPUNIT_TEST(testThreadedEvent); CPPUNIT_TEST(testThreadedMultipleFire); CPPUNIT_TEST_SUITE_END(); public: void testTimedEvent() { OsTime eventTimeout(2,0); OsEvent* pEvent; pEvent = new OsEvent(12345); time_t epochTime = time(NULL); CPPUNIT_ASSERT(pEvent->wait(eventTimeout) != OS_SUCCESS); pEvent->signal(67890); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pEvent->wait(eventTimeout)); pEvent->reset(); CPPUNIT_ASSERT(pEvent->wait(eventTimeout) != OS_SUCCESS); epochTime = time(NULL) - epochTime; // Make sure we waited (approximately) 2 seconds each time. CPPUNIT_ASSERT(epochTime > 2 && epochTime < 6); delete pEvent; } void testThreadedEvent() { // Seed the random number generator srand(OsDateTime::getSecsSinceEpoch()); int numTries = 100; int* rightResults = new int[numTries]; int* leftResults = new int[numTries]; // Create the Right thread. This context will be the // Left thread. RightEventThread rightThread(rightResults, numTries); rightThread.start(); int index; for(index = 0; index < numTries; index++) { OsEvent* event = new OsEvent(index); OsRpcMsg eventMsg(OsMsg::USER_START,0,*event); rightThread.postMessage(eventMsg); int waitTimeMsec = (rand() % 3) * 110; OsTime time(0, waitTimeMsec * 1000); event->wait(time); OsStatus eventStat = event->signal(index); if(eventStat == OS_ALREADY_SIGNALED) { // We (Left) lost the other side is done intptr_t eventData; event->getEventData(eventData); CPPUNIT_ASSERT(eventData == index); // This/Left side deletes the event delete event; event = NULL; leftResults[index] = TRUE; } else { // The other/Right side lost // Do nothing leftResults[index] = FALSE; //osPrintf("Left: %d\n", eventStat); } } OsTask::delay(1000); int leftDeletes = 0; int rightDeletes = 0; for(index = 0; index < numTries; index++) { if(leftResults[index] == TRUE) { leftDeletes++; } if(rightResults[index] == TRUE) { rightDeletes++; } if(rightResults[index] == leftResults[index]) { //osPrintf("Left deleted: %d Right deleted: %d\n", // leftDeletes, rightDeletes); //osPrintf("[%d]: Both sides %s\n", index, // rightResults[index] ? "Deleted" : "Did not delete"); } CPPUNIT_ASSERT(rightResults[index] != leftResults[index]); } //osPrintf("Left deleted: %d Right deleted: %d\n", // leftDeletes, rightDeletes); CPPUNIT_ASSERT(leftDeletes + rightDeletes == numTries); } void testThreadedMultipleFire() { OsEvent event; MultipleFireThread fireThread(-1, &event); fireThread.start(); for (int i=0; i<10000; i++) { CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, event.wait(500)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, event.reset()); } fireThread.requestShutdown(); } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsEventTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsFileIteratorTest.cpp0000644000175000017500000001241612205613256026311 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include // This prints the filter expressions and what they find //#define TRACE_TEST(x) printf x #define TRACE_TEST(x) /** * Test Description */ /** * These files are created in the setUp routine; they are used for all trials * The indexes of this array MUST MATCH those for the expected element of the * struct trial below. */ static const char* const TestFiles[] = { "001.msg", "003.msg", "001.msgx", "x001.msg", "x001.msgx", "abc.msg", "abc.def", "001.not", "001xmsg", "002.msg" }; static const int NumTestFiles = sizeof(TestFiles)/sizeof(char*); /** * Each trial is a regular expression to be used as a filter, and an array * of booleans for whether or not the matching element of the TestFiles should * have been found by it. */ static const struct trial { const char* regex; bool expected[NumTestFiles]; } Trials[] = { { "^[0-9]+\\.msg$", { true, true, false, false, false, false, false, false, false, true } }, { "[0-9]+\\.msg$", { true, true, false, true, false, false, false, false, false, true } }, { "^[a-z]+\\.msg$", { false, false, false, false, false, true, false, false, false, false } } }; static const int NumTrials = sizeof(Trials)/sizeof(struct trial); class OsFileIteratorTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsFileIteratorTest); CPPUNIT_TEST(testCreation); CPPUNIT_TEST(testIterate); CPPUNIT_TEST_SUITE_END(); /** where all tests should r/w data */ OsPath mRootPath; public: /** * Create the TestFiles */ void setUp() { OsTestUtilities::createTestDir(mRootPath); int i; CPPUNIT_ASSERT_MESSAGE("wrong number of files", NumTestFiles == 10); printf("num temp files: %d\n", NumTestFiles); for ( i= 0; i < NumTestFiles; i++ ) { OsTestUtilities::createDummyFile(mRootPath+OsPath::separator+TestFiles[i], 100); } } /** * clean up all files and directories for this test */ void tearDown() { // comment out to save test output OsTestUtilities::removeTestDir(mRootPath); } /** * Find the element in TestFiles that was matched, and record that * fact in the results array. * We do it this way because the order in which the matches will * occur is undefined. */ void recordMatch( bool results[NumTestFiles], OsPath& matched ) { int file; bool found; TRACE_TEST(("\n ####### found '%s'", matched.data())); for ( file = 0, found = false; file < NumTestFiles && ! found; file++ ) { if ( matched == TestFiles[file] ) { CPPUNIT_ASSERT_MESSAGE( "Found the same file twice.", results ); results[file] = true; found = true; } } CPPUNIT_ASSERT_MESSAGE( "Found a file not in the test set.", found ); } void testCreation() { // Example of bug XPL-12 OsFileIterator *i = new OsFileIterator(mRootPath); delete i; } void testIterate() { OsFileIterator fi(mRootPath); OsPath entry; int trial; // for ( trial = 0; trial < NumTrials; trial++ ) { TRACE_TEST(("\n\n############### filter '%s'", Trials[trial].regex)); bool results[NumTestFiles]; int i; // set result for each test file to not found for ( i = 0; i < NumTestFiles; i++ ) { results[i] = false; } OsStatus status; int numFound; // loop over the iterator, recording what gets found for( status = fi.findFirst(entry, Trials[trial].regex, OsFileIterator::FILES) ,numFound = 0; status == OS_SUCCESS && numFound <= NumTestFiles; status = fi.findNext(entry) ) { numFound++; recordMatch( results, entry ); } CPPUNIT_ASSERT( numFound <= NumTestFiles ); // test integrity check bool passed = true; // compare the results with what the trial definition expected for ( i = 0; i < NumTestFiles; i++ ) { if ( results[i] != Trials[trial].expected[i] ) { passed = false; printf( Trials[trial].expected[i] ? "\n! Expression '%s' did not find '%s'\n" : "\n! Expression '%s' should not have found '%s'\n", Trials[trial].regex, TestFiles[i] ); } } CPPUNIT_ASSERT( passed ); } TRACE_TEST(("\n")); } }; #ifdef WINCE #pragma message( "OsFileIteratorTest disabled undef Win CE" ) #else CPPUNIT_TEST_SUITE_REGISTRATION(OsFileIteratorTest); #endif sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsFileSystemTest.cpp0000644000175000017500000001300512205613256025777 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include class OsFileSystemTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsFileSystemTest); CPPUNIT_TEST(testCreateDir); CPPUNIT_TEST(testRemoveDir); CPPUNIT_TEST(testCreateRecursiveDir); CPPUNIT_TEST(testRenameDir); CPPUNIT_TEST(testGetInfo); CPPUNIT_TEST(testRemoveTree); CPPUNIT_TEST_SUITE_END(); /** where all tests should r/w data */ OsPath mRootPath; public: void setUp() { OsTestUtilities::createTestDir(mRootPath); } void tearDown() { OsTestUtilities::removeTestDir(mRootPath); } void testCreateDir() { OsStatus stat; OsPath testDir = mRootPath + OsPath::separator + "testCreateDir"; stat = OsFileSystem::createDir(testDir); CPPUNIT_ASSERT_MESSAGE("Creating directory", stat == OS_SUCCESS); CPPUNIT_ASSERT_MESSAGE("Directory actually exists", OsFileSystem::exists(testDir)); } void testCreateRecursiveDir() { OsStatus stat; OsPath testDir = mRootPath + OsPath::separator + "testCreateParentDir" + OsPath::separator + "testCreateDir"; stat = OsFileSystem::createDir(testDir, TRUE); CPPUNIT_ASSERT_MESSAGE("Creating directory", stat == OS_SUCCESS); CPPUNIT_ASSERT_MESSAGE("Directory actually exists", OsFileSystem::exists(testDir)); } void testRemoveDir() { OsStatus stat; OsPath testDir = mRootPath + OsPath::separator + "testRemoveDir"; stat = OsFileSystem::createDir(testDir); CPPUNIT_ASSERT_MESSAGE("Creating directory", stat == OS_SUCCESS); stat = OsFileSystem::remove(testDir, FALSE, TRUE); CPPUNIT_ASSERT_MESSAGE("Removed directory", stat == OS_SUCCESS); CPPUNIT_ASSERT_MESSAGE("Directory actually removed", !OsFileSystem::exists(testDir)); } void testRenameDir() { OsStatus stat; OsPath renameFrom = mRootPath + OsPath::separator + "testRenameDirFrom"; OsPath renameTo = mRootPath + OsPath::separator + "testRenameDirTo"; stat = OsFileSystem::createDir(renameFrom); CPPUNIT_ASSERT_MESSAGE("Creating directory", stat == OS_SUCCESS); stat = OsFileSystem::rename(renameFrom, renameTo); CPPUNIT_ASSERT_MESSAGE("Renamed dir", stat == OS_SUCCESS); CPPUNIT_ASSERT_MESSAGE("New dir name there", OsFileSystem::exists(renameTo)); CPPUNIT_ASSERT_MESSAGE("Old dir name not there", !OsFileSystem::exists(renameFrom)); } void testGetInfo() { OsStatus stat; OsPath testDir = mRootPath + OsPath::separator + "testGetInfo"; OsFileInfo info; OsPath path(testDir); stat = OsFileSystem::getFileInfo(testDir, info); CPPUNIT_ASSERT_MESSAGE("Fail getting info on non-exists dir", stat != OS_SUCCESS); stat = OsFileSystem::createDir(testDir); CPPUNIT_ASSERT_MESSAGE("Creating directory", stat == OS_SUCCESS); stat = OsFileSystem::getFileInfo(testDir, info); CPPUNIT_ASSERT_MESSAGE("Fail getting info on non-exists dir", stat == OS_SUCCESS); OsTime createTime; info.getCreateTime(createTime); //time_t etime = createTime.seconds(); //osPrintf("Got dir info. now %d created %d\n", now, createTime.seconds()); } void testRemoveTree() { OsStatus stat; OsPath level1dir = mRootPath + OsPath::separator + "level1"; OsPath level2dir = level1dir + OsPath::separator + "level2"; OsPath level3dir = level2dir + OsPath::separator + "level3"; stat = OsFileSystem::createDir(level1dir); CPPUNIT_ASSERT(stat == OS_SUCCESS); stat = OsFileSystem::createDir(level2dir); CPPUNIT_ASSERT(stat == OS_SUCCESS); stat = OsFileSystem::createDir(level3dir); CPPUNIT_ASSERT(stat == OS_SUCCESS); OsPath filename; //now create the files under each dir for (int loop = 0; loop < 30;loop++) { UtlString levelStr = "level1_"; filename = level1dir + OsPath::separator + levelStr; if (loop > 9) { levelStr = "level2_"; filename = level2dir + OsPath::separator + levelStr; } if (loop > 19) { levelStr = "level3_"; filename = level3dir + OsPath::separator + levelStr; } char buf[10]; sprintf(buf,"%d",loop); filename.append(buf); OsFile *tmpfile = new OsFile(filename); tmpfile->touch(); delete tmpfile; } //now delete the tree OsPath delPath(level1dir); stat = OsFileSystem::remove(delPath, FALSE, TRUE); CPPUNIT_ASSERT_MESSAGE("Should fail to delete recursively", stat != OS_SUCCESS); stat = OsFileSystem::remove(delPath, TRUE, TRUE); CPPUNIT_ASSERT_MESSAGE("Should success to delete recursively", stat == OS_SUCCESS); } }; #ifdef WINCE #pragma message( "OsFileSystemTest disabled undef Win CE" ) #else CPPUNIT_TEST_SUITE_REGISTRATION(OsFileSystemTest); #endif sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsFileTest.cpp0000644000175000017500000001741212205613256024600 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2005 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2005 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// #include #include #include #include #ifndef WINCE #include #endif /** * Test Description */ class OsFileTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsFileTest); CPPUNIT_TEST(testCreateFile); CPPUNIT_TEST(testDeleteFile); CPPUNIT_TEST(testReadWriteBuffer); CPPUNIT_TEST(testCopyFile); CPPUNIT_TEST(testReadOnly); CPPUNIT_TEST(testTouch); #ifndef _WIN32 CPPUNIT_TEST(testFileLocking); #endif CPPUNIT_TEST_SUITE_END(); /** where all tests should r/w data */ OsPath mRootPath; public: void setUp() { OsTestUtilities::createTestDir(mRootPath); } void tearDown() { OsTestUtilities::removeTestDir(mRootPath); } /** * Create empty file */ void testCreateFile() { OsPath testFile = mRootPath + OsPath::separator + "testCreateFile"; OsFile file(testFile); file.touch(); CPPUNIT_ASSERT_MESSAGE("Touched file exists", file.exists()); } /** * Create and delete empty file */ void testDeleteFile() { OsStatus stat; OsPath testFile = mRootPath + OsPath::separator + "testDeleteFile"; OsFile file(testFile); file.touch(); CPPUNIT_ASSERT(file.exists()); stat = file.remove(); CPPUNIT_ASSERT_MESSAGE("File deleted", stat == OS_SUCCESS); CPPUNIT_ASSERT(!file.exists()); } /** * Creates a new dummy file then reads it back in to verify it's * contents, buffer by buffer. */ void testReadWriteBuffer() { /////////////////////// // W R I T E /////////////////////// OsStatus stat; OsPath testFile = mRootPath + OsPath::separator + "testWriteBuffer"; char wbuff[10000]; unsigned long wbuffsize = (unsigned long)sizeof(wbuff); OsTestUtilities::initDummyBuffer(wbuff, sizeof(wbuff)); OsFile wfile(testFile); stat = wfile.open(OsFile::CREATE); CPPUNIT_ASSERT(stat == OS_SUCCESS); unsigned long wposition = 0; int i; for (i = 0; wposition < wbuffsize; i++) { unsigned long remaining = wbuffsize - wposition; unsigned long byteswritten = 0; stat = wfile.write(wbuff + wposition, remaining, byteswritten); CPPUNIT_ASSERT(stat == OS_SUCCESS); wposition += byteswritten; } //close the file after working with it. wfile.close(); /////////////////////// // R E A D /////////////////////// char rbuff[256]; unsigned long rbuffsize = (unsigned long)sizeof(rbuff); OsFile rfile(testFile); stat = rfile.open(); CPPUNIT_ASSERT(stat == OS_SUCCESS); unsigned long rposition = 0; for (i = 0; rposition < wbuffsize; i++) { unsigned long remaining = (wbuffsize - rposition); unsigned long readsize = remaining < rbuffsize ? remaining : rbuffsize; unsigned long bytesread = 0; stat = rfile.read(rbuff, readsize, bytesread); CPPUNIT_ASSERT_MESSAGE("Read buffer", stat == OS_SUCCESS); UtlBoolean ok = OsTestUtilities::testDummyBuffer(rbuff, bytesread, rposition); CPPUNIT_ASSERT_MESSAGE("Test buffer data", ok); rposition += bytesread; } // proper EOF unsigned long zeroread = 0; stat = rfile.read(rbuff, 1, zeroread); CPPUNIT_ASSERT_MESSAGE("End of file", stat == OS_FILE_EOF); CPPUNIT_ASSERT_MESSAGE("No bytes read", zeroread == 0); } /** * Creates a dummy file, copies it into a new file then verifies * it's contents */ void testCopyFile() { OsStatus stat; OsPath copyFrom = mRootPath + OsPath::separator + "testCopyFileFrom"; OsPath copyTo = mRootPath + OsPath::separator + "testCopyFileTo"; stat = OsTestUtilities::createDummyFile(copyFrom, 1000); CPPUNIT_ASSERT_MESSAGE("Create test file", stat == OS_SUCCESS); OsFile copyFromFile(copyFrom); copyFromFile.copy(copyTo); CPPUNIT_ASSERT_MESSAGE("Copies file exists", OsFileSystem::exists(copyTo)); UtlBoolean ok = OsTestUtilities::verifyDummyFile(copyTo, 1000); CPPUNIT_ASSERT_MESSAGE("Test file verified", ok); } void testReadOnly() { OsStatus stat; OsPath testPath = mRootPath + OsPath::separator + "testReadOnly"; OsFile testFile(testPath); testFile.touch(); stat = testFile.setReadOnly(TRUE); CPPUNIT_ASSERT_MESSAGE("No error setting read only", stat == OS_SUCCESS); CPPUNIT_ASSERT_MESSAGE("Read only", testFile.isReadonly()); stat = testFile.setReadOnly(FALSE); CPPUNIT_ASSERT_MESSAGE("No error setting read only", stat == OS_SUCCESS); CPPUNIT_ASSERT_MESSAGE("Not Read only", !testFile.isReadonly()); } void testTouch() { OsFileInfoBase info; OsTime time1, time2; OsPath testFile = mRootPath + OsPath::separator + "testTouch"; OsFile file(testFile); // Create the file CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, file.touch()); // Get the modification time and sleep for a few seconds CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, file.getFileInfo(info)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, info.getModifiedTime(time1)); OsTask::delay(3000); // Touch the file and get the modification time again CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, file.touch()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, file.getFileInfo(info)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, info.getModifiedTime(time2)); // The modification times must differ by the sleep amount CPPUNIT_ASSERT_MESSAGE("The time is the same", time1.seconds() != time2.seconds()); } /** * Created dummy files and attempts to gain and deny access to locks */ void testFileLocking() { OsStatus stat; OsPath testPath = mRootPath + OsPath::separator + "testFileLocking"; OsFile testFile1(testPath); OsFile testFile2(testPath); OsFile testFile3(testPath); OsFile testFile4(testPath); testFile1.touch(); stat = testFile1.open(OsFile::READ_ONLY | OsFile::FSLOCK); CPPUNIT_ASSERT_MESSAGE("Attempt to open a file read-only with a lock", stat != OS_SUCCESS); stat = testFile1.open(OsFile::READ_ONLY); CPPUNIT_ASSERT_MESSAGE("Open a file", stat == OS_SUCCESS); stat = testFile2.open(OsFile::READ_WRITE | OsFile::FSLOCK_WAIT); CPPUNIT_ASSERT_MESSAGE("Wait to open a file with a lock", stat == OS_SUCCESS); stat = testFile3.open(OsFile::READ_WRITE); CPPUNIT_ASSERT_MESSAGE("Open a locked file ignoring the lock", stat == OS_SUCCESS); stat = testFile4.open(OsFile::READ_WRITE | OsFile::FSLOCK); CPPUNIT_ASSERT_MESSAGE("Attempt to open a locked file with a lock", stat != OS_SUCCESS); testFile2.close(); stat = testFile4.open(OsFile::READ_WRITE | OsFile::FSLOCK); CPPUNIT_ASSERT_MESSAGE("Open a file with a lock", stat == OS_SUCCESS); testFile4.close(); testFile3.close(); testFile1.close(); testFile1.remove(); // TODO: Properly test FSLOCK_WAIT and cross-process locking } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsFileTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsLockTest.cpp0000644000175000017500000001523012205613256024605 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include #include #include class LockOnMutexMember { public: LockOnMutexMember() : mMutex(OsMutex::Q_PRIORITY + OsMutex::INVERSION_SAFE + OsMutex::DELETE_SAFE), mCounter(OsMutex::Q_PRIORITY + OsMutex::INVERSION_SAFE + OsMutex::DELETE_SAFE) //mCounter(OsCSem::Q_PRIORITY, 1000, 1000, &mMutex) { //printf("LockOnMutexMember constructed\n"); }; void doLockedStuff() { { OsLock lock(mMutex); } } OsMutex mMutex; OsMutex mCounter; }; class OsLockTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsLockTest); CPPUNIT_TEST(testLockBasicSemaphore); CPPUNIT_TEST(testLockMutex); CPPUNIT_TEST(testLockedMember); CPPUNIT_TEST_SUITE_END(); public: /** * Locking of basic semaphores */ void testLockBasicSemaphore() { // Create a binary semaphore for use with an OsLock object OsBSem *pBSem = new OsBSem(OsBSem::Q_PRIORITY, OsBSem::FULL); int ret = 0; // Acquire semaphore at the start of the block, release it on exit block { ret = pBSem->tryAcquire(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Semaphor should be available", (int)OS_SUCCESS, ret); ret = pBSem->release(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Semaphor should be available", (int)OS_SUCCESS, ret); OsLock lock(*pBSem); // if this were a real guarded method, we'd do useful work here // destroying the OsReadLock variable that has been allocated on the stack // should release the reader lock automatically when we leave block // Should not be available ret = pBSem->tryAcquire(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Semaphor should be available", (int)OS_BUSY, ret); } // Should be available ret = pBSem->tryAcquire(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Semaphor should be available", (int)OS_SUCCESS, ret); delete pBSem; } /** * Locking of mutex'es */ void testLockMutex() { // Create an OsRWMutex for use with OsReadLock and OsWriteLock objects OsRWMutex *pRWMutex = new OsRWMutex(OsRWMutex::Q_FIFO); int ret = 0; // Acquire read lock at the start of the block, release it on exit { ret = pRWMutex->tryAcquireRead(); CPPUNIT_ASSERT_EQUAL_MESSAGE("should be available", (int)OS_SUCCESS, ret); // Multiple read should be allowed ret = pRWMutex->tryAcquireRead(); CPPUNIT_ASSERT_EQUAL_MESSAGE("should be available", (int)OS_SUCCESS, ret); // Should not be available ret = pRWMutex->tryAcquireWrite(); CPPUNIT_ASSERT_EQUAL_MESSAGE("should not be available", (int)OS_BUSY, ret); ret = pRWMutex->releaseRead(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Semaphor should be available", (int)OS_SUCCESS, ret); ret = pRWMutex->releaseRead(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Semaphor should be available", (int)OS_SUCCESS, ret); OsReadLock lock(*pRWMutex); // Should not be available ret = pRWMutex->tryAcquireWrite(); CPPUNIT_ASSERT_EQUAL_MESSAGE("should not be available", (int)OS_BUSY, ret); // Multiple read should be allowed ret = pRWMutex->tryAcquireRead(); CPPUNIT_ASSERT_EQUAL_MESSAGE("should be available", (int)OS_SUCCESS, ret); ret = pRWMutex->releaseRead(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Semaphor should be available", (int)OS_SUCCESS, ret); } // Should be available ret = pRWMutex->tryAcquireWrite(); CPPUNIT_ASSERT_EQUAL_MESSAGE("should be available", (int)OS_SUCCESS, ret); ret = pRWMutex->releaseWrite(); CPPUNIT_ASSERT_EQUAL_MESSAGE("should release", (int)OS_SUCCESS, ret); // Acquire write lock at the start of the block, release it on exit { ret = pRWMutex->tryAcquireRead(); CPPUNIT_ASSERT_EQUAL_MESSAGE("should be available", (int)OS_SUCCESS, ret); ret = pRWMutex->releaseRead(); CPPUNIT_ASSERT_EQUAL_MESSAGE("should release", (int)OS_SUCCESS, ret); // Should be available ret = pRWMutex->tryAcquireWrite(); CPPUNIT_ASSERT_EQUAL_MESSAGE("should be available", (int)OS_SUCCESS, ret); ret = pRWMutex->releaseWrite(); CPPUNIT_ASSERT_EQUAL_MESSAGE("should release", (int)OS_SUCCESS, ret); OsWriteLock lock(*pRWMutex); // Should not be available ret = pRWMutex->tryAcquireWrite(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Semaphor should be available", (int)OS_BUSY, ret); ret = pRWMutex->tryAcquireRead(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Semaphor should be available", (int)OS_BUSY, ret); } // Should be available ret = pRWMutex->tryAcquireWrite(); CPPUNIT_ASSERT_EQUAL_MESSAGE("should be available", (int)OS_SUCCESS, ret); ret = pRWMutex->releaseWrite(); CPPUNIT_ASSERT_EQUAL_MESSAGE("should release", (int)OS_SUCCESS, ret); delete pRWMutex; } void testLockedMember() { int ret = 0; OsMutex localMutex(OsMutex::Q_PRIORITY + OsMutex::INVERSION_SAFE + OsMutex::DELETE_SAFE); localMutex.OsMutexShow(); ret = localMutex.tryAcquire(); CPPUNIT_ASSERT_EQUAL_MESSAGE("mutex should be available, it was just initialized", (int) OS_SUCCESS, ret); LockOnMutexMember lockingClass; ret = lockingClass.mMutex.tryAcquire(); CPPUNIT_ASSERT_EQUAL_MESSAGE("mutex should be available, it was just initialized", (int) OS_SUCCESS, ret); ret = lockingClass.mMutex.release(); CPPUNIT_ASSERT_EQUAL_MESSAGE("mutext should release", (int) OS_SUCCESS, ret); // Not a very friendly test. This test will block if lock cannot be taken lockingClass.doLockedStuff(); CPPUNIT_ASSERT_MESSAGE("the fact that we got here is a pass of the test", true); } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsLockTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsMsgQTest.cpp0000644000175000017500000000436112205613256024567 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include UtlBoolean gMsgReceived; UtlBoolean msgSendHook(const OsMsg& rOsMsg) { gMsgReceived = TRUE; return FALSE; } class OsMsgQTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsMsgQTest); CPPUNIT_TEST(testMessageQueue); CPPUNIT_TEST_SUITE_END(); public: void testMessageQueue() { OsMsgQ* pMsgQ1; OsMsg* pMsg1; OsMsg* pMsg2; OsMsg* pRecvMsg; pMsgQ1 = new OsMsgQ(OsMsgQ::DEF_MAX_MSGS, OsMsgQ::DEF_MAX_MSG_LEN, OsMsgQ::Q_PRIORITY, "MQ1"); pMsg1 = new OsMsg(OsMsg::UNSPECIFIED, 0); pMsg2 = new OsMsg(OsMsg::UNSPECIFIED, 0); CPPUNIT_ASSERT(pMsgQ1->isEmpty()); CPPUNIT_ASSERT_EQUAL(0, pMsgQ1->numMsgs()); CPPUNIT_ASSERT(pMsgQ1->getSendHook() == NULL); pMsgQ1->setSendHook(msgSendHook); CPPUNIT_ASSERT(pMsgQ1->getSendHook() == msgSendHook); gMsgReceived = FALSE; OsStatus stat = pMsgQ1->send(*pMsg1); CPPUNIT_ASSERT(gMsgReceived); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, stat); CPPUNIT_ASSERT(!pMsgQ1->isEmpty()); CPPUNIT_ASSERT_EQUAL(1, pMsgQ1->numMsgs()); stat = pMsgQ1->send(*pMsg2); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, stat); CPPUNIT_ASSERT_EQUAL(2, pMsgQ1->numMsgs()); stat = pMsgQ1->receive(pRecvMsg); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, stat); delete pRecvMsg; CPPUNIT_ASSERT_EQUAL(1, pMsgQ1->numMsgs()); stat = pMsgQ1->receive(pRecvMsg); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, stat); delete pRecvMsg; CPPUNIT_ASSERT_EQUAL(0, pMsgQ1->numMsgs()); delete pMsg1; delete pMsg2; delete pMsgQ1; } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsMsgQTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsMsgDispatcherTest.cpp0000644000175000017500000000643512205613256026461 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// #include "utl/UtlRandom.h" #include "os/OsDateTime.h" #include "os/OsMsgDispatcher.h" #include "os/OsSysLog.h" #include /** * Unittest for OsMsgDispatcher */ class OsMsgDispatcherTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsMsgDispatcherTest); CPPUNIT_TEST(testSingleMessage); CPPUNIT_TEST(testFullDispatcher); CPPUNIT_TEST_SUITE_END(); public: void setUp() { OsTime t; OsDateTime::getCurTime(t); mpRandGenerator = new UtlRandom((int)t.cvtToMsecs()); } void tearDown() { delete mpRandGenerator; mpRandGenerator = NULL; } void testSingleMessage() { OsMsg msg(1, (char)mpRandGenerator->rand()); OsMsg* pReceivedMsg = NULL; OsMsgDispatcher dispatcher; CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, dispatcher.post(msg)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, dispatcher.receive(pReceivedMsg)); CPPUNIT_ASSERT(pReceivedMsg != NULL); //CPPUNIT_ASSERT_EQUAL(&msg, pReceivedMsg); // This may not be true, as queue may make copy. CPPUNIT_ASSERT_EQUAL(msg.getMsgSubType(), pReceivedMsg->getMsgSubType()); delete pReceivedMsg; } void testFullDispatcher() { OsMsgDispatcher dispatcher; OsMsg** pMsgArray = new OsMsg*[dispatcher.maxMsgs()+1]; int i; for(i = 0; i < dispatcher.maxMsgs() + 1; i++) { pMsgArray[i] = new OsMsg(1, (char)mpRandGenerator->rand()); } // Fill the dispatcher till it is just full, no more. for(i = 0; i < dispatcher.maxMsgs(); i++) { CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, dispatcher.post(*pMsgArray[i])); } // Now, the prime assertion for this test -- the next message pushed // should fail having reached the limit of the queue. CPPUNIT_ASSERT_EQUAL(OS_LIMIT_REACHED, dispatcher.post(*pMsgArray[dispatcher.maxMsgs()])); // Check all the messages in the queue to make sure that they start with // the contents of pMsgArray[1], all up through pMsgArray[maxMsgs-1], not // including that last one that was tried to be pushed. OsMsg* pCurRMsg = NULL; for(i = 0; i < dispatcher.maxMsgs(); i++) { CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, dispatcher.receive(pCurRMsg)); CPPUNIT_ASSERT(pCurRMsg != NULL); CPPUNIT_ASSERT_EQUAL(pMsgArray[i]->getMsgSubType(), pCurRMsg->getMsgSubType()); delete pCurRMsg; pCurRMsg = NULL; } // Now, if we try to receive one more, with a timeout, it is expected to // timeout and return without the message. CPPUNIT_ASSERT_EQUAL(OS_WAIT_TIMEOUT, dispatcher.receive(pCurRMsg, OsTime(50))); // Cleanup dynamic array. for(i = 0; i < dispatcher.maxMsgs() + 1; i++) { delete pMsgArray[i]; } delete[] pMsgArray; } protected: UtlRandom* mpRandGenerator; }; CPPUNIT_TEST_SUITE_REGISTRATION(OsMsgDispatcherTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsMutexTest.cpp0000644000175000017500000000350312205613256025017 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include class OsMutexTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsMutexTest); CPPUNIT_TEST(testMutex); CPPUNIT_TEST(testRWMutex); CPPUNIT_TEST_SUITE_END(); public: void testMutex() { OsMutex* pMutex; pMutex = new OsMutex(OsMutex::Q_FIFO); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMutex->acquire()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMutex->acquire(100)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMutex->tryAcquire()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMutex->release()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMutex->release()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMutex->release()); // TBD: test mutex locked by another thread! delete pMutex; } void testRWMutex() { OsRWMutex* pRWMutex; pRWMutex = new OsRWMutex(OsRWMutex::Q_FIFO); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pRWMutex->acquireRead()); CPPUNIT_ASSERT_EQUAL(OS_BUSY, pRWMutex->tryAcquireWrite()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pRWMutex->releaseRead()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pRWMutex->tryAcquireWrite()); CPPUNIT_ASSERT_EQUAL(OS_BUSY, pRWMutex->tryAcquireRead()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pRWMutex->releaseWrite()); delete pRWMutex; } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsMutexTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsNameDbTest.cpp0000644000175000017500000000403012205613256025037 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include class OsNameDbTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsNameDbTest); CPPUNIT_TEST(testNameDb); CPPUNIT_TEST_SUITE_END(); public: void testNameDb() { OsNameDb* pNameDb; intptr_t storedInt; pNameDb = OsNameDb::getNameDb(); /* * Because OsNameDb is a singleton, other tests may have already * instantiated it and stored things in it. So this one can't assume * that it was initially empty. */ int startingEntries; startingEntries = pNameDb->numEntries(); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pNameDb->insert("test1", 1)); CPPUNIT_ASSERT(!pNameDb->isEmpty()); CPPUNIT_ASSERT_EQUAL(startingEntries+1, pNameDb->numEntries()); CPPUNIT_ASSERT_EQUAL(OS_NAME_IN_USE, pNameDb->insert("test1", 2)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pNameDb->insert("test2", 2)); CPPUNIT_ASSERT_EQUAL(startingEntries+2, pNameDb->numEntries()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pNameDb->lookup("test1", NULL)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pNameDb->lookup("test1", &storedInt)); CPPUNIT_ASSERT_EQUAL(intptr_t(1), storedInt); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pNameDb->lookup("test2", &storedInt)); CPPUNIT_ASSERT_EQUAL(intptr_t(2), storedInt); CPPUNIT_ASSERT_EQUAL(OS_NOT_FOUND, pNameDb->lookup("test3", NULL)); pNameDb->remove("test1"); pNameDb->remove("test2"); } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsNameDbTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsPathTest.cpp0000644000175000017500000000411212205613256024606 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include class OsPathTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsPathTest); CPPUNIT_TEST(testPathInfo); CPPUNIT_TEST_SUITE_END(); /** where all tests should r/w data */ OsPath mRootPath; public: void setUp() { //OsTestUtilities::createTestDir(mRootPath); } void tearDown() { //OsTestUtilities::removeTestDir(mRootPath); } void testPathInfo() { UtlString testDir = "../../filename.ext"; OsPath testPath = testDir; UtlString parentPath; parentPath.append("..").append(OsPath::separator).append("..").append(OsPath::separator); ASSERT_STR_EQUAL_MESSAGE("Extension", ".ext", testPath.getExt().data()); ASSERT_STR_EQUAL_MESSAGE("Parent Path", parentPath, testPath.getDirName().data()); ASSERT_STR_EQUAL_MESSAGE("Volume", "", testPath.getVolume().data()); ASSERT_STR_EQUAL_MESSAGE("Filename no extension", "filename", testPath.getFilename().data()); // little risky, may not have permissions, but '../../' is too // good a test to not try. Refactor if this is bad assumption OsFile file(testPath); file.touch(); OsPath nativePath; testPath.getNativePath(nativePath); // dont' know what's right, but know whats wrong CPPUNIT_ASSERT_MESSAGE("Resolved relative path", !nativePath.contains("..")); //printf("Native path is %s\n", nativePath.data()); file.remove(); } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsPathTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsProcessIteratorTest.cpp0000644000175000017500000000332612205613256027050 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include class OsProcessIteratorTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsProcessIteratorTest); CPPUNIT_TEST(testIterator); CPPUNIT_TEST_SUITE_END(); public: /** * Just excersizes AIP. Unclear how to create pass/fail tests */ void testIterator() { OsStatus stat; OsProcess process; OsProcessIterator pi; stat = pi.findFirst(process); CPPUNIT_ASSERT_MESSAGE("First process", stat == OS_SUCCESS); while (stat == OS_SUCCESS) { UtlString name; process.getProcessName(name); #ifdef WIN32 /*on Windows, the system process is pid 0 */ CPPUNIT_ASSERT_MESSAGE("Valid PID",process.getPID() >= 0); #else CPPUNIT_ASSERT_MESSAGE("Valid PID", process.getPID() != 0); #endif CPPUNIT_ASSERT_MESSAGE("Valid Parent PID", process.getParentPID() >= 0); CPPUNIT_ASSERT_MESSAGE("Valid process name", name.data() != NULL); stat = pi.findNext(process); } } }; #ifdef WINCE #pragma message( "OsProcessIteratorTest disabled undef Win CE" ) #else CPPUNIT_TEST_SUITE_REGISTRATION(OsProcessIteratorTest); #endif sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsProcessMgrTest.cpp0000644000175000017500000000620312205613256026001 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2010 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include // Short circuit the autotools config as the path will most likely not work // for cross compile test runs off the machine the unit tests were built on. #ifndef TEST_DIR #ifdef WIN32 #define TEST_DIR "C:\\windows\\temp\\" #else #define TEST_DIR "/tmp/" #endif #endif class OsProcessMgrTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsProcessMgrTest); CPPUNIT_TEST(testManager); CPPUNIT_TEST_SUITE_END(); public: void testManager() { #ifdef ANDROID CPPUNIT_ASSERT_MESSAGE("ANDROID_HANG", 0); return; #endif OsStatus stat; printf("Creating process lock file in dir: %s\n", TEST_DIR); OsProcessMgr processManager(TEST_DIR); UtlString alias = "MyPing1"; UtlString appName = "ping"; UtlString params[10]; params[0] = "127.0.0.1"; #ifdef _WIN32 //need to do this only on win32, linux already does this by default params[1] = "-t"; #endif OsPath inputFile = ""; //this means it will use standard input OsPath MyPing1OutputFile = "testManager1.out"; OsPath MyPing2OutputFile = "testManager2.out"; OsPath errFile = "testManager.err"; processManager.setIORedirect(inputFile, MyPing1OutputFile, errFile); UtlString MyPing1("MyPing1"); UtlString MyPing2("MyPing2"); OsPath startupDir = ""; stat = processManager.startProcess(MyPing1, appName, params, startupDir); CPPUNIT_ASSERT_MESSAGE("Started first proccess", stat == OS_SUCCESS); CPPUNIT_ASSERT_EQUAL_MESSAGE("Alias state", PROCESS_STARTED, processManager.getAliasState(MyPing1)); processManager.setIORedirect(inputFile, MyPing2OutputFile, errFile); stat = processManager.startProcess(MyPing2, appName, params, startupDir); CPPUNIT_ASSERT_MESSAGE("Started 2nd proccess", stat == OS_SUCCESS); CPPUNIT_ASSERT_EQUAL_MESSAGE("2nd alias state", PROCESS_STARTED, processManager.getAliasState(MyPing2)); //std::cout << "Waiting 2 secs before killing process MyPing1...\n"; OsTask::delay(2000); stat = processManager.stopProcess(MyPing1); CPPUNIT_ASSERT_MESSAGE("Killed 1st process", stat == OS_SUCCESS); //std::cout << "Waiting 2 secs before killing process MyPing2...\n"; OsTask::delay(2000); stat = processManager.stopProcess(MyPing2); CPPUNIT_ASSERT_MESSAGE("Killed 2nd process", stat == OS_SUCCESS); } }; #ifdef WINCE #pragma message( "OsProcessMgrTest disabled undef Win CE" ) #else CPPUNIT_TEST_SUITE_REGISTRATION(OsProcessMgrTest); #endif sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsProcessTest.cpp0000644000175000017500000000501312205613256025331 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include class OsProcessTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsProcessTest); #ifndef _WIN32 CPPUNIT_TEST(testLaunch); #endif CPPUNIT_TEST_SUITE_END(); public: void testLaunch() { OsStatus stat; UtlString appName = "ping"; UtlString params[10]; params[0] = "127.0.0.1"; #ifdef _WIN32 //need to do this only on win32, linux already does this by default params[1] = "-t"; #endif OsPath inputFile = ""; //this means it will use standard input OsPath outputFile = "testLaunch.out"; OsPath errFile = "testLaunch.err"; OsProcess process; process.setIORedirect(inputFile, outputFile, errFile); UtlString envKey = "TESTKEY1"; UtlString envValue = "TESTVALUE1"; process.setEnv(envKey,envValue); envKey = "TESTKEY2"; envValue ="TESTVALUE2"; process.setEnv(envKey,envValue); envKey = "TESTKEY3"; envValue = "TESTVALUE3"; process.setEnv(envKey,envValue); OsPath startupDir = "."; //std::cout << "Launching process: " << appName.data() << std::endl; stat = process.launch(appName,params,startupDir); CPPUNIT_ASSERT_MESSAGE("Launched application", stat == OS_SUCCESS); CPPUNIT_ASSERT_MESSAGE("Application running", process.isRunning()); int priority; process.setPriority(1); process.getPriority(priority); CPPUNIT_ASSERT_EQUAL_MESSAGE("Set priority ok", 1, priority); OsProcess newProcess; stat = OsProcess::getByPID(process.getPID(), newProcess); CPPUNIT_ASSERT_MESSAGE("Got process pid ok", stat == OS_SUCCESS); //std::cout << "Waiting 5 secs before killing process..." << std::endl; OsTask::delay(5000); stat = newProcess.kill(); CPPUNIT_ASSERT_MESSAGE("Able to kill process", stat == OS_SUCCESS); } }; #ifdef WINCE #pragma message( "OsProcessTest disabled undef Win CE" ) #else CPPUNIT_TEST_SUITE_REGISTRATION(OsProcessTest); #endif sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsSemTest.cpp0000644000175000017500000000447512205613256024452 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include class OsSemTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsSemTest); CPPUNIT_TEST(testBasicSemaphore); CPPUNIT_TEST(testCountingSemaphore); CPPUNIT_TEST_SUITE_END(); public: void testBasicSemaphore() { OsBSem* pBSem; pBSem = new OsBSem(OsBSem::Q_PRIORITY, OsBSem::FULL); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pBSem->acquire()); CPPUNIT_ASSERT_EQUAL(OS_BUSY, pBSem->tryAcquire()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pBSem->release()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pBSem->acquire(100)); CPPUNIT_ASSERT_EQUAL(OS_WAIT_TIMEOUT, pBSem->acquire(100)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pBSem->release()); delete pBSem; } void testCountingSemaphore() { OsCSem* pCSem; // the initial count on the semaphore will be 2 pCSem = new OsCSem(OsCSem::Q_PRIORITY, 2); // take it once CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pCSem->acquire(100)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pCSem->acquire()); // take it twice CPPUNIT_ASSERT_EQUAL(OS_BUSY, pCSem->tryAcquire()); // try thrice // try once more CPPUNIT_ASSERT_EQUAL(OS_WAIT_TIMEOUT, pCSem->acquire(100)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pCSem->release()); // release once CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pCSem->release()); // release twice // This check work fine under Windows and with sipX implementation // of semaphores on Linux. But native pthread's semaphores behave // differently. So we could not rely on this property. // CPPUNIT_ASSERT_EQUAL(OS_BUSY, pCSem->release()); // release thrice delete pCSem; } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsSemTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsServerTaskTest.cpp0000644000175000017500000000342212205613256026006 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include /// How many times to start/stop threads #define TEST_START_STOP_ITERATIONS 5 /// Stub class for testing OsServerTask. /** * Only purpose of this class is to implement abstract members of OsServerTask. * It is possible to do other fancy things in it, though. */ class TestServerTask : public OsServerTask { public: TestServerTask(const UtlString& name) : OsServerTask(name) {} virtual ~TestServerTask() {} protected: virtual UtlBoolean handleMessage(OsMsg& rMsg) { return FALSE; } }; class OsServerTaskTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsServerTaskTest); CPPUNIT_TEST(testFastStartStop); CPPUNIT_TEST_SUITE_END(); public: void testFastStartStop() { UtlBoolean boolRes; for (int i=0; i #include #include #include #if defined WIN32 && defined WINCE #define LIB_NAME "coredll.dll" #elif defined WIN32 #define LIB_NAME "kernel32.dll" #elif defined __linux__ #define LIB_NAME "libm.so.6" #elif defined __APPLE__ #define LIB_NAME "libm.dylib" #elif defined ANDROID #define LIB_NAME "libm.so" #else #error Please define LIB_NAME for your platform #endif class OsSharedLibMgrTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsSharedLibMgrTest); CPPUNIT_TEST(testLoadUnload); CPPUNIT_TEST_SUITE_END(); public: void testLoadUnload() { OsStatus res; OsSharedLibMgrBase* pLibMgr = OsSharedLibMgr::getOsSharedLibMgr(); CPPUNIT_ASSERT(pLibMgr != NULL); res = pLibMgr->loadSharedLib(LIB_NAME); CPPUNIT_ASSERT(res == OS_SUCCESS); res = pLibMgr->loadSharedLib(LIB_NAME); CPPUNIT_ASSERT(res == OS_SUCCESS); res = pLibMgr->unloadSharedLib(LIB_NAME); CPPUNIT_ASSERT(res == OS_SUCCESS); res = pLibMgr->unloadSharedLib(LIB_NAME); CPPUNIT_ASSERT(res == OS_INVALID); } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsSharedLibMgrTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsSocketTest.cpp0000644000175000017500000001545712205613256025160 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include #include #include #include #include #include class SocketsTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(SocketsTest); CPPUNIT_TEST(testSocketUtils); CPPUNIT_TEST(testWriteMsg); CPPUNIT_TEST(testWriteAndAcceptMsg); CPPUNIT_TEST(testMulticast); CPPUNIT_TEST_SUITE_END(); public: static UtlString mLocalHost; void testSocketUtils() { OsSocket::getHostIp(&mLocalHost); if(mLocalHost.isNull()) { // Otherwise all subsequent tests will fail mLocalHost = "127.0.0.1"; } printf("testSocketUtils setting mLocalHost=\"%s\"\n", mLocalHost.data()); CPPUNIT_ASSERT(!mLocalHost.isNull()); CPPUNIT_ASSERT(OsSocket::isIp4Address(mLocalHost)); } /** * Open datagram socket and send a few bytes. */ void testWriteMsg() { OsSocket* s = new OsDatagramSocket(8020, mLocalHost); if(!s->isOk() || s->getSocketDescriptor() < 0) { printf("socket descripter not valid: %d\n", s->getSocketDescriptor()); } CPPUNIT_ASSERT(s->getSocketDescriptor() >= 0); CPPUNIT_ASSERT(s->isOk()); const char* msg = "hello\n"; int len = (int)strlen(msg); int bytesWritten = s->write(msg, len); CPPUNIT_ASSERT_EQUAL_MESSAGE("write correct number of bytes", bytesWritten, len); s->close(); delete s; } /** * Start a client and server and send 2 messages over TCP thru them */ void testWriteAndAcceptMsg() { int port = 8021; long socketTimeout = 5000; OsServerSocket* server = new OsServerSocket(50, port, mLocalHost); printf("binding to %s:%d\n", mLocalHost.data(), port); // This test being single threaded stresses some platform specific issues // On some platforms you can do a blocking connect on the client and then accept on the // server side. On others its the other way around. So we do a non-blocking connect on // the client side. We block latter after the accept to assure it connects. UtlBoolean block = FALSE; OsSocket* client = new OsConnectionSocket(port, mLocalHost, block); OsSocket* serverClient = NULL; /*int delayCount = 0; while(!server->isConnectionReady()) { OsTask::delay(100); delayCount++; if(delayCount > 50) break; } if(server->isConnectionReady()) {*/ serverClient = server->accept(); CPPUNIT_ASSERT(serverClient); /*} else { CPPUNIT_ASSERT_MESSAGE("server->isConnectionReady returned false", 0); }*/ // Now make client connection blocking. // With non-blocking client server-to-client message test will fail // on fast machines (say on Core 2 Duo processors). client->makeBlocking(); // Now make client connection blocking. // With non-blocking client server-to-client message test will fail // on fast machines (say on Core 2 Duo processors). client->makeBlocking(); CPPUNIT_ASSERT_MESSAGE("socket server failed to accept connection", serverClient != NULL); const char* msg = "hello\n"; int len = (int)strlen(msg) + 1; // +1 for NULL int bytesWritten = client->write(msg, len, socketTimeout); CPPUNIT_ASSERT_EQUAL_MESSAGE("write correct number of bytes", bytesWritten, len); char recvBuf[1024]; int bytesRead = serverClient->read(recvBuf, sizeof(recvBuf) - 1, socketTimeout); CPPUNIT_ASSERT_EQUAL_MESSAGE("read correct number of bytes", len, bytesRead); ASSERT_STR_EQUAL_MESSAGE("message same as was sent", msg, recvBuf); const char *resp = "bye"; len = (int)strlen(resp) + 1; // +1 for NULL bytesWritten = serverClient->write(resp, len, socketTimeout); CPPUNIT_ASSERT_EQUAL_MESSAGE("write correct number of bytes on 2nd msg", len, bytesWritten); bytesRead = client->read(recvBuf, sizeof(recvBuf) - 1, socketTimeout); CPPUNIT_ASSERT_EQUAL_MESSAGE("read correct number of bytes on 2nd msg", len, bytesRead); CPPUNIT_ASSERT_EQUAL_MESSAGE("write correct number of bytes on 2nd msg", len, bytesWritten); ASSERT_STR_EQUAL_MESSAGE("2nd message same as was sent", resp, recvBuf); serverClient->close(); client->close(); server->close(); delete client; delete server; } /** * Open two multicast sockets and enable local loopback. * Send a few bytes on the 1st & make sure we receive the data back on the 2nd. */ void testMulticast() { OsMulticastSocket* writer = new OsMulticastSocket(8022, "224.10.11.12", 8022, "224.10.11.12"); OsMulticastSocket* reader = new OsMulticastSocket(8022, "224.10.11.12", 8022, "224.10.11.12"); writer->setHopCount(1); // Make sure we'll receive our own message. // * In Winsock, the IP_MULTICAST_LOOP option applies only to the receive path. // * In the UNIX version, the IP_MULTICAST_LOOP option applies to the send path. #ifdef WIN32 // [ reader->setLoopback(true); #else // WIN32 ][ writer->setLoopback(true); #endif // WIN32 ] const char* msg = "hello\n"; int len = strlen(msg) + 1; // +1 for NULL int bytesWritten = writer->write(msg, len); CPPUNIT_ASSERT_EQUAL_MESSAGE("write correct number of bytes", bytesWritten, len); char recvBuf[1024]; int bytesRead = reader->OsSocket::read(recvBuf, sizeof(recvBuf) - 1, 100); CPPUNIT_ASSERT_EQUAL_MESSAGE("read correct number of bytes", len, bytesRead); ASSERT_STR_EQUAL_MESSAGE("message same as was sent", msg, recvBuf); writer->close(); reader->close(); delete writer; delete reader; } }; UtlString SocketsTest::mLocalHost; CPPUNIT_TEST_SUITE_REGISTRATION(SocketsTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsTestUtilities.cpp0000644000175000017500000001111212205613256025663 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2013 SIPez LLC All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include //Application Includes #include #include #include #include #include void OsTestUtilities::createTestDir(OsPath& root) { OsStatus stat; #ifdef ANDROID root = "/sdcard"; #else OsFileSystem::getWorkingDirectory(root); #endif printf("Test dir root: %s\n", root.data()); root.append(OsPath::separator).append("OsFileSystemTest"); if (OsFileSystem::exists(root)) { removeTestDir(root); } stat = OsFileSystem::createDir(root); CPPUNIT_ASSERT_MESSAGE("setup root test dir", stat == OS_SUCCESS); } void OsTestUtilities::removeTestDir(OsPath &root) { OsStatus stat; if (OsFileSystem::exists(root)) { stat = OsFileSystem::remove(root, TRUE, TRUE); KNOWN_BUG("Fails randomly on build server and fails everytime, the first time its run on a new machine", "XPL-191"); CPPUNIT_ASSERT_MESSAGE("teardown root test dir", stat == OS_SUCCESS); } } void OsTestUtilities::initDummyBuffer(char *buff, int size) { printf("OsTestUtilities::initDummyBuffer(%p, %d)\n", buff, size); for (int i = 0; i < size; i++) { buff[i] = (char)(i % 256); } printf("exit OsTestUtilities::initDummyBuffer\n"); } UtlBoolean OsTestUtilities::testDummyBuffer(char *buff, unsigned long size, unsigned long position) { for (unsigned long i = 0; i < size; i++) { char expected = (char)((position + i) % 256); if (buff[i] != expected) { printf("buff[%li] = %i, expected = %i\n", position, buff[i], expected); return false; } } return true; } OsStatus OsTestUtilities::createDummyFile(OsPath testFile, unsigned long size) { printf("OsTestUtilities::createDummyFile(%s, %l)\n", testFile.data(), size); OsStatus stat; char wbuff[10000]; unsigned long wbuffsize = (unsigned long)sizeof(wbuff); OsTestUtilities::initDummyBuffer(wbuff, sizeof(wbuff)); printf("construct OsFile\n"); OsFile wfile(testFile); printf("opening %s\n", testFile.data()); stat = wfile.open(OsFile::CREATE); printf("created\n"); UtlString msg("failed to create file: "); msg.append(testFile); msg.appendFormat(" error: %d", stat); CPPUNIT_ASSERT_MESSAGE(msg.data(), stat == OS_SUCCESS); if (stat == OS_SUCCESS) { printf("stat ok\n"); unsigned long wposition = 0; for (int i = 0; stat == OS_SUCCESS && wposition < wbuffsize; i++) { printf("about to write\n"); unsigned long remaining = wbuffsize - wposition; unsigned long byteswritten = 0; stat = wfile.write(wbuff + wposition, remaining, byteswritten); printf("write %d bytes return: %d\n", byteswritten, stat); wposition += byteswritten; } wfile.close(); } printf("exit OsTestUtilities::createDummyFile\n"); return stat; } UtlBoolean OsTestUtilities::verifyDummyFile(OsPath testFile, unsigned long size) { OsStatus stat; UtlBoolean ok = false; char rbuff[256]; unsigned long rbuffsize = (unsigned long)sizeof(rbuff); OsFile rfile(testFile); stat = rfile.open(); UtlString msg("Failed to create file: "); msg.append(testFile); CPPUNIT_ASSERT_MESSAGE(testFile.data(), stat == OS_SUCCESS); if (stat == OS_SUCCESS) { unsigned long rposition = 0; ok = true; for (int i = 0; ok && rposition < size; i++) { unsigned long remaining = (size - rposition); unsigned long readsize = remaining < rbuffsize ? remaining : rbuffsize; unsigned long bytesread = 0; stat = rfile.read(rbuff, readsize, bytesread); CPPUNIT_ASSERT_MESSAGE("Failed to read", stat != 0); if (stat != OS_SUCCESS) { ok = false; printf("Error reading file, status = %i", stat); } else { ok = OsTestUtilities::testDummyBuffer(rbuff, bytesread, rposition); rposition += bytesread; } } rfile.close(); } return ok; } sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsTestUtilities.h0000644000175000017500000000232412205613256025335 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsTestUtilities_h_ #define _OsTestUtilities_h_ /** * Common utility functions for unittests */ class OsTestUtilities { public: /** * Create root dir for tests */ static void createTestDir(OsPath &root); /** * Destroy root dir for tests */ static void removeTestDir(OsPath &root); /** * create a simple buffer w/all possible chars */ static void initDummyBuffer(char *buff, int size); /** * test that simple buffer is read correctly */ static UtlBoolean testDummyBuffer(char *buff, unsigned long size, unsigned long position); /** * Create a dummy file with predicatable contents */ static OsStatus createDummyFile(OsPath testFile, unsigned long size); /** * Test the contents of dummy files */ static UtlBoolean verifyDummyFile(OsPath testFile, unsigned long size); }; #endif sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsTimerTaskTest.cpp0000644000175000017500000000235512205613256025624 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include class OsTimerTaskTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsTimerTaskTest); CPPUNIT_TEST(testTimerTask); CPPUNIT_TEST_SUITE_END(); public: void testTimerTask() { OsTimerTask* pTimerTask; pTimerTask = OsTimerTask::getTimerTask(); CPPUNIT_ASSERT_MESSAGE("Timer task created 1", pTimerTask != NULL); OsTask::delay(500); // wait 1/2 second pTimerTask->destroyTimerTask(); OsTask::delay(500); // wait 1/2 second pTimerTask = OsTimerTask::getTimerTask(); CPPUNIT_ASSERT_MESSAGE("Timer task created 2", pTimerTask != NULL); OsTask::delay(500); // wait 1/2 second pTimerTask->destroyTimerTask(); } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsTimerTaskTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsTimerTest.cpp0000644000175000017500000007531312205613256025005 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2010 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include #include #include #include #include #include #include /* System-dependent definition of "current time" structure. */ #if defined(WIN32) || defined(_VXWORKS) typedef struct _GTimeVal { long tv_usec; long tv_sec; } GTimeVal; #elif defined(__pingtel_on_posix__) #include typedef struct timeval GTimeVal; #else #error "Cannot determine system type." #endif /* System-dependent code to fetch the current time. */ #if defined(WIN32) void g_get_current_time(GTimeVal* curTime) { typedef union { FILETIME ft ; unsigned __int64 int64 ; } g_FILETIME ; unsigned __int64 ticks ; unsigned __int64 freq ; static bool sbInitialized = false ; static g_FILETIME sOsFileTime ; static unsigned __int64 sLastTicks = 0 ; static unsigned __int64 sResetTime = 0 ; QueryPerformanceCounter((LARGE_INTEGER*) &ticks) ; QueryPerformanceFrequency((LARGE_INTEGER*) &freq) ; if (!sbInitialized || sOsFileTime.int64 > sResetTime) { sbInitialized = true ; GetSystemTimeAsFileTime(&sOsFileTime.ft); sResetTime = -1 ; // sOsFileTime.int64 + (freq - 1) ; sLastTicks = ticks ; } else { unsigned __int64 delta = ticks - sLastTicks ; sLastTicks = ticks ; sOsFileTime.int64 = sOsFileTime.int64 + (((unsigned __int64) 10000000) * (delta / freq)) + (((unsigned __int64) 10000000) * (delta % freq)) / freq ; SYSTEMTIME si ; FileTimeToSystemTime(&sOsFileTime.ft, &si) ; } curTime->tv_sec = (long) ((sOsFileTime.int64 - ((unsigned __int64) 116444736000000000)) / ((unsigned __int64) 10000000)); curTime->tv_usec = (long) ((sOsFileTime.int64 / ((unsigned __int64) 10)) % ((unsigned __int64) 1000000)); } #elif defined(_VXWORKS) void g_get_current_time(GTimeVal* curTime) { OsTime rTime; OsDateTimeVxw::highResTime( rTime ); curTime->tv_sec = rTime.seconds(); curTime->tv_usec = rTime.usecs(); } #elif defined(__pingtel_on_posix__) void g_get_current_time(GTimeVal* curTime) { gettimeofday(curTime, NULL); } #endif /* * OSTIMETOLERANCE is the allowed 'slop', in milliseconds; timers may * be off by this much before the test is considered a failure. The * current value may be too high; see XPL-39. */ #define OSTIMETOLERANCE 40 #define REPORT_SKEW(x) printf x //#define REPORT_SKEW(x) /* x */ OsTime tenMsec(0, 10000);// timer offset ten msec into the future OsTime hundredMsec(0, 100000);// timer offset hundred msec into the future OsTime oneSecond(1,0); // timer offset one second into the future OsTime twoSeconds(2,0); // timer offset two seconds into the future OsTime tenSeconds(10,0); // timer offset ten seconds into the future OsTime tenYears(10*365*24*60*60, 0); // ten years into the future class OsTimerTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsTimerTest); CPPUNIT_TEST(testImmediateTimer); CPPUNIT_TEST(testOneShotAfter); CPPUNIT_TEST(testTimerAccuracy) ; CPPUNIT_TEST(testOneShotAt) ; CPPUNIT_TEST(testStopTimerAfterOneShot); CPPUNIT_TEST(testPeriodicTimer) ; CPPUNIT_TEST(testOneshotPeriodicComboTimer) ; CPPUNIT_TEST(testStopPeriodicTimer) ; CPPUNIT_TEST(testPeriodicTimer_FractionalTime); CPPUNIT_TEST(testDeleteTimerBeforeExpires); CPPUNIT_TEST(testStartFire); CPPUNIT_TEST(testStartStop); CPPUNIT_TEST(testStartPeriodicStop); CPPUNIT_TEST(testStartDelete); CPPUNIT_TEST(testStartStopStartFire); CPPUNIT_TEST(testStartStart); CPPUNIT_TEST(testStartStopStop); CPPUNIT_TEST(testStartFireStop); CPPUNIT_TEST(testStop); // Test to verify that GTimeVal and g_get_current_time work in the // current environment. CPPUNIT_TEST(sanityVerificationOfTimeFunctions); CPPUNIT_TEST(testDelayedStopMessage); CPPUNIT_TEST_SUITE_END(); private : static GTimeVal progStart; GTimeVal startTV; GTimeVal delayTV; GTimeVal endTV; int gCallBackCount; public: void setUp() { gCallBackCount = 0; startTV.tv_sec = startTV.tv_usec = 0; endTV = startTV; } void tearDown() { } void setTVCalled() { g_get_current_time(&endTV); gCallBackCount++ ; } static void TVCallback(const intptr_t userData, const intptr_t eventData) { OsTimerTest* foo = (OsTimerTest*) userData; foo->setTVCalled(); } long SecsToUsecs(long secs) { return (secs*OsTime::USECS_PER_SEC) ; } long MsecsToUsecs(long mSecs) { return (mSecs*OsTime::USECS_PER_MSEC) ; } long SecsToMsecs(long secs) { return (secs * OsTime::MSECS_PER_SEC) ; } long getTimeDeltaInUsecs() { return (SecsToUsecs(endTV.tv_sec - startTV.tv_sec) + (endTV.tv_usec - startTV.tv_usec)) ; } void DynaTest() { } void testImmediateTimer() { OsCallback* pNotifier ; OsTimer* pTimer ; OsStatus returnValue; long diffUSecs ; pNotifier = new OsCallback((intptr_t)this, TVCallback); pTimer = new OsTimer(*pNotifier); gCallBackCount = 0; g_get_current_time(&startTV); returnValue = pTimer->oneshotAfter(OsTime::NO_WAIT_TIME); // Although the message is supposed to be immediate, give a // little extra time OsTask::delay(OSTIMETOLERANCE); CPPUNIT_ASSERT_MESSAGE("Handle timer 1 (immediate) - ReturnValue", returnValue == OS_SUCCESS); CPPUNIT_ASSERT_MESSAGE("Handle timer 1 (immediate) - Timer was fired", gCallBackCount == 1); CPPUNIT_ASSERT_MESSAGE("Handle timer 1 (immediate) - mWasFired = TRUE", pTimer->getWasFired() == TRUE); diffUSecs = getTimeDeltaInUsecs() ; REPORT_SKEW((" Timing inaccuracy = %6ld us;\n", diffUSecs)); CPPUNIT_ASSERT_MESSAGE("Handle timer 1 (immediate) - Verify timer was " "fired immediately", diffUSecs > 0 && diffUSecs <= MsecsToUsecs(OSTIMETOLERANCE)); delete pTimer; delete pNotifier; } void testOneShotAfter() { struct TestOneShotStruct { const char* testDescription ; long seconds ; long milliseconds ; int tolerance ; } ; OsCallback* pNotifier; string Message ; int testCount ; TestOneShotStruct testData[] = { { "Test one shot after when time is specified as 0", 0, 0, OSTIMETOLERANCE }, { "Test one shot after when time is equal to one second", 1, 0, OSTIMETOLERANCE }, /* The next case was added to check if the inaccuracy applies ONLY to decimal values or even to integers */ { "Test one shot after when time is greater than one second", 2, 285, OSTIMETOLERANCE }, { "Test one shot after when time is an integer > 1", 3, 0, OSTIMETOLERANCE }, { "Test one shot after when time is greater than 0 but less than 1", 0, 252, OSTIMETOLERANCE } } ; testCount = sizeof(testData)/ sizeof(testData[0]) ; for (int i = 0 ; i < testCount ; i++) { long expectedWaitUSecs; long diffUSecs; OsTimer* pTimer; UtlBoolean returnValue; OsTime timeToWait(testData[i].seconds, testData[i].milliseconds*OsTime::USECS_PER_MSEC) ; pNotifier = new OsCallback((intptr_t)this, TVCallback); pTimer = new OsTimer(*pNotifier); expectedWaitUSecs= SecsToUsecs(testData[i].seconds) + MsecsToUsecs(testData[i].milliseconds) ; // Give a small delay so we synchronize with the timer. OsTask::delay(20); g_get_current_time(&startTV); gCallBackCount = 0; returnValue = pTimer->oneshotAfter(timeToWait); OsTask::delay(expectedWaitUSecs / OsTime::USECS_PER_MSEC + testData[i].tolerance) ; Message = testData[i].testDescription; Message.append(" - verify return value"); // gCallBackCount is reinitialized to 0 each iteration, so // its value should be 1 now. CPPUNIT_ASSERT_MESSAGE("Verify timer was fired for each iteration", gCallBackCount == 1); CPPUNIT_ASSERT_MESSAGE("mWasFired = TRUE in the current iteration", pTimer->getWasFired() == TRUE); CPPUNIT_ASSERT_MESSAGE(Message.data(), returnValue); Message = testData[i].testDescription; Message.append(" - verify timer *was* fired"); diffUSecs = getTimeDeltaInUsecs(); REPORT_SKEW((" Timing inaccuracy for iter %3d = %8ld us; Time = %ld.%03ld;\n", i, diffUSecs - expectedWaitUSecs, testData[i].seconds, testData[i].milliseconds )); CPPUNIT_ASSERT_MESSAGE(Message.data(), diffUSecs >= expectedWaitUSecs - MsecsToUsecs(testData[i].tolerance) && diffUSecs <= expectedWaitUSecs + MsecsToUsecs(testData[i].tolerance)); delete pTimer; delete pNotifier; } } void testTimerAccuracy() { OsCallback* pNotifier; OsTimer* pTimer; long expectedWaitUSecs; long diffUSecs; pNotifier = new OsCallback((intptr_t)this, TVCallback); pTimer = new OsTimer(*pNotifier); expectedWaitUSecs=(1*OsTime::USECS_PER_SEC) + (250*OsTime::USECS_PER_MSEC) ; OsTime timeToWait(1, 250*OsTime::USECS_PER_MSEC) ; // Give a small delay so we synchronize with the timer. OsTask::delay(20); g_get_current_time(&startTV); pTimer->oneshotAfter(timeToWait); //Sleep for a slightly additional time OsTask::delay(expectedWaitUSecs / OsTime::USECS_PER_MSEC + OSTIMETOLERANCE) ; CPPUNIT_ASSERT_MESSAGE("Timer was fired", gCallBackCount == 1); diffUSecs = getTimeDeltaInUsecs(); REPORT_SKEW((" Timing inaccuracy = %8ld us; Time = %d.%03d;\n", diffUSecs - expectedWaitUSecs, 1, 250 )); CPPUNIT_ASSERT_MESSAGE("Verify that the timer is fired accurately", diffUSecs >= expectedWaitUSecs - MsecsToUsecs(OSTIMETOLERANCE) && diffUSecs <= expectedWaitUSecs + MsecsToUsecs(OSTIMETOLERANCE)); delete pTimer; delete pNotifier; } void testOneShotAt() { OsCallback* pNotifier ; OsTimer* pTimer ; UtlBoolean returnValue ; long diffUSecs ; pNotifier = new OsCallback((intptr_t)this, TVCallback); pTimer = new OsTimer(*pNotifier); // Create an OsDateTime object for 2 seconds in the future // and call oneShotAt. // Get the current time in seconds. time_t now = time(NULL) ; now += 2 ; // Split it into the components needed to construct an OsDateTime. tm* gmtPlus2 = gmtime(&now) ; // Get the current time to microsecond resolution. OsDateTime current; OsDateTime::getCurTime(current); // Put the components of gmtime into an OsDateTime, and add the // microseconds from "current". OsDateTime odt( // gmtime returns (year - 1900), but OsDateTime requires 4-digit year. (unsigned short) gmtPlus2->tm_year + 1900, (unsigned char)gmtPlus2->tm_mon, (unsigned char)gmtPlus2->tm_mday, (unsigned char)gmtPlus2->tm_hour, (unsigned char)gmtPlus2->tm_min, (unsigned char)gmtPlus2->tm_sec, (unsigned int) current.getMicrosecond() ); g_get_current_time(&startTV); gCallBackCount = 0; returnValue = pTimer->oneshotAt(odt); //Although the message is supposed to be immediate, give a little extra time OsTask::delay(2000 + OSTIMETOLERANCE); CPPUNIT_ASSERT_MESSAGE("Handle timer 1 - returnValue", returnValue); CPPUNIT_ASSERT_MESSAGE("Timer was fired", gCallBackCount == 1); CPPUNIT_ASSERT_MESSAGE("mWasFired = TRUE", pTimer->getWasFired() == TRUE); diffUSecs = getTimeDeltaInUsecs(); REPORT_SKEW((" Timing inaccuracy = %6ld us;\n", diffUSecs - MsecsToUsecs(2000))); CPPUNIT_ASSERT_MESSAGE("Handle timer 1 - Verify timer was fired " "after 2 secs", diffUSecs > MsecsToUsecs(2000 - OSTIMETOLERANCE) && diffUSecs < MsecsToUsecs(2000 + OSTIMETOLERANCE)); delete pTimer; delete pNotifier; } void testStopTimerAfterOneShot() { OsCallback* pNotifier; OsTimer* pTimer ; pNotifier = new OsCallback((intptr_t)this, TVCallback); pTimer = new OsTimer(*pNotifier); gCallBackCount = 0; pTimer->oneshotAfter(oneSecond) ; OsTask::delay(500) ; pTimer->stop() ; OsTask::delay(1200) ; // We have waited for 1.7 sec after arming the timer, and the timer // was scheduled to fire after 1.0 sec. But we disarmed the timer // after 0.5 sec, so gCallBackCount should be 0. CPPUNIT_ASSERT_MESSAGE("Verify that canceling the timer disarms it", gCallBackCount == 0); CPPUNIT_ASSERT_MESSAGE("mWasFired = FALSE", pTimer->getWasFired() == FALSE); delete pTimer ; delete pNotifier; } void testPeriodicTimer() { OsCallback* pNotifier ; OsTimer* pTimer ; UtlBoolean returnValue ; pNotifier = new OsCallback((intptr_t)this, TVCallback); pTimer = new OsTimer(*pNotifier); gCallBackCount = 0; returnValue = pTimer->periodicEvery(twoSeconds, twoSeconds) ; //Give a delay of 10+ seconds . If all went well the call back method //must have been called once every 2 seconds and hence the callback count //must be up by 5. OsTask::delay(11250) ; CPPUNIT_ASSERT_MESSAGE("Test periodic timer - verify return value", returnValue) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Test periodic timer - verify that the " "timer is called periodically", 5, gCallBackCount); //we didn't stop the timer, and it fired, so flag should be TRUE CPPUNIT_ASSERT_MESSAGE("mWasFired = TRUE", pTimer->getWasFired() == TRUE); delete pTimer ; delete pNotifier; } void testPeriodicTimer_FractionalTime() { OsCallback* pNotifier ; OsTimer* pTimer ; pNotifier = new OsCallback((intptr_t)this, TVCallback); pTimer = new OsTimer(*pNotifier); gCallBackCount = 0; pTimer->periodicEvery(OsTime::NO_WAIT_TIME, hundredMsec); //Give a delay of 1+ seconds . If all went well the call back method //must have been called once in the beginning and every 100 milliseconds thereafter //and hence the callback count must be up by 10+1. OsTask::delay(1010) ; KNOWN_BUG("Intermittent failure here; not predictable", "XPL-52"); CPPUNIT_ASSERT_EQUAL_MESSAGE("Test periodic timer - verify that the fractional timer is " "*indeed* called periodically", 11, gCallBackCount); CPPUNIT_ASSERT_MESSAGE("mWasFired = TRUE", pTimer->getWasFired() == TRUE); delete pTimer ; delete pNotifier; } void testOneshotPeriodicComboTimer() { UtlBoolean returnValue ; OsCallback* pNotifier ; OsTimer* pTimer ; long diffUSecs ; pNotifier = new OsCallback((intptr_t)this, TVCallback); pTimer = new OsTimer(*pNotifier); gCallBackCount = 0; g_get_current_time(&startTV); returnValue = pTimer->periodicEvery(oneSecond, twoSeconds) ; OsTask::delay(1000 + OSTIMETOLERANCE) ; CPPUNIT_ASSERT_MESSAGE("Test oneshot & periodic timer combo - " "verify return value", returnValue) ; CPPUNIT_ASSERT_MESSAGE("Timer was fired", gCallBackCount == 1); diffUSecs = getTimeDeltaInUsecs(); REPORT_SKEW((" Timing inaccuracy = %ld us;\n", diffUSecs - MsecsToUsecs(1000))); CPPUNIT_ASSERT_MESSAGE("Test oneshot/periodic combo - " "Verify first call is based on first argument", diffUSecs > MsecsToUsecs(1000 - OSTIMETOLERANCE) && diffUSecs < MsecsToUsecs(1000 + OSTIMETOLERANCE) ) ; // now wait for another 5+ seconds. The total time after starting the timer is // 6 seconds. OsTask::delay(5340) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Test oneshot/periodic combo - Verify the timer is called " "repeatadly as per the second argument", 3, gCallBackCount); delete pTimer ; delete pNotifier; } void testStopPeriodicTimer() { OsCallback* pNotifier ; OsTimer* pTimer ; OsTimer* pTimer2 ; long diffUSecs ; pNotifier = new OsCallback((intptr_t)this, TVCallback); pTimer = new OsTimer(*pNotifier); gCallBackCount = 0; pTimer->periodicEvery(oneSecond, twoSeconds) ; // Test the case where the timer is stopped even before the first leg // is fired OsTask::delay(350) ; pTimer->stop() ; // Wait for another 5 seconds. Neither the first shot nor the repeat legs // should ever have been called. OsTask::delay(5000) ; CPPUNIT_ASSERT_MESSAGE("Verify that a periodic timer can be stopped even " "before the first leg is called", gCallBackCount == 0); CPPUNIT_ASSERT_MESSAGE("mWasFired = FALSE", pTimer->getWasFired() == FALSE); delete pTimer ; pTimer2 = new OsTimer(*pNotifier); gCallBackCount = 0; g_get_current_time(&startTV); pTimer2->periodicEvery(oneSecond, twoSeconds) ; OsTask::delay(1000 + OSTIMETOLERANCE) ; pTimer2->stop() ; // Wait for another 5 seconds. Only the first shot should have been called. OsTask::delay(5000) ; CPPUNIT_ASSERT_MESSAGE("Timer was fired", gCallBackCount == 1); diffUSecs = getTimeDeltaInUsecs() ; REPORT_SKEW((" Timing inaccuracy = %ld us;\n", diffUSecs - MsecsToUsecs(1000))); CPPUNIT_ASSERT_MESSAGE("Test stopping periodic timer - Verify that the " "first leg was fired", diffUSecs > MsecsToUsecs(1000 - OSTIMETOLERANCE) && diffUSecs < MsecsToUsecs(1000 + OSTIMETOLERANCE) ) ; // Also verify that only the first leg was called. CPPUNIT_ASSERT_EQUAL_MESSAGE("Test stopping periodic timer - Verify that ONLY the first " "leg was fired", 1, gCallBackCount); // timer was stopped manually, so FALSE CPPUNIT_ASSERT_MESSAGE("mWasFired = FALSE", pTimer2->getWasFired() == FALSE); delete pTimer2 ; delete pNotifier; } void testDeleteTimerBeforeExpires() { OsCallback* pNotifier ; OsTimer* pTimer ; pNotifier = new OsCallback((intptr_t)this, TVCallback); pTimer = new OsTimer(*pNotifier); gCallBackCount = 0; pTimer->periodicEvery(oneSecond, twoSeconds) ; OsTask::delay(350) ; delete pTimer ; // Wait for another 5 seconds. Neither the first shot nor the repeat legs // should ever have been called. OsTask::delay(5000) ; CPPUNIT_ASSERT_MESSAGE("Verify that a periodic timer can be stopped even " "before the first leg is called", gCallBackCount == 0); delete pNotifier ; } // Tests for various sequences of operations. void testStartFire() { OsStatus returnValue; OsCallback notifier((intptr_t) this, TVCallback); OsTimer timer(notifier); gCallBackCount = 0; returnValue = timer.oneshotAfter(oneSecond); CPPUNIT_ASSERT_MESSAGE("oneshotAfter", returnValue == OS_SUCCESS); OsTask::delay(5000); CPPUNIT_ASSERT_MESSAGE("Test start/fire", gCallBackCount == 1); CPPUNIT_ASSERT_MESSAGE("mWasFired = TRUE", timer.getWasFired() == TRUE); } void testStartStop() { OsStatus returnValue; OsCallback notifier((intptr_t) this, TVCallback); OsTimer timer(notifier); gCallBackCount = 0; returnValue = timer.oneshotAfter(oneSecond); CPPUNIT_ASSERT_MESSAGE("oneshotAfter", returnValue == OS_SUCCESS); OsTask::delay(500); returnValue = timer.stop(); CPPUNIT_ASSERT_MESSAGE("stop", returnValue == OS_SUCCESS); CPPUNIT_ASSERT_MESSAGE("mWasFired = FALSE", timer.getWasFired() == FALSE); OsTask::delay(5000); CPPUNIT_ASSERT_MESSAGE("Test start/stop", gCallBackCount == 0); } void testStartPeriodicStop() { OsStatus returnValue; OsCallback notifier((intptr_t) this, TVCallback); OsTimer timer(notifier); gCallBackCount = 0; returnValue = timer.periodicEvery(oneSecond, twoSeconds); CPPUNIT_ASSERT_MESSAGE("periodicEvery", returnValue == OS_SUCCESS); // Allow to fire 3 times OsTask::delay(6000); CPPUNIT_ASSERT_MESSAGE("mWasFired = TRUE", timer.getWasFired() == TRUE); returnValue = timer.stop(); CPPUNIT_ASSERT_MESSAGE("stop", returnValue == OS_SUCCESS); CPPUNIT_ASSERT_MESSAGE("mWasFired = FALSE", timer.getWasFired() == FALSE); OsTask::delay(5000); CPPUNIT_ASSERT_MESSAGE("Test start-periodic/fire/stop", gCallBackCount == 3); } void testStartDelete() { OsStatus returnValue; OsCallback notifier((intptr_t) this, TVCallback); OsTimer* pTimer = new OsTimer(notifier); gCallBackCount = 0; returnValue = pTimer->oneshotAfter(oneSecond); CPPUNIT_ASSERT_MESSAGE("oneshotAfter", returnValue == OS_SUCCESS); OsTask::delay(500); CPPUNIT_ASSERT_MESSAGE("mWasFired = FALSE", pTimer->getWasFired() == FALSE); // Delete the timer before it can fire. delete pTimer; // Make sure it did not fire. OsTask::delay(5000); CPPUNIT_ASSERT_MESSAGE("Test start/delete", gCallBackCount == 0); } void testStartStopStartFire() { OsStatus returnValue; OsCallback notifier((intptr_t) this, TVCallback); OsTimer timer(notifier); gCallBackCount = 0; returnValue = timer.oneshotAfter(oneSecond); CPPUNIT_ASSERT_MESSAGE("oneshotAfter 1", returnValue == OS_SUCCESS); OsTask::delay(500); returnValue = timer.stop(); CPPUNIT_ASSERT_MESSAGE("mWasFired = FALSE", timer.getWasFired() == FALSE); CPPUNIT_ASSERT_MESSAGE("stop", returnValue == OS_SUCCESS); OsTask::delay(500); returnValue = timer.oneshotAfter(oneSecond); CPPUNIT_ASSERT_MESSAGE("oneshotAfter 2", returnValue == OS_SUCCESS); OsTask::delay(5000); CPPUNIT_ASSERT_MESSAGE("Test start/fire", gCallBackCount == 1); } void testStartStart() { OsStatus returnValue; OsCallback notifier((intptr_t) this, TVCallback); OsTimer timer(notifier); gCallBackCount = 0; returnValue = timer.oneshotAfter(oneSecond); CPPUNIT_ASSERT_MESSAGE("oneshotAfter 1", returnValue == OS_SUCCESS); OsTask::delay(500); returnValue = timer.oneshotAfter(oneSecond); CPPUNIT_ASSERT_MESSAGE("oneshotAfter 2", returnValue == OS_FAILED); OsTask::delay(5000); CPPUNIT_ASSERT_MESSAGE("Test start/fire", gCallBackCount == 1); } void testStartStopStop() { OsStatus returnValue; OsCallback notifier((intptr_t) this, TVCallback); OsTimer timer(notifier); gCallBackCount = 0; returnValue = timer.oneshotAfter(oneSecond); CPPUNIT_ASSERT_MESSAGE("oneshotAfter", returnValue == OS_SUCCESS); OsTask::delay(500); returnValue = timer.stop(); CPPUNIT_ASSERT_MESSAGE("stop 1", returnValue == OS_SUCCESS); OsTask::delay(500); returnValue = timer.stop(); CPPUNIT_ASSERT_MESSAGE("stop 2", returnValue == OS_FAILED); OsTask::delay(5000); CPPUNIT_ASSERT_MESSAGE("Test start/fire", gCallBackCount == 0); } void testStartFireStop() { OsStatus returnValue; OsCallback notifier((intptr_t) this, TVCallback); OsTimer timer(notifier); gCallBackCount = 0; returnValue = timer.oneshotAfter(oneSecond); CPPUNIT_ASSERT_MESSAGE("oneshotAfter", returnValue == OS_SUCCESS); OsTask::delay(1500); returnValue = timer.stop(); CPPUNIT_ASSERT_MESSAGE("stop", returnValue == OS_FAILED); OsTask::delay(5000); CPPUNIT_ASSERT_MESSAGE("Test start/fire", gCallBackCount == 1); } void testStop() { OsStatus returnValue; OsCallback notifier((intptr_t) this, TVCallback); OsTimer timer(notifier); gCallBackCount = 0; returnValue = timer.stop(); CPPUNIT_ASSERT_MESSAGE("stop", returnValue == OS_FAILED); CPPUNIT_ASSERT_MESSAGE("Test start/fire", gCallBackCount == 0); } // Test to verify that GTimeVal and g_get_current_time work in the // current environment. void sanityVerificationOfTimeFunctions() { #define N_TIME_DELTAS 10 int i; struct TimeDeltas { int iterCount ; GTimeVal start ; } ; TimeDeltas td[N_TIME_DELTAS] ; GTimeVal tStart, tNow; int calls; for (i=0; i= 0) { g_get_current_time(&tNow) ; calls++; } td[i].iterCount = calls; td[i].start = tStart; tStart = tNow; } for (i=0; ipostMessage(msg); assert(res == OS_SUCCESS); event.wait(); } else { // Send message. OsTimerMsg msg(OsTimerMsg::OS_TIMER_UPDATE, &timer, NULL); OsStatus res = OsTimerTask::getTimerTask()->postMessage(msg); assert(res == OS_SUCCESS); } } } CPPUNIT_ASSERT(result == OS_SUCCESS); } // We do no explicit test for success of this test, as the success // condition is that it does not trigger "assert(current)" in // OsTimerTask::removeTimer. } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsTimerTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/os/OsTimeTest.cpp0000644000175000017500000001273512205613256024622 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include /** * Unittest for OsTime */ class OsTimeTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(OsTimeTest); CPPUNIT_TEST(testSeconds); CPPUNIT_TEST(testCopyConstructor); CPPUNIT_TEST_SUITE_END(); public: void testSeconds() { const char *msg; OsTime *pInterval1; msg = "test the default constructor (if implemented)"; pInterval1 = new OsTime(); CPPUNIT_ASSERT_MESSAGE(msg, 0 == pInterval1->seconds()); CPPUNIT_ASSERT_MESSAGE(msg, 0 == pInterval1->usecs()); delete pInterval1; // test other constructors (if implemented) msg = "if a constructor parameter is used to set information in \ an ancestor class, then verify it gets set correctly (i.e., via ancestor \ class accessor method."; msg = "try giving the constructor a positive \"millisecond\" value"; pInterval1 = new OsTime(3010); CPPUNIT_ASSERT_MESSAGE(msg, 3 == pInterval1->seconds()); CPPUNIT_ASSERT_MESSAGE(msg, 10000 == pInterval1->usecs()); delete pInterval1; msg = "try giving the constructor a negative \"millisecond\" value"; pInterval1 = new OsTime(-3010); CPPUNIT_ASSERT_MESSAGE(msg, -3010 == pInterval1->cvtToMsecs()); delete pInterval1; msg = "try giving the constructor a positive \"second\" and \"microsecond\" values"; pInterval1 = new OsTime(30, 10); CPPUNIT_ASSERT_MESSAGE(msg, 30 == pInterval1->seconds()); CPPUNIT_ASSERT_MESSAGE(msg, 10 == pInterval1->usecs()); delete pInterval1; msg = "try giving the constructor a negative \"seconds\" value"; pInterval1 = new OsTime(-20, 10); CPPUNIT_ASSERT_MESSAGE(msg, -20 == pInterval1->seconds()); CPPUNIT_ASSERT_MESSAGE(msg, 10 == pInterval1->usecs()); delete pInterval1; msg = "try giving the constructor a negative \"microseconds\" value"; pInterval1 = new OsTime(20, -30); CPPUNIT_ASSERT_MESSAGE(msg, 19 == pInterval1->seconds()); CPPUNIT_ASSERT_MESSAGE(msg, OsTime::USECS_PER_SEC - 30 == pInterval1->usecs()); delete pInterval1; msg = "try giving the constructor a \"microseconds\" value greater \ than one sec"; pInterval1 = new OsTime(20, 2000001); CPPUNIT_ASSERT_MESSAGE(msg, 22 == pInterval1->seconds()); CPPUNIT_ASSERT_MESSAGE(msg, 1 == pInterval1->usecs()); delete pInterval1; msg = "try giving the constructor a \"microseconds\" value less \ than one sec"; pInterval1 = new OsTime(20, -2000001); CPPUNIT_ASSERT_MESSAGE(msg, 17 == pInterval1->seconds()); CPPUNIT_ASSERT_MESSAGE(msg, OsTime::USECS_PER_SEC - 1 == pInterval1->usecs()); delete pInterval1; msg = "try giving the constructor a \"microseconds\" value less \ than one sec"; pInterval1 = new OsTime(20, -1999999); CPPUNIT_ASSERT_MESSAGE(msg, 18 == pInterval1->seconds()); CPPUNIT_ASSERT_MESSAGE(msg, 1 == pInterval1->usecs()); delete pInterval1; } void testCopyConstructor() { const char *msg; OsTime *pInterval1; OsTime *pInterval2; msg = "test the copy constructor applied to an object created \ using the default constructor"; pInterval1 = new OsTime(); pInterval2 = new OsTime(*pInterval1); CPPUNIT_ASSERT_MESSAGE(msg, 0 == pInterval1->seconds()); CPPUNIT_ASSERT_MESSAGE(msg, 0 == pInterval1->usecs()); CPPUNIT_ASSERT_MESSAGE(msg, pInterval2->seconds() == pInterval1->seconds()); CPPUNIT_ASSERT_MESSAGE(msg, pInterval2->usecs() == pInterval1->usecs()); delete pInterval1; delete pInterval2; msg = "test the copy constructor applied to an object create using a \ non-default constructor"; pInterval1 = new OsTime(30, 10); pInterval2 = new OsTime(*pInterval1); CPPUNIT_ASSERT_MESSAGE(msg, 30 == pInterval1->seconds()); CPPUNIT_ASSERT_MESSAGE(msg, 10 == pInterval1->usecs()); CPPUNIT_ASSERT_MESSAGE(msg, pInterval2->seconds() == pInterval1->seconds()); CPPUNIT_ASSERT_MESSAGE(msg, pInterval2->usecs() == pInterval1->usecs()); delete pInterval1; delete pInterval2; } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsTimeTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/0000755000175000017500000000000012321445024022224 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlHashMapPerformance.cpp0000644000175000017500000000700212205613256027124 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "assert.h" // APPLICATION INCLUDES #include "sipxportlib-buildstamp.h" #include "utl/UtlInt.h" #include "utl/UtlHashMap.h" #include "utl/UtlHashMapIterator.h" #include "os/OsTask.h" #include "os/OsTimeLog.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES int externalForSideEffects; // CONSTANTS // comparison base values #define NUM_THREADS 5 // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS void doHashMapOperations(); #include "UtlPerformanceStrings.h" OsTimeLog timer((NUM_THREADS + 1) * 2); class doTestThread : public OsTask { public: int run(void* taskArg) { char mynum[3]; sprintf(mynum, "%02d", getUserData()); UtlString startMsg(" start "); UtlString finishMsg(" finish "); startMsg.append(mynum); finishMsg.append(mynum); timer.addEvent(startMsg.data()); doHashMapOperations(); timer.addEvent(finishMsg.data()); return 0; } UtlBoolean waitUntilShutDown() { this->OsTask::waitUntilShutDown(); return TRUE; } }; int main() { doTestThread* threads[NUM_THREADS]; int n; UtlSList dummy; setupStrings(); for (n = 0; n < NUM_THREADS; n++) { threads[n] = new doTestThread; threads[n]->setUserData(n); } timer.addEvent("All Start"); for (n = 0; n < NUM_THREADS; n++) { threads[n]->start(); } for (n = 0; n < NUM_THREADS; n++) { threads[n]->waitUntilShutDown(); } timer.addEvent("Done"); osPrintf("UtlHashMap Performance v=%s %s:\n", SipXportlibVersion, SipXportlibBuildStamp ); timer.dumpLog(); return 0; } void doHashMapOperations() { UtlHashMap testHash; UtlInt* intValue; size_t item; // fill the hash table for (item = 0; item < NUM_PERFORMANCE_STRINGS; item++) { UtlInt* newValue = new UtlInt(item); testHash.insertKeyAndValue(&string[item], newValue); intValue = dynamic_cast(testHash.findValue(&string[item])); externalForSideEffects = (intValue == newValue); } // take the first half out by value for (item = 0; item < NUM_PERFORMANCE_STRINGS/2; item++) { UtlString key(string[item]); // make a copy so that no reference matching will work UtlContainable* foundValue; testHash.removeKeyAndValue(&key, foundValue); delete foundValue; } // take the rest out by reference for (; item < NUM_PERFORMANCE_STRINGS; item++) { intValue = dynamic_cast(testHash.removeReference(&string[item])); delete intValue; } // fill the list again for (item = 0; item < NUM_PERFORMANCE_STRINGS; item++) { testHash.insertKeyAndValue(&string[item], &string[item]); externalForSideEffects = testHash.entries(); } // iterate over each item in the hash UtlHashMapIterator iterate(testHash); UtlString* strValue = NULL; UtlString* entry; while ((entry = dynamic_cast(iterate()))) { strValue = dynamic_cast(testHash.findValue(entry)); } externalForSideEffects = (strValue == &string[0]); // meaningless, just prevents optimization testHash.removeAll(); } sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlListPerformance.cpp0000644000175000017500000000776612205613256026537 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "assert.h" // APPLICATION INCLUDES #include "sipxportlib-buildstamp.h" #include "utl/UtlString.h" #include "utl/UtlSList.h" #include "utl/UtlSListIterator.h" #include "os/OsTask.h" #include "os/OsTimeLog.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES int externalForSideEffects; // CONSTANTS // comparison base values #include "UtlPerformanceStrings.h" #define NUM_THREADS 5 // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS void doListOperations(); void appendCountItems(UtlSList& list, size_t itemsToAdd); void getCountItems(UtlSList& list, size_t itemsToPop); OsTimeLog timer((NUM_THREADS + 1) * 2); class doTestThread : public OsTask { public: int run(void* taskArg) { char mynum[3]; sprintf(mynum, "%02d", getUserData()); UtlString startMsg(" start "); UtlString finishMsg(" finish "); startMsg.append(mynum); finishMsg.append(mynum); timer.addEvent(startMsg.data()); doListOperations(); timer.addEvent(finishMsg.data()); return 0; } UtlBoolean waitUntilShutDown() { this->OsTask::waitUntilShutDown(); return TRUE; } }; int main() { doTestThread* threads[NUM_THREADS]; int n; UtlSList dummy; for (n = 0; n < NUM_THREADS; n++) { threads[n] = new doTestThread; threads[n]->setUserData(n); } timer.addEvent("All Start"); for (n = 0; n < NUM_THREADS; n++) { threads[n]->start(); } for (n = 0; n < NUM_THREADS; n++) { threads[n]->waitUntilShutDown(); } timer.addEvent("Done"); osPrintf("UtlSlist Performance v=%s %s:\n", SipXportlibVersion, SipXportlibBuildStamp ); timer.dumpLog(); return 0; } void doListOperations() { UtlSList testList; // fill the list appendCountItems(testList, NUM_PERFORMANCE_STRINGS); // take the first half off the front if (!testList.isEmpty()) { getCountItems(testList, NUM_PERFORMANCE_STRINGS / 2); } // take the rest off the end by reference if (!testList.isEmpty()) { UtlContainable* lastItem = testList.last(); delete dynamic_cast(testList.removeReference(lastItem)); } // fill the list appendCountItems(testList, NUM_PERFORMANCE_STRINGS); // search the list for each item by value UtlString target; int targetIndex; for (targetIndex = 0; targetIndex < NUM_PERFORMANCE_STRINGS; targetIndex += 1) { target = string[targetIndex]; UtlString* found = dynamic_cast(testList.find(&target)); if (found) { externalForSideEffects = found->length(); } } // get the object in the middle of the list by index, and remove it by value while(!testList.isEmpty()) { int numberLeft = testList.entries(); UtlString* middle = dynamic_cast(testList.at((numberLeft / 2))); delete dynamic_cast(testList.remove(middle)); } // fill the list appendCountItems(testList, NUM_PERFORMANCE_STRINGS); // iterate over each item in the list UtlSListIterator iterate(testList); UtlString* item; while ((item = dynamic_cast(iterate()))) { externalForSideEffects = item->length(); delete item; } } void appendCountItems(UtlSList& list, size_t itemsToAdd) { assert(itemsToAdd); size_t item; for (item = 0; item < itemsToAdd; item++) { list.append(new UtlString(string[item])); } } void getCountItems(UtlSList& list, size_t itemsToPop) { assert(itemsToPop); for (; !list.isEmpty() && itemsToPop; itemsToPop--) { delete dynamic_cast(list.get()); } } sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/PluginHooksTest.cpp0000644000175000017500000003301412205613256026040 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include "utl/UtlString.h" #include "os/OsConfigDb.h" #include "utl/TestPlugin.h" #include "utl/PluginHooks.h" #include #include #define PLUGIN_LIB_DIR TEST_DIR "/testplugin/.libs/" #ifdef __APPLE__ # define PLUGIN_EXT ".dylib" #else # define PLUGIN_EXT ".so" #endif class PluginHooksTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(PluginHooksTest); CPPUNIT_TEST(testNoHooks); CPPUNIT_TEST(testOneHook); CPPUNIT_TEST(testReadConfig); CPPUNIT_TEST(testTwoInstances); CPPUNIT_TEST(testTwoHookTypes); CPPUNIT_TEST(testReconfigure); CPPUNIT_TEST_SUITE_END(); public: void testNoHooks() { OsConfigDb configuration; configuration.set("NOHOOKS_NOTPASSED_HOOK_LIBRARY.Error", PLUGIN_LIB_DIR "libfoo" PLUGIN_EXT); configuration.set("NOHOOKS_OTHERPARAM", "DummyValue"); // there are no hooks configured for this prefix PluginHooks testPlugins("getTestPlugin", "NOHOOKS_PASSED"); testPlugins.readConfig(configuration); PluginIterator shouldBeEmpty(testPlugins); UtlString name; // confirm that there are no hooks configured. CPPUNIT_ASSERT(shouldBeEmpty.next(&name) == NULL); CPPUNIT_ASSERT(name.isNull()); CPPUNIT_ASSERT(shouldBeEmpty.next() == NULL); } void testOneHook() { OsConfigDb configuration; configuration.set("ONEHOOK_NOTPASSED_HOOK_LIBRARY.Error", PLUGIN_LIB_DIR "libfoo" PLUGIN_EXT); configuration.set("ONEHOOK_OTHERPARAM", "DummyValue"); // configure one hook, with no parameters configuration.set("ONEHOOK_TEST_HOOK_LIBRARY.Only", PLUGIN_LIB_DIR "libtestpluginA" PLUGIN_EXT); PluginHooks testPlugins("getTestPlugin", "ONEHOOK_TEST"); testPlugins.readConfig(configuration); PluginIterator plugin(testPlugins); UtlString name; TestPlugin* thePlugin; // get that one hook thePlugin = static_cast(plugin.next(&name)); // confirm that it is loaded and that it has the right instance name CPPUNIT_ASSERT(thePlugin != NULL); CPPUNIT_ASSERT(!name.isNull()); ASSERT_STR_EQUAL("Only",name.data()); // invoke the pluginName method from the hook to confirm that it's there UtlString fullName; thePlugin->pluginName(fullName); ASSERT_STR_EQUAL("TestPluginA::Only",fullName.data()); // confirm that it is the only configured hook CPPUNIT_ASSERT(plugin.next(&name) == NULL); CPPUNIT_ASSERT(name.isNull()); } void testReadConfig() { OsConfigDb configuration; configuration.set("READCONFIG_NOTPASSED_HOOK_LIBRARY.Error", PLUGIN_LIB_DIR "libfoo" PLUGIN_EXT); configuration.set("READCONFIG_OTHERPARAM", "DummyValue"); // configure a hook configuration.set("READCONFIG_TEST_HOOK_LIBRARY.Only", PLUGIN_LIB_DIR "libtestpluginA" PLUGIN_EXT); // with two configuration values configuration.set("READCONFIG_TEST.Only.VALUE1", "FirstValue"); configuration.set("READCONFIG_TEST.Only.VALUE2", "SecondValue"); PluginHooks testPlugins("getTestPlugin", "READCONFIG_TEST"); testPlugins.readConfig(configuration); PluginIterator plugin(testPlugins); UtlString name; TestPlugin* thePlugin; // get the hook and confirm the name thePlugin = static_cast(plugin.next(&name)); CPPUNIT_ASSERT(thePlugin != NULL); CPPUNIT_ASSERT(!name.isNull()); ASSERT_STR_EQUAL("Only",name.data()); UtlString fullName; thePlugin->pluginName(fullName); ASSERT_STR_EQUAL("TestPluginA::Only",fullName.data()); // read the two parameters and confirm that the hook got them UtlString pluginValue; CPPUNIT_ASSERT(thePlugin->getConfiguredValueFor("VALUE1", pluginValue)); ASSERT_STR_EQUAL("FirstValue",pluginValue.data()); CPPUNIT_ASSERT(thePlugin->getConfiguredValueFor("VALUE2", pluginValue)); ASSERT_STR_EQUAL("SecondValue",pluginValue.data()); // try some bogus parameter CPPUNIT_ASSERT(!thePlugin->getConfiguredValueFor("UNCONFIGURED", pluginValue)); // confirm that this is the only hook CPPUNIT_ASSERT(plugin.next(&name) == NULL); CPPUNIT_ASSERT(name.isNull()); } void testTwoInstances() { OsConfigDb configuration; configuration.set("TWO_INST_NOTPASSED_HOOK_LIBRARY.Error", PLUGIN_LIB_DIR "libfoo" PLUGIN_EXT); configuration.set("TWO_INST_OTHERPARAM", "DummyValue"); // configure two instances of the same hook library, with different parameters configuration.set("TWO_INST_TEST_HOOK_LIBRARY.First", PLUGIN_LIB_DIR "libtestpluginA" PLUGIN_EXT); configuration.set("TWO_INST_TEST.First.VALUE", "FirstValue"); configuration.set("TWO_INST_TEST_HOOK_LIBRARY.Second", PLUGIN_LIB_DIR "libtestpluginA" PLUGIN_EXT); configuration.set("TWO_INST_TEST.Second.VALUE", "SecondValue"); // load up the hooks PluginHooks testPlugins("getTestPlugin", "TWO_INST_TEST"); testPlugins.readConfig(configuration); PluginIterator plugin(testPlugins); UtlString name; TestPlugin* thePlugin; // get the first instance and check its name thePlugin = static_cast(plugin.next(&name)); CPPUNIT_ASSERT(thePlugin != NULL); CPPUNIT_ASSERT(!name.isNull()); ASSERT_STR_EQUAL("First",name.data()); UtlString fullName; thePlugin->pluginName(fullName); ASSERT_STR_EQUAL("TestPluginA::First",fullName.data()); const UtlString ValueKey("VALUE"); // check that the first instance is using the correct configuration value UtlString pluginValue; CPPUNIT_ASSERT(thePlugin->getConfiguredValueFor(ValueKey, pluginValue)); ASSERT_STR_EQUAL("FirstValue",pluginValue.data()); // get the second instance and confirm its name thePlugin = static_cast(plugin.next(&name)); CPPUNIT_ASSERT(thePlugin != NULL); CPPUNIT_ASSERT(!name.isNull()); ASSERT_STR_EQUAL("Second",name.data()); thePlugin->pluginName(fullName); ASSERT_STR_EQUAL("TestPluginA::Second",fullName.data()); // check that the second instance is using the correct configuration value CPPUNIT_ASSERT(thePlugin->getConfiguredValueFor(ValueKey, pluginValue)); ASSERT_STR_EQUAL("SecondValue",pluginValue.data()); // and make sure that is the end of the iteration CPPUNIT_ASSERT(plugin.next(&name) == NULL); CPPUNIT_ASSERT(name.isNull()); } void testTwoHookTypes() { OsConfigDb configuration; configuration.set("TWO_TYPE_NOTPASSED_HOOK_LIBRARY.Error", PLUGIN_LIB_DIR "libfoo" PLUGIN_EXT); configuration.set("TWO_TYPE_OTHERPARAM", "DummyValue"); // Configure two different hook types - each in its own library // (we cheat - it's the same source, modified by configuration // switches; see comments in ../testplugin/TestPlugin.cpp) configuration.set("TWO_TYPE1_HOOK_LIBRARY.First", PLUGIN_LIB_DIR "libtestpluginA" PLUGIN_EXT); configuration.set("TWO_TYPE1.First.VALUE", "FirstValue"); configuration.set("TWO_TYPE2_HOOK_LIBRARY.Second", PLUGIN_LIB_DIR "libtestpluginB" PLUGIN_EXT); configuration.set("TWO_TYPE2.Second.VALUE", "SecondValue"); // load the first hook type PluginHooks test1Plugins("getTestPlugin", "TWO_TYPE1"); test1Plugins.readConfig(configuration); // load the second hook type PluginHooks test2Plugins("getTestPlugin", "TWO_TYPE2"); test2Plugins.readConfig(configuration); // create iterators for both hook types PluginIterator plugin1(test1Plugins); PluginIterator plugin2(test2Plugins); UtlString name; TestPlugin* thePlugin; UtlString fullName; // get the first instance of the first hook type and confirm the names thePlugin = static_cast(plugin1.next(&name)); CPPUNIT_ASSERT(thePlugin != NULL); thePlugin->pluginName(fullName); ASSERT_STR_EQUAL("TestPluginA::First",fullName.data()); // confirm the first hook type is using the correct configuration value const UtlString ValueKey("VALUE"); UtlString pluginValue; CPPUNIT_ASSERT(thePlugin->getConfiguredValueFor(ValueKey, pluginValue)); ASSERT_STR_EQUAL("FirstValue",pluginValue.data()); // get the first instance of the second hook type and confim its names thePlugin = static_cast(plugin2.next(&name)); CPPUNIT_ASSERT(thePlugin != NULL); thePlugin->pluginName(fullName); ASSERT_STR_EQUAL("TestPluginB::Second",fullName.data()); // confirm the configuration of the second hook type CPPUNIT_ASSERT(thePlugin->getConfiguredValueFor(ValueKey, pluginValue)); ASSERT_STR_EQUAL("SecondValue",pluginValue.data()); // make sure each type only has the one instance CPPUNIT_ASSERT(plugin1.next(&name) == NULL); CPPUNIT_ASSERT(name.isNull()); CPPUNIT_ASSERT(plugin2.next(&name) == NULL); CPPUNIT_ASSERT(name.isNull()); } void testReconfigure() { PluginHooks testPlugins("getTestPlugin", "RECONFIG_TEST"); const UtlString ValueKey("VALUE"); UtlString name; TestPlugin* thePlugin; UtlString pluginValue; UtlString fullName; { // Do the initial configuration of two instances of a hook OsConfigDb configuration; configuration.set("RECONFIG_TEST_HOOK_LIBRARY.First", PLUGIN_LIB_DIR "libtestpluginA" PLUGIN_EXT); configuration.set("RECONFIG_TEST.First.VALUE", "FirstValue"); configuration.set("RECONFIG_TEST_HOOK_LIBRARY.Second", PLUGIN_LIB_DIR "libtestpluginA" PLUGIN_EXT); configuration.set("RECONFIG_TEST.Second.VALUE", "SecondValue"); // load them up testPlugins.readConfig(configuration); PluginIterator plugin(testPlugins); // check the first instance thePlugin = static_cast(plugin.next(&name)); CPPUNIT_ASSERT(thePlugin != NULL); CPPUNIT_ASSERT(!name.isNull()); ASSERT_STR_EQUAL("First",name.data()); thePlugin->pluginName(fullName); ASSERT_STR_EQUAL("TestPluginA::First",fullName.data()); CPPUNIT_ASSERT(thePlugin->getConfiguredValueFor(ValueKey, pluginValue)); ASSERT_STR_EQUAL("FirstValue",pluginValue.data()); // check the second instance thePlugin = static_cast(plugin.next(&name)); CPPUNIT_ASSERT(thePlugin != NULL); CPPUNIT_ASSERT(!name.isNull()); ASSERT_STR_EQUAL("Second",name.data()); thePlugin->pluginName(fullName); ASSERT_STR_EQUAL("TestPluginA::Second",fullName.data()); CPPUNIT_ASSERT(thePlugin->getConfiguredValueFor(ValueKey, pluginValue)); ASSERT_STR_EQUAL("SecondValue",pluginValue.data()); // and confirm that is the end CPPUNIT_ASSERT(plugin.next(&name) == NULL); CPPUNIT_ASSERT(name.isNull()); } { // Now create a new configuration that eliminates the First instance // and changes the configuration value for the Second instance OsConfigDb configuration; configuration.set("RECONFIG_TEST_HOOK_LIBRARY.Second", PLUGIN_LIB_DIR "libtestpluginA" PLUGIN_EXT); configuration.set("RECONFIG_TEST.Second.VALUE", "NewValue"); // reconfigure the plugins testPlugins.readConfig(configuration); PluginIterator plugin(testPlugins); // confirm that we still get the Second instance (but we get it first :-) thePlugin = static_cast(plugin.next(&name)); CPPUNIT_ASSERT(thePlugin != NULL); CPPUNIT_ASSERT(!name.isNull()); ASSERT_STR_EQUAL("Second",name.data()); thePlugin->pluginName(fullName); ASSERT_STR_EQUAL("TestPluginA::Second",fullName.data()); // and check that it has the new configuration value CPPUNIT_ASSERT(thePlugin->getConfiguredValueFor(ValueKey, pluginValue)); ASSERT_STR_EQUAL("NewValue",pluginValue.data()); // and that it's the only hook configured now CPPUNIT_ASSERT(plugin.next(&name) == NULL); CPPUNIT_ASSERT(name.isNull()); } } }; CPPUNIT_TEST_SUITE_REGISTRATION(PluginHooksTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/TestPlugin.h0000644000175000017500000000242312205613256024501 0ustar00danieldaniel00000000000000// // Copyright (C) 2005 Pingtel Corp. // ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "assert.h" // APPLICATION INCLUDES #include "utl/UtlString.h" #include "utl/UtlHashMap.h" #include "utl/Plugin.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class TestPlugin; extern "C" TestPlugin* getTestPlugin(const UtlString& name); /** * TestPlugin defines the interface for plugins to the PluginsTest. * */ class TestPlugin : public Plugin { public: virtual ~TestPlugin(); /// Read (or re-read) whatever configuration the hook requires. void readConfig( OsConfigDb& configDb ); /// Return the integer value for a given configuration key virtual bool getConfiguredValueFor(const UtlString& key, UtlString& value ) const; /// Set type to the unique library name virtual void pluginName(UtlString& name) const; static const char* LibraryName; static const char* FactoryName; private: friend TestPlugin* getTestPlugin(const UtlString& name); /// The constructor is called from getHook factory method. TestPlugin(const UtlString& hookName); UtlHashMap mConfiguration; bool mConfigured; }; sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlChainTest.cpp0000644000175000017500000003154012205613256025307 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include "utl/UtlLink.h" /// Unit test of the UtlChain class UtlChainTest : public SIPX_UNIT_BASE_CLASS, public UtlChain { CPPUNIT_TEST_SUITE(UtlChainTest); CPPUNIT_TEST(testBefore); CPPUNIT_TEST(testAfter); CPPUNIT_TEST(testUnchainUnlinked); CPPUNIT_TEST(testUnchainFirst); CPPUNIT_TEST(testUnchainLast); CPPUNIT_TEST(testUnchainMiddle); CPPUNIT_TEST(testChainRing); CPPUNIT_TEST(testListBefore); CPPUNIT_TEST(testListAfter); CPPUNIT_TEST_SUITE_END(); private: public: void testBefore() { UtlChain chain1; UtlChain chain2; UtlChain chain3; // new chains should be properly terminated. CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == NULL); CPPUNIT_ASSERT(chain2.prev == NULL); CPPUNIT_ASSERT(chain2.next == NULL); CPPUNIT_ASSERT(chain3.prev == NULL); CPPUNIT_ASSERT(chain3.next == NULL); chain2.chainBefore(&chain3); CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == NULL); CPPUNIT_ASSERT(chain2.prev == NULL); CPPUNIT_ASSERT(chain2.next == &chain3); CPPUNIT_ASSERT(chain3.prev == &chain2); CPPUNIT_ASSERT(chain3.next == NULL); chain1.chainBefore(&chain2); CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == &chain2); CPPUNIT_ASSERT(chain2.prev == &chain1); CPPUNIT_ASSERT(chain2.next == &chain3); CPPUNIT_ASSERT(chain3.prev == &chain2); CPPUNIT_ASSERT(chain3.next == NULL); } void testAfter() { UtlChain chain1; UtlChain chain2; UtlChain chain3; // new chains should be properly terminated. CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == NULL); CPPUNIT_ASSERT(chain2.prev == NULL); CPPUNIT_ASSERT(chain2.next == NULL); CPPUNIT_ASSERT(chain3.prev == NULL); CPPUNIT_ASSERT(chain3.next == NULL); chain2.chainAfter(&chain1); CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == &chain2); CPPUNIT_ASSERT(chain2.prev == &chain1); CPPUNIT_ASSERT(chain2.next == NULL); CPPUNIT_ASSERT(chain3.prev == NULL); CPPUNIT_ASSERT(chain3.next == NULL); chain3.chainAfter(&chain2); CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == &chain2); CPPUNIT_ASSERT(chain2.prev == &chain1); CPPUNIT_ASSERT(chain2.next == &chain3); CPPUNIT_ASSERT(chain3.prev == &chain2); CPPUNIT_ASSERT(chain3.next == NULL); } void testUnchainUnlinked() { UtlChain unlinked; CPPUNIT_ASSERT(unlinked.prev == NULL); CPPUNIT_ASSERT(unlinked.next == NULL); unlinked.unchain(); CPPUNIT_ASSERT(unlinked.prev == NULL); CPPUNIT_ASSERT(unlinked.next == NULL); } void testUnchainFirst() { UtlChain chain1; UtlChain chain2; UtlChain chain3; CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == NULL); CPPUNIT_ASSERT(chain2.prev == NULL); CPPUNIT_ASSERT(chain2.next == NULL); CPPUNIT_ASSERT(chain3.prev == NULL); CPPUNIT_ASSERT(chain3.next == NULL); chain2.chainBefore(&chain3); chain1.chainBefore(&chain2); CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == &chain2); CPPUNIT_ASSERT(chain2.prev == &chain1); CPPUNIT_ASSERT(chain2.next == &chain3); CPPUNIT_ASSERT(chain3.prev == &chain2); CPPUNIT_ASSERT(chain3.next == NULL); chain1.unchain(); CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == NULL); CPPUNIT_ASSERT(chain2.prev == NULL); CPPUNIT_ASSERT(chain2.next == &chain3); CPPUNIT_ASSERT(chain3.prev == &chain2); CPPUNIT_ASSERT(chain3.next == NULL); } void testUnchainLast() { UtlChain chain1; UtlChain chain2; UtlChain chain3; CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == NULL); CPPUNIT_ASSERT(chain2.prev == NULL); CPPUNIT_ASSERT(chain2.next == NULL); CPPUNIT_ASSERT(chain3.prev == NULL); CPPUNIT_ASSERT(chain3.next == NULL); chain2.chainBefore(&chain3); chain1.chainBefore(&chain2); CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == &chain2); CPPUNIT_ASSERT(chain2.prev == &chain1); CPPUNIT_ASSERT(chain2.next == &chain3); CPPUNIT_ASSERT(chain3.prev == &chain2); CPPUNIT_ASSERT(chain3.next == NULL); chain3.unchain(); CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == &chain2); CPPUNIT_ASSERT(chain2.prev == &chain1); CPPUNIT_ASSERT(chain2.next == NULL); CPPUNIT_ASSERT(chain3.prev == NULL); CPPUNIT_ASSERT(chain3.next == NULL); } void testUnchainMiddle() { UtlChain chain1; UtlChain chain2; UtlChain chain3; CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == NULL); CPPUNIT_ASSERT(chain2.prev == NULL); CPPUNIT_ASSERT(chain2.next == NULL); CPPUNIT_ASSERT(chain3.prev == NULL); CPPUNIT_ASSERT(chain3.next == NULL); chain2.chainBefore(&chain3); chain1.chainBefore(&chain2); CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == &chain2); CPPUNIT_ASSERT(chain2.prev == &chain1); CPPUNIT_ASSERT(chain2.next == &chain3); CPPUNIT_ASSERT(chain3.prev == &chain2); CPPUNIT_ASSERT(chain3.next == NULL); chain2.unchain(); CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == &chain3); CPPUNIT_ASSERT(chain2.prev == NULL); CPPUNIT_ASSERT(chain2.next == NULL); CPPUNIT_ASSERT(chain3.prev == &chain1); CPPUNIT_ASSERT(chain3.next == NULL); } void testChainRing() { UtlChain chain1; UtlChain chain2; UtlChain chain3; CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == NULL); CPPUNIT_ASSERT(chain2.prev == NULL); CPPUNIT_ASSERT(chain2.next == NULL); CPPUNIT_ASSERT(chain3.prev == NULL); CPPUNIT_ASSERT(chain3.next == NULL); chain1.chainBefore(&chain1); CPPUNIT_ASSERT(chain1.prev == &chain1); CPPUNIT_ASSERT(chain1.next == &chain1); CPPUNIT_ASSERT(chain2.prev == NULL); CPPUNIT_ASSERT(chain2.next == NULL); CPPUNIT_ASSERT(chain3.prev == NULL); CPPUNIT_ASSERT(chain3.next == NULL); chain2.chainAfter(&chain1); CPPUNIT_ASSERT(chain1.prev == &chain2); CPPUNIT_ASSERT(chain1.next == &chain2); CPPUNIT_ASSERT(chain2.prev == &chain1); CPPUNIT_ASSERT(chain2.next == &chain1); CPPUNIT_ASSERT(chain3.prev == NULL); CPPUNIT_ASSERT(chain3.next == NULL); chain3.chainBefore(&chain1); CPPUNIT_ASSERT(chain1.prev == &chain3); CPPUNIT_ASSERT(chain1.next == &chain2); CPPUNIT_ASSERT(chain2.prev == &chain1); CPPUNIT_ASSERT(chain2.next == &chain3); CPPUNIT_ASSERT(chain3.prev == &chain2); CPPUNIT_ASSERT(chain3.next == &chain1); chain3.unchain(); CPPUNIT_ASSERT(chain1.prev == &chain2); CPPUNIT_ASSERT(chain1.next == &chain2); CPPUNIT_ASSERT(chain2.prev == &chain1); CPPUNIT_ASSERT(chain2.next == &chain1); CPPUNIT_ASSERT(chain3.prev == NULL); CPPUNIT_ASSERT(chain3.next == NULL); chain1.unchain(); CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == NULL); CPPUNIT_ASSERT(chain2.prev == &chain2); CPPUNIT_ASSERT(chain2.next == &chain2); CPPUNIT_ASSERT(chain3.prev == NULL); CPPUNIT_ASSERT(chain3.next == NULL); chain2.unchain(); CPPUNIT_ASSERT(chain1.prev == NULL); CPPUNIT_ASSERT(chain1.next == NULL); CPPUNIT_ASSERT(chain2.prev == NULL); CPPUNIT_ASSERT(chain2.next == NULL); CPPUNIT_ASSERT(chain3.prev == NULL); CPPUNIT_ASSERT(chain3.next == NULL); } void testListBefore() { UtlChain list; UtlChain link1; link1.listBefore(&list, NULL); CPPUNIT_ASSERT(link1.prev == NULL); CPPUNIT_ASSERT(link1.next == NULL); CPPUNIT_ASSERT(list.prev == &link1); CPPUNIT_ASSERT(list.next == &link1); UtlChain link3; link3.listBefore(&list, NULL); CPPUNIT_ASSERT(list.next == &link1); CPPUNIT_ASSERT(link1.prev == NULL); CPPUNIT_ASSERT(link1.next == &link3); CPPUNIT_ASSERT(link3.prev == &link1); CPPUNIT_ASSERT(link3.next == NULL); CPPUNIT_ASSERT(list.prev == &link3); UtlChain link2; link2.listBefore(&list, &link3); CPPUNIT_ASSERT(list.next == &link1); CPPUNIT_ASSERT(link1.prev == NULL); CPPUNIT_ASSERT(link1.next == &link2); CPPUNIT_ASSERT(link2.prev == &link1); CPPUNIT_ASSERT(link2.next == &link3); CPPUNIT_ASSERT(link3.prev == &link2); CPPUNIT_ASSERT(link3.next == NULL); CPPUNIT_ASSERT(list.prev == &link3); void* returnedLink; returnedLink = link2.detachFromList(&list); CPPUNIT_ASSERT(returnedLink == &link2); CPPUNIT_ASSERT(list.next == &link1); CPPUNIT_ASSERT(link1.prev == NULL); CPPUNIT_ASSERT(link1.next == &link3); CPPUNIT_ASSERT(link3.prev == &link1); CPPUNIT_ASSERT(link3.next == NULL); CPPUNIT_ASSERT(list.prev == &link3); returnedLink = link1.detachFromList(&list); CPPUNIT_ASSERT(returnedLink == &link1); CPPUNIT_ASSERT(list.next == &link3); CPPUNIT_ASSERT(link3.prev == NULL); CPPUNIT_ASSERT(link3.next == NULL); CPPUNIT_ASSERT(list.prev == &link3); returnedLink = link3.detachFromList(&list); CPPUNIT_ASSERT(returnedLink == &link3); CPPUNIT_ASSERT(list.prev == NULL); CPPUNIT_ASSERT(list.next == NULL); } void testListAfter() { UtlChain list; UtlChain link3; link3.listAfter(&list, NULL); CPPUNIT_ASSERT(list.next == &link3); CPPUNIT_ASSERT(link3.prev == NULL); CPPUNIT_ASSERT(link3.next == NULL); CPPUNIT_ASSERT(list.prev == &link3); UtlChain link1; link1.listAfter(&list, NULL); CPPUNIT_ASSERT(list.next == &link1); CPPUNIT_ASSERT(link1.prev == NULL); CPPUNIT_ASSERT(link1.next == &link3); CPPUNIT_ASSERT(link3.prev == &link1); CPPUNIT_ASSERT(link3.next == NULL); CPPUNIT_ASSERT(list.prev == &link3); UtlChain link2; link2.listAfter(&list, &link1); CPPUNIT_ASSERT(list.next == &link1); CPPUNIT_ASSERT(link1.prev == NULL); CPPUNIT_ASSERT(link1.next == &link2); CPPUNIT_ASSERT(link2.prev == &link1); CPPUNIT_ASSERT(link2.next == &link3); CPPUNIT_ASSERT(link3.prev == &link2); CPPUNIT_ASSERT(link3.next == NULL); CPPUNIT_ASSERT(list.prev == &link3); void* returnedLink; returnedLink = link2.detachFromList(&list); CPPUNIT_ASSERT(returnedLink == &link2); CPPUNIT_ASSERT(list.next == &link1); CPPUNIT_ASSERT(link1.prev == NULL); CPPUNIT_ASSERT(link1.next == &link3); CPPUNIT_ASSERT(link3.prev == &link1); CPPUNIT_ASSERT(link3.next == NULL); CPPUNIT_ASSERT(list.prev == &link3); returnedLink = link1.detachFromList(&list); CPPUNIT_ASSERT(returnedLink == &link1); CPPUNIT_ASSERT(list.next == &link3); CPPUNIT_ASSERT(link3.prev == NULL); CPPUNIT_ASSERT(link3.next == NULL); CPPUNIT_ASSERT(list.prev == &link3); returnedLink = link3.detachFromList(&list); CPPUNIT_ASSERT(returnedLink == &link3); CPPUNIT_ASSERT(list.prev == NULL); CPPUNIT_ASSERT(list.next == NULL); } }; CPPUNIT_TEST_SUITE_REGISTRATION(UtlChainTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlContainableTestStub.cpp0000644000175000017500000000277412205613256027351 0ustar00danieldaniel00000000000000#include #include #include #include int UtlContainableTestStub::cCount = 0 ; const UtlContainableType UtlContainableTestStub::TYPE = "UtlContainableTestStub" ; UtlContainableTestStub::UtlContainableTestStub() { cCount++ ; id = -1 ; } UtlContainableTestStub::UtlContainableTestStub(int i) { id = i ; cCount++ ; } UtlContainableTestStub :: ~UtlContainableTestStub() { UtlContainableTestStub::cCount-- ; } void UtlContainableTestStub :: printCount() { printf("Creation count = %d;\n", cCount) ; } UtlBoolean UtlContainableTestStub :: isEqual(const UtlContainable* c) const { return (compareTo(c) == 0) ; } unsigned UtlContainableTestStub :: hash() const { return id ; } int UtlContainableTestStub :: compareTo(UtlContainable const* c) const { int cmp = 1 ; if (c->getContainableType() == TYPE) { UtlContainableTestStub* t = (UtlContainableTestStub*)c ; int inId = t -> id ; cmp = id - inId ; } return cmp ; } UtlContainableType UtlContainableTestStub::getContainableType() const { return TYPE; } int UtlContainableTestStub :: getCount() { return cCount ; } void UtlContainableTestStub::clearCount() { cCount = 0 ; } UtlBoolean UtlContainableTestStub::isInstance(UtlContainable const* c) const { bool result = false ; UtlContainableType cType = c -> getContainableType() ; result = (strcmp(cType, "UtlContainableTestStub") == 0) ; return result; } sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlContainableTestStub.h0000644000175000017500000000150312205613256027003 0ustar00danieldaniel00000000000000#ifndef _UtlContainableTestStub_h #define _UtlContainableTestStub_h #include "utl/UtlContainable.h" class UtlContainableTestStub : public UtlContainable { private: int id ; static int cCount ; static const UtlContainableType TYPE; // Nobody should ever be calling the no arg constructor UtlContainableTestStub() ; public : UtlContainableTestStub(int ) ; virtual ~UtlContainableTestStub() ; static void printCount() ; virtual UtlBoolean isEqual(const UtlContainable* c) const ; virtual unsigned hash() const ; virtual int compareTo(UtlContainable const* c) const ; virtual UtlContainableType getContainableType() const; virtual UtlBoolean isInstance(UtlContainable const*) const ; static int getCount() ; static void clearCount() ; } ; #endif sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlCrc32Test.cpp0000644000175000017500000000501612205613256025140 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include /** This class is used to test the UtlCrc32 utility class. * * PLEASE READ THE README FILE THAT CAN FOUND IN THE SAME DIRECTORY AS * THIS FILE. The Readme describes the organization / flow of tests and * without reading this file, the following class (and all unit tests) * may not make a lot of sense and might be difficult to comprehend. */ class UtlCrc32Tests : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlCrc32Tests); CPPUNIT_TEST(testAll) ; CPPUNIT_TEST_SUITE_END(); private: public: UtlCrc32Tests() { } void setUp() { } void tearDown() { } ~UtlCrc32Tests() { } /** Sandbox method for experimenting with the API Under Test. * This method MUST be empty when the test drivers are being * checked in (final checkin) to the repository. */ void DynaTest() { } /** * Some simple tests to verify that Crc32s are generated correctly. * - validate checksums * - validate all APIs / methods of adding data */ void testAll() { UtlCrc32 mGenerator ; // By default, Crc32 is zero CPPUNIT_ASSERT(mGenerator.getValue() == 0) ; // Add single byte of data mGenerator.calc(0x80) ; CPPUNIT_ASSERT(mGenerator.getValue() == 0x3FBA6CAD) ; // Make sure reset, does reset. mGenerator.reset() ; CPPUNIT_ASSERT(mGenerator.getValue() == 0) ; // Try adding a sequences of bytes mGenerator.calc((unsigned char*) "bandreasen", 10) ; CPPUNIT_ASSERT(mGenerator.getValue() == 0xB78D3286) ; // Try appending more bytes mGenerator.calc((unsigned char*) "bandreasen", 10) ; CPPUNIT_ASSERT(mGenerator.getValue() == 0x71BD42B1) ; // Trying using a UtlString as a container mGenerator.reset() ; UtlString str("eatatjoes") ; mGenerator.calc(str) ; CPPUNIT_ASSERT(mGenerator.getValue() == 0xFDF73AB6) ; } }; CPPUNIT_TEST_SUITE_REGISTRATION(UtlCrc32Tests); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlCryptoTest.cpp0000644000175000017500000000672312205613256025552 0ustar00danieldaniel00000000000000// // Copyright (C) 2008-2010 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Sergey Kostanbaev #ifdef HAVE_SSL #include #include #include #include #include #include #include #include // NOTE Test packet set to PCMU payload static const unsigned char test_frame[] = { //RTP header 0x80, 0, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, //Payload 0x52,0x49,0x46,0x46,0x6C,0x71,0x02,0x00,0x57,0x41,0x56,0x45, 0x66,0x6D,0x74,0x20,0x10,0x00,0x00,0x00,0x01,0x00,0x01,0x00, 0x40,0x1F,0x00,0x00,0x80,0x3E,0x00,0x00,0x02,0x00,0x10,0x00, 0x64,0x61,0x74,0x61,0xFE,0x70,0x02,0x00,0x00,0x00,0xB7,0x33, 0xAB,0x5E,0x56,0x79,0x6A,0x7F,0x99,0x6F,0xD7,0x4C,0xE2,0x1C, 0x05,0xE8,0x45,0xB7,0xE6,0x92,0x39,0x81,0x21,0x85,0x15,0x9E, 0xB7,0xC7,0xFA,0xFA,0x17,0x2F,0x2A,0x5B,0xAD,0x77,0xBC,0x7F, 0xFC,0x71,0xC6,0x50,0xC2,0x21,0xFA,0xEC,0x75,0xBB,0x9F,0x95, 0xFD,0x81,0xD3,0x83,0xED,0x9A,0x3E,0xC3,0xF6,0xF5,0x66,0x2A, 0x8F,0x57,0xD7,0x75,0xE4,0x7F,0x39,0x74,0x96,0x54,0x98,0x26 }; class UtlCryptoTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlCryptoTest); CPPUNIT_TEST(testCreate); CPPUNIT_TEST(testSymmetricSocket); CPPUNIT_TEST_SUITE_END(); void testCreate() { UtlCryptoKeyRsa a; UtlCryptoKeySym b; } void testSymmetricSocket() { char buffer[1000]; char tempMemory[1000]; UtlCryptoKeySym symKey; symKey.generateKey(); symKey.getBinaryKey(tempMemory, 1000); printf("KeyDump:\n%s\n", symKey.output().data()); int port1 = 10001; int port2 = 10011; int port3 = 10021; int port4 = 10031; OsNatDatagramSocketCrypto s1(port2, "127.0.0.1", port1, "127.0.0.1", NULL, tempMemory, 1000, tempMemory, 1000); OsNatDatagramSocketCrypto s2(port1, "127.0.0.1", port2, "127.0.0.1", NULL, tempMemory, 1000, tempMemory, 1000); OsNatDatagramSocketCrypto s3(port4, "127.0.0.1", port3, "127.0.0.1", NULL, tempMemory, 1000, tempMemory, 1000); OsNatDatagramSocket s4(port3, "127.0.0.1", port4, "127.0.0.1", NULL); CPPUNIT_ASSERT_EQUAL(TRUE, s1.isOk()); CPPUNIT_ASSERT_EQUAL(TRUE, s2.isOk()); CPPUNIT_ASSERT_EQUAL(TRUE, s3.isOk()); CPPUNIT_ASSERT_EQUAL(TRUE, s4.isOk()); s1.write((const char*)test_frame, sizeof(test_frame)); OsTask::delay(10); int i; UtlString str; int port = 0; int len = s2.read((char*)buffer, 1000, &str, &port ); CPPUNIT_ASSERT_EQUAL(len, (int)sizeof(test_frame)); for (i = 0; i < len; i++) CPPUNIT_ASSERT_EQUAL(buffer[i], (char)test_frame[i]); s3.write((const char*)test_frame, sizeof(test_frame)); OsTask::delay(10); UtlBoolean different = FALSE; len = s4.read((char*)buffer, 1000, &str, &port ); CPPUNIT_ASSERT(len > 0); for (i = 0; i < len; i++) { if (buffer[i] != (char)test_frame[i]) { different = TRUE; break; } } CPPUNIT_ASSERT_EQUAL(TRUE, different); } }; CPPUNIT_TEST_SUITE_REGISTRATION(UtlCryptoTest); #endif sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlDList.cpp0000644000175000017500000011455412205613256024453 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include #include #include #include /** This class is used to test the UtlDList utility class. * * PLEASE READ THE README FILE THAT CAN FOUND IN THE SAME DIRECTORY AS * THIS FILE. The Readme describes the organization / flow of tests and * without reading this file, the following class (and all unit tests) * may not make a lot of sense and might be difficult to comprehend. */ class UtlDListTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlDListTest); CPPUNIT_TEST(checkSanity_Append_Entries_And_At) ; CPPUNIT_TEST(testAppend) ; CPPUNIT_TEST(testInsert) ; CPPUNIT_TEST(testInsertAt_EmptyList) ; CPPUNIT_TEST(testInsertAt_NonEmptyList) ; CPPUNIT_TEST(testFirst_And_Last) ; CPPUNIT_TEST(testIndex) ; CPPUNIT_TEST(testFind) ; CPPUNIT_TEST(testContains) ; CPPUNIT_TEST(testContainsReference) ; CPPUNIT_TEST(testOccurancesOf) ; CPPUNIT_TEST(testRemove) ; CPPUNIT_TEST(testRemoveReference) ; CPPUNIT_TEST(testRemoveAndDestroy) ; CPPUNIT_TEST(testGet) ; CPPUNIT_TEST(testIsEmpty) ; CPPUNIT_TEST(testClear) ; CPPUNIT_TEST(testClearAndDestroy) ; CPPUNIT_TEST_SUITE_END(); private: static const int commonEntriesCount ; UtlDList commonList ; UtlDList emptyList ; UtlString commonString1 ; UtlString commonString2 ; UtlString commonString3 ; UtlInt commonInt1 ; UtlInt commonInt2 ; UtlInt commonInt3 ; UtlString commonString1_clone; UtlString commonString2_clone ; UtlString commonString3_clone ; UtlInt commonInt1_clone ; UtlInt commonInt2_clone ; UtlInt commonInt3_clone ; static const char* longAlphaNumString ; static const char* regularString ; UtlContainable** commonContainables ; UtlContainable** commonContainables_Clone ; enum IndexOrContains { TEST_INDEX, TEST_FIND, TEST_CONTAINS, TEST_CONTAINS_REF } ; enum TestInsertOrAppend {TEST_APPEND, TEST_INSERT} ; enum RemoveType {TEST_REMOVE, TEST_REMOVE_REF } ; public: UtlDListTest() { commonContainables = new UtlContainable*[commonEntriesCount] ; commonContainables_Clone = new UtlContainable*[commonEntriesCount] ; } ~UtlDListTest() { delete[] commonContainables ; delete[] commonContainables_Clone ; } void setUp() { // remove junk from prior tests commonList.removeAll(); UtlContainableTestStub::clearCount() ; commonString1 = UtlString(regularString) ; commonString1_clone = UtlString(regularString) ; commonString2 = UtlString("") ; commonString2_clone = UtlString("") ; commonString3 = UtlString(longAlphaNumString) ; commonString3_clone = UtlString(longAlphaNumString) ; commonInt1 = UtlInt(0) ; commonInt1_clone = UtlInt(0) ; commonInt2 = UtlInt(INT_MAX) ; commonInt2_clone = UtlInt(INT_MAX) ; commonInt3 = UtlInt(INT_MIN) ; commonInt3_clone = UtlInt(INT_MIN) ; commonList.append(&commonString1) ; commonContainables[0] = &commonString1 ; commonContainables_Clone[0] = &commonString1_clone ; commonList.append(&commonInt1) ; commonContainables[1] = &commonInt1 ; commonContainables_Clone[1] = &commonInt1_clone ; commonList.append(&commonInt2) ; commonContainables[2] = &commonInt2 ; commonContainables_Clone[2] = &commonInt2_clone; commonList.append(&commonString2) ; commonContainables[3] = &commonString2 ; commonContainables_Clone[3] = &commonString2_clone ; commonList.append(&commonInt3) ; commonContainables[4] = &commonInt3 ; commonContainables_Clone[4] = &commonInt3_clone ; commonList.append(&commonString3) ; commonContainables[5] = &commonString3 ; commonContainables_Clone[5] = &commonString3_clone ; } void tearDown() { // remove junk from this test commonList.removeAll(); } /** Sandbox method for experimenting with the API Under Test. * This method MUST be empty when the test drivers are being * checked in (final checkin) to the repository. */ void DynaTest() { } /*a! This test is more of a sanity check to verify that * the basic append(), entries() and at() methods work as expected. * All future tests will depend heavily on the at() method * and the most common way of having something in the list is * by means of the append() method. * */ void checkSanity_Append_Entries_And_At() { for (int i = 0 ; i < commonEntriesCount; i++) { UtlContainable* ucExpected = commonContainables[i] ; UtlContainable* ucActual = commonList.at(i) ; string msg ; char strItr[33] ; sprintf(strItr, "%d", i); TestUtilities::createMessage(3, &msg, "Verify that the at(n) method, where n = ", \ strItr, " ;") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), ucExpected, ucActual) ; } CPPUNIT_ASSERT_EQUAL_MESSAGE("Verify that the entries() for an empty list returns 0", \ (int)emptyList.entries(), 0) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Verify the entries() method for a list", \ (int)commonList.entries(), commonEntriesCount) ; }// checkSanity_Append_And_At() /*a! Test the append method for a list that is not empty * The test data for this test are :- * a) Append a CollectableString * b) Append a CollectableInt * */ void testAppend() { utlTestAppend_Insert(TEST_APPEND) ; } /*a! Test the insert method for a list that is not empty * * Since the insert method does exactly the same thing as * the append method, the test data for these two are the same */ void testInsert() { utlTestAppend_Insert(TEST_INSERT) ; } void utlTestAppend_Insert(TestInsertOrAppend type) { int testCount = 2 ; const char* prefix = ""; UtlInt testInt(1234) ; UtlString testString("Test String") ; if (type == TEST_APPEND) { commonList.append(&testInt) ; commonList.append(&testString) ; prefix = "Test the append(UtlContainable*) method for a non empty list" ; } else if (type == TEST_INSERT) { commonList.insert(&testInt) ; commonList.insert(&testString) ; prefix = "Test the insert(UtlContainable*) method for a non empty list" ; } int expectedCount = commonEntriesCount + testCount ; UtlContainable* uActual ; UtlContainable* uExpected ; string msg ; // Verify that the number of entries has increased accordingly TestUtilities::createMessage(2, &msg, prefix, " :- Verify the number of entries") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedCount, \ (int)commonList.entries()) ; // Verify that the first entry has still not changed. uActual = commonList.at(0) ; uExpected = commonContainables[0] ; TestUtilities::createMessage(2, &msg, prefix, \ " :- Verify that the first entry is not changed") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uActual, uExpected) ; // Verify the entry at the previous last position TestUtilities::createMessage(2, &msg, prefix, \ " :- Verify that the previous last entry is intact") ; // Verify that the number of entries has increased accordingly TestUtilities::createMessage(2, &msg, prefix, \ " :- Verify the number of entries") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedCount, \ (int)commonList.entries()) ; // Verify that the first entry has still not changed. uActual = commonList.at(0) ; uExpected = commonContainables[0] ; TestUtilities::createMessage(2, &msg, prefix, \ " :- Verify that the first entry is not changed") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uActual, uExpected) ; // Verify the entry at the previous last position TestUtilities::createMessage(2, &msg, prefix, \ " :- Verify that the previous last entry is intact") ; uActual = commonList.at(commonEntriesCount-1) ; uExpected = commonContainables[commonEntriesCount-1] ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uActual, uExpected) ; // Verify that the two new entries are added. TestUtilities::createMessage(2, &msg, prefix, \ " :- Verify that the Collectable Integer has been added") ; uActual = commonList.at(commonEntriesCount) ; uExpected = &testInt ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uActual, uExpected) ; TestUtilities::createMessage(2, &msg, prefix, \ " :- Verify that the Collectable String has been added") ; uActual = commonList.at(commonEntriesCount + 1) ; uExpected = &testString ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uActual, uExpected) ; } //testAppend /*!a! Test case to verify insertAt(size_t, UtlContainable*) for an * empty list. * The test data for this test are * a) Insert a UtlString to the 0th location, * b) Insert a UtlInt to the 0th location, * c) Insert any UtlContainable object to a 'non-zero' location */ void testInsertAt_EmptyList() { const int testCount = 3 ; const char* prefix = "Test insert(n, Collectable*) for an empty list; "\ "where Collectable is " ; const char* Msgs[] = { \ "a UtlString and n = 0", \ "a UtlInt and n = 0", \ "a UtlContainableXXX and n > 0" \ }; const char* suffix1 = " :- Verify return value" ; const char* suffix2 = " :- Verify value is appended" ; UtlInt testInt(102) ; UtlString testString("Test String") ; UtlString testNegative("This should not get added") ; UtlContainable* itemToAdd[] = { &testString, &testInt, &testNegative } ; UtlContainable* expectedValue[] = { &testString, &testInt, NULL} ; int insertLocation[] = { 0, 0, 1} ; for (int i = 0 ; i < testCount ; i++) { UtlDList testList ; string msg ; // insertAt now returns void. Retain this block of comment in case // we (I think we should return a Collectable / bool) decide to return // a collectable. UtlContainable* result = testList.insertAt(insertLocation[i], itemToAdd[i]); //verify that the right value is returned. TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValue[i], result) ; testList.insertAt(insertLocation[i], itemToAdd[i]) ; // verify that the value is inserted TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValue[i], testList.at(0)) ; } }//testInsertAt_EmptyList /*!a Test case to verify insertAt(size_t, UtlContainable*) for a * list that is not empty. * The test data for this test are * a) Insert any UtlContainable to the 0th location, * b) Insert a UtlInt to a 'mid' location, * c) Insert any UtlString object to a 'mid' location * d) Insert any UtlContainable object to the last location */ void testInsertAt_NonEmptyList() { const int testCount = 4 ; const char* prefix = "Test insert(n, Collectable*) for a list that is not empty; "\ "where Collectable is " ; const char* Msgs[] = { \ "a UtlContainableXXX and n = 0", \ "a UtlString and n > 0 && n < size", \ "a UtlInt and n > 0 && n < size", \ "a UtlContainableXXX where n = size-1" \ }; const char* suffix1 = " :- Verify return value" ; const char* suffix2 = " :- Verify value is appended" ; const char* suffix3 = " :- Verify new list size" ; UtlString testFirst("First Entry") ; UtlInt testInt(102) ; UtlString testString("Test String") ; UtlInt testLast(99999) ; UtlContainable* itemToAdd[] = { &testFirst, &testInt, &testString, &testLast } ; UtlContainable* expectedValue[] = { &testFirst, &testInt, &testString, &testLast} ; int insertLocation[] = { 0, 2, 3, commonEntriesCount+3} ; int tmpCount = commonEntriesCount ; int expectedEntries[] = {++tmpCount, ++tmpCount, ++tmpCount, ++tmpCount} ; for (int i = 0 ; i < testCount ; i++) { UtlContainable* uActual ; string msg ; // comment out for now. Uncomment if implementation returns Collectable uActual = commonList.insertAt(insertLocation[i], itemToAdd[i]); //verify that the right value is returned. TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValue[i], uActual) ; //`commonList.insertAt(insertLocation[i], itemToAdd[i]); // verify that the value is inserted TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix2) ; uActual = commonList.at(insertLocation[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValue[i], uActual) ; //verify that the total number of entries has incremented by one. TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedEntries[i], \ (int)commonList.entries()) ; } }//testInsertAt_NonEmptyList() /*!a Test case to test the first() and last() method. * * The test data for this test case is :- * a) Test the first and last element after appending * b) Test the first and last element after insertAt(midlevel) * c) Test the first and last element after insertAt(0) * d) Test the first and last element after insertAt(last) */ void testFirst_And_Last() { const char* prefix1 = "Test the first() method "; const char* prefix2 = "Test the last() method " ; string msg ; UtlContainable* uActual ; UtlContainable* uData ; UtlContainable* uExpected ; const char* Msgs[] = { \ "after appending ", \ "after insertAt(0) ", \ "after insertAt(last) ", \ "after insertAt(mid-level) " \ } ; // Since this testcase requires a different test data // for each of its test data, the regula test-matrix // technique is not being used here. // create a new list and append one element to it. UtlDList testList ; uData = commonContainables[0] ; testList.append(uData); // Test the first() and last() element immeidately after // appending to an empty list. TestUtilities::createMessage(2, &msg, prefix1, Msgs[0]); uActual = testList.first() ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uData, uActual) ; uActual = testList.last() ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[0]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uData, uActual) ; // insert more values to populate the List testList.append(commonContainables[1]) ; testList.append(commonContainables[2]) ; // test the first() / last() methods // after insertAt(0..) uData = commonContainables[3] ; testList.insertAt(0, uData) ; uExpected = commonContainables[3] ; uActual = testList.first() ; TestUtilities::createMessage(2, &msg, prefix1, Msgs[1]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uExpected, uActual) ; uExpected = commonContainables[2] ; uActual = testList.last() ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[1]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uExpected, uActual) ; // test after inserting at the last location uData = commonContainables[4] ; testList.insertAt(4, uData) ; uExpected = commonContainables[3] ; uActual = testList.first() ; TestUtilities::createMessage(2, &msg, prefix1, Msgs[2]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uExpected, uActual) ; uExpected = commonContainables[4] ; uActual = testList.last() ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[2]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uExpected, uActual) ; //test after inserting at the midLocation uData = commonContainables[5] ; testList.insertAt(2, uData) ; uExpected = commonContainables[3] ; uActual = testList.first() ; TestUtilities::createMessage(2, &msg, prefix1, Msgs[3]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uExpected, uActual) ; uExpected = commonContainables[4] ; uActual = testList.last() ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[3]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uExpected, uActual) ; } //testFirst_And_Last /*!a Test case for the index() method * * The test data for this test case are :- * a) When the match is the first element. * b) When the match is the last element. * c) When the match is a mid element(unique). * d) When the match has two value matches (but a single ref match) * e) When the match has two ref matches. * f) When there is no match at all! */ void testIndex() { utlTestIndex_Find_And_Contains(TEST_INDEX) ; } /*!a Test case for the find() method. * * The test data for this test case are the same as * testIndex() test case. */ void testFind() { utlTestIndex_Find_And_Contains(TEST_FIND) ; } /*!a Test case for the contains() method * * The test data for this test case are the same as * testIndex() test case. */ void testContains() { utlTestIndex_Find_And_Contains(TEST_CONTAINS) ; } /*!a Test case for the containsReference() method * * The test data for this test case are the same as * testIndex() test case. */ void testContainsReference() { utlTestIndex_Find_And_Contains(TEST_CONTAINS_REF) ; } // Since the test setup / preconditions for the index, find, // contains and containsReference are all the same, these // tests have been combined into one utility function. Based // on the type argument, the method to be tested is varied. void utlTestIndex_Find_And_Contains(IndexOrContains type) { const int testCount = 7 ; const char* prefixIndex = "Test the index() method when the match " ; const char* prefixFind = "Test the find() method when the match " ; const char* prefixContains = "Test the contains() method when the match " ; const char* prefixContainsRef = "Test the containsReference() method when the match " ; const char* Msgs[] = { \ "is the first element ", \ "is the last element ", \ "is a mid element (unique match) ", \ "has two value matches but a single ref match ", \ "has two ref matches", \ "has a value match but no ref match", \ "has no match at all" \ } ; // insert a clone of the 4th element to the 1st position commonList.insertAt(1, commonContainables_Clone[4]) ; // The new index for a value match of commonContainables[4] must be 1. // insert another copy of the 3rd element to the 2nd position. commonList.insertAt(2, commonContainables[3]) ; // The new index for commonContainables[3] must be 2) ; // what used to be the second element has now moved to 4. UtlString noExist("This cannot and should not exist!!!") ; UtlContainable* searchValues[] = { \ commonContainables[0], commonContainables[5], commonContainables[2], \ commonContainables[4], commonContainables[3], \ commonContainables_Clone[2], &noExist \ } ; size_t expectedValues_Index[] = { 0, 7, 4, 1, 2, 4, UTL_NOT_FOUND } ; bool expectedValues_Contains[] = {true, true, true, true, true, true, false } ; bool expectedValues_ContainsRef[] = {true, true, true, true, true, false, false} ; UtlContainable* searchValuesForFind[] = { \ commonContainables[0], commonContainables[5], commonContainables[2], \ commonContainables[4], commonContainables[3], \ commonContainables_Clone[1], &noExist \ } ; UtlContainable* expectedValuesForFind[] = { \ commonContainables[0], commonContainables[5], commonContainables[2], \ commonContainables_Clone[4], commonContainables[3], \ commonContainables[1], NULL \ } ; for (int i = 0 ; i < testCount ; i++) { //printf("line: %d file: %s i: %d testCount: %d\n", // __LINE__, __FILE__, i, testCount); string msg ; if (type == TEST_INDEX) { size_t actual = commonList.index(searchValues[i]) ; msg = prefixIndex; msg.append(Msgs[i]); CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValues_Index[i], actual) ; } else if (type == TEST_FIND) { UtlContainable* actual = commonList.find(searchValuesForFind[i]) ; msg = prefixFind; msg.append(Msgs[i]); CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValuesForFind[i], actual) ; } else if (type == TEST_CONTAINS) { UtlBoolean actual = commonList.contains(searchValues[i]) ; TestUtilities::createMessage(2, &msg, prefixContains, Msgs[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValues_Contains[i], \ (TRUE == actual)) ; } else if (type == TEST_CONTAINS_REF) { UtlBoolean actual = commonList.containsReference(searchValues[i]) ; TestUtilities::createMessage(2, &msg, prefixContainsRef, Msgs[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValues_ContainsRef[i], \ (TRUE == actual)) ; } } }//utlTestIndex /*!a Test the occurancesOf() method . * * The test data for this test are :- * a) When the search data is the first entry * b) When the search data is the last entry * c) When the search data is the mid(unique) entry * d) When the search data has a matching value but not ref. * e) When the search data has multiple matches - mixture of ref / values * f) When the search data has no match at all. */ void testOccurancesOf() { const int testCount = 6 ; const char* prefix = "Test the occurancesOf(UtlContainable* cl); where cl " ; const char* Msgs[] = { \ "is the first entry ", \ "is the last entry and ref matches ", \ "is the mid entry and is unique ", \ "has a matching value but not reference ", \ "has multiple matches ", \ "has no match at all " \ } ; commonList.insertAt(3, commonContainables_Clone[4]) ; commonList.insertAt(5, commonContainables[4]) ; UtlString notExistCollectable("This cannot and willnot exist"); UtlContainable* searchValues[] = { \ commonContainables[0], commonContainables[commonEntriesCount -1], \ commonContainables[2], commonContainables_Clone[3], \ commonContainables[4], ¬ExistCollectable \ } ; size_t matchCount[] = { 1, 1, 1, 1, 3, 0 } ; for (int i = 0 ; i < testCount ; i++) { string msg ; TestUtilities::createMessage(2, &msg, prefix, Msgs[i]) ; size_t actual = commonList.occurrencesOf(searchValues[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), matchCount[i], actual) ; } } //testOccurancesOf /*!a Test case for testRemove() * * The Test data for this test case is * a) is the first entry's reference * b) is the last entry' reference * c) is the mid entry's value(not reference) * d) is the first of multiple matches and is the value match * e) has no match at all */ void testRemove() { utlTestRemove(TEST_REMOVE) ; } /*!a Test case for testRemoveReference() * * The test data for this test case is * the same as teh remove() method. */ void testRemoveReference() { utlTestRemove(TEST_REMOVE_REF) ; } /*!a Test case to test the destroy() * method. */ void testRemoveAndDestroy() { const char* prefix = "test the destroy() method " ; UtlContainableTestStub uStub(0) ; UtlContainableTestStub* uStubPtr ; uStubPtr = new UtlContainableTestStub(1) ; commonList.append(&uStub) ; commonList.append(uStubPtr) ; int cCountBefore = UtlContainableTestStub :: getCount() ; UtlBoolean returnValue = commonList.destroy(uStubPtr) ; UtlContainable* uLast = commonList.last() ; string msg ; TestUtilities::createMessage(2, &msg, prefix, ":- Verify the return value") ; CPPUNIT_ASSERT_MESSAGE(msg.data(), returnValue) ; TestUtilities::createMessage(2, &msg, prefix, ":- Verify that the entry is removed") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)&uStub, (void*)uLast) ; // The CollectableTestStub has been implemented such that a static counter gets decremented // for every descruction of an object instance. To verify that the object was destroyed, // verify that the static count went down. int cCountAfter = UtlContainableTestStub :: getCount() ; TestUtilities::createMessage(2, &msg, prefix, ":- Verify that the object was deleted") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), cCountBefore -1, cCountAfter) ; } void utlTestRemove(RemoveType type) { int testCount = 5 ; const char* prefix = ""; if (type == TEST_REMOVE) { prefix = "test the remove(UtlContainable* c) method where c" ; } else if (type == TEST_REMOVE_REF) { prefix = "test the removeReference(UtlContainable* c) where c" ; } const char* Msgs[] = { \ "is the first entry's reference ", \ "is the last entry' reference ", \ "is the mid entry's value(not reference) ", \ "is the first of multiple matches and is the value match ", \ "has no match at all " \ } ; const char* suffix1 = " :- Verify returned value" ; const char* suffix2 = " :- Verify total entries" ; commonList.insertAt(2, commonContainables_Clone[4]) ; UtlString notExistCollectable("This cannot and willnot exist"); UtlContainable* itemToRemove[] = { \ commonContainables[0], commonContainables[commonEntriesCount -1 ], \ commonContainables_Clone[2], commonContainables[4], \ ¬ExistCollectable \ } ; int totalEnt = commonEntriesCount + 1; UtlContainable* expectedValue[] = { \ commonContainables[0], commonContainables[commonEntriesCount -1 ], \ commonContainables[2], commonContainables_Clone[4], \ NULL \ }; int entriesValue[] = { --totalEnt, --totalEnt, --totalEnt, --totalEnt, totalEnt } ; totalEnt = commonEntriesCount + 1; UtlContainable* expectedRef[] = { \ commonContainables[0], commonContainables[commonEntriesCount -1 ], \ NULL, commonContainables[4], \ NULL \ }; int entriesRef[] = { --totalEnt, --totalEnt, totalEnt, --totalEnt, totalEnt } ; for (int i = 0 ; i < testCount ; i++) { string msg ; if (type == TEST_REMOVE) { TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix1) ; UtlContainable* retValue = commonList.remove(itemToRemove[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValue[i], retValue) ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), entriesValue[i], (int)commonList.entries()) ; } else if (type == TEST_REMOVE_REF) { UtlContainable* uRemoved = commonList.removeReference(itemToRemove[i]) ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedRef[i], uRemoved) ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), entriesRef[i], (int)commonList.entries()) ; } } } //utlRemove /*!a Test case for the get() method. * * The test data for this test is :- * 1) The first entry is a CollectableString * 2) The first entry is a CollectableInt * 3) The List has only one entry * 4) The List has no entries */ void testGet() { const int testCount = 4 ; const char* prefix = "Verify the get() method for a list when " ; const char* Msgs[] = { \ "the first entry is a CollectableString", \ "the first entry is a CollectableInt", \ "when the list has only one entry", \ "when the list is empty" \ } ; const char* suffix1 = ":- verify return value" ; const char* suffix2 = ":- verify the number of entries in the list" ; UtlDList testList ; testList.append(&commonString1) ; testList.append(&commonInt1) ; testList.append(&commonString2) ; UtlContainable* expectedValue[] = { \ &commonString1 , &commonInt1, &commonString2, NULL \ } ; int entryCount[] = { 2, 1, 0, 0 } ; for (int i = 0 ; i < testCount ; i++) { UtlContainable* actual = testList.get() ; string msg ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValue[i], actual) ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), entryCount[i], (int)testList.entries()) ; } } //testGet() /*!a Test case for the isEmpty() method. * The test data for this test are :- * a) When the list has just been created. * b) When the list has one entry in it * c) When the list has multiple entries in it. * d) When all the entries in a list have been removed using get. * e) When all the entries in a list have been removed using removeAll() */ void testIsEmpty() { const int testCount = 5 ; const char* prefix = "Test the isEmpty() method when " ; const char* Msgs[] = { \ "the list has just been created" , \ "the list has just one entry in it", \ "the list has multiple entries in it", \ "all the list entries have been retreieved using get()", \ "all the list entries have been retreived using removeAll()" \ } ; UtlDList newList ; UtlDList secondNewList ; UtlDList commonList_Clone ; // first populate a list and then retreive all elements using get for (int i = 0 ; i < commonEntriesCount ; i++) { commonList_Clone.append(commonContainables_Clone[i]) ; } for (int j = 0 ; j < commonEntriesCount; j++) { commonList_Clone.get(); } UtlString uS1 = UtlString("Lone Entry") ; newList.append(&uS1) ; // populate the second list and then clear all entries. secondNewList.append(&uS1) ; UtlInt uI1 = UtlInt(232) ; secondNewList.append(&uI1) ; secondNewList.removeAll() ; UtlDList* testLists[] = { \ &emptyList, &newList, &commonList, &commonList_Clone, &secondNewList \ } ; bool expectedValue[] = { true, false, false, true, true } ; for (int k = 0 ; k < testCount; k++) { string msg ; TestUtilities::createMessage(2, &msg, prefix, Msgs[k]) ; UtlBoolean actual = testLists[k] -> isEmpty() ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (UtlBoolean)expectedValue[k], \ actual) ; } } // testIsEmpty /*!a test the removeAll() method. * * The test data for this method is * a) When the list is empty * b) When the list has one entry. * c) When the list multiple entries * d) When removeAll has been called and entries are added again * d) When the removeAll is called twice on the list. */ void testClear() { const int testCount = 5 ; const char* prefix = "Test the removeAll() method when :- " ; const char* Msgs[] = { \ "the list is empty", \ "the list has one entry", \ "the list has multiple entries", \ "removeAll() has been called and entries are added again", \ "removeAll() has already been called", \ } ; const char* suffix = " :- Verify number of entries after removeAll()" ; UtlDList uSingleList ; UtlDList uAddAfterClear ; UtlDList uDoubleClear ; uSingleList.append(&commonString1) ; // call removeAll() on a list and then add entries again. uAddAfterClear.append(&commonInt1) ; uAddAfterClear.append(&commonString1) ; uAddAfterClear.removeAll() ; uAddAfterClear.append(&commonInt2) ; // call removeAll on a list twice. uDoubleClear.append(&commonString3) ; uDoubleClear.append(&commonInt3) ; uDoubleClear.removeAll() ; UtlDList* testLists[] = { \ &emptyList, &uSingleList, &commonList, &uAddAfterClear, &uDoubleClear } ; int expectedEntries[] = { 0 , 0, 0, 1, 0 } ; // since we are not calling removeAll for all the data, do it outside the for loop. emptyList.removeAll() ; uSingleList.removeAll() ; commonList.removeAll() ; // no removeAll() for uAddAfterClear uDoubleClear.removeAll() ; for ( int i = 0 ; i < testCount ; i++) { string msg ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data() , expectedEntries[i], \ (int)testLists[i]->entries()) ; } } //testClear() /*!a Test case to test the destroyAll() * method. */ void testClearAndDestroy() { const char* prefix = "test the destroyAll() method " ; const char* suffix1 = ":- Verify that all entries are removed" ; const char* suffix2 = ":- The objects are deleted" ; UtlContainableTestStub* uStub ; UtlContainableTestStub* uStubPtr ; uStub = new UtlContainableTestStub(0) ; uStubPtr = new UtlContainableTestStub(1) ; emptyList.append(uStub) ; emptyList.append(uStubPtr) ; emptyList.destroyAll() ; int cCountAfter = UtlContainableTestStub::getCount() ; string msg ; TestUtilities::createMessage(2, &msg, prefix, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), 0, (int)emptyList.entries()) ; // Since the TestStub has been implemented such that destructor // decrements the static counter, to verify that the objects have // been deleted, verify that the static counter has been decremented. TestUtilities::createMessage(2, &msg, prefix, suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), 0, cCountAfter) ; } //testClearAndDestroy }; const int UtlDListTest::commonEntriesCount = 6; const char* UtlDListTest::longAlphaNumString = \ "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvw" ; const char* UtlDListTest::regularString = "This makes sense" ; CPPUNIT_TEST_SUITE_REGISTRATION(UtlDListTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlDListIterator.cpp0000644000175000017500000004452712205613256026167 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include #include #include class UtlDListIteratorTests : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlDListIteratorTests); CPPUNIT_TEST(testAdvancingOperator) ; CPPUNIT_TEST(testFindNext) ; CPPUNIT_TEST(testLast) ; CPPUNIT_TEST(testInsertAfterPoint_EmptyList) ; CPPUNIT_TEST(testInsertAfterPoint) ; CPPUNIT_TEST_SUITE_END(); private: static const int INDEX_NOT_EXIST ; static const int commonEntriesCount ; UtlDList commonList ; UtlDList emptyList ; UtlString commonString1 ; UtlString commonString2 ; UtlString commonString3 ; UtlInt commonInt1 ; UtlInt commonInt2 ; UtlInt commonInt3 ; UtlString commonString1_clone; UtlString commonString2_clone ; UtlString commonString3_clone ; UtlInt commonInt1_clone ; UtlInt commonInt2_clone ; UtlInt commonInt3_clone ; static const char* longAlphaNumString ; static const char* regularString ; UtlContainable** commonContainables; UtlContainable** commonContainables_Clone; enum IndexOrContains { TEST_INDEX, TEST_FIND, TEST_CONTAINS, TEST_CONTAINS_REF } ; enum TestInsertOrAppend {TEST_APPEND, TEST_INSERT} ; enum RemoveType {TEST_REMOVE, TEST_REMOVE_REF } ; public: void setUp() { // In case a test aborts without tearDown always clean the list out commonList.removeAll(); commonString1 = UtlString(regularString) ; commonString1_clone = UtlString(regularString) ; commonString2 = UtlString("") ; commonString2_clone = UtlString("") ; commonString3 = UtlString(longAlphaNumString) ; commonString3_clone = UtlString(longAlphaNumString) ; commonInt1 = UtlInt(0) ; commonInt1_clone = UtlInt(0) ; commonInt2 = UtlInt(INT_MAX) ; commonInt2_clone = UtlInt(INT_MAX) ; commonInt3 = UtlInt(INT_MIN) ; commonInt3_clone = UtlInt(INT_MIN) ; commonList.append(&commonString1) ; commonContainables[0] = &commonString1 ; commonContainables_Clone[0] = &commonString1_clone ; commonList.append(&commonInt1) ; commonContainables[1] = &commonInt1 ; commonContainables_Clone[1] = &commonInt1_clone ; commonList.append(&commonInt2) ; commonContainables[2] = &commonInt2 ; commonContainables_Clone[2] = &commonInt2_clone; commonList.append(&commonString2) ; commonContainables[3] = &commonString2 ; commonContainables_Clone[3] = &commonString2_clone ; commonList.append(&commonInt3) ; commonContainables[4] = &commonInt3 ; commonContainables_Clone[4] = &commonInt3_clone ; commonList.append(&commonString3) ; commonContainables[5] = &commonString3 ; commonContainables_Clone[5] = &commonString3_clone ; } void tearDown() { } /* Sandbox - please ignore */ void DynaTest() { } UtlDListIteratorTests() { commonContainables = new UtlContainable*[commonEntriesCount] ; commonContainables_Clone = new UtlContainable*[commonEntriesCount] ; } ~UtlDListIteratorTests() { delete[] commonContainables ; delete[] commonContainables_Clone ; } /*!a Test case for the () operator. * * The test data for this test is :- * 1) The next entry is a UtlString * 2) The next entry is a UtlInt * 3) The next entry is the last entry * 4) All entries have been read */ void testAdvancingOperator() { const int testCount = 4 ; const char* prefix = "Verify the () operator for an iterator when " ; const char* Msgs[] = { \ "the first entry is a UtlString", \ "the first entry is a UtlInt", \ "when the list has only one entry", \ "when the list is empty" \ } ; const char* suffix1 = " :- verify return value" ; const char* suffix2 = " :- verify number of entries in the list" ; UtlDList testList ; testList.append(&commonString1) ; testList.append(&commonInt1) ; testList.append(&commonString2) ; UtlDListIterator iter(testList) ; UtlContainable* exp[] = { \ &commonString1 , &commonInt1, &commonString2, NULL \ } ; int expEntries = 3 ; for (int i = 0 ; i < testCount ; i++) { UtlContainable* act = iter() ; string msg ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), exp[i], act) ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix2); CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expEntries, (int)testList.entries()) ; } // Test the () operator for an empty list UtlDListIterator emptyIter(emptyList) ; UtlContainable* act = emptyIter() ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Test the () operator for an empty list iterator" , (void*)NULL, (void*)act) ; } //testAdvancingOperator() /*!a Test case for the findNext() method * * The test data for this test case are :- * a) When the match is the first element. * b) When the match is the last element. * c) When the match is a mid element(unique). * d) When the match has two value matches (but a single ref match) * e) When the match has two ref matches. * f) When there is no match at all! * g) When the match is after the current find. */ void testFindNext() { const int testCount = 7 ; const char* prefixFind = "Test the find() method when the match " ; const char* Msgs[] = { \ "is the first element ", \ "is the last element ", \ "is a mid element (unique match) ", \ "has two value matches but a single ref match ", \ "has two ref matches", \ "has a value match but no ref match", \ "has no match at all" \ } ; // insert a clone of the 4th element to the 1st position commonList.insertAt(1, (UtlContainable*)commonContainables_Clone[4]) ; // The new index for a value match of commonContainables[4] must be 1. // insert another copy of the 3rd element to the 2nd position. commonList.insertAt(2, (UtlContainable*)commonContainables[3]) ; // The new index for commonContainables[3] must be 2) ; // what used to be the second element has now moved to 4. UtlString noExist("This cannot and should not exist!!!") ; const UtlContainable* searchValuesForFind[] = { \ commonContainables[0], commonContainables[5], commonContainables[2], \ commonContainables[4], commonContainables[3], \ commonContainables_Clone[1], &noExist \ } ; const UtlContainable* expValuesForFind[] = { \ commonContainables[0], commonContainables[5], commonContainables[2], \ commonContainables_Clone[4], commonContainables[3], \ commonContainables[1], NULL \ } ; UtlDListIterator iter(commonList) ; for (int i = 0 ; i < testCount ; i++) { string msg ; const UtlContainable* act = iter.findNext(searchValuesForFind[i]) ; const UtlContainable* exp = expValuesForFind[i] ; TestUtilities::createMessage(2, &msg, prefixFind, Msgs[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), exp, act) ; iter.reset() ; } // Now test the case where the iterator is 'past' the index iter.reset() ; iter() ; iter() ; iter() ; iter() ; iter() ; UtlContainable* act = iter.findNext(commonContainables[1]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("test findNext() when the iterator has moved past the search index", (void*)NULL, (void*)act) ; }//testFindNext /*!a Test case to test the toLast() and atLast() methods. * * The test data for this test case is :- * a) An empty list * b) A non-empty list iterator that is in its initial position * c) A non-empty list iterator that is in its last position. * d) A non-empty list that is in its mid position */ void testLast() { UtlDList testList ; const char* prefix1 = "Test the toLast() method for " ; const char* prefix2 = "Test the atLast() method(after calling toLast()) for " ; string msg ; UtlContainable* uAct ; bool isAtLast = false ; const char* Msgs[] = { \ "an empty list iterator ", \ "a list iterator that is in its zeroth position ", \ "a non empty list that is already in its last position ", \ "a non empty list that is in its mid position " \ } ; UtlDListIterator iter(emptyList) ; UtlDListIterator iter2(commonList) ; // since this test requires adifferent test setup for each // of the test data, tests are done individually rather than using // the test array style of testing. // Test#1 - Test the methods for an empty list. int ti = 0 ; iter.toLast() ; isAtLast = (TRUE == iter.atLast()) ; uAct = iter() ; TestUtilities::createMessage(2, &msg, prefix1, Msgs[ti]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)NULL, (void*)uAct) ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[ti]) ; // since the list is empty, any position is __PAST__ the last position CPPUNIT_ASSERT_MESSAGE(msg.data(), !isAtLast) ; // Test#2 - Test the methods for a list that is not empty. ti++ ; iter2.reset() ; iter2.toLast() ; isAtLast = (TRUE == iter2.atLast()) ; uAct = iter2() ; TestUtilities::createMessage(2, &msg, prefix1, Msgs[ti]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)NULL, (void*)uAct) ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[ti]) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), isAtLast) ; // Test#3 - Test the methods for a list that is not empty when // the list is already in its last position. ti++ ; iter2.reset() ; iter2.toLast() ; iter2.toLast() ; isAtLast = (TRUE == iter2.atLast()) ; uAct = iter2() ; TestUtilities::createMessage(2, &msg, prefix1, Msgs[ti]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)NULL, (void*)uAct) ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[ti]) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), isAtLast) ; // Test#4 - Test the methods for a list that is not empty when the // list has been iterated to somewhere in its middle position. ti++ ; iter2.reset() ; iter2() ; iter2() ; iter2.toLast() ; isAtLast = (TRUE == iter2.atLast()) ; uAct = iter2() ; TestUtilities::createMessage(2, &msg, prefix1, Msgs[ti]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)NULL, (void*)uAct) ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[ti]) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), isAtLast) ; } //testFirst_And_Last /*!a Test case for the insertAfterPoint() method when the * the list is empty */ void testInsertAfterPoint_EmptyList() { const char* prefix = "Test the insertAfterPoint() method for an empty list " ; const char* suffix1 = ":- Verify return value" ; const char* suffix2 = ":- Verify that the entry has been added" ; string msg ; UtlDListIterator iter(emptyList) ; const UtlContainable* uReturn = iter.insertAfterPoint((UtlContainable*)commonContainables[0]) ; TestUtilities::createMessage(2, &msg, prefix, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)commonContainables[0], (void*)uReturn) ; iter.reset() ; UtlContainable* uAppended = iter() ; TestUtilities::createMessage(2, &msg, prefix, suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)commonContainables[0], (void*)uAppended) ; } /*!a Test case for the insertAfterPoint() method. * * The test data is :- * a) Insert when the iterator is the starting position * b) Insert when the iterator is at mid position * c) Insert when the iterator is at the last position * d) Insert to an empty Iterator. */ void testInsertAfterPoint() { const char* prefix = "Test the insertAfterPoint() method when " ; const char* Msgs[] = {\ "the iterator is the starting position " , \ "the iterator is at mid-position ", \ "the iterator is at the last position " \ } ; const char* suffix1 = ":- Verify return value" ; const char* suffix2 = ":- Verify value is inserted" ; const char* suffix3 = ":- Verify that previous value is not lost" ; UtlDListIterator iter(commonList) ; const UtlContainable* uReturn ; UtlContainable* uAppended ; UtlContainable* uOrig ; string msg ; UtlString newColString1("Insert at starting position") ; UtlInt newColInt2(101) ; UtlString newColString3 ("Insert at last position") ; UtlContainable* insertValues[] = { \ &newColString1, &newColInt2, &newColString3 \ }; const UtlContainable* oldValues[] = { \ commonContainables[0], commonContainables[1], commonContainables[5] \ } ; // Since this test requires different steps for the different test data, // steps are executed individually rather than the regular technique of // iterating through the test-array loop //Test#1 - Verify the case when the iterator has been reset int ti = 0 ; iter.reset() ; uReturn = iter.insertAfterPoint(insertValues[ti]) ; TestUtilities::createMessage(3, &msg, prefix, Msgs[ti], suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE (msg.data(), (void*)insertValues[ti], (void*)uReturn) ; // The item is inserted at first position // old[0] is now @ pos1. old[1] is now @ pos2 iter.reset() ; uAppended = iter() ; TestUtilities::createMessage(3, &msg, prefix, Msgs[ti], suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)insertValues[ti], (void*)uAppended) ; // Verify that the original item is still retained. uOrig = iter() ; TestUtilities::createMessage(3, &msg, prefix, Msgs[ti], suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)oldValues[ti], (void*)uOrig) ; //Test#2 - inserting at mid position ti = 1; iter.reset() ; iter() ; //moves cursor to 0 iter() ; //moves cursor to 1 iter() ; //moves cursor to 2 // old[1] stays at pos2 // Value is now inserted at pos3 uReturn = iter.insertAfterPoint(insertValues[ti]) ; TestUtilities::createMessage(3, &msg, prefix, Msgs[ti], suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE (msg.data(), (void*)insertValues[ti], (void*)uReturn) ; iter.reset() ; iter() ; // moves cursor to 0 iter() ; // moves cursor to 1 // Verify that the original item is still retained. uOrig = iter() ; TestUtilities::createMessage(3, &msg, prefix, Msgs[ti], suffix3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)oldValues[ti], (void*)uOrig) ; // The item is inserted just after the position. uAppended = iter() ; //moves cursor to pos3 and returns item at pos2 TestUtilities::createMessage(3, &msg, prefix, Msgs[ti], suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)insertValues[ti], (void*)uAppended) ; // Test#3 - Now verify when the cursor is at the last position. ti = 2 ; iter.reset() ; iter.toLast() ; uReturn = iter.insertAfterPoint(insertValues[ti]) ; TestUtilities::createMessage(3, &msg, prefix, Msgs[ti], suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)insertValues[ti], (void*)uReturn) ; iter.reset() ; // now move the cursor all the way to the penultimate position for (size_t i = 0 ; i < commonList.entries() - 1; i++) { uOrig = iter() ; } // verify original is still retained. TestUtilities::createMessage(3, &msg, prefix, Msgs[ti], suffix3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)oldValues[ti], (void*)uOrig) ; uAppended = iter() ; TestUtilities::createMessage(3, &msg, prefix, Msgs[ti], suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE( msg.data(), (void*)insertValues[ti], (void*)uAppended) ; } //testInsertAfterPoint }; const int UtlDListIteratorTests::INDEX_NOT_EXIST = -1; const int UtlDListIteratorTests::commonEntriesCount = 6; const char* UtlDListIteratorTests::longAlphaNumString = \ "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvw" ; const char* UtlDListIteratorTests::regularString = "This makes sense" ; CPPUNIT_TEST_SUITE_REGISTRATION(UtlDListIteratorTests); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlHashBag.cpp0000644000175000017500000007525612205613256024736 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include //#include #include #include #include #include #include #include #include #include class UtlHashBagTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlHashBagTest); CPPUNIT_TEST(checkSanity_Insert_Entries_And_At) ; CPPUNIT_TEST(testInsert) ; CPPUNIT_TEST(testFind) ; CPPUNIT_TEST(testContains) ; CPPUNIT_TEST(testRemove) ; CPPUNIT_TEST(testRemoveAndDestroy) ; CPPUNIT_TEST(testIsEmpty) ; CPPUNIT_TEST(testClear) ; CPPUNIT_TEST(testClearAndDestroy) ; CPPUNIT_TEST(testRemoveReference) ; CPPUNIT_TEST(testOneThousandInserts); CPPUNIT_TEST_SUITE_END(); private: static const int INDEX_NOT_EXIST ; static const int commonEntriesCount ; UtlHashBag commonList ; UtlHashBag emptyList ; UtlString commonString1 ; UtlString commonString2 ; UtlString commonString3 ; UtlInt commonInt1 ; UtlInt commonInt2 ; UtlInt commonInt3 ; UtlString commonString1_clone; UtlString commonString2_clone ; UtlString commonString3_clone ; UtlInt commonInt1_clone ; UtlInt commonInt2_clone ; UtlInt commonInt3_clone ; static const char* longAlphaNumString ; static const char* regularString ; UtlContainable** commonContainables ; UtlContainable** commonContainables_Clone ; enum FindOrContains { TEST_FIND, TEST_CONTAINS} ; enum TestInsertOrAppend {TEST_APPEND, TEST_INSERT} ; enum RemoveType {TEST_REMOVE, TEST_REMOVE_REF } ; public: UtlHashBagTest() { commonContainables = new UtlContainable*[commonEntriesCount] ; commonContainables_Clone = new UtlContainable*[commonEntriesCount] ; } ~UtlHashBagTest() { delete[] commonContainables ; delete[] commonContainables_Clone ; } void setUp() { UtlContainableTestStub::clearCount() ; commonString1 = UtlString(regularString) ; commonString1_clone = UtlString(regularString) ; commonString2 = UtlString("") ; commonString2_clone = UtlString("") ; commonString3 = UtlString(longAlphaNumString) ; commonString3_clone = UtlString(longAlphaNumString) ; commonInt1 = UtlInt(0) ; commonInt1_clone = UtlInt(0) ; commonInt2 = UtlInt(INT_MAX) ; commonInt2_clone = UtlInt(INT_MAX) ; commonInt3 = UtlInt(INT_MIN) ; commonInt3_clone = UtlInt(INT_MIN) ; commonList.removeAll(); commonList.insert(&commonString1) ; commonContainables[0] = &commonString1 ; commonContainables_Clone[0] = &commonString1_clone ; commonList.insert(&commonInt1) ; commonContainables[1] = &commonInt1 ; commonContainables_Clone[1] = &commonInt1_clone ; commonList.insert(&commonInt2) ; commonContainables[2] = &commonInt2 ; commonContainables_Clone[2] = &commonInt2_clone; commonList.insert(&commonString2) ; commonContainables[3] = &commonString2 ; commonContainables_Clone[3] = &commonString2_clone ; commonList.insert(&commonInt3) ; commonContainables[4] = &commonInt3 ; commonContainables_Clone[4] = &commonInt3_clone ; commonList.insert(&commonString3) ; commonContainables[5] = &commonString3 ; commonContainables_Clone[5] = &commonString3_clone ; } void tearDown() { } // Sandbox - Please ignore. void DynaTest() { } //DynaTest /*a! This test is more of a sanity check to verify that * the basic insert(), entries() and at() methods work as expected. * All future tests will depend heavily on the at() method * and the most common way of having something in the list is * by means of the insert() method. * */ void checkSanity_Insert_Entries_And_At() { // Verify that the hashtables that were created and populated in the setup method // have their entries set to the right value. CPPUNIT_ASSERT_EQUAL_MESSAGE("Verify that the entries() for an empty HashTable returns 0", (int)emptyList.entries(), 0) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Verify the entries() method for a HashTable", commonEntriesCount, (int)commonList.entries()) ; }// checkSanity_Append_And_At() /*a! Test the insert method for a list that is not empty. Add both unique and non-unique entries. * * The test data for this test is :- * a) Add a new UtlInt * b) Add a new UtlString * c) Add a new UtlVoidPtr * d) Add a new Containable such that a similar one (value match) exists already * e) Add a new Containable such that the same one (reference match) exists already */ void testInsert() { struct testInsertStructure { const char* testDescription ; UtlContainable* itemToAdd ; UtlContainable* expectedReturnValue ; // In case of the hashtable, searching for a key can return *ANY* of the values // that matches and we dont care about which one. so we need two set of expected values UtlContainable* expectedFoundValue ; UtlContainable* altExpectedFoundValue ; } ; const char* prefix = "Test the insert(UtlContainable*) method for a non empty HashTable " ; const char* suffix1 = " :- Verify return value" ; const char* suffix2 = " :- Verify that the value is inserted" ; const char* suffix3 = " :- Verify that the number of entries is incremented by one" ; UtlInt uInt = UtlInt(1234) ; UtlString uString = UtlString("Test String") ; UtlVoidPtr uVoidPtr((char*)"Hello world") ; testInsertStructure testData[] = { \ { "Add a new UtlInt ", &uInt, &uInt, &uInt, &uInt}, \ { "Add a new UtlString ", &uString, &uString, &uString, &uString}, \ { "Add a new UtlVoidPtr ", &uVoidPtr, &uVoidPtr, &uVoidPtr, &uVoidPtr}, \ { "Add a Containable such that an identical one(value match) " \ "exists in the table ", commonContainables_Clone[3], commonContainables_Clone[3], \ commonContainables[3], commonContainables_Clone[3] }, \ { "Add a Containable such that an exact duplicate " \ "(including reference match) exists in the table ", commonContainables[4], commonContainables[4], commonContainables[4] } \ } ; int expCount = commonEntriesCount; string msg ; UtlContainable* uAct ; UtlContainable* uReturn ; /* :TODO: this part of the test is in error. * when there is more than one of the same value in the bage, * the find() method may return any of the objects with that value. */ int testCount = sizeof(testData)/sizeof(testData[0]) ; for (int i = 0 ; i < testCount ; i++) { uReturn = commonList.insert(testData[i].itemToAdd) ; expCount++ ; uAct = commonList.find(testData[i].itemToAdd) ; TestUtilities::createMessage(3, &msg, prefix, \ testData[i].testDescription, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), \ testData[i].expectedReturnValue, uReturn) ; // when there is more than one of the same value in the bag, // the find() method may return any of the objects with that value. bool isFound = (uAct == testData[i].expectedFoundValue) || \ (uAct == testData[i].altExpectedFoundValue) ; TestUtilities::createMessage(3, &msg, prefix, \ testData[i].testDescription, suffix2) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), isFound) ; TestUtilities::createMessage(3, &msg, prefix, \ testData[i].testDescription, suffix3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expCount, (int)commonList.entries()) ; } } //testInsert /*!a Test case for the find() method. * * The test data for this test case are:- * a) is the first element * b) is the last element * c) is a mid element (unique match) * d) has two value matches but a single ref match * e) has two ref matches * f) has a value match but no ref match * g) has no match at all */ void testFind() { utlTestFind_And_Contains(TEST_FIND) ; } /*!a Test case for the contains() method * * The test data for this test case are the same as * testFind() test case. */ void testContains() { utlTestFind_And_Contains(TEST_CONTAINS) ; } void utlTestFind_And_Contains(FindOrContains type) { const int testCount = 7 ; const char* prefixFind = "Test the find() method when the match " ; const char* prefixContains = "Test the contains() method when the match " ; const char* Msgs[] = { \ "is the first element ", \ "is the last element ", \ "is a mid element (unique match) ", \ "has two value matches but a single ref match ", \ "has two ref matches", \ "has a value match but no ref match", \ "has no match at all" \ } ; // insert two elements to satisfy (d) and (e) commonList.insert( commonContainables_Clone[4]) ; commonList.insert( commonContainables[3]) ; UtlString noExist("This cannot and should not exist!!!") ; UtlContainable* searchValues[] = { \ commonContainables[0], commonContainables[5], commonContainables[2], \ commonContainables[4], commonContainables[3], \ commonContainables_Clone[2], &noExist \ } ; bool expectedValues_Contains[] = {true, true, true, true, true, true, false } ; UtlContainable* searchValuesForFind[] = { \ commonContainables[0], commonContainables[5], commonContainables[2], \ commonContainables[4], commonContainables[3], \ commonContainables_Clone[1], &noExist \ } ; // In case of the hashtable, searching for a key can return *ANY* of the values // that matches and we dont care about which one. so we need two set of expected values UtlContainable* expValues_Find[][2] = { \ {commonContainables[0], commonContainables[0]}, \ {commonContainables[5], commonContainables[2]}, \ {commonContainables[2], commonContainables[2]}, \ {commonContainables_Clone[4], commonContainables[4]}, \ {commonContainables[3], commonContainables[3]}, \ {commonContainables[1], commonContainables[1]}, \ {NULL, NULL} \ } ; for (int i = 0 ; i < testCount ; i++) { string msg ; if (type == TEST_FIND) { bool isFound = false ; UtlContainable* act = commonList.find(searchValuesForFind[i]) ; // If we are expecting either 'A' or 'B' for the search isFound = (act == expValues_Find[i][0]) || (act == expValues_Find[i][1]) ; TestUtilities::createMessage(2, &msg, prefixFind, Msgs[i]) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), isFound) ; } else if (type == TEST_CONTAINS) { UtlBoolean act = commonList.contains(searchValues[i]) ; UtlBoolean exp = (UtlBoolean)expectedValues_Contains[i] ; TestUtilities::createMessage(2, &msg, prefixContains, Msgs[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), exp, act) ; } } }//utlTestIndex /*!a Test case to test the destroy() * method. */ void testRemoveAndDestroy() { const char* prefix = "test the destroy() method " ; // The ContainableTestStub has been implemented such that a static // counter is incremented everytime an instance is created and // the counter is decremented everytime an instance is destroyed. UtlContainableTestStub* uStub = new UtlContainableTestStub(0) ; UtlContainableTestStub* uStubPtr = new UtlContainableTestStub(101) ; commonList.insert(uStub) ; commonList.insert(uStubPtr) ; string msg ; int cCountBefore = UtlContainableTestStub :: getCount() ; UtlBoolean retValue = commonList.destroy(uStubPtr) ; int cCountAfter ; uStubPtr = NULL ; TestUtilities::createMessage(2, &msg, prefix, ":- Verify the return value") ; CPPUNIT_ASSERT_MESSAGE(msg.data(), retValue) ; // To verify that the object was destroyed, check to see if the static count has been // decremented. If yes, it means that the destructor was called. cCountAfter = UtlContainableTestStub :: getCount() ; TestUtilities::createMessage(2, &msg, prefix, ":- Verify that the object was deleted") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), cCountBefore -1, cCountAfter) ; // THe way to verify if the object has been removed is to // create a new stub such that it has the same value as // the removed stub. Try to find the new stub UtlContainableTestStub uStubNew(101) ; UtlContainable* uSearch = commonList.find(&uStubNew) ; TestUtilities::createMessage(2, &msg, prefix, ":- Verify that the entry is removed") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)NULL, (void*)uSearch) ; // Now test the case when you have added multiple deletable keys // and the first key inserted is deleted first. UtlContainableTestStub* uStubPtr2 = new UtlContainableTestStub(201) ; UtlContainableTestStub* uStubPtr3 = new UtlContainableTestStub(201) ; commonList.insert(uStubPtr2) ; commonList.insert(uStubPtr3) ; UtlInt uTestInt(2031) ; commonList.insert(&uTestInt) ; // after destroying, either uStubPtr or uStubPtr3 might have gotten deleted and // we have no way to find out which one. So create a new ContainableTestStub // and use that for search UtlContainableTestStub uStubTemp(201) ; cCountBefore = UtlContainableTestStub :: getCount() ; commonList.destroy(&uStubTemp) ; cCountAfter = UtlContainableTestStub :: getCount() ; uSearch = commonList.find(&uStubTemp) ; const char* msgTemp = "Verify that doing a removeAndDestroy on " \ "an item that has multiple matches removes only one entry " ; TestUtilities::createMessage(2, &msg, msgTemp, " :- Verify value is still found") ; CPPUNIT_ASSERT_MESSAGE("Verify that doing a removeAndDestroy on " \ "an item that has multiple matches removes only one entry", \ uSearch == uStubPtr2 || uSearch == uStubPtr3) ; TestUtilities::createMessage(2, &msg, msgTemp, " :- Verify value *was* destroyed") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), cCountBefore -1, cCountAfter) ; msgTemp = "Verify that the remaining entry can also be deleted" ; cCountBefore = UtlContainableTestStub :: getCount() ; commonList.destroy(&uStubTemp) ; cCountAfter = UtlContainableTestStub :: getCount() ; TestUtilities::createMessage(2, &msg, msgTemp, " :- Verify value *was* destroyed") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), cCountBefore -1, cCountAfter) ; // In all the above tests, a total of 5 entries were added // and 3 were removed. int finalCount = commonEntriesCount + 2 ; msgTemp = "Verify that the HashTable stil has the other entries" ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msgTemp, finalCount, (int)commonList.entries()) ; } /*!a Test case for testRemove() * * The Test data for this test case is * a) is an entry's reference * b) is an entry's value(not reference) * c) is the first of multiple matches and is the value match * d) is the second of multiple matches. * e) has no match at all */ void testRemove() { int testCount = 4 ; const char* prefix = "test the remove(UtlContainable* c) method where c " ; const char* Msgs[] = { \ "is an entry's reference ", \ "is an entry's value(not reference) ", \ "is first of multiple value matches ", \ "has no match at all " \ } ; const char* suffix1 = " :- Verify returned value" ; const char* suffix2 = " :- Verify total entries" ; // Insert a new value such that its value matches(isEqual to) // one of the existing items commonList.insert(commonContainables_Clone[4]) ; UtlString notExistContainable("This cannot and willnot exist"); UtlContainable* dataForRemove[] = { \ commonContainables[0], \ commonContainables_Clone[2], \ commonContainables[4], \ ¬ExistContainable \ } ; int totalEnt = commonEntriesCount + 1; UtlBoolean expectedReturnValues[] = { \ true, true, true, false \ } ; int entriesValue[] = { --totalEnt, --totalEnt, --totalEnt, totalEnt } ; totalEnt = commonEntriesCount + 1; for (int i = 0 ; i < testCount ; i++) { string msg ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix1) ; UtlContainable* retValue ; retValue = commonList.remove(dataForRemove[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (UtlBoolean)(retValue!=NULL), \ (UtlBoolean)expectedReturnValues[i]) ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix2) ; int expCount = (int)commonList.entries() ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), entriesValue[i], expCount) ; } } //testRemove /*!a Test case for the isEmpty() method. * The test data for this test are :- * a) When the list has just been created. * b) When the list has one entry in it * c) When the list has multiple entries in it. * e) When all the entries in a list have been removed using removeAll() */ void testIsEmpty() { const int testCount = 4 ; const char* prefix = "Test the isEmpty() method when " ; const char* Msgs[] = { \ "the list has just been created" , \ "the list has just one entry in it", \ "the list has multiple entries in it", \ "all the list entries have been retreived using removeAll()" \ } ; UtlHashBag newList ; UtlHashBag secondNewList ; UtlHashBag commonList_Clone ; // Add a single entry to the list. newList.insert(commonContainables[0]) ; UtlString uS1("Tester string") ; // populate the second list and then removeAll entries. secondNewList.insert(&uS1) ; UtlInt uI1 = UtlInt(232) ; secondNewList.insert(&uI1) ; secondNewList.insert(commonContainables[3]) ; secondNewList.removeAll() ; UtlHashBag* testLists[] = { \ &emptyList, &newList, &commonList, &secondNewList \ } ; bool exp[] = { true, false, false, true } ; for (int i = 0 ; i < testCount; i++) { string msg ; TestUtilities::createMessage(2, &msg, prefix, Msgs[i]) ; UtlBoolean act = testLists[i] -> isEmpty() ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (UtlBoolean)exp[i], act) ; } } // testIsEmpty /*!a test the removeAll() method. * * The test data for this method is * a) When the list is empty * b) When the list has one entry. * c) When the list multiple entries * d) When removeAll has been called and entries are added again * e) When the removeAll is called twice on the list. * f) When the removeAll is call on a list that has muliple entries * for the same key. */ void testClear() { const int testCount = 6 ; const char* prefix = "Test the removeAll() method when :- " ; const char* Msgs[] = { \ "the list is empty", \ "the list has one entry", \ "the list has multiple entries", \ " has been called and entries are added again", \ "removeAll() has already been called", \ "removeAll() is called on list that has multiple matches" \ } ; const char* suffix = " :- Verify number of entries after removeAll()" ; UtlHashBag uSingleList ; UtlHashBag uAddAfterClear ; UtlHashBag uDoubleClear ; // populate the hashtable with the 'common' values UtlHashBag commonList_Clone ; for (int i = 0 ; i < commonEntriesCount ; i++) { commonList_Clone.insert(commonContainables_Clone[i]) ; } // Add two values such that one of them has a 'value' // match already in the table and the other one has // a ref match. commonList_Clone.insert(commonContainables_Clone[3]) ; commonList_Clone.insert(commonContainables[5]) ; // Add a single entry to the list that is to be made up // of just one element uSingleList.insert(&commonString1) ; // call removeAll() on a list and then add entries again. uAddAfterClear.insert(&commonInt1) ; uAddAfterClear.insert(&commonString1) ; uAddAfterClear.removeAll() ; uAddAfterClear.insert(&commonInt2) ; // call removeAll on a list twice. uDoubleClear.insert(&commonString3) ; uDoubleClear.insert(&commonInt3) ; uDoubleClear.removeAll() ; UtlHashBag* testLists[] = { \ &emptyList, &uSingleList, &commonList, &uAddAfterClear, &uDoubleClear, &commonList_Clone } ; int expEntries[] = { 0 , 0, 0, 1, 0, 0} ; // since we are not calling removeAll for all the lists, do it outside the for loop for those // that require to be cleared. emptyList.removeAll() ; uSingleList.removeAll() ; commonList.removeAll() ; commonList_Clone.removeAll() ; // no removeAll() for uAddAfterClear uDoubleClear.removeAll() ; for ( int j = 0 ; j < testCount ; j++) { string msg ; TestUtilities::createMessage(3, &msg, prefix, Msgs[j], suffix) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data() , expEntries[j], (int)testLists[j] -> entries()) ; } } //testClear() /*!a Test case to test the DestroyAll() * method. */ void testClearAndDestroy() { const int testCount = 3 ; int cCountBefore = UtlContainableTestStub :: getCount() ; const char* prefix = "test the destroyAll() method " ; const char* suffix1 = " :- sanity check to double check that the counter was incremented for every new() call" ; const char* suffix2 = " :- Verify that all entries are removed and the objects are deleted" ; UtlContainableTestStub* uStub ; UtlContainableTestStub* uStubPtr ; UtlContainableTestStub* uStubPtr2 ; uStub = new UtlContainableTestStub(0) ; uStubPtr = new UtlContainableTestStub(201) ; uStubPtr2 = new UtlContainableTestStub(201) ; emptyList.insert(uStub) ; emptyList.insert(uStubPtr) ; emptyList.insert(uStubPtr2) ; cCountBefore = UtlContainableTestStub :: getCount() - cCountBefore ; emptyList.destroyAll() ; int cCountAfter = UtlContainableTestStub :: getCount() ; string msg ; // Make sure that static count was incremented for every instance // of the TestStub that was created. TestUtilities::createMessage(2, &msg, prefix, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), testCount, cCountBefore) ; // Verify that the list has no entries left after destroyAll() // and also ensure that all the TestStub instances were deleted. TestUtilities::createMessage(2, &msg, prefix, suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), 0, cCountAfter) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), 0, (int)emptyList.entries()) ; } //testClearAndDestroy void testRemoveReference() { // the following two entries collide if the initial bucket size is 16 UtlInt int1(1); UtlInt int16(16); UtlInt int2a(2); UtlInt int2b(2); UtlInt int3(3); UtlHashBag bag; CPPUNIT_ASSERT( bag.numberOfBuckets() == 16 ); // check assumption of collision // Load all the test objects CPPUNIT_ASSERT( bag.insert(&int1) == &int1 ); CPPUNIT_ASSERT( bag.insert(&int16) == &int16 ); CPPUNIT_ASSERT( bag.insert(&int2a) == &int2a ); CPPUNIT_ASSERT( bag.insert(&int2b) == &int2b ); CPPUNIT_ASSERT( bag.insert(&int3) == &int3 ); // Check that everything is there CPPUNIT_ASSERT( bag.entries() == 5 ); CPPUNIT_ASSERT( bag.contains(&int1) ); CPPUNIT_ASSERT( bag.contains(&int16) ); CPPUNIT_ASSERT( bag.contains(&int2a) ); // cannot test for 2a and 2b independently CPPUNIT_ASSERT( bag.contains(&int3) ); // Take entry 1 out (might collide w/ 16) CPPUNIT_ASSERT( bag.removeReference(&int1) == &int1 ); // Check that everything except entry 1 is still there, and that 1 is gone CPPUNIT_ASSERT( bag.entries() == 4 ); CPPUNIT_ASSERT( ! bag.contains(&int1) ); CPPUNIT_ASSERT( bag.contains(&int16) ); CPPUNIT_ASSERT( bag.contains(&int2a) );// cannot test for 2a and 2b independently CPPUNIT_ASSERT( bag.contains(&int3) ); // Put entry 1 back in (so that 16 will collide w/ it again) CPPUNIT_ASSERT( bag.insert(&int1) == &int1 ); // Check that everything is there CPPUNIT_ASSERT( bag.entries() == 5 ); CPPUNIT_ASSERT( bag.contains(&int1) ); CPPUNIT_ASSERT( bag.contains(&int16) ); CPPUNIT_ASSERT( bag.contains(&int2a) ); CPPUNIT_ASSERT( bag.contains(&int3) ); // Take entry 16 out (might collide w/ 1) CPPUNIT_ASSERT( bag.removeReference(&int16) == &int16 ); // Check that everything except entry 16 is still there, and that 16 is gone CPPUNIT_ASSERT( bag.entries() == 4 ); CPPUNIT_ASSERT( bag.contains(&int1) ); CPPUNIT_ASSERT( ! bag.contains(&int16) ); CPPUNIT_ASSERT( bag.contains(&int2a) );// cannot test for 2a and 2b independently CPPUNIT_ASSERT( bag.contains(&int3) ); // remove 2a (and ensure that you don't get back 2b) CPPUNIT_ASSERT( bag.removeReference(&int2a) == &int2a ); // Check that everything that should be is still there CPPUNIT_ASSERT( bag.entries() == 3 ); CPPUNIT_ASSERT( bag.contains(&int1) ); CPPUNIT_ASSERT( ! bag.contains(&int16) ); CPPUNIT_ASSERT( bag.find(&int2a) == &int2b ); // equal values, but now there's only one CPPUNIT_ASSERT( bag.contains(&int3) ); // remove 3 (no collision for this one) CPPUNIT_ASSERT( bag.removeReference(&int3) == &int3 ); // Check that everything that should be is still there CPPUNIT_ASSERT( bag.entries() == 2 ); CPPUNIT_ASSERT( bag.contains(&int1) ); CPPUNIT_ASSERT( ! bag.contains(&int16) ); CPPUNIT_ASSERT( bag.find(&int2a) == &int2b ); // equal values, but now there's only one CPPUNIT_ASSERT( ! bag.contains(&int3) ); // remove 3 again - should fail this time CPPUNIT_ASSERT( bag.removeReference(&int3) == NULL ); // Check that everything that should be is still there CPPUNIT_ASSERT( bag.entries() == 2 ); CPPUNIT_ASSERT( bag.contains(&int1) ); CPPUNIT_ASSERT( ! bag.contains(&int16) ); CPPUNIT_ASSERT( bag.find(&int2a) == &int2b ); // equal values, but now there's only one CPPUNIT_ASSERT( ! bag.contains(&int3) ); } void testOneThousandInserts() { // Test case used to validate fix to issue XPL-169 const int COUNT = 1000; const char stringPrefix[] = "Apofur81Kb"; UtlHashBag bag; char tmpString[20]; for( int i = 0; i < COUNT; i++) { sprintf(tmpString, "%s%d", stringPrefix, i); UtlString *stringToInsert = new UtlString(); *stringToInsert = tmpString; CPPUNIT_ASSERT( ! bag.contains( stringToInsert ) ); bag.insert( stringToInsert ); CPPUNIT_ASSERT_EQUAL( i+1, (int)bag.entries() ); for( unsigned int j = 0; j < bag.entries(); j++ ) { // verify that all entries are indeed in the bag sprintf( tmpString, "%s%d", stringPrefix, j ); UtlString stringTolookUp( tmpString ); CPPUNIT_ASSERT_MESSAGE( tmpString, bag.contains( &stringTolookUp ) ); } } } }; const char* UtlHashBagTest::longAlphaNumString = \ "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvw" ; const char* UtlHashBagTest::regularString = "This makes sense" ; // letting the compiler know that such a variable exists. const int UtlHashBagTest::commonEntriesCount = 6 ; const int UtlHashBagTest::INDEX_NOT_EXIST = -1; CPPUNIT_TEST_SUITE_REGISTRATION(UtlHashBagTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlHashBagIterator.cpp0000644000175000017500000004511612205613256026440 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include #include #include bool checkMask( int& foundMask, int maskBit ) { bool isOk; //printf("\ncheck %04x", maskBit); isOk = (0==(maskBit & foundMask)); foundMask |= maskBit; return isOk; } #define CHECK_FOUND(previouslyFound,thisBit) \ CPPUNIT_ASSERT_MESSAGE("Same key returned twice",checkMask(previouslyFound,thisBit)) class UtlHashBagIteratorTests : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlHashBagIteratorTests); CPPUNIT_TEST(testAdvancingOperator_And_KeyMethod) ; CPPUNIT_TEST(testFiltered) ; CPPUNIT_TEST(testCollision) ; CPPUNIT_TEST_SUITE_END(); private: static const int INDEX_NOT_EXIST ; static const int commonEntriesCount ; UtlHashBag commonList ; UtlHashBag emptyList ; UtlString commonString1 ; UtlString commonString2 ; UtlString commonString3 ; UtlInt commonInt1 ; UtlInt commonInt2 ; UtlInt commonInt3 ; UtlString commonString1_clone ; UtlString commonString2_clone ; UtlString commonString3_clone ; UtlInt commonInt1_clone ; UtlInt commonInt2_clone ; UtlInt commonInt3_clone ; static const char* longAlphaNumString ; static const char* regularString ; UtlContainable** commonContainables ; UtlContainable** commonContainables_Clone ; enum IndexOrContains { TEST_INDEX, TEST_FIND, TEST_CONTAINS, TEST_CONTAINS_REF } ; enum TestInsertOrAppend {TEST_APPEND, TEST_INSERT} ; enum RemoveType {TEST_REMOVE, TEST_REMOVE_REF } ; enum Operation { NOP, ADVANCE, RESET, REPOSITION } ; public: UtlHashBagIteratorTests() { commonContainables = new UtlContainable*[commonEntriesCount] ; commonContainables_Clone = new UtlContainable*[commonEntriesCount] ; } ~UtlHashBagIteratorTests() { delete[] commonContainables ; delete[] commonContainables_Clone ; } void setUp() { commonString1 = UtlString(regularString) ; commonString1_clone = UtlString(regularString) ; commonString2 = UtlString("") ; commonString2_clone = UtlString("") ; commonString3 = UtlString(longAlphaNumString) ; commonString3_clone = UtlString(longAlphaNumString) ; commonInt1 = UtlInt(0) ; commonInt1_clone = UtlInt(0) ; commonInt2 = UtlInt(INT_MAX) ; commonInt2_clone = UtlInt(INT_MAX) ; commonInt3 = UtlInt(INT_MIN) ; commonInt3_clone = UtlInt(INT_MIN) ; commonList.insert(&commonString1) ; commonContainables[0] = &commonString1 ; commonContainables_Clone[0] = &commonString1_clone ; commonList.insert(&commonInt1) ; commonContainables[1] = &commonInt1 ; commonContainables_Clone[1] = &commonInt1_clone ; commonList.insert(&commonInt2) ; commonContainables[2] = &commonInt2 ; commonContainables_Clone[2] = &commonInt2_clone; commonList.insert(&commonString2) ; commonContainables[3] = &commonString2 ; commonContainables_Clone[3] = &commonString2_clone ; commonList.insert(&commonInt3) ; commonContainables[4] = &commonInt3 ; commonContainables_Clone[4] = &commonInt3_clone ; commonList.insert(&commonString3) ; commonContainables[5] = &commonString3 ; commonContainables_Clone[5] = &commonString3_clone ; } void tearDown() { } /** Ignore this method. This is more like a sandbox */ void DynaTest() { } //DynaTest /*!a Test case for the () operator and the key() method. * * The test data for this test is :- * 1) The next entry is a UtlString * 2) The next entry is a UtlInt * 3) The next entry is the last entry * 4) All entries have been read */ void testAdvancingOperator_And_KeyMethod() { const int testCount = 5; const char* prefix = "Verify the () operator " ; const char* prefix_for_key = "Verify the key() method " ; const char* Msgs[] = { \ "when the entry is the first of two value matches of UtlString type", \ "when the entry is the first of two reference matches of UtlInt type", \ "when the entry is a unique Containable", \ "when the entry is the second of two reference matches of UtlInt type", \ "when the entry is the second of two value matches of UtlString type" \ } ; // Create a Hashtable such that it has one unique element (commonString2) , // 2 elements that has value matches (commonString1 / commonString1_clone) , // and 2 elements that *ARE* the same (commonInt1) UtlHashBag testList ; testList.insert(&commonString1) ; testList.insert(&commonInt1) ; testList.insert(&commonString1_clone) ; testList.insert(&commonString2) ; testList.insert(&commonInt1) ; UtlContainable* exp[] = { \ &commonString1 , &commonInt1, &commonString2, &commonInt1, &commonString1_clone } ; int expEntries = testCount; UtlHashBagIterator iter(testList) ; UtlContainable* act ; UtlContainable* expected_value_for_key_method ; string msg ; // Test the key method when the iterator has been reset. iter.reset() ; act = iter.key() ; TestUtilities::createMessage(2, &msg, prefix, "when the iterator has been reset") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)NULL, (void*)act) ; // Now iterate through the whole iterator and verify that all the items are // retreived. The () operator retreives the next item in the list. The // key item should retreive the item under the current position. (That is, // the key() method should always return what the previous () returned) for (int i = 0 ; i < testCount ; i++) { act = iter() ; expected_value_for_key_method = act; const char* curMessage = ""; bool wasFound = false ; // We dont care about which item matches where. We only want to make sure // that each item *IS* retreived once and *ONLY* once. for (int j =0 ; j < testCount; j++) { // If the item was already found during a previous iteration, // we would have set the exp. value to NULL. so ignore all NULL // expected values. // The idea behind this is illustrated with the following example. // Let us say that invoking foo.search(bar) can return either return // either 90, 100 or 120 on the first search(either return is valid). // Let's say that it returns 100. But if foo.search(bar) is invoked the // second time, it should only return 90 or 120. So setting the element // of the expected array that used to contain 100 to NULL means that // that '100' is no longer a valid expected value. if (exp[j] != NULL && act == exp[j]) { wasFound = true ; exp[j] = NULL ; // Unlike traditional tests in which we know before hand the message // for a particular iteration, in this case, the message is constructed // based on the return value. curMessage = Msgs[j] ; break ; } } if (!wasFound) { curMessage = " :- One of the expected items was not retreived" \ " using an indexing operator" ; } TestUtilities::createMessage(3, &msg, prefix, curMessage, " :- Verify return value") ; CPPUNIT_ASSERT_MESSAGE(msg.data(), wasFound) ; TestUtilities::createMessage(3, &msg, prefix, curMessage, " :- Verify that the number of entries has not changed") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expEntries, (int)testList.entries()) ; // Verfiy that using the key() method retreives the value at the current position. // without repositioning the iterator. act = iter.key() ; TestUtilities::createMessage(2, &msg, prefix_for_key, curMessage) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expected_value_for_key_method, act) ; } // Test the () operator when the whole list has been iterated act = iter() ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Verify that the indexing operator on a list that has been traversed fully returns NULL", \ (void*)NULL, (void*)act) ; // Test the () operator for an empty list UtlHashBagIterator emptyIter(emptyList) ; act = emptyIter() ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Test the () operator for an empty list iterator" , (void*)NULL, (void*)act) ; } //testAdvancingOperator() void testFiltered() { UtlString key1a("key1"); UtlString key1b("key1"); UtlString key2("key2"); UtlString key3("key3"); UtlHashBag theBag; theBag.insert(&key1a); theBag.insert(&key1b); theBag.insert(&key2); theBag.insert(&key3); UtlString* content; { UtlString filter("key2"); UtlHashBagIterator each(theBag,&filter); int foundMask; foundMask = 0; while ((content = (UtlString*)each())) { if ( &key1a == content ) { CHECK_FOUND(foundMask,0x0001); } else if ( &key1b == content ) { CHECK_FOUND(foundMask,0x0002); } else if ( &key2 == content ) { CHECK_FOUND(foundMask,0x0004); } else if ( &key3 == content ) { CHECK_FOUND(foundMask,0x0008); } else { CPPUNIT_FAIL("Unknown element returned"); } } CPPUNIT_ASSERT_MESSAGE("Expected element not found",0x0004==foundMask); } { UtlString filter("key1"); UtlHashBagIterator each(theBag,&filter); int foundMask; foundMask = 0; while ((content = (UtlString*)each())) { if ( &key1a == content ) { CHECK_FOUND(foundMask,0x0001); } else if ( &key1b == content ) { CHECK_FOUND(foundMask,0x0002); } else if ( &key2 == content ) { CHECK_FOUND(foundMask,0x0004); } else if ( &key3 == content ) { CHECK_FOUND(foundMask,0x0008); } else { CPPUNIT_FAIL("Unknown element returned"); } } CPPUNIT_ASSERT_MESSAGE("Expected element not found",0x0003==foundMask); } { UtlString filter("key1"); UtlHashBagIterator each(theBag,&filter); int foundMask; foundMask = 0; UtlString* removed = (UtlString*)theBag.remove(&filter); if ( &key1a == removed ) { CHECK_FOUND(foundMask,0x0001); } else if ( &key1b == removed ) { CHECK_FOUND(foundMask,0x0002); } else { CPPUNIT_FAIL("Unknown element removed"); } while ((content = (UtlString*)each())) { if ( &key1a == content ) { CHECK_FOUND(foundMask,0x0001); } else if ( &key1b == content ) { CHECK_FOUND(foundMask,0x0002); } else if ( &key2 == content ) { CHECK_FOUND(foundMask,0x0004); } else if ( &key3 == content ) { CHECK_FOUND(foundMask,0x0008); } else { CPPUNIT_FAIL("Unknown element returned"); } } CPPUNIT_ASSERT_MESSAGE("Expected element not found",0x0003==foundMask); } { UtlString filter("key3"); UtlHashBagIterator each(theBag,&filter); int foundMask; foundMask = 0; UtlString* removed = (UtlString*)theBag.remove(&filter); CPPUNIT_ASSERT(&key3==removed); while ((content = (UtlString*)each())) { if ( &key1a == content ) { CHECK_FOUND(foundMask,0x0001); } else if ( &key1b == content ) { CHECK_FOUND(foundMask,0x0002); } else if ( &key2 == content ) { CHECK_FOUND(foundMask,0x0004); } else if ( &key3 == content ) { CHECK_FOUND(foundMask,0x0008); } else { CPPUNIT_FAIL("Unknown element returned"); } } CPPUNIT_ASSERT_MESSAGE("Expected element not found",0x0000==foundMask); } { UtlString filter("key4"); UtlHashBagIterator each(theBag,&filter); int foundMask; foundMask = 0; UtlString* removed = (UtlString*)theBag.remove(&filter); CPPUNIT_ASSERT(NULL==removed); while ((content = (UtlString*)each())) { if ( &key1a == content ) { CHECK_FOUND(foundMask,0x0001); } else if ( &key1b == content ) { CHECK_FOUND(foundMask,0x0002); } else if ( &key2 == content ) { CHECK_FOUND(foundMask,0x0004); } else if ( &key3 == content ) { CHECK_FOUND(foundMask,0x0008); } else { CPPUNIT_FAIL("Unknown element returned"); } } CPPUNIT_ASSERT_MESSAGE("Expected element not found",0x0000==foundMask); } } /* Check for a problem that turned up in insert(): If an object * was inserted that should have been put at the end of a chain, * it was instead inserted at the beginning. * * This test detects the problem by inserting two objects which we arrange * to fall into the same bucket. The object with the largest hash is * inserted second, so it should go at the end of the list, but instead * is inserted at the beginning. The result is that the small-hash * object can't be seen by a selective HashBagIterator. * * The objects we use to exercise this case have to be tuned to the hash * algorithm of the objects and the algorithm * (UtlHashBag::bucketNumber) for turning hashes into bucket numbers. */ void testCollision() { UtlHashBag bag; // For UtlInt's, the hash is the value. UtlInt small_hash_object(1); bag.insert(&small_hash_object); // put in some other objects UtlInt other_hash_object3(3); bag.insert(&other_hash_object3); UtlInt other_hash_object4(4); bag.insert(&other_hash_object4); UtlInt other_hash_object5(5); bag.insert(&other_hash_object5); UtlContainable* found; { // check that a keyed iterator sees the small_hash_object UtlHashBagIterator itor(bag, new UtlInt(1)); found = itor(); CPPUNIT_ASSERT(found == &small_hash_object); // and nothing else found = itor(); CPPUNIT_ASSERT(found == NULL); } // We depend on the fact that a HashBag initially has 16 buckets and // folds hashes with XOR. Under these conditions, 1 & 16 collide and // land in the same bucket. UtlInt large_hash_object(16); bag.insert(&large_hash_object); { // check that a keyed iterator sees the small_hash_object UtlHashBagIterator itor(bag, new UtlInt(1)); found = itor(); CPPUNIT_ASSERT(found == &small_hash_object); // and nothing else found = itor(); CPPUNIT_ASSERT(found == NULL); } { // check that a keyed iterator sees the large_hash_object UtlHashBagIterator itor(bag, new UtlInt(16)); found = itor(); CPPUNIT_ASSERT(found == &large_hash_object); // and nothing else found = itor(); CPPUNIT_ASSERT(found == NULL); } } // testCollision }; const int UtlHashBagIteratorTests::INDEX_NOT_EXIST = -1; const int UtlHashBagIteratorTests::commonEntriesCount = 6; const char* UtlHashBagIteratorTests::longAlphaNumString = \ "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvw" ; const char* UtlHashBagIteratorTests::regularString = "This makes sense" ; CPPUNIT_TEST_SUITE_REGISTRATION(UtlHashBagIteratorTests); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlHashMap.cpp0000644000175000017500000011655412205613256024757 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include #include #include #include #include #define commonHashMapEntriesCount 4 static const char* regularString = "This makes sense" ; static const char* longAlphaNumString = \ "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvw" ; class UtlHashMapTests : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlHashMapTests); CPPUNIT_TEST(checkSanity_Insert_Entries_And_At) ; // CPPUNIT_TEST(DynaTest) ; CPPUNIT_TEST(testInsertKeyAndValue) ; CPPUNIT_TEST(testInsert) ; CPPUNIT_TEST(testFind) ; CPPUNIT_TEST(testContains) ; CPPUNIT_TEST(testRemove) ; CPPUNIT_TEST(testRemoveKeyAndValue) ; CPPUNIT_TEST(testRemoveAndDestroy) ; CPPUNIT_TEST(testIsEmpty) ; CPPUNIT_TEST(testClear) ; CPPUNIT_TEST(testClearAndDestroy) ; CPPUNIT_TEST(testCopyInto) ; CPPUNIT_TEST(testRemoveCollision) ; CPPUNIT_TEST(testOneThousandInserts) ; CPPUNIT_TEST(testDeepCopy); CPPUNIT_TEST_SUITE_END(); private: static const int INDEX_NOT_EXIST; //const int UtlHashMapTests::commonHashMapEntriesCount = 4 ; //static const int commonHashMapEntriesCount ; UtlHashMap commonList ; UtlHashMap commonList_clone ; UtlHashMap emptyList ; UtlString commonString1 ; UtlString commonString2 ; UtlString commonString3 ; UtlString commonString4 ; UtlInt commonInt1 ; UtlInt commonInt2 ; UtlInt commonInt3 ; UtlInt commonInt4 ; UtlString commonString1_clone; UtlString commonString2_clone ; UtlString commonString3_clone ; UtlString commonString4_clone ; UtlInt commonInt1_clone ; UtlInt commonInt2_clone ; UtlInt commonInt3_clone ; UtlInt commonInt4_clone ; UtlContainable* commonKeyValuePairs[commonHashMapEntriesCount][2] ; UtlContainable* commonKeyValuePairs_clone[commonHashMapEntriesCount][2] ; enum FindOrContains { TEST_FIND, TEST_CONTAINS} ; enum TestInsertOrAppend {TEST_APPEND, TEST_INSERT} ; enum RemoveType {TEST_REMOVE, TEST_REMOVE_KEY_AND_VALUE} ; public: void setUp() { // In case prior test aborts and tearDown does not get called, empty lists commonList.removeAll(); commonString1 = UtlString(regularString) ; commonString1_clone = UtlString(regularString) ; commonString2 = UtlString("") ; commonString2_clone = UtlString("") ; commonString3 = UtlString(longAlphaNumString) ; commonString3_clone = UtlString(longAlphaNumString) ; commonString4 = UtlString("Another String") ; commonString4_clone = UtlString("Another String") ; commonInt1 = UtlInt(0) ; commonInt1_clone = UtlInt(0) ; commonInt2 = UtlInt(INT_MAX) ; commonInt2_clone = UtlInt(INT_MAX) ; commonInt3 = UtlInt(INT_MIN) ; commonInt3_clone = UtlInt(INT_MIN) ; commonInt4 = UtlInt(101) ; commonInt4_clone = UtlInt(101) ; // Insert 3 name value pairs into the commonList :- // a) Key = String, Value = Int // b) Key = Int, Value = String: // c) Key = String, Value = String commonList.insertKeyAndValue(&commonString1, &commonInt1) ; commonList.insertKeyAndValue(&commonInt2, &commonString2) ; commonList.insertKeyAndValue(&commonString3, &commonString4) ; commonList.insertKeyAndValue(&commonInt3, &commonInt4) ; // The above values also become the name-value pair array // The first index of the 2nd dimension represents the key // while the second index represents the value expected. commonKeyValuePairs[0][0] = &commonString1 ; commonKeyValuePairs[0][1] = &commonInt1 ; commonKeyValuePairs[1][0] = &commonInt2 ; commonKeyValuePairs[1][1] = &commonString2 ; commonKeyValuePairs[2][0] = &commonString3 ; commonKeyValuePairs[2][1] = &commonString4 ; commonKeyValuePairs[3][0] = &commonInt3 ; commonKeyValuePairs[3][1] = &commonInt4 ; // Similarly create a clone of the list and the expected data. commonList_clone.insertKeyAndValue(&commonString1_clone, &commonInt1_clone) ; commonList_clone.insertKeyAndValue(&commonInt2_clone, &commonString2_clone) ; commonList_clone.insertKeyAndValue(&commonString3_clone, &commonString4_clone) ; commonList_clone.insertKeyAndValue(&commonInt3_clone, &commonInt4_clone) ; // The above values also become the name-value pair array // The first index of the 2nd dimension represents the key // while the second index represents the value expected. commonKeyValuePairs_clone[0][0] = &commonString1_clone ; commonKeyValuePairs_clone[0][1] = &commonInt1_clone ; commonKeyValuePairs_clone[1][0] = &commonInt2_clone ; commonKeyValuePairs_clone[1][1] = &commonString2_clone ; commonKeyValuePairs_clone[2][0] = &commonString3_clone ; commonKeyValuePairs_clone[2][1] = &commonString4_clone ; commonKeyValuePairs_clone[3][0] = &commonInt3_clone ; commonKeyValuePairs_clone[3][1] = &commonInt4_clone ; } void tearDown() { } /* Sandbox - please ignore */ void DynaTest() { } ~UtlHashMapTests() { } void testCopyInto() { UtlString testData[] = { UtlString("key1"), UtlString("value1") }; UtlHashMap *source = new UtlHashMap(); source->insertKeyAndValue(&testData[0], &testData[1]); UtlHashMap *destination = new UtlHashMap(); source->copyInto(*destination); // elements should live on in copy delete source; CPPUNIT_ASSERT_MESSAGE("Copy received", 1 == destination->entries()); UtlContainable *key = destination->find(&testData[0]); CPPUNIT_ASSERT_MESSAGE("Found key in copy", key != NULL); CPPUNIT_ASSERT_MESSAGE("Found expected key in copy", key->isEqual(&testData[0])); UtlContainable *value = destination->findValue(&testData[0]); CPPUNIT_ASSERT_MESSAGE("Found key in copy", value != NULL); CPPUNIT_ASSERT_MESSAGE("Found expected value in copy", value->isEqual(&testData[1])); delete destination; } /*a! This test is more of a sanity check to verify that * the basic insert(), entries() and at() methods work as expected. * All future tests will depend heavily on the at() method * and the most common way of having something in the list is * by means of the insert() method. * */ void checkSanity_Insert_Entries_And_At() { CPPUNIT_ASSERT_EQUAL_MESSAGE("Verify that the entries() for an empty HashDictionary returns 0", (int)emptyList.entries(), 0) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Verify the entries() method for a HashDictionary", commonHashMapEntriesCount, (int)commonList.entries()) ; }// checkSanity_Append_And_At() /*a! Test the insert method for a list that is not empty. Add both unique and non-unique entries. * * The test data for this test is :- * a) Add a new unique pair * b) Add a new pair such that such a key doesn't exist but the table has a value that is equal to the key * b) Add a new Containable such that a similar one (value match) exists already * c) Add a new Containable such that the same one (reference match) exists already */ void testInsertKeyAndValue() { int testCount = 7; const char* prefix = "Test the insert(UtlContainable*) method for a " \ "non empty HashDictionary " ; const char* Msgs[] = { \ "Add a new unique pair ", \ "Add a new pair such that the key is unique, but another key has " \ "the pair's value ", \ "Add a new pair such that there is no match for that key but the table " \ "has a value that is equal to the key ", \ "Add a new pair such that the table has an existing key which is equal " \ "to a the key (but not same) ", \ "Add a new pair such that an exact duplicate of the key " \ "(including reference match) exists in the table ", \ "Add a new pair such that newKey.isEqual(oldKey) and " \ "newValue.isEqual(oldValue) for an existing key-value pair", \ "Add a new pair such that that key-value pair is an exact duplicate " \ "of an existing pair" \ } ; const char* suffix1 = " :- Verify the return value for the insert method" ; const char* suffix2 = " :- Verify the return value for the findKeyAndValue() method " ; const char* suffix3 = " :- Verify that the value is inserted and found by the " \ "findKeyAndValue() method" ; const char* suffix4 = " :- Verify that the number of entries is incremented by one" ; UtlInt uInt = UtlInt(1234) ; UtlString uString = UtlString("Test String") ; UtlString strUniqueKey = UtlString("Unique_Key_For_Existing_Value") ; UtlString strUniqueValue = UtlString("Unique_Value_For_Existing_Key") ; UtlString strUniqueValue2 = UtlString("Another Unique Value") ; UtlContainable* ItemsToAdd[][2] = { \ {&uInt, &uString} , \ {&strUniqueKey, commonKeyValuePairs[0][1]}, \ {commonKeyValuePairs[1][1], &strUniqueValue},\ {commonKeyValuePairs_clone[2][0], &strUniqueValue2}, \ {commonKeyValuePairs[3][0], &uString}, \ {commonKeyValuePairs_clone[3][0], commonKeyValuePairs_clone[3][1]}, \ {&uInt, &uString} \ } ; UtlContainable* ExpReturn_Key[] = { \ &uInt, \ &strUniqueKey, \ commonKeyValuePairs[1][1], \ NULL, \ NULL, \ NULL, \ NULL, \ } ; UtlContainable* ExpFind_Return_Key[] = { \ &uInt, \ &strUniqueKey, \ commonKeyValuePairs[1][1], \ commonKeyValuePairs[2][0], \ commonKeyValuePairs[3][0], \ commonKeyValuePairs[3][0], \ &uInt \ } ; UtlContainable* ExpFind_Value[] = { \ &uString, \ commonKeyValuePairs[0][1], \ &strUniqueValue, \ commonKeyValuePairs[2][1], \ commonKeyValuePairs[3][1], \ commonKeyValuePairs[3][1], \ &uString \ } ; int expCount = commonHashMapEntriesCount; string msg ; UtlContainable* uReturn_Key ; UtlContainable* uFound_Key ; UtlContainable* uFound_Value ; UtlContainable* uExp_Return_Key; //What is the expected return when insert.. is called ? UtlContainable* uExp_Find_Return_Key; // What is the expected return find... is called ? UtlContainable* uExp_Value ; // What is value part for a name-value pair find ? for (int i = 0 ; i < testCount ; i++) { uExp_Return_Key = ExpReturn_Key[i]; uExp_Find_Return_Key = ExpFind_Return_Key[i] ; uExp_Value = ExpFind_Value[i] ; uReturn_Key = commonList.insertKeyAndValue(ItemsToAdd[i][0], ItemsToAdd[i][1]) ; uFound_Key = commonList.find(ItemsToAdd[i][0]) ; uFound_Value = commonList.findValue(ItemsToAdd[i][0]) ; if (uExp_Return_Key != NULL) { expCount++ ; } // Verify that the correct value for the key was returned. TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uExp_Return_Key, uReturn_Key) ; // Verify that the return value of the find returns the // correcy key TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uExp_Find_Return_Key, uFound_Key) ; // verify that find() found the right value. TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uExp_Value, uFound_Value) ; // Verify that the number of entries is accurate. TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix4) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expCount, (int)commonList.entries()) ; } } //testInsertKeyAndValue /*a! Test the insert method for a list that is not empty. Add both unique and non-unique entries. * * The test data for this test is :- * a) Add a new unique pair * b) Add a new Containable such that a similar one (value match) exists already * c) Add a new Containable such that the same one (reference match) exists already */ void testInsert() { struct TestInsertKeyStruct { const char* testDescription ; UtlContainable* insertKey ; UtlContainable* expectedReturnKey ; UtlContainable* expectedSearchKey ; UtlContainable* expectedSearchValue ; } ; const char* prefix = "Test the insert(UtlContainable*) method for a " \ "non empty HashDictionary " ; const char* suffix1 = " :- Verify the return value for the insert method" ; const char* suffix2 = " :- Verify the key returned by the find() method " ; const char* suffix3 = " :- Verify the value found by the findValue() method" ; string Message ; UtlString strUniqueKey = UtlString("Unique_Key") ; TestInsertKeyStruct testData[] = { \ { "Add a new unique pair ", &strUniqueKey, &strUniqueKey, \ &strUniqueKey, NULL }, \ { "Add a new pair such that the table has an existing key which is equal " \ "to a the key (but not same) ", commonKeyValuePairs_clone[1][0], NULL, \ commonKeyValuePairs[1][0], commonKeyValuePairs[1][1] }, \ { "Add a new pair such that an exact duplicate of the key " \ "(including reference match) exists in the table ", commonKeyValuePairs[0][0], \ NULL, commonKeyValuePairs[0][0], commonKeyValuePairs[0][1] } \ } ; int testCount = sizeof(testData)/sizeof(testData[0]) ; for (int i = 0 ; i < testCount; i++) { UtlContainable* actualReturnKey = commonList.insert(testData[i].insertKey) ; UtlContainable* actualSearchKey = commonList.find(testData[i].insertKey) ; UtlContainable* actualSearchValue = commonList.findValue(testData[i].insertKey) ; TestUtilities::createMessage(3, &Message, prefix, testData[i].testDescription, \ suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), testData[i].expectedReturnKey, \ actualReturnKey) ; TestUtilities::createMessage(3, &Message, prefix, testData[i].testDescription, \ suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), testData[i].expectedSearchKey, \ actualSearchKey) ; TestUtilities::createMessage(3, &Message, prefix, testData[i].testDescription, \ suffix3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), testData[i].expectedSearchValue, \ actualSearchValue) ; } }//testInsert() /*!a Test case for the find() method. * * The test data for this test case are:- * a) is a Containable String * b) is ta UtlInt and the HashDictionary has this key * c) is equal to(not the same) a key in the HashDictionary * d)is equal to a value in the HashDictionary but the dictionary has no such key * e) has no match at all */ void testFind() { utlTestFind_Or_Contains(TEST_FIND) ; } /*!a Test case for the contains() method * * The test data for this test case are the same as * testFind() test case. */ void testContains() { utlTestFind_Or_Contains(TEST_CONTAINS) ; } // Utility that can be used to either test the find or // contains methods. void utlTestFind_Or_Contains(FindOrContains type) { const int testCount = 5 ; const char* prefixFind = "Test the find() method when the search key " ; const char* prefixFindValue = "Test the findValue() method when the search key " ; const char* prefixContains = "Test the contains() method when the search key " ; const char* Msgs[] = { \ "is a UtlString and the HashDictionary has this key ", \ "is a UtlInt and the HashDictionary has this key ", \ "is equal to(not the same) a key in the HashDictionary ", \ "is equal to a value in the HashDictionary but the dictionary has no such key ", \ "has no match at all" \ } ; UtlString noExist("This cannot and should not exist!!!") ; UtlContainable* searchValues[] = { \ commonKeyValuePairs[0][0], \ commonKeyValuePairs[1][0], \ commonKeyValuePairs_clone[2][0], \ commonKeyValuePairs[3][1], \ &noExist \ } ; bool expectedValues_Contains[] = { \ true, true, true, false, false \ } ; UtlContainable* expected_FindKeys[] = { \ commonKeyValuePairs[0][0], \ commonKeyValuePairs[1][0], \ commonKeyValuePairs[2][0], \ NULL, \ NULL \ } ; UtlContainable* expected_FindValues[] = { \ commonKeyValuePairs[0][1], \ commonKeyValuePairs[1][1], \ commonKeyValuePairs[2][1], \ NULL, \ NULL \ } ; for (int i = 0 ; i < testCount ; i++) { string msg ; if (type == TEST_FIND) { UtlContainable* foundKey = commonList.find(searchValues[i]) ; UtlContainable* foundValue = commonList.findValue(searchValues[i]) ; TestUtilities::createMessage(2, &msg, prefixFind, Msgs[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*) expected_FindKeys[i], (void*)foundKey) ; TestUtilities::createMessage(2, &msg, prefixFindValue, Msgs[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)expected_FindValues[i], (void*)foundValue) ; } else if (type == TEST_CONTAINS) { bool act = (TRUE == commonList.contains(searchValues[i])) ; bool exp = expectedValues_Contains[i] ; TestUtilities::createMessage(2, &msg, prefixContains, Msgs[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), exp, act) ; } } }//utlTestFindOrContains /*!a Test case to test the destroy() * method. */ void testRemoveAndDestroy() { const char* prefix = "test the destroy() method " ; const char* suffix1 = ":- Verify the return value" ; const char* suffix2 = ":- Verify that the object was deleted" ; const char* suffix3 = ":- Verify that the entry is removed" ; const char* suffix4 = ":- Verify number of entries" ; UtlContainableTestStub uStub(0) ; UtlContainableTestStub uStubValue(1) ; UtlContainableTestStub* uStubPtr ; UtlContainableTestStub* uStubPtrValue ; uStubPtr = new UtlContainableTestStub(101) ; uStubPtrValue = new UtlContainableTestStub(202) ; commonList.insertKeyAndValue(&uStub, &uStubValue) ; commonList.insertKeyAndValue(uStubPtr, uStubPtrValue) ; int cCountBefore = UtlContainableTestStub :: getCount() ; string msg ; bool retValue = (TRUE == commonList.destroy(uStubPtr)) ; TestUtilities::createMessage(2, &msg, prefix, suffix1) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), retValue) ; // The ContainableTestStub has been implemented such that a static // counter is decremented for every instance destruction. Since the // Hashtable has set of name-value pairs, calling the removeAndDestroy // should destroy both the key and the value; thus the count goes down // by two . int cCountAfter = UtlContainableTestStub :: getCount() ; TestUtilities::createMessage(2, &msg, prefix, suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), cCountBefore -2, cCountAfter) ; // THe way to verify if the object has been removed is to // create a new stub . This stub will now have the same value as // the deleted stub. Try to find the new stub UtlContainableTestStub uStubNew(101) ; UtlContainable* uSearch = commonList.find(&uStubNew) ; TestUtilities::createMessage(2, &msg, prefix, suffix3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)NULL, (void*)uSearch) ; // In all the above tests, a total of 2 entries were added // and 1 wes removed. int finalCount = commonHashMapEntriesCount + 1 ; TestUtilities::createMessage(2, &msg, prefix, suffix4) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), finalCount, (int)commonList.entries()) ; }// testRemoveAndDestroy /*!a Test case for testRemove() * * The Test data for this test case is * a) Key is a Containable String * b) Key is a Containable Int * c) Key has a value match * d) has no match at all */ void testRemove() { utlTestRemove(TEST_REMOVE) ; } /** This test case verfies the removeKeyAndValue() method. * * The test data for this case is the same as the testRemove() * method */ void testRemoveKeyAndValue() { utlTestRemove(TEST_REMOVE_KEY_AND_VALUE) ; } /** Utility method that is called by the testRemove() and * testRemoveKeyAndValue() methods. Based on the argument * passed as 'type', one of these methods is tested. */ void utlTestRemove(RemoveType type) { const int testCount = 4; const char* prefix = ""; if (type == TEST_REMOVE) { prefix = "Test the remove(UtlContainable* c) method where " ; } else if (type== TEST_REMOVE_KEY_AND_VALUE) { prefix = "Test the removeKeyAndValue(UtlContainable* c) method where " ; } const char* Msgs[] = { \ "c is a Containable String that exists as a key in the Dictionary ", \ "c is a Containable Int that exists as a key in the Dictionary ", \ "a key that is equal to c exists in the Dictionary ", \ "has no match at all " \ } ; const char* suffix1 = " :- Verify returned key" ; const char* suffix2 = " :- Verify total entries" ; const char* suffix3 = " :- Verify returned value" ; UtlString noExist("This cannot and willnot exist"); UtlContainable* testData_Remove[] = { \ commonKeyValuePairs[0][0], \ commonKeyValuePairs[1][0], \ commonKeyValuePairs_clone[2][0], \ &noExist \ } ; UtlContainable* exp_ReturnKey[] = { \ commonKeyValuePairs[0][0], \ commonKeyValuePairs[1][0], \ commonKeyValuePairs[2][0], \ NULL \ }; UtlContainable* exp_ReturnValue[] = { \ commonKeyValuePairs[0][1], \ commonKeyValuePairs[1][1], \ commonKeyValuePairs[2][1], \ NULL \ }; int totalEnt = commonHashMapEntriesCount; int entriesValue[] = { --totalEnt, --totalEnt, --totalEnt, totalEnt } ; for (int i = 0 ; i < testCount ; i++) { string msg ; // Verify that remove() returns the correct value. TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix1) ; if (type == TEST_REMOVE) { UtlContainable* foundKey = commonList.remove(testData_Remove[i]) ; UtlContainable* expectedKey = exp_ReturnKey[i] ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)foundKey, (void*)expectedKey) ; } else if(type == TEST_REMOVE_KEY_AND_VALUE) { UtlContainable* expectedKey = exp_ReturnKey[i] ; UtlContainable* expectedValue = exp_ReturnValue[i] ; UtlContainable* foundValue ; UtlContainable* foundKey = commonList.removeKeyAndValue(testData_Remove[i], foundValue) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)expectedKey, (void*)foundKey) ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)expectedValue, (void*)foundValue) ; } // Verify the number of entries left in the hashdictionary after remove() TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix2) ; int expCount = (int)commonList.entries() ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), entriesValue[i], expCount) ; } } //testRemove /*!a Test case for the isEmpty() method. * The test data for this test are :- * a) When the list has just been created. * b) When the list has one entry in it * c) When the list has multiple entries in it. * e) When all the entries in a list have been removed using removeAll() */ void testIsEmpty() { const int testCount = 4 ; const char* prefix = "Test the isEmpty() method when " ; const char* Msgs[] = { \ "the list has just been created" , \ "the list has just one entry in it", \ "the list has multiple entries in it", \ "all the list entries have been retreived using removeAll()" \ } ; UtlHashMap newList ; UtlHashMap secondNewList ; // Add a single entry to the list. newList.insertKeyAndValue(&commonString1, &commonInt1) ; // populate the second list and then clear all entries. UtlString uS1("Tester string") ; UtlInt uI1 = UtlInt(232) ; secondNewList.insertKeyAndValue(&uS1, &commonInt2) ; secondNewList.insertKeyAndValue(&uI1, &commonString2) ; secondNewList.insertKeyAndValue(&commonString3, &commonInt3) ; secondNewList.removeAll() ; UtlHashMap* testLists[] = { \ &emptyList, &newList, &commonList, &secondNewList \ } ; bool expected_IsEmpty[] = { true, false, false, true } ; for (int i = 0 ; i < testCount; i++) { string msg ; TestUtilities::createMessage(2, &msg, prefix, Msgs[i]) ; bool act_isEmpty = (TRUE == testLists[i] -> isEmpty()) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expected_IsEmpty[i], act_isEmpty) ; } } // testIsEmpty /*!a test the removeAll() method. * * The test data for this method is * a) When the list is empty * b) When the list has one entry. * c) When the list multiple entries * d) When clear has been called and entries are added again * e) When the clear is called twice on the list. * f) When the clear is call on a list that has muliple entries * for the same key. */ void testClear() { const int testCount = 6 ; const char* prefix = "Test the removeAll() method when :- " ; const char* Msgs[] = { \ "the list is empty", \ "the list has one entry", \ "the list has multiple entries", \ " has been called and entries are added again", \ "removeAll() has already been called", \ "removeAll() is called on list that has multiple matches" \ } ; const char* suffix = " :- Verify number of entries after removeAll()" ; UtlHashMap uSingleList ; UtlHashMap uAddAfterClear ; UtlHashMap uDoubleClear ; uSingleList.insertKeyAndValue(&commonString1, &commonInt1) ; // call removeAll() on a list and then add entries again. uAddAfterClear.insertKeyAndValue(&commonInt1, &commonString2) ; uAddAfterClear.insertKeyAndValue(&commonString1, &commonInt3) ; uAddAfterClear.removeAll() ; uAddAfterClear.insertKeyAndValue(&commonInt2, &commonInt4) ; // call clear on a list twice. uDoubleClear.insertKeyAndValue(&commonString3, &commonString1) ; uDoubleClear.insertKeyAndValue(&commonInt3, &commonString2) ; uDoubleClear.removeAll() ; UtlHashMap* testLists[] = { \ &emptyList, &uSingleList, &commonList, &uAddAfterClear, &uDoubleClear, &commonList_clone } ; int expected_Entries[] = {0 , 0, 0, 1, 0, 0} ; // since we are not calling clear for all the data, do it outside the for loop. emptyList.removeAll() ; uSingleList.removeAll() ; commonList.removeAll() ; commonList_clone.removeAll() ; // no removeAll() for uAddAfterClear uDoubleClear.removeAll() ; for ( int i = 0 ; i < testCount ; i++) { string msg ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data() , expected_Entries[i], (int)testLists[i] -> entries()) ; } } //testClear() /*!a Test case to test the destroyAll() * method. */ void testClearAndDestroy() { const char* prefix = "Test the destroyAll() method " ; const char* suffix = ":- Verify that all entries are removed and the objects are deleted" ; int cCountBefore ; UtlContainableTestStub* uStub ; UtlContainableTestStub* uStub2 ; UtlContainableTestStub* uStubPtr ; UtlContainableTestStub* uStubPtr2 ; uStub = new UtlContainableTestStub(101) ; uStub2 = new UtlContainableTestStub(152) ; uStubPtr = new UtlContainableTestStub(202) ; uStubPtr2 = new UtlContainableTestStub(252) ; emptyList.insertKeyAndValue(uStub, uStub2) ; emptyList.insertKeyAndValue(uStubPtr, uStubPtr2) ; // The ContainableStub is implemented such that a static // counter is decremented for every call to the destrcutor. // Since four instances (2 sets of n-v pairs) were destroyed, // we should verify that he count goes down by 4. cCountBefore = UtlContainableTestStub :: getCount() ; emptyList.destroyAll() ; int cCountAfter = UtlContainableTestStub :: getCount() ; string msg ; TestUtilities::createMessage(2, &msg, prefix, suffix) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), 0, cCountAfter) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), cCountBefore - 4, (int)emptyList.entries()) ; } //testClearAndDestroy void testRemoveCollision() { // the following two entries collide if the initial bucket size is 16 UtlInt int1(1); UtlInt int16(16); UtlInt int2(2); UtlInt int3(3); UtlHashMap map; CPPUNIT_ASSERT( map.numberOfBuckets() == 16 ); // check assumption of collision // Load all the test objects CPPUNIT_ASSERT( map.insert(&int1) == &int1 ); CPPUNIT_ASSERT( map.insert(&int2) == &int2 ); CPPUNIT_ASSERT( map.insert(&int3) == &int3 ); CPPUNIT_ASSERT( map.insert(&int16) == &int16 ); // Check that everything is there CPPUNIT_ASSERT( map.entries() == 4 ); CPPUNIT_ASSERT( map.contains(&int1) ); CPPUNIT_ASSERT( map.contains(&int2) ); CPPUNIT_ASSERT( map.contains(&int3) ); CPPUNIT_ASSERT( map.contains(&int16) ); // Take entry 1 out (will collide w/ 16) CPPUNIT_ASSERT( map.removeReference(&int1) == &int1 ); // Check that everything except entry 1 is still there, and that 1 is gone CPPUNIT_ASSERT( map.entries() == 3 ); CPPUNIT_ASSERT( ! map.contains(&int1) ); CPPUNIT_ASSERT( map.contains(&int2) ); CPPUNIT_ASSERT( map.contains(&int3) ); CPPUNIT_ASSERT( map.contains(&int16) ); // Put entry 1 back in (so that 16 will collide w/ it again) CPPUNIT_ASSERT( map.insert(&int1) == &int1 ); // Check that everything is there CPPUNIT_ASSERT( map.entries() == 4 ); CPPUNIT_ASSERT( map.contains(&int1) ); CPPUNIT_ASSERT( map.contains(&int2) ); CPPUNIT_ASSERT( map.contains(&int3) ); CPPUNIT_ASSERT( map.contains(&int16) ); // Take entry 16 out (will collide w/ 1) CPPUNIT_ASSERT( map.removeReference(&int16) == &int16 ); // Check that everything except entry 16 is still there, and that 16 is gone CPPUNIT_ASSERT( map.entries() == 3 ); CPPUNIT_ASSERT( map.contains(&int1) ); CPPUNIT_ASSERT( map.contains(&int2) ); CPPUNIT_ASSERT( map.contains(&int3) ); CPPUNIT_ASSERT( ! map.contains(&int16) ); CPPUNIT_ASSERT( map.removeReference(&int2) == &int2 ); // Check that everything that should be is still there CPPUNIT_ASSERT( map.entries() == 2 ); CPPUNIT_ASSERT( map.contains(&int1) ); CPPUNIT_ASSERT( ! map.contains(&int2) ); CPPUNIT_ASSERT( map.contains(&int3) ); CPPUNIT_ASSERT( ! map.contains(&int16) ); // remove 3 (no collision for this one) CPPUNIT_ASSERT( map.removeReference(&int3) == &int3 ); // Check that everything that should be is still there CPPUNIT_ASSERT( map.entries() == 1 ); CPPUNIT_ASSERT( map.contains(&int1) ); CPPUNIT_ASSERT( ! map.contains(&int2) ); CPPUNIT_ASSERT( ! map.contains(&int3) ); CPPUNIT_ASSERT( ! map.contains(&int16) ); // remove 3 again - should fail this time CPPUNIT_ASSERT( map.removeReference(&int3) == NULL ); // Check that everything that should be is still there CPPUNIT_ASSERT( map.entries() == 1 ); CPPUNIT_ASSERT( map.contains(&int1) ); CPPUNIT_ASSERT( ! map.contains(&int2) ); CPPUNIT_ASSERT( ! map.contains(&int3) ); CPPUNIT_ASSERT( ! map.contains(&int16) ); } void testOneThousandInserts() { // Test case used to validate fix to issue XPL-169 const int COUNT = 1000; const char stringPrefix[] = "Apofur81Kb"; UtlHashMap map; char tmpString[20]; for( int i = 0; i < COUNT; i++) { sprintf(tmpString, "%s%d", stringPrefix, i); UtlString *stringToInsert = new UtlString(); *stringToInsert = tmpString; CPPUNIT_ASSERT( ! map.contains( stringToInsert ) ); map.insert( stringToInsert ); CPPUNIT_ASSERT_EQUAL( i+1, (int)map.entries() ); for( unsigned int j = 0; j < map.entries(); j++ ) { // verify that all entries are indeed in the map sprintf( tmpString, "%s%d", stringPrefix, j ); UtlString stringTolookUp( tmpString ); CPPUNIT_ASSERT_MESSAGE( tmpString, map.contains( &stringTolookUp ) ); } } } void testDeepCopy() { UtlHashMap source; source.insertKeyAndValue(new UtlString("1"), new UtlBool(TRUE)); source.insertKeyAndValue(new UtlString("2"), new UtlInt(2)); source.insertKeyAndValue(new UtlString("3"), new UtlString("3")); UtlHashMap target; OsStatus status = source.deepCopyInto(target); CPPUNIT_ASSERT_EQUAL(status, OS_SUCCESS); CPPUNIT_ASSERT_EQUAL(3, target.entries()); // Test UtlBool clone UtlBool aBool(FALSE); CPPUNIT_ASSERT(aBool.isInstanceOf(UtlCopyableContainable::TYPE)); UtlString firstKey("1"); UtlContainable* keyPtr = target.find(&firstKey); CPPUNIT_ASSERT(keyPtr); CPPUNIT_ASSERT(keyPtr->isInstanceOf(UtlString::TYPE)); UtlContainable* valuePtr = target.findValue(&firstKey); CPPUNIT_ASSERT(valuePtr); CPPUNIT_ASSERT(valuePtr->isInstanceOf(UtlBool::TYPE)); CPPUNIT_ASSERT_EQUAL(((UtlBool*)valuePtr)->getValue(), TRUE); // Test UtlInt clone UtlInt aInt(44); CPPUNIT_ASSERT(aInt.isInstanceOf(UtlCopyableContainable::TYPE)); UtlString secondKey("2"); keyPtr = target.find(&secondKey); CPPUNIT_ASSERT(keyPtr); CPPUNIT_ASSERT(keyPtr->isInstanceOf(UtlString::TYPE)); valuePtr = target.findValue(&secondKey); CPPUNIT_ASSERT(valuePtr); CPPUNIT_ASSERT(valuePtr->isInstanceOf(UtlInt::TYPE)); CPPUNIT_ASSERT_EQUAL(*((UtlInt*)valuePtr), 2); // Test UtlString clone UtlString thirdKey("3"); CPPUNIT_ASSERT(thirdKey.isInstanceOf(UtlCopyableContainable::TYPE)); valuePtr = target.findValue(&thirdKey); CPPUNIT_ASSERT(valuePtr); CPPUNIT_ASSERT(valuePtr->isInstanceOf(UtlString::TYPE)); CPPUNIT_ASSERT_EQUAL(*((UtlString*)valuePtr), "3"); // Should fail to copy ask keys already to exist in target status = source.deepCopyInto(target); CPPUNIT_ASSERT_EQUAL(status, OS_NAME_IN_USE); // OsSocket is not a cloneable object OsDatagramSocket aSocket(50505, "127.0.0.1"); CPPUNIT_ASSERT(! aSocket.isInstanceOf(UtlCopyableContainable::TYPE)); target.destroyAll(); UtlString socketKey("4"); source.insertKeyAndValue(&socketKey, &aSocket); status = source.deepCopyInto(target); CPPUNIT_ASSERT_EQUAL(status, OS_NOT_SUPPORTED); CPPUNIT_ASSERT_EQUAL(3, target.entries()); CPPUNIT_ASSERT(source.remove(&socketKey)); target.destroyAll(); source.destroyAll(); } }; const int UtlHashMapTests::INDEX_NOT_EXIST = -1; CPPUNIT_TEST_SUITE_REGISTRATION(UtlHashMapTests); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlHashMapIterator.cpp0000644000175000017500000003037612205613256026466 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include #include #include static const char* longAlphaNumString = \ "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvw" ; static const char* regularString = "This makes sense" ; static const int commonEntriesCount=4 ; static const int INDEX_NOT_EXIST = -1; /** This class is used to test the UtlHashMapIterator utility class. * * PLEASE READ THE README FILE THAT CAN FOUND IN THE SAME DIRECTORY AS * THIS FILE. The Readme describes the organization / flow of tests and * without reading this file, the following class (and all unit tests) * may not make a lot of sense and might be difficult to comprehend. */ class UtlHashMapIteratorTests : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlHashMapIteratorTests); CPPUNIT_TEST(checkSanity_Insert_Entries_And_At); CPPUNIT_TEST(testAdvancingOperator_And_KeyMethod) ; CPPUNIT_TEST_SUITE_END(); private: struct KeyValueStructure { const char* testDescription ; const UtlContainable* key ; const UtlContainable* value ; }; UtlHashMap commonList ; UtlHashMap commonList_clone ; UtlHashMap emptyList ; UtlString commonString1 ; UtlString commonString2 ; UtlString commonString3 ; UtlString commonString4 ; UtlInt commonInt1 ; UtlInt commonInt2 ; UtlInt commonInt3 ; UtlInt commonInt4 ; UtlString commonString1_clone; UtlString commonString2_clone ; UtlString commonString3_clone ; UtlString commonString4_clone ; UtlInt commonInt1_clone ; UtlInt commonInt2_clone ; UtlInt commonInt3_clone ; UtlInt commonInt4_clone ; KeyValueStructure* commonTestData ; KeyValueStructure* commonTestData_clone ; enum FindOrContains { TEST_FIND, TEST_CONTAINS} ; enum TestInsertOrAppend {TEST_APPEND, TEST_INSERT} ; enum RemoveType {TEST_REMOVE, TEST_REMOVE_KEY_AND_VALUE} ; public: UtlHashMapIteratorTests() { commonTestData = new KeyValueStructure[commonEntriesCount] ; commonTestData_clone = new KeyValueStructure[commonEntriesCount] ; } ~UtlHashMapIteratorTests() { delete[] commonTestData ; delete[] commonTestData_clone ; } void setUp() { commonString1 = UtlString(regularString) ; commonString1_clone = UtlString(regularString) ; commonString2 = UtlString("") ; commonString2_clone = UtlString("") ; commonString3 = UtlString(longAlphaNumString) ; commonString3_clone = UtlString(longAlphaNumString) ; commonString4 = UtlString("Another String") ; commonString4_clone = UtlString("Another String") ; commonInt1 = UtlInt(0) ; commonInt1_clone = UtlInt(0) ; commonInt2 = UtlInt(INT_MAX) ; commonInt2_clone = UtlInt(INT_MAX) ; commonInt3 = UtlInt(INT_MIN) ; commonInt3_clone = UtlInt(INT_MIN) ; commonInt4 = UtlInt(101) ; commonInt4_clone = UtlInt(101) ; // Insert 3 name value pairs into the commonList :- // a) Key = String, Value = Int // b) Key = Int, Value = String: // c) Key = String, Value = String commonList.insertKeyAndValue(&commonString1, &commonInt1) ; commonList.insertKeyAndValue(&commonInt2, &commonString2) ; commonList.insertKeyAndValue(&commonString3, &commonString4) ; commonList.insertKeyAndValue(&commonInt3, &commonInt4) ; // The above values also become the name-value pair array // The first index of the 2nd dimension represents the key // while the second index represents the value expected. commonTestData[0].testDescription = "key = UtlString. value = UtlInt" ; commonTestData[0].key = &commonString1; commonTestData[0].value = &commonInt1 ; commonTestData[1].testDescription = "key = UtlInt. value = UtlString" ; commonTestData[1].key = &commonInt2 ; commonTestData[1].value = &commonString2 ; commonTestData[2].testDescription = "key = UtlString. value = UtlString" ; commonTestData[2].key = &commonString3 ; commonTestData[2].value = &commonString4 ; commonTestData[3].testDescription = "key = UtlVoidPtr. value = UtlInt" ; commonTestData[3].key = &commonInt3 ; commonTestData[3].value = &commonInt4 ; // Similarly create a clone of the list and the expected data. commonList_clone.insertKeyAndValue(&commonString1_clone, &commonInt1_clone) ; commonList_clone.insertKeyAndValue(&commonInt2_clone, &commonString2_clone) ; commonList_clone.insertKeyAndValue(&commonString3_clone, &commonString4_clone) ; commonList_clone.insertKeyAndValue(&commonInt3_clone, &commonInt4_clone) ; // The above values also become the name-value pair array // The first index of the 2nd dimension represents the key // while the second index represents the value expected. commonTestData_clone[0].key = &commonString1_clone; commonTestData_clone[1].value = &commonInt1_clone ; commonTestData_clone[1].key = &commonInt2_clone ; commonTestData_clone[1].value = &commonString2_clone ; commonTestData_clone[2].key = &commonString3_clone ; commonTestData_clone[2].value = &commonString4_clone ; commonTestData_clone[3].key = &commonInt3_clone ; commonTestData_clone[3].value = &commonInt4_clone ; } void tearDown() { } /** Sandbox method for experimenting with the API Under Test. * This method MUST be empty when the test drivers are being * checked in (final checkin) to the repository. */ void DynaTest() { } /*a! This test is more of a sanity check to verify that * the basic insert(), entries() and at() methods work as expected. * All future tests will depend heavily on the at() method * and the most common way of having something in the list is * by means of the insert() method. * */ void checkSanity_Insert_Entries_And_At() { CPPUNIT_ASSERT_EQUAL_MESSAGE("Verify that the entries() for an empty HashMap \ returns 0", (int)emptyList.entries(), 0) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Verify the entries() method for a HashMap", \ commonEntriesCount, (int)commonList.entries()) ; }// checkSanity_Append_And_At() /*!a Test case for the () operator and the key() method. * * The test data for this test is :- * Verify that all items in the dictionary can be iteratated through. * Verify that attempting to iterate when all items have been read returns a null */ void testAdvancingOperator_And_KeyMethod() { const char* prefix1 = "Verify the () operator " ; const char* prefix2 = "Verify the key() method " ; const char* prefix3 = "Verify the value() method " ; string Message ; UtlHashMapIterator iter(commonList) ; iter() ; UtlContainable* actualKey ; UtlContainable* actualValue ; // Test the key/value methods when the iterator has been reset. iter.reset() ; actualKey = iter.key() ; actualValue = iter.value() ; TestUtilities::createMessage(2, &Message, prefix2, \ "when the iterator has been reset") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), (void*)NULL, (void*)actualKey) ; TestUtilities::createMessage(2, &Message, prefix3, \ "when the iterator has been reset") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), (void*)NULL, (void*)actualValue) ; // Now iterate through the whole iterator and verify that all the items are // retreived. The () operator retreives the key for next item in the list. The // key item should retreive the item under the current position. (That is, // the key() method should always return what the previous () returned). The // value() method should return the value corresponding to the key under the current // cursor. // Loop to iterate through all the entries in the Hashdictionary for (int i = 0 ; i < commonEntriesCount ; i++) { actualKey = iter() ; actualKey = iter.key() ; actualValue = iter.value() ; int foundIndex = -1 ; // Now iterate through the test data array and see if the key retreived // above matches any one of the array values. If it does, mark that as the // foundIndex for (int j = 0 ; j < commonEntriesCount; j++) { if (commonTestData[j].key && commonTestData[j].key == actualKey) { foundIndex = j ; break ; } } if (foundIndex != -1) { TestUtilities::createMessage(2, &Message, prefix1, \ commonTestData[foundIndex].testDescription) ; // If we have come into this loop,it means that we have already // found the key using the () operator. CPPUNIT_ASSERT_MESSAGE(Message.data(), true) ; actualKey = iter.key() ; actualValue = iter.value() ; TestUtilities::createMessage(2, &Message, prefix2, \ commonTestData[foundIndex].testDescription) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), \ (void*)commonTestData[foundIndex].key, (void*)actualKey) ; TestUtilities::createMessage(2, &Message, prefix3, \ commonTestData[foundIndex].testDescription) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), \ (void*)commonTestData[foundIndex].value, (void*)actualValue) ; // Now set the key in the test data array for this index to NULL. // The idea behind this is that if a key is retreived once, it should never be // retreived again! commonTestData[foundIndex].key = NULL ; } else { TestUtilities::createMessage(2, &Message, prefix1, \ "- Did not find one of the expected keys") ; CPPUNIT_ASSERT_MESSAGE(Message.data(), false) ; } }// End loop to iterate through all entries in the hashTable // Now verify that iterating through the iterator after all entries // have been read, returns NULL. actualKey = iter() ; const char* msgLast = "when all entries have been read" ; TestUtilities::createMessage(2, &Message, prefix1, msgLast) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), (void*)NULL, (void*)actualKey) ; actualKey = iter.key() ; actualValue = iter.value() ; TestUtilities::createMessage(2, &Message, prefix2, msgLast) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), (void*)NULL, (void*)actualKey) ; TestUtilities::createMessage(2, &Message, prefix3, msgLast) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), (void*)NULL, (void*)actualValue) ; } //testAdvancingOperator_And_KeyMethod() }; CPPUNIT_TEST_SUITE_REGISTRATION(UtlHashMapIteratorTests); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlInt.cpp0000644000175000017500000003755212205613256024170 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2010 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include /* PLEASE VERIFY WITH SCOTT */ /* // -------------------Forward declarations------------------------------------ class UtlIntTests ; // ------------------- Static constant initializers ------------------------- const int UtlIntTests::int_Zero = 0 ; const int UtlIntTests::int_Positive = 101 ; const int UtlIntTests::int_Negative = -51 ; const int UtlIntTests::commonTestDataSet[] = { \ int_Zero, int_Positive, int_Negative, \ INT_MAX, INT_MIN \ } ; const char* UtlIntTests::commonTestDataSetMessages[] = { \ "Zero" , \ "Positive Integer", \ "Negative Integer", \ "MAX VALUE Positive Integer", \ "MIN VALUE Negative Integer" \ } ; */ /** This class is used to test the UtlInt utility class. * * PLEASE READ THE README FILE THAT CAN FOUND IN THE SAME DIRECTORY AS * THIS FILE. The Readme describes the organization / flow of tests and * without reading this file, the following class (and all unit tests) * may not make a lot of sense and might be difficult to comprehend. */ class UtlIntTests : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlIntTests); CPPUNIT_TEST(testConstructor) ; CPPUNIT_TEST(testCompareTo) ; CPPUNIT_TEST(testCompareTo_NonInt) ; CPPUNIT_TEST(testEquals) ; CPPUNIT_TEST(testEquals_NonInteger) ; CPPUNIT_TEST(testSetValue) ; CPPUNIT_TEST(testGetContainableType) ; CPPUNIT_TEST(testOperators) ; CPPUNIT_TEST_SUITE_END(); private: struct BasicIntVerifier { const char* message ; int input ; int expectedValue ; } ; static const int int_Zero ; static const int int_Positive ; static const int int_Negative ; //INT_MAX //INT_MIN static const int INDEX_NOT_FOUND ; // An indication that the test should be ignored. static const int IGNORE_TEST ; static const BasicIntVerifier commonTestSet[] ; static const int commonTestSetLength ; enum EqualOrCompareTest { TEST_EQUAL, TEST_COMPARE } ; public: UtlIntTests() { } void setUp() { } void tearDown() { } ~UtlIntTests() { } /** Sandbox method for experimenting with the API Under Test. * This method MUST be empty when the test drivers are being * checked in (final checkin) to the repository. */ void DynaTest() { } /** Test the constructor * * The test data for this test case is :- * a) int = 0 * b) int = +ve integer * c) int = -ve integer * d) int = max +ve integer * e) int = max -ve integer. * The above set of data will be referred to as the * Common Data Set henceforth! The common data set has been defined * as a static const array of integers and a short description about * the data is in a const array of char* * */ void testConstructor() { // First test the default constructor UtlInt testInt ; const char* msg0 = "Test the default constructor" ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg0, 0, testInt.getValue()) ; //Now test the single argument constructor for each of // the common test data type const char* prefix = "Test UtlInt(int value), where value = " ; for (int i = 0 ;i < commonTestSetLength; i++) { string msg ; TestUtilities::createMessage(2, &msg, prefix, commonTestSet[i].message) ; UtlInt testInt(commonTestSet[i].input) ; int actualValue = testInt.getValue() ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), commonTestSet[i].expectedValue, actualValue) ; } } /** Test the compareTo method * * The test data for this test is :- * with the common data set, compare the data with * another value that is a) equal to, b) greater than * and c) less than itself */ void testCompareTo() { utlTestCompareOrEquals(TEST_COMPARE) ; } /** Test the isEqual(UtlContainable*) method. * * The test data for this test is the same as the compareTo method. */ void testEquals() { utlTestCompareOrEquals(TEST_EQUAL) ; } /* Test the isEqual method or the compareTo method. */ void utlTestCompareOrEquals(EqualOrCompareTest testType) { const char* prefix = ""; if (testType == TEST_COMPARE) { prefix = "Test the compareTo method for an Integer whose value = " ; } else if (testType == TEST_EQUAL) { prefix = "Test the isEqual method for an Integer whose value = " ; } const char* suffix1 = " - when value == arg" ; const char* suffix2 = " - when value > arg" ; const char* suffix3 = " - when value < arg" ; string msg ; struct compareToData { const char* message ; // Description about the type of test data int baseValue ; // The value of the test UtlInt int equalToBase ; // An Integer that is equal to the base value int greaterThanBase ; // Integer that is greater than the base value int lessThanBase ; // Integer that is less than the base value } ; const compareToData testData[] = { \ { "zero", 0, 0, 10, -10 }, \ { "positive integer", int_Positive, int_Positive, int_Positive+10, int_Positive-10 }, \ { "negative integer", int_Negative, int_Negative, int_Negative+10, int_Negative-10 }, \ { "integer at its maximum allowed value", INT_MAX, INT_MAX, IGNORE_TEST, INT_MAX-10 }, \ { "integer at its minimum allowed value", INT_MIN, INT_MIN, INT_MIN+10, IGNORE_TEST } } ; const int testCount = sizeof(testData)/sizeof(testData[0]) ; int expectedForEquals = 0 ; int expectedForGreaterThan = 10 ; int expectedForLessThan = -10 ; // Loop to iterate through the array of test data. for (int i = 0 ; i < testCount ; i++) { UtlInt testInt(testData[i].baseValue) ; UtlInt intForCompare ; // ------------------------------------------------------------------------- // first test the case when the rhs's int = base int. intForCompare = UtlInt(testData[i].equalToBase) ; TestUtilities::createMessage(3, &msg, prefix, \ testData[i].message, suffix1) ; if (testType == TEST_COMPARE) { int actual = testInt.compareTo(&intForCompare) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedForEquals, actual) ; } else if (testType == TEST_EQUAL) { UtlBoolean actual = testInt.isEqual(&intForCompare) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), actual) ; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // Now test the case where the integer's value is greater than the argument's value // In this case we SHOULD not try to compare for an integer which is at the // MINIMUM value that any integer can assume as such an integer cannot be greater // than anything else. This is bound to cause overruns thus yielding unexpected results. if (testData[i].baseValue != INT_MIN) { intForCompare = UtlInt(testData[i].lessThanBase) ; TestUtilities::createMessage(3, &msg, prefix, \ testData[i].message, suffix2) ; if (testType == TEST_COMPARE) { int actual = testInt.compareTo(&intForCompare) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedForGreaterThan, actual) ; } else if (testType == TEST_EQUAL) { UtlBoolean actual = testInt.isEqual(&intForCompare) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), !actual) ; } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // Now test the case where the integer's value is less than the argument's value // In this case we SHOULD not try to compare for an integer which is at the // MAXIMUM value that any integer can assume as such an integer cannot be less than // anything else. This is bound to cause overruns thus yielding unexpected results. if (testData[i].baseValue != INT_MAX) { intForCompare = UtlInt(testData[i].greaterThanBase) ; TestUtilities::createMessage(3, &msg, prefix, \ testData[i].message, suffix3) ; if (testType == TEST_COMPARE) { int actual = testInt.compareTo(&intForCompare) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedForLessThan, actual) ; } else if (testType == TEST_EQUAL) { UtlBoolean actual = testInt.isEqual(&intForCompare) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), !actual) ; } } // ------------------------------------------------------------------------- } // End of loop to iterate through test data. } /*!a Test the compareTo method when a non-UtlInt is passed. * */ void testCompareTo_NonInt() { UtlString testUtlString("Test String") ; UtlInt testUtlInt(INT_MAX) ; int actual = testUtlInt.compareTo(&testUtlString) ; // If a collectable is *NOT* an Integer, then the only thing that is predictible is // that this is not equal to the argument CPPUNIT_ASSERT_MESSAGE( "Compare an Int with a String ", (actual != 0 )) ; } /*!a Test the Equals Method when the argument passed is not a UtlInt * */ void testEquals_NonInteger() { const char* prefix = "Test the isEquals(UtlContainable other) for an Integer whose " \ "value is " ; const char* suffix = ", where other is a UtlContainable object that is not a " \ "UtlInt" ; UtlString testString("This is a test string") ; for (int i = 0 ; i < commonTestSetLength; i++) { UtlInt testInt(commonTestSet[i].input) ; string msg ; UtlBoolean isEqual =testInt.isEqual(&testString); TestUtilities::createMessage(3, &msg, prefix, commonTestSet[i].message, suffix) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (UtlBoolean)false, isEqual) ; } } //testEquals_NonInteger /*!a Test the setValue(int) method. * * Test Data :- * For each type in the common dataset as the base * integer, add each type of common dataset integer */ void testSetValue() { const char* prefix = "Test the setValue(int setter) method for a UtlInt " \ "whose value is " ; const char* suffix1 = " -- verify that the previous value is returned " ; const char* suffix2 = " -- verify that the new value has been set " ; string msg ; // For each type of UtlInt, verify that you can set // every common type of Integer. for (int i = 0 ; i < commonTestSetLength ; i++) { // Loop to test setting each common type of integer // for any given type of integer for (int j = 0 ; j < commonTestSetLength ; j++) { UtlInt baseInt(commonTestSet[i].input) ; int oldActualValue = baseInt.setValue(commonTestSet[j].input) ; int newActualValue = baseInt.getValue() ; // Verify that the return value = previous value TestUtilities::createMessage(5, &msg, prefix, commonTestSet[i].message, \ " where setter = ", commonTestSet[j].message, \ suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), commonTestSet[i].expectedValue, \ oldActualValue) ; // Verify that the value has been set. TestUtilities::createMessage(5, &msg, prefix, commonTestSet[i].message, \ " where setter = ", commonTestSet[j].message, \ suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), commonTestSet[j].expectedValue, \ newActualValue) ; } } } //testSetValue /*!a Test the getContainableType method * * Test data = common test data set */ void testGetContainableType() { const char* prefix = "Test the getContainableType() method for a UtlInt " \ "whose value is " ; string msg ; for (int i = 0 ; i < commonTestSetLength; i++) { UtlInt testInt(commonTestSet[i].input) ; UtlContainableType actual = testInt.getContainableType() ; TestUtilities::createMessage(2, &msg, prefix, commonTestSet[i].message) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), string("UtlInt"), \ string(actual)) ; } } //testGetContainableType void testOperators() { // test prefix and postfix operators UtlInt testInt(1); CPPUNIT_ASSERT((++testInt).getValue() == 2); CPPUNIT_ASSERT((testInt++).getValue() == 2); CPPUNIT_ASSERT((--testInt).getValue() == 2); CPPUNIT_ASSERT((testInt--).getValue() == 2); // test conversion operator UtlInt testInt2(11); CPPUNIT_ASSERT(testInt2 == 11); UtlString stringifiedInt; UtlInt::toString(stringifiedInt, 123456); CPPUNIT_ASSERT(stringifiedInt.compareTo("123456") == 0); UtlInt::toString(stringifiedInt, -98765); CPPUNIT_ASSERT(stringifiedInt.compareTo("-98765") == 0); } //testOperators }; // ------------------- Static constant initializers ------------------------- const int UtlIntTests::int_Zero = 0 ; const int UtlIntTests::int_Positive = 101 ; const int UtlIntTests::int_Negative = -51 ; const UtlIntTests::BasicIntVerifier \ UtlIntTests::commonTestSet[] = { \ {"Zero", int_Zero, int_Zero}, \ {"Positive Integer", int_Positive, int_Positive}, \ {"Negative Integer", int_Negative, int_Negative}, \ {"MAX VALUE Positive Integer", INT_MAX, INT_MAX}, \ {"MIN VALUE Negative Integer", INT_MIN, INT_MIN} \ } ; const int UtlIntTests::commonTestSetLength = 5 ; const int UtlIntTests::INDEX_NOT_FOUND = -1 ; const int UtlIntTests::IGNORE_TEST=-1 ; CPPUNIT_TEST_SUITE_REGISTRATION(UtlIntTests); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlLinkTest.cpp0000644000175000017500000003572212205613256025170 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include "utl/UtlLink.h" #include "utl/UtlInt.h" #include /// Unit test of the UtlLink and UtlLinkPool classes. static UtlInt data1(1); static UtlInt data2(2); static UtlInt data3(3); /// Unit test of the UtlLink, UtlLinkPool, and UtlChain classes. class UtlLinkTest : public SIPX_UNIT_BASE_CLASS, public UtlLink { CPPUNIT_TEST_SUITE(UtlLinkTest); /* CPPUNIT_TEST(testEmptyPool); - removed because with the addition of test logging the pool has already been used by parts of the OsSysLog infrastructure, so it's not empty. If you really really want to run this test with this enabled, see sipXportLib/src/test/sipxunit/TestRunner.cpp and comment out the call to install the TestOsSysLogListener. */ CPPUNIT_TEST(testLinkBefore); CPPUNIT_TEST(testListBefore); CPPUNIT_TEST(testLinkAfter); CPPUNIT_TEST(testListAfter); CPPUNIT_TEST(testLinkReuse); CPPUNIT_TEST_SUITE_END(); private: public: void testEmptyPool() { CPPUNIT_ASSERT_EQUAL_MESSAGE("Initial UtlLinkPool allocation should be zero!", \ (size_t)0, \ totalAllocated() ); } void testLinkBefore() { UtlChain start; UtlLink* link3 = UtlLink::before(&start, &data3); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(link3->prev() == NULL); CPPUNIT_ASSERT(link3->next() == &start); CPPUNIT_ASSERT(start.prev == link3); CPPUNIT_ASSERT(start.next == NULL); UtlLink* link2 = UtlLink::before(link3, &data2); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(link2->data == &data2 && data2.getValue() == 2); CPPUNIT_ASSERT(link2->prev() == NULL); CPPUNIT_ASSERT(link2->next() == link3); CPPUNIT_ASSERT(link3->prev() == link2); CPPUNIT_ASSERT(link3->next() == &start); CPPUNIT_ASSERT(start.prev == link3); CPPUNIT_ASSERT(start.next == NULL); UtlLink* link1 = UtlLink::before(link2, &data1); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(link2->data == &data2 && data2.getValue() == 2); CPPUNIT_ASSERT(link1->data == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(link1->prev() == NULL); CPPUNIT_ASSERT(link1->next() == link2); CPPUNIT_ASSERT(link2->prev() == link1); CPPUNIT_ASSERT(link2->next() == link3); CPPUNIT_ASSERT(link3->prev() == link2); CPPUNIT_ASSERT(link3->next() == &start); CPPUNIT_ASSERT(start.prev == link3); CPPUNIT_ASSERT(start.next == NULL); void* returnedData; returnedData = link2->unlink(); CPPUNIT_ASSERT(returnedData == &data2 && data2.getValue() == 2); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(link1->data == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(link1->prev() == NULL); CPPUNIT_ASSERT(link1->next() == link3); CPPUNIT_ASSERT(link3->prev() == link1); CPPUNIT_ASSERT(link3->next() == &start); CPPUNIT_ASSERT(start.prev == link3); CPPUNIT_ASSERT(start.next == NULL); returnedData = link1->unlink(); CPPUNIT_ASSERT(returnedData == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(link3->prev() == NULL); CPPUNIT_ASSERT(link3->next() == &start); CPPUNIT_ASSERT(start.prev == link3); CPPUNIT_ASSERT(start.next == NULL); returnedData = link3->unlink(); CPPUNIT_ASSERT(returnedData == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(start.prev == NULL); CPPUNIT_ASSERT(start.next == NULL); } void testListBefore() { UtlChain list; UtlLink* link1 = UtlLink::listBefore(&list, NULL, &data1); CPPUNIT_ASSERT(link1->data == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(link1->prev() == NULL); CPPUNIT_ASSERT(link1->next() == NULL); CPPUNIT_ASSERT(list.prev == link1); CPPUNIT_ASSERT(list.next == link1); UtlLink* link3 = UtlLink::listBefore(&list, NULL, &data3); CPPUNIT_ASSERT(link1->data == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(list.next == link1); CPPUNIT_ASSERT(link1->prev() == NULL); CPPUNIT_ASSERT(link1->next() == link3); CPPUNIT_ASSERT(link3->prev() == link1); CPPUNIT_ASSERT(link3->next() == NULL); CPPUNIT_ASSERT(list.prev == link3); UtlLink* link2 = UtlLink::listBefore(&list, link3, &data2); CPPUNIT_ASSERT(link1->data == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(link2->data == &data2 && data2.getValue() == 2); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(list.next == link1); CPPUNIT_ASSERT(link1->prev() == NULL); CPPUNIT_ASSERT(link1->next() == link2); CPPUNIT_ASSERT(link2->prev() == link1); CPPUNIT_ASSERT(link2->next() == link3); CPPUNIT_ASSERT(link3->prev() == link2); CPPUNIT_ASSERT(link3->next() == NULL); CPPUNIT_ASSERT(list.prev == link3); void* returnedData; returnedData = link2->detachFrom(&list); CPPUNIT_ASSERT(returnedData == &data2 && data2.getValue() == 2); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(link1->data == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(list.next == link1); CPPUNIT_ASSERT(link1->prev() == NULL); CPPUNIT_ASSERT(link1->next() == link3); CPPUNIT_ASSERT(link3->prev() == link1); CPPUNIT_ASSERT(link3->next() == NULL); CPPUNIT_ASSERT(list.prev == link3); returnedData = link1->detachFrom(&list); CPPUNIT_ASSERT(returnedData == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(list.next == link3); CPPUNIT_ASSERT(link3->prev() == NULL); CPPUNIT_ASSERT(link3->next() == NULL); CPPUNIT_ASSERT(list.prev == link3); returnedData = link3->detachFrom(&list); CPPUNIT_ASSERT(returnedData == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(list.prev == NULL); CPPUNIT_ASSERT(list.next == NULL); } void testLinkAfter() { UtlChain start; UtlLink* link1 = UtlLink::after(&start, &data1); CPPUNIT_ASSERT(link1->data == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(start.prev == NULL); CPPUNIT_ASSERT(start.next == link1); CPPUNIT_ASSERT(link1->prev() == &start); CPPUNIT_ASSERT(link1->next() == NULL); UtlLink* link2 = UtlLink::after(link1, &data2); CPPUNIT_ASSERT(link1->data == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(link2->data == &data2 && data2.getValue() == 2); CPPUNIT_ASSERT(start.prev == NULL); CPPUNIT_ASSERT(start.next == link1); CPPUNIT_ASSERT(link1->prev() == &start); CPPUNIT_ASSERT(link1->next() == link2); CPPUNIT_ASSERT(link2->prev() == link1); CPPUNIT_ASSERT(link2->next() == NULL); UtlLink* link3 = UtlLink::after(link2, &data3); CPPUNIT_ASSERT(link1->data == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(link2->data == &data2 && data2.getValue() == 2); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(start.prev == NULL); CPPUNIT_ASSERT(start.next == link1); CPPUNIT_ASSERT(link1->prev() == &start); CPPUNIT_ASSERT(link1->next() == link2); CPPUNIT_ASSERT(link2->prev() == link1); CPPUNIT_ASSERT(link2->next() == link3); CPPUNIT_ASSERT(link3->prev() == link2); CPPUNIT_ASSERT(link3->next() == NULL); void* returnedData; returnedData = link2->unlink(); CPPUNIT_ASSERT(returnedData == &data2 && data2.getValue() == 2); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(link1->data == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(start.prev == NULL); CPPUNIT_ASSERT(start.next == link1); CPPUNIT_ASSERT(link1->prev() == &start); CPPUNIT_ASSERT(link1->next() == link3); CPPUNIT_ASSERT(link3->prev() == link1); CPPUNIT_ASSERT(link3->next() == NULL); returnedData = link1->unlink(); CPPUNIT_ASSERT(returnedData == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(link3->prev() == &start); CPPUNIT_ASSERT(link3->next() == NULL); CPPUNIT_ASSERT(start.prev == NULL); CPPUNIT_ASSERT(start.next == link3); returnedData = link3->unlink(); CPPUNIT_ASSERT(returnedData == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(start.prev == NULL); CPPUNIT_ASSERT(start.next == NULL); } void testListAfter() { UtlChain list; UtlLink* link3 = UtlLink::listAfter(&list, NULL, &data3); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(list.next == link3); CPPUNIT_ASSERT(link3->prev() == NULL); CPPUNIT_ASSERT(link3->next() == NULL); CPPUNIT_ASSERT(list.prev == link3); UtlLink* link1 = UtlLink::listAfter(&list, NULL, &data1); CPPUNIT_ASSERT(link1->data == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(list.next == link1); CPPUNIT_ASSERT(link1->prev() == NULL); CPPUNIT_ASSERT(link1->next() == link3); CPPUNIT_ASSERT(link3->prev() == link1); CPPUNIT_ASSERT(link3->next() == NULL); CPPUNIT_ASSERT(list.prev == link3); UtlLink* link2 = UtlLink::listAfter(&list, link1, &data2); CPPUNIT_ASSERT(link1->data == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(link2->data == &data2 && data2.getValue() == 2); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(list.next == link1); CPPUNIT_ASSERT(link1->prev() == NULL); CPPUNIT_ASSERT(link1->next() == link2); CPPUNIT_ASSERT(link2->prev() == link1); CPPUNIT_ASSERT(link2->next() == link3); CPPUNIT_ASSERT(link3->prev() == link2); CPPUNIT_ASSERT(link3->next() == NULL); CPPUNIT_ASSERT(list.prev == link3); void* returnedData; returnedData = link2->detachFrom(&list); CPPUNIT_ASSERT(returnedData == &data2 && data2.getValue() == 2); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(link1->data == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(list.next == link1); CPPUNIT_ASSERT(link1->prev() == NULL); CPPUNIT_ASSERT(link1->next() == link3); CPPUNIT_ASSERT(link3->prev() == link1); CPPUNIT_ASSERT(link3->next() == NULL); CPPUNIT_ASSERT(list.prev == link3); returnedData = link1->detachFrom(&list); CPPUNIT_ASSERT(returnedData == &data1 && data1.getValue() == 1); CPPUNIT_ASSERT(link3->data == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(list.next == link3); CPPUNIT_ASSERT(link3->prev() == NULL); CPPUNIT_ASSERT(link3->next() == NULL); CPPUNIT_ASSERT(list.prev == link3); returnedData = link3->detachFrom(&list); CPPUNIT_ASSERT(returnedData == &data3 && data3.getValue() == 3); CPPUNIT_ASSERT(list.prev == NULL); CPPUNIT_ASSERT(list.next == NULL); } void testLinkReuse() { UtlChain start; size_t startingPoolSize = totalAllocated(); // chain on links until a new block is allocated int i; for (i = 0; startingPoolSize == totalAllocated(); i++ ) { UtlLink::after(&start, &data1); } size_t peakPoolSize = totalAllocated(); // how many we had after that allocation // release all those links while (!start.isUnLinked()) { start.head()->unlink(); } // verify that the number of allocated links didn't change CPPUNIT_ASSERT(peakPoolSize == totalAllocated()); // now repeatedly use more links, but no more than the peak usage, and free them again for (int iteration = 0; iteration < 1000; iteration++) { // fill the start list with the number of blocks it took to force an allocation // // cannot assume starting pool size to be zero. // for (size_t i = startingPoolSize; i < (peakPoolSize - startingPoolSize); i++) { UtlLink::after(&start, &data1); } char msg[1000]; sprintf(msg, "New allocations after filling in iteration %d\n" " startingPoolSize %d\n" " peakPoolSize %d\n" " totalAllocated %d\n", iteration, startingPoolSize, peakPoolSize, totalAllocated() ); CPPUNIT_ASSERT_EQUAL_MESSAGE("peakPoolSize is not same as totalAllocated!", \ peakPoolSize, \ totalAllocated() ); // release all those links while (!start.isUnLinked()) { start.head()->unlink(); } sprintf(msg, "New allocations after release in iteration %d\n" " startingPoolSize %d\n" " peakPoolSize %d\n" " totalAllocated %d\n", iteration, startingPoolSize, peakPoolSize, totalAllocated() ); CPPUNIT_ASSERT_MESSAGE(msg, peakPoolSize == totalAllocated()); } } }; CPPUNIT_TEST_SUITE_REGISTRATION(UtlLinkTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlLongLongInt.cpp0000644000175000017500000003702412205613256025622 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2010 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// #include "os/OsIntTypes.h" #include #include #include #include #include #include /** This class is used to test the UtlLongLongInt utility class. * * PLEASE READ THE README FILE THAT CAN FOUND IN THE SAME DIRECTORY AS * THIS FILE. The Readme describes the organization / flow of tests and * without reading this file, the following class (and all unit tests) * may not make a lot of sense and might be difficult to comprehend. */ class UtlLongLongIntTests : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlLongLongIntTests); CPPUNIT_TEST(testConstructor) ; CPPUNIT_TEST(testCompareTo) ; CPPUNIT_TEST(testCompareTo_NonIntll) ; CPPUNIT_TEST(testEquals) ; CPPUNIT_TEST(testEquals_NonIntll) ; CPPUNIT_TEST(testSetValue) ; CPPUNIT_TEST(testGetContainableType) ; CPPUNIT_TEST(testOperators) ; CPPUNIT_TEST_SUITE_END(); private: struct BasicIntllVerifier { const char* message ; int64_t input ; int64_t expectedValue ; } ; static const int64_t llint_Zero ; static const int64_t llint_Positive ; static const int64_t llint_Negative ; static const int INDEX_NOT_FOUND ; // An indication that the test should be ignored. static const int IGNORE_TEST ; static const BasicIntllVerifier commonTestSet[] ; static const int commonTestSetLength ; enum EqualOrCompareTest { TEST_EQUAL, TEST_COMPARE } ; public: UtlLongLongIntTests() { } void setUp() { } void tearDown() { } ~UtlLongLongIntTests() { } /** Sandbox method for experimenting with the API Under Test. * This method MUST be empty when the test drivers are being * checked in (final checkin) to the repository. */ void DynaTest() { } /** Test the constructor * * The test data for this test case is :- * a) llint = 0 * b) llint = +ve long long integer * c) llint = -ve long long integer * d) llint = max +ve long long integer * e) llint = max -ve long long integer. * The above set of data will be referred to as the * Common Data Set henceforth! The common data set has been defined * as a static const array of long long integers and a short description about * the data is in a const array of char* */ void testConstructor() { // First test the default constructor UtlLongLongInt testIntll ; const char* msg0 = "Test the default constructor" ; CPPUNIT_ASSERT_MESSAGE(msg0, UtlLongLongIntTests::llint_Zero == testIntll.getValue()) ; // Now test the single argument constructor for each of // the common test data type const char* prefix = "Test UtlLongLongInt(int value), where value = " ; for (int i = 0 ;i < commonTestSetLength; i++) { string msg ; TestUtilities::createMessage(2, &msg, prefix, commonTestSet[i].message) ; UtlLongLongInt testIntll(commonTestSet[i].input) ; int64_t actualValue = testIntll.getValue() ; CPPUNIT_ASSERT_MESSAGE(msg.data(), commonTestSet[i].expectedValue == actualValue) ; } } /** Test the compareTo method * * The test data for this test is :- * with the common data set, compare the data with * another value that is a) equal to, b) greater than * and c) less than itself */ void testCompareTo() { utlTestCompareOrEquals(TEST_COMPARE) ; } /** Test the isEqual(UtlContainable*) method. * * The test data for this test is the same as the compareTo method. */ void testEquals() { utlTestCompareOrEquals(TEST_EQUAL) ; } /* Test the isEqual method or the compareTo method. */ void utlTestCompareOrEquals(EqualOrCompareTest testType) { const char* prefix = ""; if (testType == TEST_COMPARE) { prefix = "Test the compareTo method for a Long Long Integer whose value = " ; } else if (testType == TEST_EQUAL) { prefix = "Test the isEqual method for a Long Long Integer whose value = " ; } const char* suffix1 = " - when value == arg" ; const char* suffix2 = " - when value > arg" ; const char* suffix3 = " - when value < arg" ; string msg ; struct compareToData { const char* message ; // Description about the type of test data int64_t baseValue ; // The value of the test UtlLongLongInt int64_t equalToBase ; // A Long Long Integer that is equal to the base value int64_t greaterThanBase ; // Long Long Integer that is greater than the base value int64_t lessThanBase ; // Long Long Integer that is less than the base value } ; const compareToData testData[] = { \ { "zero", 0, 0, 10, -10 }, \ { "positive integer", llint_Positive, llint_Positive, llint_Positive+10, llint_Positive-10 }, \ { "negative integer", llint_Negative, llint_Negative, llint_Negative+10, llint_Negative-10 }, \ { "integer at its maximum allowed value", INT64_MAX, INT64_MAX, IGNORE_TEST, INT64_MAX-10 }, \ { "integer at its minimum allowed value", INT64_MIN, INT64_MIN, INT64_MIN+10, IGNORE_TEST } } ; const int testCount = sizeof(testData)/sizeof(testData[0]) ; int64_t expectedForEquals = 0 ; int64_t expectedForGreaterThan = 1 ; int64_t expectedForLessThan = -1 ; // Loop to iterate through the array of test data. for (int i = 0 ; i < testCount ; i++) { UtlLongLongInt testIntll(testData[i].baseValue) ; UtlLongLongInt llintForCompare ; // ------------------------------------------------------------------------- // first test the case when the rhs's llint = base llint. llintForCompare = UtlLongLongInt(testData[i].equalToBase) ; TestUtilities::createMessage(3, &msg, prefix, \ testData[i].message, suffix1) ; if (testType == TEST_COMPARE) { int64_t actual = testIntll.compareTo(&llintForCompare) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), expectedForEquals == actual) ; } else if (testType == TEST_EQUAL) { UtlBoolean actual = testIntll.isEqual(&llintForCompare) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), actual) ; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // Now test the case where the llint's value is greater than the argument's value // In this case we SHOULD not try to compare for a llint which is at the // MINIMUM value that any llint can assume as such a llint cannot be greater // than anything else. This is bound to cause overruns thus yielding unexpected results. if (testData[i].baseValue != INT64_MIN) { llintForCompare = UtlLongLongInt(testData[i].lessThanBase) ; TestUtilities::createMessage(3, &msg, prefix, \ testData[i].message, suffix2) ; if (testType == TEST_COMPARE) { int64_t actual = testIntll.compareTo(&llintForCompare) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), expectedForGreaterThan == actual) ; } else if (testType == TEST_EQUAL) { UtlBoolean actual = testIntll.isEqual(&llintForCompare) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), !actual) ; } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // Now test the case where the integer's value is less than the argument's value // In this case we SHOULD not try to compare for an integer which is at the // MAXIMUM value that any integer can assume as such an integer cannot be less than // anything else. This is bound to cause overruns thus yielding unexpected results. if (testData[i].baseValue != INT64_MAX) { llintForCompare = UtlLongLongInt(testData[i].greaterThanBase) ; TestUtilities::createMessage(3, &msg, prefix, \ testData[i].message, suffix3) ; if (testType == TEST_COMPARE) { int64_t actual = testIntll.compareTo(&llintForCompare) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), expectedForLessThan == actual) ; } else if (testType == TEST_EQUAL) { UtlBoolean actual = testIntll.isEqual(&llintForCompare) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), !actual) ; } } // ------------------------------------------------------------------------- } // End of loop to iterate through test data. } /*!a Test the compareTo method when a non-UtlLongLongInt is passed. * */ void testCompareTo_NonIntll() { UtlString testUtlString("Test String") ; UtlLongLongInt testUtlLongLongInt(INT64_MAX) ; int64_t actual = testUtlLongLongInt.compareTo(&testUtlString) ; // If a collectable is *NOT* an Integer, then the only thing that is predictible is // that this is not equal to the argument CPPUNIT_ASSERT_MESSAGE( "Compare a Long Long Integer with a String ", (actual != 0 )) ; } /*!a Test the Equals Method when the argument passed is not a UtlLongLongInt * */ void testEquals_NonIntll() { const char* prefix = "Test the isEquals(UtlContainable other) for an Integer whose " \ "value is " ; const char* suffix = ", where other is a UtlContainable object that is not a " \ "UtlLongLongInt" ; UtlString testString("This is a test string") ; for (int i = 0 ; i < commonTestSetLength; i++) { UtlLongLongInt testIntll(commonTestSet[i].input) ; string msg ; UtlBoolean isEqual = testIntll.isEqual(&testString); TestUtilities::createMessage(3, &msg, prefix, commonTestSet[i].message, suffix) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (UtlBoolean)false, isEqual) ; } } //testEquals_NonIntll /*!a Test the setValue(llint) method. * * Test Data :- * For each type in the common dataset as the base * integer, add each type of common dataset llint */ void testSetValue() { const char* prefix = "Test the setValue(llint setter) method for a UtlLongLongInt " \ "whose value is " ; const char* suffix1 = " -- verify that the previous value is returned " ; const char* suffix2 = " -- verify that the new value has been set " ; string msg ; // For each type of UtlLongLongInt, verify that you can set // every common type of Long Long Integer. for (int i = 0 ; i < commonTestSetLength ; i++) { // Loop to test setting each common type of llint // for any given type of llint for (int j = 0 ; j < commonTestSetLength ; j++) { UtlLongLongInt baseIntll(commonTestSet[i].input) ; int64_t oldActualValue = baseIntll.setValue(commonTestSet[j].input) ; int64_t newActualValue = baseIntll.getValue() ; // Verify that the return value = previous value TestUtilities::createMessage(5, &msg, prefix, commonTestSet[i].message, \ " where setter = ", commonTestSet[j].message, \ suffix1) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), commonTestSet[i].expectedValue == \ oldActualValue) ; // Verify that the value has been set. TestUtilities::createMessage(5, &msg, prefix, commonTestSet[i].message, \ " where setter = ", commonTestSet[j].message, \ suffix2) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), commonTestSet[j].expectedValue == \ newActualValue) ; } } } //testSetValue /*!a Test the getContainableType method * * Test data = common test data set */ void testGetContainableType() { const char* prefix = "Test the getContainableType() method for a UtlLongLongInt " \ "whose value is " ; string msg ; for (int i = 0 ; i < commonTestSetLength; i++) { UtlLongLongInt testIntll(commonTestSet[i].input) ; UtlContainableType actual = testIntll.getContainableType() ; TestUtilities::createMessage(2, &msg, prefix, commonTestSet[i].message) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), string("UtlLongLongInt"), \ string(actual)) ; } } //testGetContainableType void testOperators() { UtlLongLongInt testIntll(1); CPPUNIT_ASSERT((++testIntll).getValue() == 2); CPPUNIT_ASSERT((testIntll++).getValue() == 2); CPPUNIT_ASSERT((--testIntll).getValue() == 2); CPPUNIT_ASSERT((testIntll--).getValue() == 2); // test conversion operator UtlLongLongInt testIntll2(INT64_MAX); CPPUNIT_ASSERT(testIntll2 == INT64_MAX); } //testOperators }; // ------------------- Static constant initializers ------------------------- const int64_t UtlLongLongIntTests::llint_Zero = 0; const int64_t UtlLongLongIntTests::llint_Positive = 101; const int64_t UtlLongLongIntTests::llint_Negative = -51; const UtlLongLongIntTests::BasicIntllVerifier \ UtlLongLongIntTests::commonTestSet[] = { \ {"Zero", llint_Zero, llint_Zero}, \ {"Positive Long Long Integer", llint_Positive, llint_Positive}, \ {"Negative Long Long Integer", llint_Negative, llint_Negative}, \ {"MAX VALUE Positive Long Long Integer", INT64_MAX, INT64_MAX}, \ {"MIN VALUE Negative Long Long Integer", INT64_MIN, INT64_MIN} \ } ; const int UtlLongLongIntTests::commonTestSetLength = 5 ; const int UtlLongLongIntTests::INDEX_NOT_FOUND = -1 ; const int UtlLongLongIntTests::IGNORE_TEST=-1 ; CPPUNIT_TEST_SUITE_REGISTRATION(UtlLongLongIntTests); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlRegex.cpp0000644000175000017500000002242712205613256024503 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include /** * Unit test for RegEx * * This is designed to test the encapsulation of PCRE, not PCRE itself. * These tests assume that the actual regular expression matching is * correct (although most will fail if it is not) because PCRE has its * own excellent unit tests. If you are incorporating a modified version * of PCRE, you must use its unit tests to confirm the correctness of * the modifications before this test will be useful. */ #include class UtlRegExTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlRegExTest); CPPUNIT_TEST(testInput1); CPPUNIT_TEST(testMatchInfo); CPPUNIT_TEST(testUnMatchInfo); CPPUNIT_TEST(testMatchStart); CPPUNIT_TEST(testMatchUtlInfo); CPPUNIT_TEST(testMatchUtlLookAhead); CPPUNIT_TEST(testMatchAfter); CPPUNIT_TEST(testMatchUtlLookBehind); CPPUNIT_TEST(testCopy1); CPPUNIT_TEST(testRecursionLimit); CPPUNIT_TEST_SUITE_END(); # define EXPRESSION( expression, options ) \ { if ( TheRegEx ) { delete TheRegEx; } \ TheRegEx = new RegEx( expression, options ); \ CPPUNIT_ASSERT_MESSAGE( "compiling expression /" expression "/", TheRegEx ); \ } # define SHOULD_MATCH( matches, in ) \ CPPUNIT_ASSERT_MESSAGE( "'" in "' should have matched" #matches, \ TheRegEx->Search( in ) && ( TheRegEx->SubStrings() == matches ) \ ); # define MATCH( n, matchVal ) \ CPPUNIT_ASSERT_MESSAGE( "'" matchVal "' should have been a match", \ ( strcmp( TheRegEx->Match(n), matchVal ) == 0 ) \ ); # define SHOULD_NOT_MATCH( in ) \ CPPUNIT_ASSERT_MESSAGE( "'" in "' should not have matched", \ ! TheRegEx->Search( in ) \ ); public: void testInput1() { RegEx* TheRegEx = 0; EXPRESSION( "the quick brown fox", 0 ); SHOULD_MATCH( 1, "the quick brown fox" ); MATCH( 0, "the quick brown fox" ); SHOULD_NOT_MATCH("The quick brown FOX"); SHOULD_MATCH( 1, "What do you know about the quick brown fox?" ); MATCH( 0, "the quick brown fox" ); SHOULD_NOT_MATCH("What do you know about THE QUICK BROWN FOX?"); delete TheRegEx; } void testCopy1() { static const RegEx ConstRegEx("^[a-z]+([0-9]+)$"); RegEx* TheRegEx = new RegEx(ConstRegEx); SHOULD_MATCH(2,"foo35"); MATCH(0,"foo35"); MATCH(1,"35"); SHOULD_NOT_MATCH( "abc" ); SHOULD_NOT_MATCH( "Foo35" ); SHOULD_NOT_MATCH( "12Foo35" ); SHOULD_NOT_MATCH( "foo35 " ); delete TheRegEx; } void testCopy2() { static const RegEx ConstRegEx("^[a-z]+([0-9]+)$"); RegEx TheCopiedRegEx(ConstRegEx); RegEx* TheRegEx = &TheCopiedRegEx; SHOULD_MATCH(2,"foo35"); MATCH(0,"foo35"); MATCH(1,"35"); SHOULD_NOT_MATCH( "abc" ); SHOULD_NOT_MATCH( "Foo35" ); SHOULD_NOT_MATCH( "12Foo35" ); SHOULD_NOT_MATCH( "foo35 " ); } void testMatchInfo() { RegEx matchABCs("A+(B+)(C+)"); CPPUNIT_ASSERT(matchABCs.Search("xxxAABBBBC")); CPPUNIT_ASSERT( matchABCs.Matches() == 3 ); int start; int length; CPPUNIT_ASSERT( matchABCs.Match(0, start, length)); CPPUNIT_ASSERT( start == 3 ); CPPUNIT_ASSERT( length == 7 ); CPPUNIT_ASSERT( matchABCs.Match(1, start, length)); CPPUNIT_ASSERT( start == 5 ); CPPUNIT_ASSERT( length == 4 ); CPPUNIT_ASSERT( matchABCs.Match(2, start, length)); CPPUNIT_ASSERT( start == 9 ); CPPUNIT_ASSERT( length == 1 ); } void testUnMatchInfo() { RegEx matchABCs("(A+|(B+))(C+)"); CPPUNIT_ASSERT(matchABCs.Search("xxxAACC")); CPPUNIT_ASSERT( matchABCs.Matches() == 4 ); int start; int length; CPPUNIT_ASSERT( matchABCs.Match(0, start, length)); CPPUNIT_ASSERT( start == 3 ); CPPUNIT_ASSERT( length == 4 ); CPPUNIT_ASSERT( matchABCs.Match(3, start, length)); CPPUNIT_ASSERT( start == 5 ); CPPUNIT_ASSERT( length == 2 ); CPPUNIT_ASSERT( matchABCs.Match(1, start, length)); CPPUNIT_ASSERT( start == 3 ); CPPUNIT_ASSERT( length == 2 ); CPPUNIT_ASSERT( !matchABCs.Match(2, start, length)); CPPUNIT_ASSERT( start == -1 ); CPPUNIT_ASSERT( length == 0 ); } void testMatchStart() { RegEx matchABCs("A+(B+)(C+)"); CPPUNIT_ASSERT(matchABCs.Search("xxxAABBBBC")); CPPUNIT_ASSERT( matchABCs.Matches() == 3 ); CPPUNIT_ASSERT( matchABCs.MatchStart(0) == 3 ); CPPUNIT_ASSERT( matchABCs.MatchStart(1) == 5 ); CPPUNIT_ASSERT( matchABCs.MatchStart(2) == 9 ); } void testMatchUtlInfo() { RegEx matchABCs("A+(B+)(C+)"); const char* subject = "xxxAABBBBC"; CPPUNIT_ASSERT(matchABCs.Search(subject)); CPPUNIT_ASSERT( matchABCs.Matches() == 3 ); int start; int length; CPPUNIT_ASSERT( matchABCs.Match(0, start, length)); CPPUNIT_ASSERT( start == 3 ); CPPUNIT_ASSERT( length == 7 ); CPPUNIT_ASSERT( matchABCs.Match(1, start, length)); CPPUNIT_ASSERT( start == 5 ); CPPUNIT_ASSERT( length == 4 ); CPPUNIT_ASSERT( matchABCs.Match(2, start, length)); CPPUNIT_ASSERT( start == 9 ); CPPUNIT_ASSERT( length == 1 ); CPPUNIT_ASSERT( matchABCs.SearchAt(subject, 2)); CPPUNIT_ASSERT( matchABCs.Match(0, start, length)); CPPUNIT_ASSERT( start == 3 ); CPPUNIT_ASSERT( length == 7 ); CPPUNIT_ASSERT( matchABCs.Match(1, start, length)); CPPUNIT_ASSERT( start == 5 ); CPPUNIT_ASSERT( length == 4 ); CPPUNIT_ASSERT( matchABCs.Match(2, start, length)); CPPUNIT_ASSERT( start == 9 ); CPPUNIT_ASSERT( length == 1 ); } void testMatchUtlLookAhead() { RegEx matchAs("A+(?=:)"); const char* subject = "xxxAA:x"; int start; int length; CPPUNIT_ASSERT(matchAs.Search(subject)); CPPUNIT_ASSERT( matchAs.Matches() == 1 ); CPPUNIT_ASSERT( matchAs.Match(0, start, length)); CPPUNIT_ASSERT( start == 3 ); CPPUNIT_ASSERT( length == 2 ); UtlString after; matchAs.AfterMatchString(&after); CPPUNIT_ASSERT( after.compareTo(":x") == 0 ); } void testMatchAfter() { RegEx matchBseq("A+(B+)C+"); CPPUNIT_ASSERT(matchBseq.Search("xxAABBBCCCyy")); CPPUNIT_ASSERT(matchBseq.AfterMatch(1) == 7); CPPUNIT_ASSERT(matchBseq.AfterMatch(0) == 10); } void testMatchUtlLookBehind() { RegEx matchAs("(?<=:)A+"); const char* subject = "xxx:AAyyyyy"; CPPUNIT_ASSERT(matchAs.Search(subject)); CPPUNIT_ASSERT( matchAs.Matches() == 1 ); int start; int length; CPPUNIT_ASSERT( matchAs.Match(0, start, length)); CPPUNIT_ASSERT( start == 4 ); CPPUNIT_ASSERT( length == 2 ); UtlString before; matchAs.BeforeMatchString(&before); CPPUNIT_ASSERT( before.compareTo("xxx:") == 0 ); CPPUNIT_ASSERT(matchAs.SearchAt(subject, 4)); CPPUNIT_ASSERT( matchAs.Matches() == 1 ); CPPUNIT_ASSERT( matchAs.Match(0, start, length)); CPPUNIT_ASSERT( start == 4 ); CPPUNIT_ASSERT( length == 2 ); } void testRecursionLimit() { // this pattern recurses for every character RegEx matchAs("([^<]|<(?!inet))+", 0, 100 ); /* * Because we are using a version of PCRE that does not support a limit on * recursion, this string must be much shorter than the limit. See the * cautionary note in UtlRegEx.h on MAX_RECURSION. */ UtlString okSubject( /* 45 x 'a' */ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa #include #include #include #include #include #include #include #include /** This class is used to test the UtlSList utility class. * * PLEASE READ THE README FILE THAT CAN FOUND IN THE SAME DIRECTORY AS * THIS FILE. The Readme describes the organization / flow of tests and * without reading this file, the following class (and all unit tests) * may not make a lot of sense and might be difficult to comprehend. */ class UtlSListTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlSListTest); CPPUNIT_TEST(checkSanity_Append_Entries_And_At) ; CPPUNIT_TEST(testAppend) ; CPPUNIT_TEST(testInsert) ; CPPUNIT_TEST(testInsertAt_EmptyList) ; CPPUNIT_TEST(testInsertAt_NonEmptyList) ; CPPUNIT_TEST(testFirst_And_Last) ; CPPUNIT_TEST(testIndex) ; CPPUNIT_TEST(testFind) ; CPPUNIT_TEST(testContains) ; CPPUNIT_TEST(testContainsReference) ; CPPUNIT_TEST(testOccurancesOf) ; CPPUNIT_TEST(testRemove) ; CPPUNIT_TEST(testRemoveReference) ; CPPUNIT_TEST(testRemoveAndDestroy) ; CPPUNIT_TEST(testGet) ; CPPUNIT_TEST(testIsEmpty) ; CPPUNIT_TEST(testClear) ; CPPUNIT_TEST(testClearAndDestroy) ; CPPUNIT_TEST_SUITE_END(); private: static const int commonEntriesCount ; UtlSList commonList ; UtlSList emptyList ; UtlString commonString1 ; UtlString commonString2 ; UtlString commonString3 ; UtlInt commonInt1 ; UtlInt commonInt2 ; UtlInt commonInt3 ; UtlString commonString1_clone; UtlString commonString2_clone ; UtlString commonString3_clone ; UtlInt commonInt1_clone ; UtlInt commonInt2_clone ; UtlInt commonInt3_clone ; static const char* longAlphaNumString ; static const char* regularString ; UtlContainable** commonContainables ; UtlContainable** commonContainables_Clone ; enum IndexOrContains { TEST_INDEX, TEST_FIND, TEST_CONTAINS, TEST_CONTAINS_REF } ; enum TestInsertOrAppend {TEST_APPEND, TEST_INSERT} ; enum RemoveType {TEST_REMOVE, TEST_REMOVE_REF } ; public: UtlSListTest() { commonContainables = new UtlContainable*[commonEntriesCount] ; commonContainables_Clone = new UtlContainable*[commonEntriesCount] ; } ~UtlSListTest() { delete[] commonContainables ; delete[] commonContainables_Clone ; } void setUp() { UtlContainableTestStub::clearCount() ; commonString1 = UtlString(regularString) ; commonString1_clone = UtlString(regularString) ; commonString2 = UtlString("") ; commonString2_clone = UtlString("") ; commonString3 = UtlString(longAlphaNumString) ; commonString3_clone = UtlString(longAlphaNumString) ; // If a prior test fails and we bail, the list may have junk in it commonList.removeAll(); commonInt1 = UtlInt(0) ; commonInt1_clone = UtlInt(0) ; commonInt2 = UtlInt(INT_MAX) ; commonInt2_clone = UtlInt(INT_MAX) ; commonInt3 = UtlInt(INT_MIN) ; commonInt3_clone = UtlInt(INT_MIN) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("setUp: ", 0, (int)commonList.entries()); commonList.append(&commonString1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("setUp: ", 1, (int)commonList.entries()); commonContainables[0] = &commonString1 ; commonContainables_Clone[0] = &commonString1_clone ; commonList.append(&commonInt1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("setUp: ", 2, (int)commonList.entries()); commonContainables[1] = &commonInt1 ; commonContainables_Clone[1] = &commonInt1_clone ; commonList.append(&commonInt2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("setUp: ", 3, (int)commonList.entries()); commonContainables[2] = &commonInt2 ; commonContainables_Clone[2] = &commonInt2_clone; commonList.append(&commonString2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("setUp: ", 4, (int)commonList.entries()); commonContainables[3] = &commonString2 ; commonContainables_Clone[3] = &commonString2_clone ; commonList.append(&commonInt3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("setUp: ", 5, (int)commonList.entries()); commonContainables[4] = &commonInt3 ; commonContainables_Clone[4] = &commonInt3_clone ; commonList.append(&commonString3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("setUp: ", 6, (int)commonList.entries()); commonContainables[5] = &commonString3 ; commonContainables_Clone[5] = &commonString3_clone ; } void tearDown() { commonList.removeAll(); } /** Sandbox method for experimenting with the API Under Test. * This method MUST be empty when the test drivers are being * checked in (final checkin) to the repository. */ void DynaTest() { } /*a! This test is more of a sanity check to verify that * the basic append(), entries() and at() methods work as expected. * All future tests will depend heavily on the at() method * and the most common way of having something in the list is * by means of the append() method. * */ void checkSanity_Append_Entries_And_At() { UtlString msg; for (int i = 0 ; i < commonEntriesCount; i++) { UtlContainable* ucExpected = commonContainables[i] ; UtlContainable* ucActual = commonList.at(i) ; msg = "Verify that the at(n) method, where n = "; msg.appendFormat("%d ;", i); CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), ucExpected, ucActual) ; } CPPUNIT_ASSERT_EQUAL_MESSAGE("Verify that the entries() for an empty list returns 0", \ (int)emptyList.entries(), 0) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Verify the entries() method for a list", \ (int)commonList.entries(), commonEntriesCount) ; }// checkSanity_Append_And_At() /*a! Test the append method for a list that is not empty * The test data for this test are :- * a) Append a CollectableString * b) Append a CollectableInt * */ void testAppend() { utlTestAppend_Insert(TEST_APPEND) ; } /*a! Test the insert method for a list that is not empty * * Since the insert method does exactly the same thing as * the append method, the test data for these two are the same */ void testInsert() { utlTestAppend_Insert(TEST_INSERT) ; } void utlTestAppend_Insert(TestInsertOrAppend type) { int testCount = 2 ; const char* prefix = ""; UtlInt testInt(1234) ; UtlString testString("Test String") ; if (type == TEST_APPEND) { commonList.append(&testInt) ; commonList.append(&testString) ; prefix = "Test the append(UtlContainable*) method for a non empty list" ; } else if (type == TEST_INSERT) { commonList.insert(&testInt) ; commonList.insert(&testString) ; prefix = "Test the insert(UtlContainable*) method for a non empty list" ; } int expectedCount = commonEntriesCount + testCount ; UtlContainable* uActual ; UtlContainable* uExpected ; string msg ; // Verify that the number of entries has increased accordingly TestUtilities::createMessage(2, &msg, prefix, " :- Verify the number of entries") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedCount, \ (int)commonList.entries()) ; // Verify that the first entry has still not changed. uActual = commonList.at(0) ; uExpected = commonContainables[0] ; TestUtilities::createMessage(2, &msg, prefix, \ " :- Verify that the first entry is not changed") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uActual, uExpected) ; // Verify the entry at the previous last position TestUtilities::createMessage(2, &msg, prefix, \ " :- Verify that the previous last entry is intact") ; // Verify that the number of entries has increased accordingly TestUtilities::createMessage(2, &msg, prefix, \ " :- Verify the number of entries") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedCount, \ (int)commonList.entries()) ; // Verify that the first entry has still not changed. uActual = commonList.at(0) ; uExpected = commonContainables[0] ; TestUtilities::createMessage(2, &msg, prefix, \ " :- Verify that the first entry is not changed") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uActual, uExpected) ; // Verify the entry at the previous last position TestUtilities::createMessage(2, &msg, prefix, \ " :- Verify that the previous last entry is intact") ; uActual = commonList.at(commonEntriesCount-1) ; uExpected = commonContainables[commonEntriesCount-1] ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uActual, uExpected) ; // Verify that the two new entries are added. TestUtilities::createMessage(2, &msg, prefix, \ " :- Verify that the Collectable Integer has been added") ; uActual = commonList.at(commonEntriesCount) ; uExpected = &testInt ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uActual, uExpected) ; TestUtilities::createMessage(2, &msg, prefix, \ " :- Verify that the Collectable String has been added") ; uActual = commonList.at(commonEntriesCount + 1) ; uExpected = &testString ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uActual, uExpected) ; } //testAppend /*!a! Test case to verify insertAt(size_t, UtlContainable*) for an * empty list. * The test data for this test are * a) Insert a UtlString to the 0th location, * b) Insert a UtlInt to the 0th location, * c) Insert any UtlContainable object to a 'non-zero' location */ void testInsertAt_EmptyList() { const int testCount = 3 ; const char* prefix = "Test insert(n, Collectable*) for an empty list; "\ "where Collectable is " ; const char* Msgs[] = { \ "a UtlString and n = 0", \ "a UtlInt and n = 0", \ "a UtlContainableXXX and n > 0" \ }; const char* suffix1 = " :- Verify return value" ; const char* suffix2 = " :- Verify value is appended" ; UtlInt testInt(102) ; UtlString testString("Test String") ; UtlString testNegative("This should not get added") ; UtlContainable* itemToAdd[] = { &testString, &testInt, &testNegative } ; UtlContainable* expectedValue[] = { &testString, &testInt, NULL} ; int insertLocation[] = { 0, 0, 1} ; for (int i = 0 ; i < testCount ; i++) { UtlSList testList ; string msg ; // insertAt now returns void. Retain this block of comment in case // we (I think we should return a Collectable / bool) decide to return // a collectable. UtlContainable* result = testList.insertAt(insertLocation[i], itemToAdd[i]); //verify that the right value is returned. TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValue[i], result) ; testList.insertAt(insertLocation[i], itemToAdd[i]) ; // verify that the value is inserted TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValue[i], testList.at(0)) ; } }//testInsertAt_EmptyList /*!a Test case to verify insertAt(size_t, UtlContainable*) for a * list that is not empty. * The test data for this test are * a) Insert any UtlContainable to the 0th location, * b) Insert a UtlInt to a 'mid' location, * c) Insert any UtlString object to a 'mid' location * d) Insert any UtlContainable object to the last location */ void testInsertAt_NonEmptyList() { const int testCount = 4 ; const char* prefix = "Test insert(n, Collectable*) for a list that is not empty; "\ "where Collectable is " ; const char* Msgs[] = { \ "a UtlContainableXXX and n = 0", \ "a UtlString and n > 0 && n < size", \ "a UtlInt and n > 0 && n < size", \ "a UtlContainableXXX where n = size-1" \ }; const char* suffix1 = " :- Verify return value" ; const char* suffix2 = " :- Verify value is appended" ; const char* suffix3 = " :- Verify new list size" ; UtlString testFirst("First Entry") ; UtlInt testInt(102) ; UtlString testString("Test String") ; UtlInt testLast(99999) ; UtlContainable* itemToAdd[] = { &testFirst, &testInt, &testString, &testLast } ; UtlContainable* expectedValue[] = { &testFirst, &testInt, &testString, &testLast} ; int insertLocation[] = { 0, 2, 3, commonEntriesCount+3} ; int tmpCount = commonEntriesCount ; int expectedEntries[] = {++tmpCount, ++tmpCount, ++tmpCount, ++tmpCount} ; for (int i = 0 ; i < testCount ; i++) { UtlContainable* uActual ; string msg ; // comment out for now. Uncomment if implementation returns Collectable uActual = commonList.insertAt(insertLocation[i], itemToAdd[i]); //verify that the right value is returned. TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValue[i], uActual) ; //`commonList.insertAt(insertLocation[i], itemToAdd[i]); // verify that the value is inserted TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix2) ; uActual = commonList.at(insertLocation[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValue[i], uActual) ; //verify that the total number of entries has incremented by one. TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedEntries[i], \ (int)commonList.entries()) ; } }//testInsertAt_NonEmptyList() /*!a Test case to test the first() and last() method. * * The test data for this test case is :- * a) Test the first and last element after appending * b) Test the first and last element after insertAt(midlevel) * c) Test the first and last element after insertAt(0) * d) Test the first and last element after insertAt(last) */ void testFirst_And_Last() { const char* prefix1 = "Test the first() method "; const char* prefix2 = "Test the last() method " ; string msg ; UtlContainable* uActual ; UtlContainable* uData ; UtlContainable* uExpected ; const char* Msgs[] = { \ "after appending ", \ "after insertAt(0) ", \ "after insertAt(last) ", \ "after insertAt(mid-level) " \ } ; // Since this testcase requires a different test data // for each of its test data, the regula test-matrix // technique is not being used here. // create a new list and append one element to it. UtlSList testList ; uData = commonContainables[0] ; testList.append(uData); // Test the first() and last() element immeidately after // appending to an empty list. TestUtilities::createMessage(2, &msg, prefix1, Msgs[0]); uActual = testList.first() ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uData, uActual) ; uActual = testList.last() ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[0]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uData, uActual) ; // insert more values to populate the List testList.append(commonContainables[1]) ; testList.append(commonContainables[2]) ; // test the first() / last() methods // after insertAt(0..) uData = commonContainables[3] ; testList.insertAt(0, uData) ; uExpected = commonContainables[3] ; uActual = testList.first() ; TestUtilities::createMessage(2, &msg, prefix1, Msgs[1]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uExpected, uActual) ; uExpected = commonContainables[2] ; uActual = testList.last() ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[1]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uExpected, uActual) ; // test after inserting at the last location uData = commonContainables[4] ; testList.insertAt(4, uData) ; uExpected = commonContainables[3] ; uActual = testList.first() ; TestUtilities::createMessage(2, &msg, prefix1, Msgs[2]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uExpected, uActual) ; uExpected = commonContainables[4] ; uActual = testList.last() ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[2]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uExpected, uActual) ; //test after inserting at the midLocation uData = commonContainables[5] ; testList.insertAt(2, uData) ; uExpected = commonContainables[3] ; uActual = testList.first() ; TestUtilities::createMessage(2, &msg, prefix1, Msgs[3]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uExpected, uActual) ; uExpected = commonContainables[4] ; uActual = testList.last() ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[3]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), uExpected, uActual) ; } //testFirst_And_Last /*!a Test case for the index() method * * The test data for this test case are :- * a) When the match is the first element. * b) When the match is the last element. * c) When the match is a mid element(unique). * d) When the match has two value matches (but a single ref match) * e) When the match has two ref matches. * f) When there is no match at all! */ void testIndex() { utlTestIndex_Find_And_Contains(TEST_INDEX) ; } /*!a Test case for the find() method. * * The test data for this test case are the same as * testIndex() test case. */ void testFind() { utlTestIndex_Find_And_Contains(TEST_FIND) ; } /*!a Test case for the contains() method * * The test data for this test case are the same as * testIndex() test case. */ void testContains() { utlTestIndex_Find_And_Contains(TEST_CONTAINS) ; } /*!a Test case for the containsReference() method * * The test data for this test case are the same as * testIndex() test case. */ void testContainsReference() { utlTestIndex_Find_And_Contains(TEST_CONTAINS_REF) ; } // Since the test setup / preconditions for the index, find, // contains and containsReference are all the same, these // tests have been combined into one utility function. Based // on the type argument, the method to be tested is varied. void utlTestIndex_Find_And_Contains(IndexOrContains type) { const int testCount = 7 ; const char* prefixIndex = "Test the index() method when the match " ; const char* prefixFind = "Test the find() method when the match " ; const char* prefixContains = "Test the contains() method when the match " ; const char* prefixContainsRef = "Test the containsReference() method when the match " ; const char* Msgs[] = { \ "is the first element ", \ "is the last element ", \ "is a mid element (unique match) ", \ "has two value matches but a single ref match ", \ "has two ref matches", \ "has a value match but no ref match", \ "has no match at all" \ } ; // insert a clone of the 4th element to the 1st position commonList.insertAt(1, commonContainables_Clone[4]) ; // The new index for a value match of commonContainables[4] must be 1. // insert another copy of the 3rd element to the 2nd position. commonList.insertAt(2, commonContainables[3]) ; // The new index for commonContainables[3] must be 2) ; // what used to be the second element has now moved to 4. UtlString noExist("This cannot and should not exist!!!") ; UtlContainable* searchValues[] = { \ commonContainables[0], commonContainables[5], commonContainables[2], \ commonContainables[4], commonContainables[3], \ commonContainables_Clone[2], &noExist \ } ; size_t expectedValues_Index[] = { 0, 7, 4, 1, 2, 4, UTL_NOT_FOUND } ; bool expectedValues_Contains[] = {true, true, true, true, true, true, false } ; bool expectedValues_ContainsRef[] = {true, true, true, true, true, false, false} ; UtlContainable* searchValuesForFind[] = { \ commonContainables[0], commonContainables[5], commonContainables[2], \ commonContainables[4], commonContainables[3], \ commonContainables_Clone[1], &noExist \ } ; UtlContainable* expectedValuesForFind[] = { \ commonContainables[0], commonContainables[5], commonContainables[2], \ commonContainables_Clone[4], commonContainables[3], \ commonContainables[1], NULL \ } ; for (int i = 0 ; i < testCount ; i++) { string msg ; if (type == TEST_INDEX) { size_t actual = commonList.index(searchValues[i]) ; TestUtilities::createMessage(2, &msg, prefixIndex, Msgs[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValues_Index[i], actual) ; } else if (type == TEST_FIND) { UtlContainable* actual = commonList.find(searchValuesForFind[i]) ; TestUtilities::createMessage(2, &msg, prefixFind, Msgs[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValuesForFind[i], actual) ; } else if (type == TEST_CONTAINS) { UtlBoolean actual = commonList.contains(searchValues[i]) ; TestUtilities::createMessage(2, &msg, prefixContains, Msgs[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValues_Contains[i], \ (TRUE == actual)) ; } else if (type == TEST_CONTAINS_REF) { UtlBoolean actual = commonList.containsReference(searchValues[i]) ; TestUtilities::createMessage(2, &msg, prefixContainsRef, Msgs[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValues_ContainsRef[i], \ (TRUE == actual)) ; } } }//utlTestIndex /*!a Test the occurancesOf() method . * * The test data for this test are :- * a) When the search data is the first entry * b) When the search data is the last entry * c) When the search data is the mid(unique) entry * d) When the search data has a matching value but not ref. * e) When the search data has multiple matches - mixture of ref / values * f) When the search data has no match at all. */ void testOccurancesOf() { const int testCount = 6 ; const char* prefix = "Test the occurancesOf(UtlContainable* cl); where cl " ; const char* Msgs[] = { \ "is the first entry ", \ "is the last entry and ref matches ", \ "is the mid entry and is unique ", \ "has a matching value but not reference ", \ "has multiple matches ", \ "has no match at all " \ } ; commonList.insertAt(3, commonContainables_Clone[4]) ; commonList.insertAt(5, commonContainables[4]) ; UtlString notExistCollectable("This cannot and willnot exist"); UtlContainable* searchValues[] = { \ commonContainables[0], commonContainables[commonEntriesCount -1], \ commonContainables[2], commonContainables_Clone[3], \ commonContainables[4], ¬ExistCollectable \ } ; size_t matchCount[] = { 1, 1, 1, 1, 3, 0 } ; for (int i = 0 ; i < testCount ; i++) { string msg ; TestUtilities::createMessage(2, &msg, prefix, Msgs[i]) ; size_t actual = commonList.occurrencesOf(searchValues[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), matchCount[i], actual) ; } } //testOccurancesOf /*!a Test case for testRemove() * * The Test data for this test case is * a) is the first entry's reference * b) is the last entry' reference * c) is the mid entry's value(not reference) * d) is the first of multiple matches and is the value match * e) has no match at all */ void testRemove() { utlTestRemove(TEST_REMOVE) ; } /*!a Test case for testRemoveReference() * * The test data for this test case is * the same as teh remove() method. */ void testRemoveReference() { utlTestRemove(TEST_REMOVE_REF) ; } /*!a Test case to test the destroy() * method. */ void testRemoveAndDestroy() { const char* prefix = "test the destroy() method " ; UtlContainableTestStub uStub(0) ; UtlContainableTestStub* uStubPtr ; uStubPtr = new UtlContainableTestStub(1) ; commonList.append(&uStub) ; commonList.append(uStubPtr) ; int cCountBefore = UtlContainableTestStub :: getCount() ; UtlBoolean returnValue = commonList.destroy(uStubPtr) ; UtlContainable* uLast = commonList.last() ; string msg ; TestUtilities::createMessage(2, &msg, prefix, ":- Verify the return value") ; CPPUNIT_ASSERT_MESSAGE(msg.data(), returnValue) ; TestUtilities::createMessage(2, &msg, prefix, ":- Verify that the entry is removed") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)&uStub, (void*)uLast) ; // The CollectableTestStub has been implemented such that a static counter gets decremented // for every descruction of an object instance. To verify that the object was destroyed, // verify that the static count went down. int cCountAfter = UtlContainableTestStub :: getCount() ; TestUtilities::createMessage(2, &msg, prefix, ":- Verify that the object was deleted") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), cCountBefore -1, cCountAfter) ; } void utlTestRemove(RemoveType type) { int testCount = 5 ; const char* prefix = ""; if (type == TEST_REMOVE) { prefix = "test the remove(UtlContainable* c) method where c" ; } else if (type == TEST_REMOVE_REF) { prefix = "test the removeReference(UtlContainable* c) where c" ; } const char* Msgs[] = { \ "is the first entry's reference ", \ "is the last entry' reference ", \ "is the mid entry's value(not reference) ", \ "is the first of multiple matches and is the value match ", \ "has no match at all " \ } ; const char* suffix1 = " :- Verify returned value" ; const char* suffix2 = " :- Verify total entries" ; commonList.insertAt(2, commonContainables_Clone[4]) ; UtlString notExistCollectable("This cannot and willnot exist"); UtlContainable* itemToRemove[] = { \ commonContainables[0], commonContainables[commonEntriesCount -1 ], \ commonContainables_Clone[2], commonContainables[4], \ ¬ExistCollectable \ } ; int totalEnt = commonEntriesCount + 1; UtlContainable* expectedValue[] = { \ commonContainables[0], commonContainables[commonEntriesCount -1 ], \ commonContainables[2], commonContainables_Clone[4], \ NULL \ }; int entriesValue[] = { --totalEnt, --totalEnt, --totalEnt, --totalEnt, totalEnt } ; totalEnt = commonEntriesCount + 1; UtlContainable* expectedRef[] = { \ commonContainables[0], commonContainables[commonEntriesCount -1 ], \ NULL, commonContainables[4], \ NULL \ }; int entriesRef[] = { --totalEnt, --totalEnt, totalEnt, --totalEnt, totalEnt } ; for (int i = 0 ; i < testCount ; i++) { string msg ; if (type == TEST_REMOVE) { TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix1) ; UtlContainable* retValue = commonList.remove(itemToRemove[i]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValue[i], retValue) ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), entriesValue[i], (int)commonList.entries()) ; } else if (type == TEST_REMOVE_REF) { UtlContainable* uRemoved = commonList.removeReference(itemToRemove[i]) ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedRef[i], uRemoved) ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), entriesRef[i], (int)commonList.entries()) ; } } } //utlRemove /*!a Test case for the get() method. * * The test data for this test is :- * 1) The first entry is a CollectableString * 2) The first entry is a CollectableInt * 3) The List has only one entry * 4) The List has no entries */ void testGet() { const int testCount = 4 ; const char* prefix = "Verify the get() method for a list when " ; const char* Msgs[] = { \ "the first entry is a CollectableString", \ "the first entry is a CollectableInt", \ "when the list has only one entry", \ "when the list is empty" \ } ; const char* suffix1 = ":- verify return value" ; const char* suffix2 = ":- verify the number of entries in the list" ; UtlSList testList ; testList.append(&commonString1) ; testList.append(&commonInt1) ; testList.append(&commonString2) ; UtlContainable* expectedValue[] = { \ &commonString1 , &commonInt1, &commonString2, NULL \ } ; int entryCount[] = { 2, 1, 0, 0 } ; for (int i = 0 ; i < testCount ; i++) { UtlContainable* actual = testList.get() ; string msg ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedValue[i], actual) ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), entryCount[i], (int)testList.entries()) ; } } //testGet() /*!a Test case for the isEmpty() method. * The test data for this test are :- * a) When the list has just been created. * b) When the list has one entry in it * c) When the list has multiple entries in it. * d) When all the entries in a list have been removed using get. * e) When all the entries in a list have been removed using removeAll() */ void testIsEmpty() { const int testCount = 5 ; const char* prefix = "Test the isEmpty() method when " ; const char* Msgs[] = { \ "the list has just been created" , \ "the list has just one entry in it", \ "the list has multiple entries in it", \ "all the list entries have been retreieved using get()", \ "all the list entries have been retreived using removeAll()" \ } ; UtlSList newList ; UtlSList secondNewList ; UtlSList commonList_Clone ; // first populate a list and then retreive all elements using get for (int i = 0 ; i < commonEntriesCount ; i++) { commonList_Clone.append(commonContainables_Clone[i]) ; } for (int j = 0 ; j < commonEntriesCount; j++) { commonList_Clone.get(); } UtlString uS1 = UtlString("Lone Entry") ; newList.append(&uS1) ; // populate the second list and then clear all entries. secondNewList.append(&uS1) ; UtlInt uI1 = UtlInt(232) ; secondNewList.append(&uI1) ; secondNewList.removeAll() ; UtlSList* testLists[] = { \ &emptyList, &newList, &commonList, &commonList_Clone, &secondNewList \ } ; bool expectedValue[] = { true, false, false, true, true } ; for (int k = 0 ; k < testCount; k++) { string msg ; TestUtilities::createMessage(2, &msg, prefix, Msgs[k]) ; UtlBoolean actual = testLists[k] -> isEmpty() ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (UtlBoolean)expectedValue[k], \ actual) ; } } // testIsEmpty /*!a test the removeAll() method. * * The test data for this method is * a) When the list is empty * b) When the list has one entry. * c) When the list multiple entries * d) When removeAll has been called and entries are added again * d) When the removeAll is called twice on the list. */ void testClear() { const int testCount = 5 ; const char* prefix = "Test the removeAll() method when :- " ; const char* Msgs[] = { \ "the list is empty", \ "the list has one entry", \ "the list has multiple entries", \ "removeAll() has been called and entries are added again", \ "removeAll() has already been called", \ } ; const char* suffix = " :- Verify number of entries after removeAll()" ; UtlSList uSingleList ; UtlSList uAddAfterClear ; UtlSList uDoubleClear ; uSingleList.append(&commonString1) ; // call removeAll() on a list and then add entries again. uAddAfterClear.append(&commonInt1) ; uAddAfterClear.append(&commonString1) ; uAddAfterClear.removeAll() ; uAddAfterClear.append(&commonInt2) ; // call removeAll on a list twice. uDoubleClear.append(&commonString3) ; uDoubleClear.append(&commonInt3) ; uDoubleClear.removeAll() ; UtlSList* testLists[] = { \ &emptyList, &uSingleList, &commonList, &uAddAfterClear, &uDoubleClear } ; int expectedEntries[] = { 0 , 0, 0, 1, 0 } ; // since we are not calling removeAll for all the data, do it outside the for loop. emptyList.removeAll() ; uSingleList.removeAll() ; commonList.removeAll() ; // no removeAll() for uAddAfterClear uDoubleClear.removeAll() ; for ( int i = 0 ; i < testCount ; i++) { string msg ; TestUtilities::createMessage(3, &msg, prefix, Msgs[i], suffix) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data() , expectedEntries[i], \ (int)testLists[i]->entries()) ; } } //testClear() /*!a Test case to test the destroyAll() * method. */ void testClearAndDestroy() { const char* prefix = "test the destroyAll() method " ; const char* suffix1 = ":- Verify that all entries are removed" ; const char* suffix2 = ":- The objects are deleted" ; UtlContainableTestStub* uStub ; UtlContainableTestStub* uStubPtr ; uStub = new UtlContainableTestStub(0) ; uStubPtr = new UtlContainableTestStub(1) ; emptyList.append(uStub) ; emptyList.append(uStubPtr) ; emptyList.destroyAll() ; int cCountAfter = UtlContainableTestStub::getCount() ; string msg ; TestUtilities::createMessage(2, &msg, prefix, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), 0, (int)emptyList.entries()) ; // Since the TestStub has been implemented such that destructor // decrements the static counter, to verify that the objects have // been deleted, verify that the static counter has been decremented. TestUtilities::createMessage(2, &msg, prefix, suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), 0, cCountAfter) ; } //testClearAndDestroy }; const int UtlSListTest::commonEntriesCount = 6; const char* UtlSListTest::longAlphaNumString = \ "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvw" ; const char* UtlSListTest::regularString = "This makes sense" ; CPPUNIT_TEST_SUITE_REGISTRATION(UtlSListTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlSListIteratorTest.cpp0000644000175000017500000006050312205613256027036 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include #include #include /** This class is used to test the UtlSListIterator utility class. * * PLEASE READ THE README FILE THAT CAN FOUND IN THE SAME DIRECTORY AS * THIS FILE. The Readme describes the organization / flow of tests and * without reading this file, the following class (and all unit tests) * may not make a lot of sense and might be difficult to comprehend. */ class UtlSListIteratorTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlSListIteratorTest); CPPUNIT_TEST(testAdvancingOperator) ; CPPUNIT_TEST(testFindNext) ; CPPUNIT_TEST(testFindNextForDummies) ; CPPUNIT_TEST(testLast) ; CPPUNIT_TEST(testOffEnd); CPPUNIT_TEST(testInsertAfterPoint_EmptyList) ; CPPUNIT_TEST(testInsertAfterPoint) ; CPPUNIT_TEST_SUITE_END(); private: static const int INDEX_NOT_EXIST ; static const int commonEntriesCount ; UtlSList commonList ; UtlSList emptyList ; UtlString commonString1 ; UtlString commonString2 ; UtlString commonString3 ; UtlInt commonInt1 ; UtlInt commonInt2 ; UtlInt commonInt3 ; UtlString commonString1_clone; UtlString commonString2_clone ; UtlString commonString3_clone ; UtlInt commonInt1_clone ; UtlInt commonInt2_clone ; UtlInt commonInt3_clone ; static const char* longAlphaNumString ; static const char* regularString ; UtlContainable** commonContainables; UtlContainable** commonContainables_Clone; enum IndexOrContains { TEST_INDEX, TEST_FIND, TEST_CONTAINS, TEST_CONTAINS_REF } ; enum TestInsertOrAppend {TEST_APPEND, TEST_INSERT} ; enum RemoveType {TEST_REMOVE, TEST_REMOVE_REF } ; public: void setUp() { commonString1 = UtlString(regularString) ; commonString1_clone = UtlString(regularString) ; commonString2 = UtlString("") ; commonString2_clone = UtlString("") ; commonString3 = UtlString(longAlphaNumString) ; commonString3_clone = UtlString(longAlphaNumString) ; commonInt1 = UtlInt(0) ; commonInt1_clone = UtlInt(0) ; commonInt2 = UtlInt(INT_MAX) ; commonInt2_clone = UtlInt(INT_MAX) ; commonInt3 = UtlInt(INT_MIN) ; commonInt3_clone = UtlInt(INT_MIN) ; // Need to make sure list is empty from prior run contents commonList.removeAll(); commonList.append(&commonString1) ; commonContainables[0] = &commonString1 ; commonContainables_Clone[0] = &commonString1_clone ; commonList.append(&commonInt1) ; commonContainables[1] = &commonInt1 ; commonContainables_Clone[1] = &commonInt1_clone ; commonList.append(&commonInt2) ; commonContainables[2] = &commonInt2 ; commonContainables_Clone[2] = &commonInt2_clone; commonList.append(&commonString2) ; commonContainables[3] = &commonString2 ; commonContainables_Clone[3] = &commonString2_clone ; commonList.append(&commonInt3) ; commonContainables[4] = &commonInt3 ; commonContainables_Clone[4] = &commonInt3_clone ; commonList.append(&commonString3) ; commonContainables[5] = &commonString3 ; commonContainables_Clone[5] = &commonString3_clone ; } void tearDown() { } /** Sandbox method for experimenting with the API Under Test. * This method MUST be empty when the test drivers are being * checked in (final checkin) to the repository. */ void DynaTest() { } UtlSListIteratorTest() { commonContainables = new UtlContainable*[commonEntriesCount] ; commonContainables_Clone = new UtlContainable*[commonEntriesCount] ; } ~UtlSListIteratorTest() { delete[] commonContainables ; delete[] commonContainables_Clone ; } /*!a Test case for the () operator. * * The test data for this test is :- * 1) The next entry is a UtlString * 2) The next entry is a UtlInt * 3) The next entry is the last entry * 4) All entries have been read */ void testAdvancingOperator() { struct TestAdvancingOperatorStruct { const char* testDescription ; const UtlContainable* expectedValue ; } ; const int testCount = 4 ; const char* prefix = "Verify the () operator for an iterator when " ; const char* suffix1 = " :- verify return value" ; const char* suffix2 = " :- verify number of entries in the list" ; UtlSList testList ; testList.append(&commonString1) ; testList.append(&commonInt1) ; testList.append(&commonString2) ; UtlSListIterator iter(testList) ; TestAdvancingOperatorStruct testData[] = { \ { "the first entry is a UtlString", &commonString1 }, \ { "the first entry is a UtlInt", &commonInt1 }, \ { "when the list has only one entry", &commonString2 }, \ { "when the list is empty", NULL } \ } ; int expectedEntries = 3 ; for (int i = 0 ; i < testCount ; i++) { string msg ; TestUtilities::createMessage(3, &msg, prefix, \ testData[i].testDescription, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)testData[i].expectedValue, \ (void*)iter()) ; TestUtilities::createMessage(3, &msg, prefix, testData[i].testDescription, \ suffix2); CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), expectedEntries, \ (int)testList.entries()) ; } // Test the () operator for an empty list UtlSListIterator emptyIter(emptyList) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Test the () operator for an empty list iterator" , \ (void*)NULL, (void*)emptyIter()) ; } //testAdvancingOperator() /** * Test for SListIterator::findNext only at places that could break * - find item not in list * - find items at endpoints * - find items after reseting iterator */ void testFindNextForDummies() { UtlString fruitData[] = { UtlString("apple"), // 0 UtlString("orange"), // 1 UtlString("banana"), // 2 UtlString("apple"), // 3 UtlString("banana"), // 4 UtlString("apple") // 5 }; int n = sizeof(fruitData) / sizeof(fruitData[0]); UtlSList fruit; for (int i = 0; i < n; i++) { fruit.append(&fruitData[i]); } // nonexistant items UtlSListIterator pineapples(fruit); UtlString pineapple("pineapple"); CPPUNIT_ASSERT_MESSAGE("Do not find item not in list", pineapples.findNext(&pineapple) == NULL); // test items at endpoints UtlSListIterator apples(fruit); UtlString apple("apple"); CPPUNIT_ASSERT_MESSAGE("Find first item", apples.findNext(&apple) == &fruitData[0]); CPPUNIT_ASSERT_MESSAGE("Find second item", apples.findNext(&apple) == &fruitData[3]); CPPUNIT_ASSERT_MESSAGE("Find third item", apples.findNext(&apple) == &fruitData[5]); CPPUNIT_ASSERT_MESSAGE("Find no more items", apples.findNext(&apple) == NULL); // test scattered items UtlSListIterator bananas(fruit); UtlString banana("banana"); CPPUNIT_ASSERT_MESSAGE("Find first item", bananas.findNext(&banana) == &fruitData[2]); CPPUNIT_ASSERT_MESSAGE("Find second item", bananas.findNext(&banana) == &fruitData[4]); CPPUNIT_ASSERT_MESSAGE("Find no more items", bananas.findNext(&banana) == NULL); // test adjustments in iterator UtlSListIterator picker(fruit); CPPUNIT_ASSERT_MESSAGE("Find first item", picker.findNext(&apple) == &fruitData[0]); picker.reset(); CPPUNIT_ASSERT_MESSAGE("Find first item again after reset", picker.findNext(&apple) == &fruitData[0]); CPPUNIT_ASSERT_MESSAGE("Find second item after initial reset", picker.findNext(&apple) == &fruitData[3]); } /*!a Test case for the findNext() method * * The test data for this test case are :- * a) When the match is the first element. * b) When the match is the last element. * c) When the match is a mid element(unique). * d) When the match has two value matches (but a single ref match) * e) When the match has two ref matches. * f) When there is no match at all! * g) When the match is after the current find. */ void testFindNext() { struct TestFindNextStruct { const char* testDescription ; const UtlContainable* searchValue ; const UtlContainable* expectedValue ; } ; const char* prefix = "Test the find() method when the match " ; UtlString noExist("This cannot and should not exist!!!") ; TestFindNextStruct testData[] = { \ { "is the first element ", commonContainables[0], commonContainables[0] }, \ { "is the last element ", commonContainables[5], commonContainables[5] }, \ { "is a mid element (unique match) ", commonContainables[2], \ commonContainables[2] }, \ { "has two value matches but a single ref match ", commonContainables[4], \ commonContainables_Clone[4] }, \ { "has two ref matches", commonContainables[3], commonContainables[3] }, \ { "has a value match but no ref match", commonContainables_Clone[1], \ commonContainables[1] }, \ { "has no match at all", &noExist, NULL } \ } ; // insert a clone of the 4th element to the 1st position commonList.insertAt(1, (UtlContainable*)commonContainables_Clone[4]) ; // The new index for a value match of commonContainables[4] must be 1. // insert another copy of the 3rd element to the 2nd position. commonList.insertAt(2, (UtlContainable*)commonContainables[3]) ; // The new index for commonContainables[3] must be 2) ; // what used to be the second element has now moved to 4. const int testCount = sizeof(testData)/sizeof(testData[0]) ; UtlSListIterator iter(commonList) ; for (int i = 0 ; i < testCount ; i++) { string msg ; const UtlContainable* actualValue = iter.findNext(testData[i].searchValue) ; TestUtilities::createMessage(2, &msg, prefix, testData[i].testDescription) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), testData[i].expectedValue, \ actualValue) ; iter.reset() ; } // Now test the case where the iterator is 'past' the index iter.reset() ; iter() ; iter() ; iter() ; iter() ; iter() ; UtlContainable* actualValue = iter.findNext(commonContainables[1]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("test findNext() when the iterator has " \ "moved past the search index", (void*)NULL, (void*)actualValue) ; }//testFindNext /*!a Test case to test the toLast() and atLast() methods. * * The test data for this test case is :- * a) An empty list * b) A non-empty list iterator that is in its initial position * c) A non-empty list iterator that is in its last position. * d) A non-empty list that is in its mid position */ void testLast() { UtlSList testList ; const char* prefix1 = "Test the toLast() method for " ; const char* prefix2 = "Test the atLast() method(after calling toLast()) for " ; string msg ; UtlContainable* actualValue ; bool isAtLast = false ; const char* Msgs[] = { \ "an empty list iterator ", \ "a list iterator that is in its zeroth position ", \ "a non empty list that is already in its last position ", \ "a non empty list that is in its mid position " \ } ; UtlSListIterator iter(emptyList) ; UtlSListIterator iter2(commonList) ; // since this test requires adifferent test setup for each // of the test data, tests are done individually rather than using // the test array style of testing. // Test#1 - Test the methods for an empty list. int ti = 0 ; iter.toLast() ; isAtLast = (TRUE == iter.atLast()) ; actualValue = iter() ; TestUtilities::createMessage(2, &msg, prefix1, Msgs[ti]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)NULL, (void*)actualValue) ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[ti]) ; // since the list is empty, any position is __PAST__ the last position CPPUNIT_ASSERT_MESSAGE(msg.data(), !isAtLast) ; // Test#2 - Test the methods for a list that is not empty. ti++ ; iter2.reset() ; iter2.toLast() ; isAtLast = (TRUE == iter2.atLast()) ; actualValue = iter2() ; TestUtilities::createMessage(2, &msg, prefix1, Msgs[ti]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)NULL, (void*)actualValue) ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[ti]) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), isAtLast) ; // Test#3 - Test the methods for a list that is not empty when // the list is already in its last position. ti++ ; iter2.reset() ; iter2.toLast() ; iter2.toLast() ; isAtLast = (TRUE == iter2.atLast()) ; actualValue = iter2() ; TestUtilities::createMessage(2, &msg, prefix1, Msgs[ti]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)NULL, (void*)actualValue) ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[ti]) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), isAtLast) ; // Test#4 - Test the methods for a list that is not empty when the // list has been iterated to somewhere in its middle position. ti++ ; iter2.reset() ; iter2() ; iter2() ; iter2.toLast() ; isAtLast = (TRUE == iter2.atLast()) ; actualValue = iter2() ; TestUtilities::createMessage(2, &msg, prefix1, Msgs[ti]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)NULL, (void*)actualValue) ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[ti]) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), isAtLast) ; } //testFirst_And_Last /*!a Test case to test walking off the end of a list * * The test data for this test case is :- * a) An empty list * b) A non-empty list */ void testOffEnd() { UtlSList testList ; const char* prefix1 = "Test the ()() method after end of the list for " ; const char* prefix2 = "Test the atLast() method after end of the list for " ; string msg ; UtlContainable* actualValue ; bool isAtLast = false ; const char* Msgs[] = { \ "an empty list iterator ", \ "a list iterator that is in its zeroth position ", \ "a non empty list that is already in its last position ", \ "a non empty list that is in its mid position " \ } ; UtlSListIterator iter(emptyList) ; UtlSListIterator iter2(commonList) ; // since this test requires adifferent test setup for each // of the test data, tests are done individually rather than using // the test array style of testing. // Test#1 - Test the methods for an empty list. int ti = 0 ; iter.toLast() ; CPPUNIT_ASSERT(iter()==NULL); actualValue=iter(); isAtLast = (TRUE == iter.atLast()) ; TestUtilities::createMessage(2, &msg, prefix1, Msgs[ti]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)NULL, (void*)actualValue) ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[ti]) ; // since the list is empty, any position is __PAST__ the last position CPPUNIT_ASSERT_MESSAGE(msg.data(), !isAtLast) ; // Test#2 - Test the methods for a list that is not empty. ti++ ; iter2.toLast() ; CPPUNIT_ASSERT(iter2()==NULL);// go off the end isAtLast = (TRUE == iter2.atLast()) ; actualValue = iter2() ; TestUtilities::createMessage(2, &msg, prefix1, Msgs[ti]) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)NULL, (void*)actualValue) ; TestUtilities::createMessage(2, &msg, prefix2, Msgs[ti]) ; CPPUNIT_ASSERT_MESSAGE(msg.data(), !isAtLast) ; } //testOffEnd /*!a Test case for the insertAfterPoint() method when the * the list is empty */ void testInsertAfterPoint_EmptyList() { const char* prefix = "Test the insertAfterPoint() method for an empty list " ; const char* suffix1 = ":- Verify return value" ; const char* suffix2 = ":- Verify that the entry has been added" ; string msg ; UtlSListIterator iter(emptyList) ; const UtlContainable* uReturn = \ iter.insertAfterPoint((UtlContainable*)commonContainables[0]) ; TestUtilities::createMessage(2, &msg, prefix, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)commonContainables[0], \ (void*)uReturn) ; iter.reset() ; UtlContainable* uAppended = iter() ; TestUtilities::createMessage(2, &msg, prefix, suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)commonContainables[0], \ (void*)uAppended) ; } /*!a Test case for the insertAfterPoint() method. * * The test data is :- * a) Insert when the iterator is the starting position * b) Insert when the iterator is at mid position * c) Insert when the iterator is at the last position * d) Insert to an empty Iterator. */ void testInsertAfterPoint() { struct TestInsertAfterStruct { const char* testDescription; UtlContainable* insertValue ; UtlContainable* oldValue ; }; const char* prefix = "Test the insertAfterPoint() method when " ; const char* suffix1 = ":- Verify return value" ; const char* suffix2 = ":- Verify value is inserted" ; const char* suffix3 = ":- Verify that previous value is not lost" ; string msg ; UtlSListIterator iter(commonList) ; UtlString newColString1("Insert at starting position") ; UtlInt newColInt2(101) ; UtlString newColString3 ("Insert at last position") ; TestInsertAfterStruct testData[] = { \ { "the iterator is the starting position " , &newColString1, \ commonContainables[0] }, \ { "the iterator is at mid-position ", &newColInt2, commonContainables[1] }, \ { "the iterator is at the last position ", &newColString3, \ commonContainables[5] } \ }; const UtlContainable* uReturn ; UtlContainable* uAppended ; UtlContainable* originalValue ; // Since this test requires different steps for the different test data, // steps are executed individually rather than the regular technique of // iterating through the test-array loop //Test#1 - Verify the case when the iterator has been reset int ti = 0 ; iter.reset() ; uReturn = iter.insertAfterPoint(testData[ti].insertValue) ; TestUtilities::createMessage(3, &msg, prefix, testData[ti].testDescription, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE (msg.data(), (void*)testData[ti].insertValue, \ (void*)uReturn) ; // The item is inserted at first position // old[0] is now @ pos1. old[1] is now @ pos2 iter.reset() ; uAppended = iter() ; TestUtilities::createMessage(3, &msg, prefix, testData[ti].testDescription, suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)testData[ti].insertValue, \ (void*)uAppended) ; // Verify that the original item is still retained. originalValue = iter() ; TestUtilities::createMessage(3, &msg, prefix, testData[ti].testDescription, suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)testData[ti].oldValue, \ (void*)originalValue) ; //Test#2 - inserting at mid position ti = 1; iter.reset() ; iter() ; //moves cursor to 0 iter() ; //moves cursor to 1 iter() ; //moves cursor to 2 // Value is now inserted after pos2 (to pos3) // old[1] stays at pos2 uReturn = iter.insertAfterPoint(testData[ti].insertValue) ; TestUtilities::createMessage(3, &msg, prefix, testData[ti].testDescription, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE (msg.data(), (void*)testData[ti].insertValue, \ (void*)uReturn) ; iter.reset() ; iter() ; // moves cursor to 0 iter() ; // moves cursor to 1 // Verify that the original item is still retained. originalValue = iter() ; TestUtilities::createMessage(3, &msg, prefix, testData[ti].testDescription, suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)testData[ti].oldValue, \ (void*)originalValue) ; // The item is inserted just after the position. uAppended = iter() ; //moves cursor to pos3 and returns item at pos2 TestUtilities::createMessage(3, &msg, prefix, testData[ti].testDescription, suffix3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)testData[ti].insertValue, \ (void*)uAppended) ; // Test#3 - Now verify when the cursor is at the last position. ti = 2 ; iter.reset() ; iter.toLast() ; uReturn = iter.insertAfterPoint(testData[ti].insertValue) ; TestUtilities::createMessage(3, &msg, prefix, testData[ti].testDescription, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)testData[ti].insertValue, \ (void*)uReturn) ; iter.reset() ; // now move the cursor all the way to the penultimate position for (size_t i = 0 ; i < commonList.entries() - 1; i++) { originalValue = iter() ; } // verify original is still retained. TestUtilities::createMessage(3, &msg, prefix, testData[ti].testDescription, suffix3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), (void*)testData[ti].oldValue, \ (void*)originalValue) ; uAppended = iter() ; TestUtilities::createMessage(3, &msg, prefix, testData[ti].testDescription, suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE( msg.data(), (void*)testData[ti].insertValue, \ (void*)uAppended) ; } //testInsertAfterPoint }; const int UtlSListIteratorTest::INDEX_NOT_EXIST = -1; const int UtlSListIteratorTest::commonEntriesCount = 6; const char* UtlSListIteratorTest::longAlphaNumString = \ "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvw" ; const char* UtlSListIteratorTest::regularString = "This makes sense" ; CPPUNIT_TEST_SUITE_REGISTRATION(UtlSListIteratorTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlSortedList.cpp0000644000175000017500000010312412205613256025517 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include #include #include #include /** This class is used to test the UtlInt utility class. * * PLEASE READ THE README FILE THAT CAN FOUND IN THE SAME DIRECTORY AS * THIS FILE. The Readme describes the organization / flow of tests and * without reading this file, the following class (and all unit tests) * may not make a lot of sense and might be difficult to comprehend. */ class UtlSortedListTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlSortedListTest); CPPUNIT_TEST(checkSanity_Insert_Entries_And_At) ; CPPUNIT_TEST(testInsert_StringList); CPPUNIT_TEST(testInsert_IntList); CPPUNIT_TEST(testInsert_MixedContainableObjects) ; CPPUNIT_TEST(testInsert_LikeExistingItem); CPPUNIT_TEST(testIndex) ; CPPUNIT_TEST(testFind) ; CPPUNIT_TEST(testContains) ; CPPUNIT_TEST(testRemove) ; CPPUNIT_TEST(testRemoveAt) ; CPPUNIT_TEST(testDestroy) ; CPPUNIT_TEST(testRemoveAll) ; CPPUNIT_TEST(testDestroyAll) ; CPPUNIT_TEST(testIsEmpty) ; CPPUNIT_TEST_SUITE_END(); private: struct TestSortedListStruct { const char* testDescription ; UtlContainable* item ; size_t expectedIndex ; }; enum FindOrContains { TEST_FIND, TEST_CONTAINS} ; enum RemoveType { REMOVE_CONTAINABLE, REMOVE_INDEX } ; static const int INDEX_NOT_EXIST ; static const int stringListCount ; static const int intListCount ; UtlSortedList emptyList ; UtlSortedList stringList ; UtlSortedList intList ; TestSortedListStruct* testDataForStringList ; TestSortedListStruct* testDataForIntList ; public: UtlSortedListTest() { testDataForStringList = new TestSortedListStruct[stringListCount] ; testDataForIntList = new TestSortedListStruct[stringListCount] ; } ~UtlSortedListTest() { for (int i = 0 ; i < stringListCount; i++) { delete testDataForStringList[i].item ; } for (int j = 0 ; j < stringListCount; j++) { delete testDataForIntList[j].item ; } delete[] testDataForStringList ; delete[] testDataForIntList ; } void setUp() { // In case a prior test aborts and tearDown does not get called: stringList.removeAll(); intList.removeAll(); testDataForStringList[0].testDescription = "A numeric string(alphabetically first!)" ; testDataForStringList[0].item = new UtlString("123") ; testDataForStringList[0].expectedIndex = 0 ; testDataForStringList[1].testDescription = "An alphabetic string(alphatically second!)" ; testDataForStringList[1].item = new UtlString("Abcd") ; testDataForStringList[1].expectedIndex = 1 ; testDataForStringList[2].testDescription = "An alphabetic string(alphabetically third!)" ; testDataForStringList[2].item = new UtlString("Zyxw") ; testDataForStringList[2].expectedIndex = 2 ; testDataForStringList[3].testDescription = \ "An alpha numeric string(alphabetically fourth!)" ; testDataForStringList[3].item = new UtlString("ab#34cd") ; testDataForStringList[3].expectedIndex = 3 ; // Add the strings in a random (non alphabetical order) stringList.insert(testDataForStringList[2].item) ; stringList.insert(testDataForStringList[0].item) ; stringList.insert(testDataForStringList[3].item) ; stringList.insert(testDataForStringList[1].item) ; testDataForIntList[0].testDescription = "A negative integer(first item)" ; testDataForIntList[0].item = new UtlInt(-25023) ; testDataForIntList[0].expectedIndex = 0 ; testDataForIntList[1].testDescription = "Integer whose value = 0(second item)" ; testDataForIntList[1].item = new UtlInt(0) ; testDataForIntList[1].expectedIndex = 1 ; testDataForIntList[2].testDescription = "Positive integer(third item)" ; testDataForIntList[2].item = new UtlInt(35) ; testDataForIntList[2].expectedIndex = 2 ; testDataForIntList[3].testDescription = "A positive integer(fourth item)" ; testDataForIntList[3].item = new UtlInt(25023) ; testDataForIntList[3].expectedIndex = 3 ; // Add the ints in a random (non alphabetical order) intList.insert(testDataForIntList[2].item) ; intList.insert(testDataForIntList[0].item) ; intList.insert(testDataForIntList[3].item) ; intList.insert(testDataForIntList[1].item) ; } void tearDown() { } /** Sandbox method for experimenting with the API Under Test. * This method MUST be empty when the test drivers are being * checked in (final checkin) to the repository. */ void DynaTest() { } /*a! This test is more of a sanity check to verify that * the basic insert(), entries() and at() methods work as expected. * All future tests will depend heavily on the at() method * and the most common way of having something in the list is * by means of the append() method. */ void checkSanity_Insert_Entries_And_At() { const char* prefix1 = "For a SortedList with UtlStrings, "; const char* prefix2 = "For a SortedList with UtlInts, " ; const char* suffix = "Verify that the at(n) method, where n = " ; for (int i = 0 ; i < stringListCount; i++) { size_t expectedIndex = testDataForStringList[i].expectedIndex ; const UtlContainable* ucAct = stringList.at(expectedIndex) ; string msg ; char strItr[33] ; sprintf(strItr, "%d", expectedIndex); TestUtilities::createMessage(3, &msg, prefix1, suffix, strItr) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), \ (void*)testDataForStringList[expectedIndex].item, (void*)ucAct) ; } for (int j = 0 ; j < intListCount; j++) { size_t expectedIndex = testDataForIntList[j].expectedIndex ; const UtlContainable* ucAct = intList.at(expectedIndex) ; string msg ; char strItr[33] ; sprintf(strItr, "%d", expectedIndex); TestUtilities::createMessage(3, &msg, prefix2, suffix, strItr) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), \ (void*)testDataForIntList[expectedIndex].item, (void*)ucAct) ; } CPPUNIT_ASSERT_EQUAL_MESSAGE("Verify that the entries() for an empty list returns 0", \ 0, (int)emptyList.entries()) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Verify the entries() method for a list", \ stringListCount, (int)stringList.entries() ) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Verify the entries() method for a int list", \ intListCount, (int)intList.entries()) ; }// checkSanity_Append_And_At() /** Test the insert() method for a SortedList of strings * * Test Data:- * a) The inserted string would now be the first item in the list * b) The inserted string would now be in the middle * c) The inserted string would be the last in the list. */ void testInsert_StringList() { const char* prefix = "For sortedlist consisting of UtlStrings, " \ "test the insert(Containable cont) method, where cont = " ; const char* suffix1 = " :- check return value" ; const char* suffix2 = " :- check if inserted at correct position" ; string Message ; UtlString string1("") ; UtlString string2("BCD") ; UtlString string3("zzzzz") ; TestSortedListStruct testData[] = { \ { "the new first list item", &string1, 0}, \ { "the new fourth item", &string2, 3 }, \ { "the new last item", &string3, 6} \ } ; // Adjust the expected indices for the original test data testDataForStringList[0].expectedIndex = 1 ; testDataForStringList[1].expectedIndex = 2 ; testDataForStringList[2].expectedIndex = 4 ; testDataForStringList[3].expectedIndex = 5 ; const int newItemsCount = sizeof(testData)/sizeof(testData[0]) ; for (int i = 0 ; i < newItemsCount; i++) { UtlContainable* returnValue = stringList.insert(testData[i].item) ; // Verify return value TestUtilities::createMessage(3,&Message, prefix, \ testData[i].testDescription, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), (void*)testData[i].item, \ (void*)returnValue) ; } // Verify that the total number of entries has increased accordingly CPPUNIT_ASSERT_EQUAL_MESSAGE("Verify that the total number of entries goes up" \ "accordingly after insert()ing items", \ stringListCount + newItemsCount, (int)stringList.entries()) ; // Verify that the new items are inserted according to their sorting order. for (int j=0 ; j data()) ; TestSortedListStruct testData[] = { \ { "first item in the list", testDataForStringList[0].item, \ testDataForStringList[0].expectedIndex }, \ { "last item in the list", testDataForStringList[stringListCount-1].item, \ testDataForStringList[stringListCount-1].expectedIndex }, \ { "like a mid item in the list", &midItemClone, \ testDataForStringList[2].expectedIndex}, \ { "item doesn't exist in the list", &noExistString, UTL_NOT_FOUND } \ }; const int testCount = sizeof(testData)/sizeof(testData[0]); for (int i =0 ; igetValue()) ; // now insert a duplicate element for position #3 intList.insert(testDataForIntList[2].item) ; TestFindDataStructure testData[] = { \ { "first element", testDataForIntList[0].item, \ testDataForIntList[0].item}, \ { "last element", testDataForIntList[intListCount -1].item,\ testDataForIntList[intListCount-1].item }, \ { "like a mid element", &midElementClone, \ testDataForIntList[2].item }, \ { "is a duplicate match", testDataForIntList[2].item, \ testDataForIntList[2].item }, \ { "has no match", &noExist, NULL } \ }; const int testCount = sizeof(testData)/sizeof(testData[0]) ; for (int i=0 ; i < testCount ; i++) { switch(type) { case TEST_FIND: { UtlContainable* foundValue = intList.find(testData[i].searchData) ; TestUtilities::createMessage(2, &Message, prefix1, \ testData[i].testDescription) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), testData[i].expectedData, \ foundValue) ; break ; } case TEST_CONTAINS: { UtlBoolean wasFound = intList.contains(testData[i].searchData) ; TestUtilities::createMessage(2, &Message, prefix2, \ testData[i].testDescription) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), testData[i].expectedData!=NULL, \ (TRUE == wasFound)) ; break ; } } } }//testFind() /** Test the remove(UtlContainable*) method. * * The TestData for this test are :- * a) The element is like a mid element. * b) The element is the first element. * c) The element is the last element. * d) The element has multiple matches. * e) The element has no matches at all * */ void testRemove() { utlTestRemove(REMOVE_CONTAINABLE) ; } //testRemove() /** Test the removeAt(size_t) method. * The test data for this method are the same as the remove(containable) * test method */ void testRemoveAt() { utlTestRemove(REMOVE_INDEX) ; } /** This utility method is used to test either the remove(UtlContainable*) * or removeAt(size_t). The actual method being tested depends on the type * parameter that was passed. */ void utlTestRemove(RemoveType remType) { struct TestRemoveDataStructure { const char* testDescription ; UtlContainable* itemToRemove ; int removeIndex ; size_t expectedIndex ; bool expectedResult ; size_t expectedEntries ; }; const char* prefix = ""; switch(remType) { case REMOVE_CONTAINABLE : prefix = "Test the remove(UtlContainable* cont) method when cont =" ; break ; case REMOVE_INDEX : prefix = "Test the removeAt(size_t index) method when cont = " ; break ; } ; const char* suffix1 = " :- Verify return value" ; const char* suffix2 = " :- Verify the total number of entries" ; const char* suffix3 = " :- Verify index() after remove" ; string Message ; UtlString noExistString("CannotExist") ; UtlString midItemClone(((UtlString*)testDataForStringList[1].item)->data()) ; //insert a duplicate element. stringList.insert(testDataForStringList[2].item) ; int elementsCount = stringListCount + 1 ; // As a result of the above operation, item at position 0 & 1 are unchanged // Item that was at position 2 is now either 2 or 3 (before remove) // The duplicate item inserted is now at either position 2 or 3 (before rem) // The item that was at position 3 (last item) is now at // position 4 (add 2) (before remove) TestRemoveDataStructure testData[] = { \ { "like a mid element", &midItemClone, 1, -1, true, --elementsCount }, \ { "is the first element", testDataForStringList[0].item, 0, -1, \ true, --elementsCount}, \ { "is the last element", testDataForStringList[stringListCount-1].item, \ 2, -1, true, --elementsCount}, \ //initialy the last index was 3. We inserted one item and made it 4. // during the above 2 steps we removed 2 items. { "is an element with duplicate entries", testDataForStringList[2].item, \ 0, 0, true, --elementsCount}, \ //It is still -2 & not -3. that is because the //previous item's position was always after and doesn't affect the cur index. { "is an element with no match", &noExistString, \ -1, -1, false, elementsCount} \ }; const int testCount = sizeof(testData)/sizeof(testData[0]) ; for (int i = 0 ; i < testCount; i++) { UtlContainable* actualResult; switch(remType) { case REMOVE_CONTAINABLE : actualResult = stringList.remove(testData[i].itemToRemove) ; break ; case REMOVE_INDEX : actualResult = stringList.removeAt(testData[i].removeIndex) ; break ; default: actualResult = NULL; break; } TestUtilities::createMessage(3, &Message, prefix, \ testData[i].testDescription, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), testData[i].expectedResult, \ (NULL != actualResult)) ; TestUtilities::createMessage(3, &Message, prefix, \ testData[i].testDescription, suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), \ (int)testData[i].expectedEntries, (int)stringList.entries()) ; size_t indexAfterRemove = stringList.index(testData[i].itemToRemove) ; TestUtilities::createMessage(3, &Message, prefix, \ testData[i].testDescription, suffix3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), testData[i].expectedIndex, \ indexAfterRemove) ; } } //utlTestRemove /** Testcase for the destroy() method. */ void testDestroy() { const char* prefix = "test the destroy() method " ; const char* suffix1 = " :- verify the return value" ; const char* suffix2 = " :- verify that the entry is removed" ; const char* suffix3 = " :- verify that the object was deleted" ; string Message ; UtlContainableTestStub stubObject(987323) ; UtlContainableTestStub* stubPtr ; stubPtr = new UtlContainableTestStub(987344) ; intList.insert(&stubObject) ; intList.insert(stubPtr) ; int cCountBefore = UtlContainableTestStub::getCount() ; UtlBoolean wasRemoved = intList.destroy(stubPtr) ; TestUtilities::createMessage(2, &Message, prefix, suffix1) ; CPPUNIT_ASSERT_MESSAGE(Message.data(), (TRUE == wasRemoved)) ; // The CollectableTestStub has been implemented such that a static counter gets decremented // for every descruction of an object instance. To verify that the object was destroyed, // verify that the static count went down. int cCountAfter = UtlContainableTestStub::getCount() ; TestUtilities::createMessage(2, &Message, prefix, suffix3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), cCountBefore-1, cCountAfter) ; // Now to verify that the object was indeed removed from the list, create a // clone of the stub and try to find it in the list stubPtr = new UtlContainableTestStub(987344) ; UtlContainable* searchResult = intList.find(stubPtr) ; delete stubPtr ; TestUtilities::createMessage(2, &Message, prefix, suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), (void*)NULL, (void*)searchResult) ; }//testDestroy() /*!a test the removeAll() method. * * The test data for this method is * a) When the list is empty * b) When the list has one entry. * c) When the list multiple entries * d) When removeAll has been called and entries are added again * d) When the removeAll is called twice on the list. */ void testRemoveAll() { const char* prefix = "Test the removeAll() method when " ; const char* suffix = " :- Verify number of entries after removeAll()" ; string Message ; //Since this method requires different lists and different operations to //be performed for each test, the conventional data driven loop will not // be used here. // Verify the case for an empty list. emptyList.removeAll() ; TestUtilities::createMessage(3, &Message, prefix, "the list is empty", suffix) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), 0, (int)emptyList.entries()) ; //Verify the case for a list with multiple entries. stringList.removeAll() ; TestUtilities::createMessage(3, &Message, prefix, "the list has entries in it", suffix) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), 0, (int)stringList.entries()) ; //Verify the case when entries are added after removeAll intList.removeAll() ; intList.insert(testDataForIntList[1].item) ; intList.insert(testDataForIntList[2].item) ; TestUtilities::createMessage(3, &Message, prefix, \ "entries are inserted after removeAll", suffix) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), 2, (int)intList.entries()) ; //Verify the case when removeAll() is called twice. emptyList.insert(testDataForStringList[0].item) ; emptyList.insert(testDataForStringList[2].item) ; emptyList.insert(testDataForStringList[3].item) ; emptyList.removeAll() ; emptyList.removeAll() ; TestUtilities::createMessage(3, &Message, prefix, \ "removeAll() is called twice", suffix) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), 0, (int)emptyList.entries()) ; }//testRemoveAll() /** Testcase to test the destroyAll() method * */ void testDestroyAll() { const char* prefix = "test the destroyAll() method " ; const char* suffix1 = " :- Verify that all entries are removed" ; const char* suffix2 = " :- Verify that all objects are deleted" ; string msg ; UtlContainableTestStub* stub1 ; UtlContainableTestStub* stub2 ; stub1 = new UtlContainableTestStub(100) ; stub2 = new UtlContainableTestStub(200) ; emptyList.insert(stub1) ; emptyList.insert(stub2) ; emptyList.destroyAll() ; int cCountAfter = UtlContainableTestStub::getCount() ; TestUtilities::createMessage(2, &msg, prefix, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), 0, (int)emptyList.entries()) ; // Since the TestStub has been implemented such that destructor // decrements the static counter, to verify that the objects have // been deleted, verify that the static counter has been decremented. TestUtilities::createMessage(2, &msg, prefix, suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(msg.data(), 0, cCountAfter) ; } //testDestroyAll() /*!a Test case for the isEmpty() method. * The test data for this test are :- * a) When the list has just been created. * b) When the list has one entry in it * c) When the list has multiple entries in it. * d) When all the entries in a list have been removed using removeAll() */ void testIsEmpty() { const char* prefix = "Test the isEmpty() method when " ; string Message ; UtlSortedList newList ; TestUtilities::createMessage(2, &Message, prefix, "the list has just been created") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), true, (TRUE == newList.isEmpty())) ; newList.insert(testDataForStringList[0].item) ; TestUtilities::createMessage(2, &Message, prefix, "the list has a single entry") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), false, (TRUE == newList.isEmpty())) ; TestUtilities::createMessage(2, &Message, prefix, \ "the list has multiple entries in it") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), false, (TRUE == stringList.isEmpty())) ; stringList.removeAll() ; TestUtilities::createMessage(2, &Message, prefix, \ "removeAll() has been called on the list") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), true, (TRUE == stringList.isEmpty())) ; }//testIsEmpty() }; const int UtlSortedListTest::INDEX_NOT_EXIST = -1 ; const int UtlSortedListTest::stringListCount = 4 ; const int UtlSortedListTest::intListCount = 4 ; CPPUNIT_TEST_SUITE_REGISTRATION(UtlSortedListTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlSortedListIteratorTest.cpp0000644000175000017500000002151712205613256030076 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include #include #include /** This class is used to test the UtlInt utility class. * * PLEASE READ THE README FILE THAT CAN FOUND IN THE SAME DIRECTORY AS * THIS FILE. The Readme describes the organization / flow of tests and * without reading this file, the following class (and all unit tests) * may not make a lot of sense and might be difficult to comprehend. */ class UtlSortedListIteratorTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlSortedListIteratorTest); CPPUNIT_TEST(check_Advancing_Operator_StringList) ; CPPUNIT_TEST(check_Advancing_Operator_IntList) ; CPPUNIT_TEST(check_Reset) ; CPPUNIT_TEST(check_FindNext) ; CPPUNIT_TEST_SUITE_END() ; private: struct TestSortedListStruct { const char* testDescription ; UtlContainable* item ; size_t expectedIndex ; }; static const int stringListCount ; static const int intListCount ; UtlSortedList emptyList ; UtlSortedList stringList ; UtlSortedList intList ; TestSortedListStruct* testDataForStringList ; TestSortedListStruct* testDataForIntList ; public: UtlSortedListIteratorTest() { testDataForStringList = new TestSortedListStruct[stringListCount] ; testDataForIntList = new TestSortedListStruct[intListCount] ; } ~UtlSortedListIteratorTest() { for (int i = 0 ; i < stringListCount; i++) { delete testDataForStringList[i].item ; } for (int j = 0 ; j < stringListCount; j++) { delete testDataForIntList[j].item ; } delete[] testDataForStringList ; delete[] testDataForIntList ; } void setUp() { // In case prior test aborts and tearDown is not invoked: stringList.destroyAll(); intList.destroyAll(); testDataForStringList[0].testDescription = "A numeric string(alphabetically first!)" ; testDataForStringList[0].item = new UtlString("123") ; testDataForStringList[0].expectedIndex = 0 ; testDataForStringList[1].testDescription = "An alphabetic string(alphatically second!)" ; testDataForStringList[1].item = new UtlString("Abcd") ; testDataForStringList[1].expectedIndex = 1 ; testDataForStringList[2].testDescription = "An alphabetic string(alphabetically third!)" ; testDataForStringList[2].item = new UtlString("Zyxw") ; testDataForStringList[2].expectedIndex = 2 ; testDataForStringList[3].testDescription = \ "An alpha numeric string(alphabetically fourth!)" ; testDataForStringList[3].item = new UtlString("ab#34cd") ; testDataForStringList[3].expectedIndex = 3 ; // Add the strings in a random (non alphabetical order) stringList.insert(testDataForStringList[2].item) ; stringList.insert(testDataForStringList[0].item) ; stringList.insert(testDataForStringList[3].item) ; stringList.insert(testDataForStringList[1].item) ; testDataForIntList[0].testDescription = "A negative integer(first item)" ; testDataForIntList[0].item = new UtlInt(-25023) ; testDataForIntList[0].expectedIndex = 0 ; testDataForIntList[1].testDescription = "Integer whose value = 0(second item)" ; testDataForIntList[1].item = new UtlInt(0) ; testDataForIntList[1].expectedIndex = 1 ; testDataForIntList[2].testDescription = "Positive integer(third item)" ; testDataForIntList[2].item = new UtlInt(35) ; testDataForIntList[2].expectedIndex = 2 ; testDataForIntList[3].testDescription = "A positive integer(fourth item)" ; testDataForIntList[3].item = new UtlInt(25023) ; testDataForIntList[3].expectedIndex = 3 ; // Add the ints in a random (non alphabetical order) intList.insert(testDataForIntList[2].item) ; intList.insert(testDataForIntList[0].item) ; intList.insert(testDataForIntList[3].item) ; intList.insert(testDataForIntList[1].item) ; } void tearDown() { } /** Sandbox method for experimenting with the API Under Test. * This method MUST be empty when the test drivers are being * checked in (final checkin) to the repository. */ void DynaTest() { } void check_Advancing_Operator_StringList() { UtlSortedListIterator slIter(stringList) ; for (int i = 0 ; i < stringListCount ; i++) { UtlContainable* uNext = slIter() ; CPPUNIT_ASSERT_EQUAL_MESSAGE(testDataForStringList[i].testDescription, \ testDataForStringList[i].item, uNext) ; } // Verify that the iterator returns null after the last advancing has been called UtlContainable* uNext = slIter() ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Null is returned after all items have been " \ "advanced ", (void*)NULL, (void*)uNext) ; } void check_Advancing_Operator_IntList() { UtlSortedListIterator slIter(intList) ; for (int i = 0 ; i < intListCount ; i++) { UtlContainable* uNext = slIter() ; CPPUNIT_ASSERT_EQUAL_MESSAGE(testDataForIntList[i].testDescription, \ testDataForIntList[i].item, uNext) ; } // Verify that the iterator returns null after the last advancing has been called UtlContainable* uNext = slIter() ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Null is returned after all items have been " \ "advanced ", (void*)NULL, (void*)uNext) ; } /** Verify that calling reset() pushes the iterator to * the begining. */ void check_Reset() { UtlSortedListIterator slIter(stringList) ; slIter() ; slIter() ; slIter.reset() ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Verify that calling reset on the iterator " \ "positions it to the begining", (void*)testDataForStringList[0].item, \ (void*)slIter()) ; } /** Test the findNext method. The various test case * for this are :- * a) Verify that all the elements can be found when the iterator has been reset. * b) Verify that any element after the current iterator position can be searched. & c) Verify that any element before the current position is not returned in a search. * Verify htat when there are two similar matches than * either of the items is returned when searching. */ void check_FindNext() { UtlSortedListIterator iter(stringList); const char* message; // Search for the first item message = "Search for the first item" ; UtlContainable* found = iter.findNext(testDataForStringList[0].item) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(message, testDataForStringList[0].item, found) ; message = "Search for the last item" ; iter.reset() ; found = iter.findNext(testDataForStringList[stringListCount-1].item) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(message, testDataForStringList[stringListCount-1].item, found) ; message = "Search for a middle item" ; iter.reset() ; found = iter.findNext(testDataForStringList[2].item) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(message, testDataForStringList[2].item, found); message = "When the iterator has not been reset, search for an item that "\ "is not yet been read" ; iter.reset() ; iter() ; found = iter.findNext(testDataForStringList[2].item) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(message, testDataForStringList[2].item, found) ; UtlString dupString1("Mnop") ; UtlString dupString2("Mnop"); stringList.insert(&dupString1) ; stringList.insert(&dupString2) ; iter.reset(); found = iter.findNext(&dupString2) ; bool isSuccess = (found == &dupString1 || found == &dupString2) ; CPPUNIT_ASSERT_MESSAGE(message, isSuccess) ; } }; const int UtlSortedListIteratorTest::stringListCount = 4 ; const int UtlSortedListIteratorTest::intListCount = 4 ; CPPUNIT_TEST_SUITE_REGISTRATION(UtlSortedListIteratorTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlStringTest.cpp0000644000175000017500000000270012205613256025527 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include const char* UtlStringTest::longAlphaString = \ "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvwzyz" "abcdefghijklmnopqrstuvw" ; const char* UtlStringTest::splCharString = "Ã墀%$',+*\"?+*a" ; const UtlStringTest::BasicStringVerifier UtlStringTest::commonTestSet[] = { \ {"empty char*", "", 0 }, \ {"single character char*", "g", 1 }, \ {"long alpha-num char*", longAlphaString, 257}, \ {"regular char*", "This makes sense", 16}, \ {"numeric char*", "12576", 5} , \ {"special characters char*", splCharString, 16} \ } ; const int UtlStringTest::commonTestSetLength = \ sizeof(commonTestSet)/sizeof(commonTestSet[0]) ; UtlStringTest::UtlStringTest() { } UtlStringTest::~UtlStringTest() { } sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlStringTest.h0000644000175000017500000000257612205613256025207 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include /** Base class for all the UtlString test unit tests */ class UtlStringTest : public SIPX_UNIT_BASE_CLASS { protected : struct BasicStringVerifier { const char* testDescription ; const char* input ; size_t length ; }; static const char* longAlphaString ; static const char* splCharString ; static const int commonTestSetLength ; static const BasicStringVerifier commonTestSet[] ; enum IndexFirstOrContainsType { TEST_INDEX, TEST_FIRST, TEST_CONTAINS} ; enum PrependInsertOrReplace {TEST_PREPEND, TEST_INSERT, TEST_REPLACEFIRST} ; enum AppendInsertReplaceOrPlusEqual{TEST_APPEND, TEST_INSERTLAST, TEST_PLUS, \ TEST_PLUSEQUAL, TEST_REPLACELAST} ; enum StringType {TYPE_CHARSTAR, TYPE_UTLSTRING} ; enum CharacterCase {CASE_LOWER, CASE_UPPER} ; public: UtlStringTest() ; virtual ~UtlStringTest() ; } ; sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlStringTest_ConstructiveManipulators.cpp0000644000175000017500000017574312205613256032720 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #if defined(NO_CPPUNIT) # define ERASE_ALL remove(0) #else # define ERASE_ALL erase() #endif #ifdef WIN32 # define MEMBER_CONST #else # define MEMBER_CONST const #endif // The following variables have been defined in the base class // and will be used in all the string tests /** const int UtlStringTest::commonTestSetLength ; const char* UtlStringTest::longAlphaString ; const char* UtlStringTest::splCharString ; const BasicStringVerifier UtlStringTest::commonTestSet[]; const int UtlStringTest::commonTestSetLength ; */ /** This class is used to test the UtlString class. * * PLEASE READ THE README FILE THAT CAN FOUND IN THE PARENT DIRECTORY. * The Readme describes the organization / flow of tests and * without reading this file, the following class (and all unit tests) * may not make a lot of sense and might be difficult to comprehend. */ class UtlStringTest_ConstructiveManipulators : public UtlStringTest { CPPUNIT_TEST_SUITE(UtlStringTest_ConstructiveManipulators); CPPUNIT_TEST(testConstructor_1) ; CPPUNIT_TEST(testConstructor_2) ; CPPUNIT_TEST(testConstructor_3) ; CPPUNIT_TEST(testConstructor_4) ; CPPUNIT_TEST(testCapacity) ; CPPUNIT_TEST(testAssign_charstar) ; CPPUNIT_TEST(testAssign_selfcharstar); CPPUNIT_TEST(testCharstarCastOperator) ; CPPUNIT_TEST(testAssign_UtlString) ; CPPUNIT_TEST(testAppendWithInt); CPPUNIT_TEST(testAppendChar); CPPUNIT_TEST(testPlusEqualChar); CPPUNIT_TEST(testAppend_charstar_toEmptyString) ; CPPUNIT_TEST(testAppend_UtlString_toEmptyString) ; CPPUNIT_TEST(testAppend_charstar_specifyAllCharacters_toEmptyString) ; CPPUNIT_TEST(testAppend_charstar_toExistingString) ; CPPUNIT_TEST(testAppend_UtlString_toExistingString) ; CPPUNIT_TEST(testAppend_charstar_specifyAllCharacters_toExistingString) ; CPPUNIT_TEST(testAppend_charstar_specifiedSize_toEmptyString) ; CPPUNIT_TEST(testAppend_charstar_specifiedSize_toExistingString) ; CPPUNIT_TEST(testAppend_charstar_zero_bytes_toExistingString) ; CPPUNIT_TEST(testAppend_charstar_zero_bytes_toExistingString) ; CPPUNIT_TEST(testAppend_format); CPPUNIT_TEST(testPlusEqual_charstar) ; CPPUNIT_TEST(testPlusEqual_UtlString) ; CPPUNIT_TEST(testPrepend) ; CPPUNIT_TEST(testInsert_AtFirstLocation) ; CPPUNIT_TEST(testInsert_AtMidLocation) ; CPPUNIT_TEST(testInsert_AtLastLocation) ; CPPUNIT_TEST(testInsert_AtVariousLocations) ; CPPUNIT_TEST(testReplace_zeroth_char) ; CPPUNIT_TEST(testReplace_last_char) ; CPPUNIT_TEST(testStringContainsNullNotAtEnd); CPPUNIT_TEST(testEfficientMemoryCopy); CPPUNIT_TEST(testSubstringAssign); CPPUNIT_TEST_SUITE_END(); public: UtlStringTest_ConstructiveManipulators() { } void setUp() { } void tearDown() { } ~UtlStringTest_ConstructiveManipulators() { } /** Sandbox method for experimenting with the API Under Test. * This method MUST be empty when the test drivers are being * checked in (final checkin) to the repository. */ void DynaTest() { } //// ========================= BEGIN TEST CASES ============================== /** ===================================================================== * Test UtlString(char* ) ; * Test the Single argument constructor that accepts a char* argument. * The test data being used for this test case are :- * a) Zero length string * b) A single character represented as a string * c) A very large length string(257 characters) - that is alphanumeric * (a), (b) and (c) are somewhat like boundry cases * (altough there is no real boundry case for a string class) * d) Any ordinary string * e) A string with just numeric digits in it. * f) A string that contains special characters in it. */ void testConstructor_1() { const char* prefix = "For a string that is made of " ; const char* suffix = ":- One arg(char*) Constructor" ; string Message ; for (int i = 0 ; i < commonTestSetLength; i++) { UtlString testString(commonTestSet[i].input) ; TestUtilities::createMessage(3, &Message, prefix, \ commonTestSet[i].testDescription, suffix) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), string(commonTestSet[i].input), \ string(testString.data())) ; } } /** ===================================================================== * Test case that tests the string constructor which accepts the capacity * of string as an argument * Test Data for this test case :- * a) size of 0; * b) A large size (say 257); * c) size of 1 ; * d) a nominal size */ void testConstructor_2() { struct CapacityConstructorVerifier { const char* testDescription ; size_t inputCapacity ; size_t minExpectedCapacity ; } ; const char* prefix = "One arg(int) constructor test for string with a capacity "; const char* suffix1 = ":- test data" ; const char* suffix2 = ":- test capacity" ; string Message ; const CapacityConstructorVerifier testData[] = { \ {"of 0", 0, 0}, \ {"that is large", 20040, 20040}, \ {"of 1", 1, 1}, \ {"that represents a regular string:-", 26, 26}, \ } ; const int testCount = sizeof(testData)/sizeof(testData[0]) ; } //testConstructor2() /** ===================================================================== * Test the copy consturctor that accepts another UtlString object as the argument * The test data being used for this test case are :- * a) Zero length string * b) A single character represented as a string * c) A very large length string(257 characters) - alphanumeric * (a), (b) and (c) are somewhat like boundry cases * (altough there is no real boundry case for a string class) * d) Any ordinary string * e) A string with just numeric digits in it. * f) A string that contains special characters in it. */ void testConstructor_3() { const char* prefix = "Test copy constructor for " ; const char* suffix1 = ":- verified copied string" ; const char* suffix2 = ":- verify capacity"; string Message ; for (int i = 0 ; i < commonTestSetLength; i++) { UtlString *tsOriginal = new UtlString(commonTestSet[i].input) ; UtlString tsCopied(*tsOriginal) ; size_t expectedCapacity = tsOriginal->capacity(); delete tsOriginal; // Verify the copied string's data TestUtilities::createMessage(3, &Message, prefix, \ commonTestSet[i].testDescription, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), \ string(commonTestSet[i].input), string(tsCopied.data())) ; // Verify that the capacity is also copied. TestUtilities::createMessage(3, &Message, prefix, \ commonTestSet[i].testDescription, suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), \ expectedCapacity, tsCopied.capacity()) ; } } //testConstructor3 /** ===================================================================== * Test the copy consturctor that accepts another UtlString object * and the length as the arguments * The test data being used for this test case are :- * a) Copy Zero bytes of a Zero length string * b) Copy Zero bytes of a non-zero length string * b) Copy 'n' bytes of a non zero length string, where n < strlen() * c) Copy 'n' bytes of a non zero length string, where n = strlen() * d) Copy 'n' bytes of a non zero length string, where n > strlen() */ void testConstructor_4() { struct TestCopyConstructor2Struct { const char* testDescription ; const char* stringToCopy ; int lengthToCopy ; const char* expectedString ; int expectedLength ; } ; const char* prefix = "Test copy constructor(that specifies the number of bytes) for " ; const char* suffix1 = ":- verified copied string" ; const char* suffix2 = ":- verify length"; string Message ; TestCopyConstructor2Struct testData[] = { \ { "empty string. specify 0 as the length to copy", "", 0, "", 0 }, \ { "a regular string. specify 0 as the length to copy", "Test String", \ 0, "", 0 }, \ { "a regular string. specify nstrlen as length to copy", "Test String", \ 14, "Test String", 11 } \ } ; int testCount = sizeof(testData)/sizeof(testData[0]) ; for (int i = 0 ; i < testCount; i++) { UtlString tsOriginal(testData[i].stringToCopy) ; KNOWN_EFENCE_BUG("Segmenation fault, unset EF_PROTECT_BELOW", "XPL-8") ; UtlString tsCopied(tsOriginal, testData[i].lengthToCopy) ; // Verify the copied string's data TestUtilities::createMessage(3, &Message, prefix, testData[i].testDescription, \ suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), \ string(testData[i].expectedString), string(tsCopied.data())) ; // Verify the copied string's length TestUtilities::createMessage(3, &Message, prefix, testData[i].testDescription, \ suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), testData[i].expectedLength, \ (int)tsCopied.length()) ; } } //testConstructor3 /** This test case verifies the capacity(long) method. * The data for the test case being used are * a) Set the capacity to 0. * b) Set the capacity to a large number. * c) Set the capacity to 0 of a String whose capacity is non zero * d) Set the capacity to a value greater than the current capacity. * e) Set the capacity to a value less that the current capacity */ void testCapacity() { // Structure that describes the test case. struct TestCapacityDataStructure { const char* testDescription ; const char* inputString ; size_t inputCapacity ; size_t minExpectedCapacity ; }; const char* prefix = "Test capacity() -" ; const char* suffix1 = ":- Check returned value" ; const char* suffix2 =":- Check actual capacity" ; string Message ; const TestCapacityDataStructure testData[] = { \ {"Set capacity of an empty string to 0", \ "", 0, 0 }, \ {"Set capacity of an empty string to " \ "a large number", "", 2543, 2543 }, \ {"Set capacity of an existing non-zero " \ "length string to 0","Some String", 0, 9 }, \ {"Set capacity of an existing string " \ "to greater than current", "Some String", 12, 12 }, \ {"Set capacity of an existing string " \ "to less than current", "Some String", 2, 9 } \ }; const int testCount = sizeof(testData)/sizeof(testData[0]) ; for (int i =0 ; i= testData[i].minExpectedCapacity) ; // Check the new capacity of the string. actualCapacity = testString.capacity() ; TestUtilities::createMessage(3, &Message, prefix, \ testData[i].testDescription, suffix2) ; CPPUNIT_ASSERT_MESSAGE(Message.data(), \ actualCapacity >= testData[i].minExpectedCapacity) ; } } //testCapacity /** * Test to see how the compiler resolves the cases that gave Scott * trouble, viz. append(char*, int) and append(UtlString, int). * Also check append(UtlString, int, int) */ void testAppendWithInt() { UtlString appendee; char* string = (char*) "abcde"; UtlString source; appendee = "12345"; /* Should append the characters of "string", with length 3, * viz., "abc". */ appendee.append(string, 3); ASSERT_STR_EQUAL_MESSAGE("append(char*, int)", "12345abc", appendee.data()); appendee = "12345"; source = string; appendee.append(source, 3); /* Should append the characters of "source", with length 3, * viz., "abc". */ ASSERT_STR_EQUAL_MESSAGE("append(UtlString, int)", "12345abc", appendee.data()); appendee = "12345"; source = string; appendee.append(source, 3, 1); /* Should append the characters of "source", at offset 3, with * length 1, viz., "d". */ ASSERT_STR_EQUAL_MESSAGE("append(UtlString, int, int)", "12345d", appendee.data()); } /** * Test append to empty string and null character */ void testAppendChar() { UtlString oneChar; ASSERT_STR_EQUAL_MESSAGE("Append single char to empty string", "x", oneChar.append('x').data()); const char *szHasNull = "null at end\0"; UtlString hasNull(szHasNull); CPPUNIT_ASSERT_MESSAGE("Append null to string", memcmp(szHasNull, hasNull.append('\0').data(), sizeof(szHasNull)) == 0); } /** * Test appending using the plus equals operator (to empty, to norm string, * adding null) */ void testPlusEqualChar() { UtlString oneChar; oneChar += 'x' ; ASSERT_STR_EQUAL_MESSAGE("Append single char to empty string", "x", oneChar.data()); UtlString manyChar("Random String") ; manyChar += '!' ; ASSERT_STR_EQUAL_MESSAGE("Append single char to norm string", "Random String!", manyChar.data()); const char *szHasNull = "null at end\0"; UtlString hasNull(szHasNull); hasNull += '\0' ; CPPUNIT_ASSERT_MESSAGE("Append null to string", memcmp(szHasNull, hasNull.data(), sizeof(szHasNull)) == 0); } /** * This test case verifies the append(const char*) / * append(const UtlString) method. * * The test data for this test case is :- * With an Empty (zero length) string * a) Append an empty string * b) Append a single character string * c) Append a very long string(which also has alpha numeric chars) * d) Append a meaningful string * e) Append a string with only digits. * f) Append a string with special characters. * With a string that already has some text in it :- * a) to f) are to be repeated. * * With a string that is long and the (number of characters) == (capacity) * a) Append another string that has alphanumeric / special characters */ void testAppend_charstar_toEmptyString() { utlTestAppend_to_EmptyString(TYPE_CHARSTAR) ; } /** The above test case for appending UtlString instead of * char* */ void testAppend_UtlString_toEmptyString() { utlTestAppend_to_EmptyString(TYPE_UTLSTRING) ; } /** * Test case to test the append(const char*, int size) method - Case a) * Case a) - Copy to an empty string - All the bytes of the char* being passed * * The test data for this test case are the same as that in the method, * testAppend_charstar_toEmptyString * */ void testAppend_charstar_specifyAllCharacters_toEmptyString() { utlTestAppend_to_EmptyString(TYPE_CHARSTAR, true) ; } /*! The above test case for appending UtlString instead of * char* */ void testAppend_UtlString_specifyAllCharacters_toEmptyString() { utlTestAppend_to_EmptyString(TYPE_UTLSTRING, true) ; } /** Utility to test the Append method to an empty string * Using this utility, you can test both append(char*) & * append(UtlString). By passing the appropriate value to the * specifyCharLenght argument, you can also test the method that * explicitly specifies the number of characters(equal to length) * to be appended. That is, you can test append(char*, len) or * append(UtlString, len) */ void utlTestAppend_to_EmptyString(StringType type, bool specifyCharLength = false) { const char* prefix = "To a zero length string, test appending a" ; // The Messages array used is the commonDataSetMessages. const char* suffix1 = ":- verify if appended to original string" ; const char* suffix2 = ":- verify returned string" ; string Message ; for (int i = 0 ; i < commonTestSetLength ; i++) { UtlString baseString("") ; const char* returnValue ; UtlString stringToAppend(commonTestSet[i].input) ; if (type == TYPE_CHARSTAR) { // If specifyCharLength is passed as 'true', then invoke the // method as append(charstarString, size), // where size = strlen(charstarString). // Otherwise invoke as strlen(charstarString) if (specifyCharLength) { UtlString &tsReturn = baseString.append( \ commonTestSet[i].input, commonTestSet[i].length) ; returnValue = tsReturn.data() ; } else { UtlString &tsReturn = baseString.append( \ commonTestSet[i].input) ; returnValue = tsReturn.data() ; } } else { if (specifyCharLength) { UtlString &tsReturn = baseString.append(stringToAppend, \ commonTestSet[i].length) ; returnValue = tsReturn.data() ; } else { UtlString &tsReturn = baseString.append(stringToAppend) ; returnValue = tsReturn.data() ; } } TestUtilities::createMessage(3, &Message, prefix, commonTestSet[i].testDescription, \ suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), string(commonTestSet[i].input), \ string(baseString.data())) ; TestUtilities::createMessage(3, &Message, prefix, commonTestSet[i].testDescription, \ suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), string(commonTestSet[i].input), \ string(returnValue)) ; } } //utlTestAppend_to_EmptyString /** * This test case verifies the append(const char*) method. * * The test data for this test case is :- * With a string that already has text in it:- * a) Append an empty string * b) Append a single character string * c) Append a very long string(which also has alpha numeric chars) * d) Append a meaningful string * e) Append a string with only digits. * f) Append a string with special characters. * * With a long string and (number of characters) == (capacity) * g) Append a string that has alphanumeric / special characters */ void testAppend_charstar_toExistingString() { utlTestAppend_Charstar_to_ExistingString(false, TEST_APPEND) ; utlTestAppend_MaxCapacity(TYPE_CHARSTAR) ; } /** * Test case to test the append(const char*, int size) method * - Copy to a non-empty string - All the bytes of the char* being passed * * The test data for this test case are :- * all cases of the testAppend_char_toExistingString() test case */ void testAppend_charstar_specifyAllCharacters_toExistingString() { utlTestAppend_Charstar_to_ExistingString(true, TEST_APPEND) ; utlTestAppend_MaxCapacity(TYPE_CHARSTAR, true) ; } void testAppend_format() { int i = 0; UtlString a("aa"); a.appendFormat("%d", 1234); CPPUNIT_ASSERT_EQUAL_MESSAGE("incorrect appendFormat", 0, strcmp("aa1234", a.data())); for (i = 0; i < 1000; i++) a.appendFormat("%x", 255); CPPUNIT_ASSERT_EQUAL_MESSAGE("incorrect appendFormat", (size_t)(2000 + 6), a.length()); } /** Test the replace(len-1, len-1, char*) method * The test data for this is the same as the testAppend() * test case */ void testReplace_last_char() { utlTestAppend_Charstar_to_ExistingString(false, TEST_REPLACELAST) ; } void testStringContainsNullNotAtEnd() { UtlString a("aa\0bb", 5); CPPUNIT_ASSERT_EQUAL_MESSAGE("lost null char in string", strlen(a.data()), (size_t) 2); CPPUNIT_ASSERT_EQUAL_MESSAGE("incorrect length with null char", a.length(), (size_t) 5); CPPUNIT_ASSERT_EQUAL_MESSAGE("did not find null char", a.index('\0'), (size_t) 2); a.append("cc\0dd", 5); CPPUNIT_ASSERT_EQUAL_MESSAGE("append with null char lost", a.length(), (size_t) 10); CPPUNIT_ASSERT_EQUAL_MESSAGE("failed to find last null char", a.last('\0'), (size_t) 7); UtlString b("\0", 1); CPPUNIT_ASSERT_EQUAL_MESSAGE("failed to create string with null char", b.length(), (size_t) 1); UtlString c(b); CPPUNIT_ASSERT_EQUAL_MESSAGE("failed to copy string with null char", c.length(), (size_t) 1); CPPUNIT_ASSERT_EQUAL_MESSAGE("copied strings w/null char not equal", c, b); CPPUNIT_ASSERT_EQUAL_MESSAGE("failed to find null char w/string", a.index(b), (size_t) 2); a.remove(3); CPPUNIT_ASSERT_EQUAL_MESSAGE("remove lost null char", a.length(), (size_t) 3); CPPUNIT_ASSERT_EQUAL_MESSAGE("data after remove lost null char", strlen(a.data()), (size_t) 2); a.remove(2); CPPUNIT_ASSERT_EQUAL_MESSAGE("failed to remove null char", strlen(a.data()), (size_t) 2); CPPUNIT_ASSERT_EQUAL_MESSAGE("wrong length after remove null char", a.length(), (size_t) 2); } void testEfficientMemoryCopy() { UtlString a; const void* dataPtr = a.data(); const void* aPtr = NULL; a = "aaa"; aPtr = a.data(); CPPUNIT_ASSERT_EQUAL_MESSAGE("char assign does not reuse memory", (void*)dataPtr, (void*)aPtr); dataPtr = a.data(); a.append("bbbb"); aPtr = a.data(); CPPUNIT_ASSERT_EQUAL_MESSAGE("char assign does not reuse memory", (void*)dataPtr, (void*)aPtr); dataPtr = a.data(); a.insert(0, "zzz"); aPtr = a.data(); KNOWN_BUG("char assign does not reuse memory", "XPL-51"); CPPUNIT_ASSERT_EQUAL_MESSAGE("char assign does not reuse memory", (void*)dataPtr, (void*)aPtr); dataPtr = a.data(); a.remove(0); aPtr = a.data(); CPPUNIT_ASSERT_EQUAL_MESSAGE("remove does not reuse memory", (void*)dataPtr, (void*)aPtr); UtlString b; b.append("ABC"); b.capacity(20); dataPtr = b.data(); b.append("34567890123456789"); aPtr = b.data(); KNOWN_BUG("char assign does not reuse memory", "XPL-51"); CPPUNIT_ASSERT_EQUAL_MESSAGE("char assign does not reuse memory", (void*)dataPtr, (void*)aPtr); } /** test the += char* operator. This operator is exactly the same as * the append method and so is the test data. */ void testPlusEqual_charstar() { utlTestAppend_Charstar_to_ExistingString(false, TEST_PLUSEQUAL) ; } /** Utility method to test the case where a char* is appended to a / UtlString. By specifying the bool parameter as false, you can test // the simple append case or if you set the param to true, you can // test the case where the entire length of string being appended is // passed as the second parameter when making the call */ void utlTestAppend_Charstar_to_ExistingString(bool specifyCharLength, \ AppendInsertReplaceOrPlusEqual optype) { const char* prefix = "To a string of " ; // Messages = common Test Data Set Messages. const char* suffix1 = " :- verify if appended" ; const char* suffix2 = " :- verify returned string" ; string strExp ; for (int i = 0 ; i < commonTestSetLength ; i++) { size_t len_baseString = strlen(commonTestSet[i].input) ; for(int j =0 ; j < commonTestSetLength; j++) { size_t len_stringToAppend = strlen(commonTestSet[j].input) ; UtlString baseString(commonTestSet[i].input) ; strExp.ERASE_ALL; strExp.append(commonTestSet[i].input) ; strExp.append(commonTestSet[j].input) ; const char* msgDataBeingAppended = ""; const char* returnValue = ""; if (specifyCharLength) { msgDataBeingAppended = \ " test append(char* c, len), where c = " ; UtlString &tsReturn = baseString.append( \ commonTestSet[j].input, len_stringToAppend) ; returnValue = tsReturn.data() ; } else { if (optype == TEST_APPEND) { msgDataBeingAppended = "test append(char*) char* = "; UtlString &tsReturn = \ baseString.append(commonTestSet[j].input) ; returnValue = tsReturn.data() ; } else if (optype == TEST_REPLACELAST) { msgDataBeingAppended = "test replace(len-1, len-1, " \ "char* c) where c = " ; UtlString &tsReturn = \ baseString.replace(len_baseString, \ len_baseString, commonTestSet[j].input) ; returnValue = tsReturn.data() ; } else if (optype == TEST_PLUSEQUAL) { msgDataBeingAppended = "test operator += (char* c), " \ "where c = " ; UtlString &tsReturn = \ (baseString += commonTestSet[j].input) ; returnValue = tsReturn.data() ; } } string compMessage ; // Check if the original string has now changed such that the // parameter passed *HAS* been appended . TestUtilities::createMessage(5, &compMessage, prefix, \ commonTestSet[i].testDescription, \ msgDataBeingAppended, \ commonTestSet[j].testDescription, suffix1); CPPUNIT_ASSERT_EQUAL_MESSAGE(compMessage.data(), strExp, \ string(baseString.data())) ; // Check the return value of append() TestUtilities::createMessage(5, &compMessage, prefix, \ commonTestSet[i].testDescription, \ msgDataBeingAppended, \ commonTestSet[j].testDescription, suffix2); CPPUNIT_ASSERT_EQUAL_MESSAGE(compMessage.data(), strExp, string(returnValue)) ; } // for int j = 0 .. (Types of strings to be appended) }// for int i = 0 to ...(Types of base strings) } //utlTestAppend_Charstar_to_ExistingString /** Utility method that is used to test the case where a string is at its * maximum capacity and you try to append. * The type parameter dictates what the right handside string's type * is going to be . You can test both append(char*), * append(UtlString) The second parameter decideds whether the * number of characters being appended needs to be explicitly specified. */ void utlTestAppend_MaxCapacity(StringType type, \ bool specifyCharLength = false) { const char* prefix = ""; const char* testTypeMsg = " for a string at max. capacity" ; const char* suffix1 = ":= verify appended" ; const char* suffix2 = ":= verify return value" ; int charLength = 257 ; const char* stringToAppend ="AnotherString123O-abz@B\")"; size_t appendLength = strlen(stringToAppend) ; UtlString baseString(longAlphaString) ; baseString.capacity(charLength) ; const char* returnValue = ""; UtlString utlStringToAppend(stringToAppend) ; // Whether the leng of the string to be appended needs to be specified // explicitly or not if (specifyCharLength) { // is the rhs for append a char* or another UtlString if (type == TYPE_CHARSTAR) { prefix = "Test append(char*, len) " ; UtlString &tsReturn = \ baseString.append(stringToAppend, appendLength) ; returnValue = tsReturn.data() ; } else if(type == TYPE_UTLSTRING) { prefix = "Test append(UtlString, len) " ; UtlString &tsReturn = baseString.append( \ utlStringToAppend, appendLength) ; returnValue = tsReturn.data() ; } } else { if (type == TYPE_CHARSTAR) { prefix = "Test append(char*) " ; UtlString &tsReturn = \ baseString.append(stringToAppend); returnValue = tsReturn.data() ; } else if (type == TYPE_UTLSTRING) { prefix = "Test append(UtlString) " ; UtlString &tsReturn = baseString.append( \ utlStringToAppend) ; returnValue = tsReturn.data() ; } } string strExp ; strExp.append(longAlphaString) ; strExp.append(stringToAppend) ; string Msg ; // Verify if string has been appended. TestUtilities::createMessage(3, &Msg, prefix, testTypeMsg, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Msg.data(), strExp, string(baseString.data())) ; // Verify return value TestUtilities::createMessage(3, &Msg, prefix, testTypeMsg, suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Msg.data(), strExp, string(returnValue)) ; } /** The above test case for appending UtlString instead of * char* */ void testAppend_UtlString_toExistingString() { utlTestAppend_to_ExistingString(TEST_APPEND) ; utlTestAppend_MaxCapacity(TYPE_UTLSTRING, false) ; } void testInsert_AtVariousLocations() { struct InsertTestData { MEMBER_CONST char* szSource ; MEMBER_CONST char* szInsert ; MEMBER_CONST int iPosition ; MEMBER_CONST char* szResults ; } ; #define INSERT_TEST_DATA_LENGTH 7 InsertTestData data[] = { {"", "INSERT", 0, "INSERT"}, // Insert at 0 w/ empty string {"XYZ123", "INSERT", 0, "INSERTXYZ123"}, // Insert at 0 w/ real string {"XYZ123", "INSERT", 6, "XYZ123INSERT"}, // Insert at very end {"XYZ123", "INSERT", 100, "XYZ123"}, // Insert past end {"XYZ123", "INSERT", -3, "XYZ123"}, // Insret before start {"XYZ123", NULL, 3, "XYZ123"}, // Bogus source pointer {"XYZ123", "INSERT", 3, "XYZINSERT123"} // Insert in middle } ; for (int i=0; i #include #include #include #ifdef WIN32 # define MEMBER_CONST #else # define MEMBER_CONST const #endif // The following variables have been defined in the base class // and will be used in all the string tests /** const int UtlStringTest::commonTestSetLength ; const char* UtlStringTest::longAlphaString ; const char* UtlStringTest::splCharString ; const BasicStringVerifier UtlStringTest::commonTestSet[]; const int UtlStringTest::commonTestSetLength ; */ /** This class is used to test the UtlString class. * * PLEASE READ THE README FILE THAT CAN FOUND IN THE SAME DIRECTORY AS * THIS FILE. The Readme describes the organization / flow of tests and * without reading this file, the following class (and all unit tests) * may not make a lot of sense and might be difficult to comprehend. */ class UtlStringTest_DestructiveManipulators : public UtlStringTest { CPPUNIT_TEST_SUITE(UtlStringTest_DestructiveManipulators); CPPUNIT_TEST(testReplace_Middle) ; CPPUNIT_TEST(testReplace_Middle_SpecifyLengthAsSize) ; CPPUNIT_TEST(testReplace_Middle_SpecifySize) ; CPPUNIT_TEST(testReplaceAt) ; CPPUNIT_TEST(testReplaceCharacter) ; CPPUNIT_TEST(testStrip_Default) ; CPPUNIT_TEST(testStrip_TrailingSpaces_SpecifyStripType) ; CPPUNIT_TEST(testStrip_LeadingSpaces) ; CPPUNIT_TEST(testStrip_AllSpaces) ; CPPUNIT_TEST(testStrip_Characters) ; CPPUNIT_TEST(testResize) ; CPPUNIT_TEST_SUITE_END(); private : struct TestStripDataStructure { const char* testDescription ; const char* input ; char characterToStrip ; const char* expectedForStripTrailing ; const char* expectedForStripLeading ; const char* expectedForStripBoth ; }; public: UtlStringTest_DestructiveManipulators() { } void setUp() { } void tearDown() { } ~UtlStringTest_DestructiveManipulators() { } /** Sandbox method for experimenting with the API Under Test. * This method MUST be empty when the test drivers are being * checked in (final checkin) to the repository. */ void DynaTest() { } void testReplaceAt() { UtlString target("won"); target.replaceAt(0,'t'); ASSERT_STR_EQUAL("ton", target.data()); target.replaceAt(1,'i'); ASSERT_STR_EQUAL("tin", target.data()); target.replaceAt(2,'e'); ASSERT_STR_EQUAL("tie", target.data()); target.replaceAt(3,'e'); ASSERT_STR_EQUAL("tie", target.data()); target.replaceAt(4,'e'); ASSERT_STR_EQUAL("tie", target.data()); target.replaceAt(5,'e'); ASSERT_STR_EQUAL("tie", target.data()); } /** Test the replace(src, tgt) * The test case for this method are * a) for an empty string replace 'a' with 'b' * e) for a string with only one occurance of 'src' replace with 'tgt' * c) for a string with multiple occurances of 'src' replace with 'tgt' * d) for a string with one or more occurances of swapped case of 'src' * replace with 'tgt' * e) for a string with one or more occurances of 'src' replace with 'src * f) for a string with zero occurances of 'src' replace with 'tgt' * g) for any string replace '0' with 'tgt' (verify that bad things dont happen * h) for a string with one or more occurances of 'src' replace with '0' */ void testReplaceCharacter() { struct TestReplaceCharStructure { MEMBER_CONST char* testDescription ; MEMBER_CONST char* input ; MEMBER_CONST char replaceSrc ; MEMBER_CONST char replaceTgt ; MEMBER_CONST char* expectedResult ; }; const char* prefix = "Test the replace(char src, char tgt) method " ; const char* suffix1 = ": Verify return value" ; const char* suffix2 = ": Verify original string" ; string Message ; TestReplaceCharStructure testData[] = { \ { "for an empty string replace 'a' with 'b'", "", 'a', 'b', "" }, \ { "for a string with only one occurance of 'src', replace with 'tgt'", \ "Test string", 'e', 'o', "Tost string" }, \ { "for a string with multiple occurances of 'src' replace with 'tgt'", \ "Test string", 's', 'f', "Teft ftring" }, \ { "for a string with occurance(s) of 'src', replace with swapped case of src", \ "Test string", 'R', 'l', "Test string" }, \ { "for a string with occurance(s) of 'src' replace with 'src'", \ "Test string", 's', 's', "Test string" }, \ { "for a string with no occurance of 'src' replace with 'tgt'", \ "Test string", 'm', 'p', "Test string" }, \ { "for any string replace '0' with 'tgt' ", \ "Test string", (char)0, 'b', "Test string" }, \ { "for a string with occurance(s) of 'src' replace 'src' with '0'", \ "Test string", 's', (char)0, "Test string" } } ; int testCount = sizeof(testData) / sizeof(testData[0]) ; for (int i = 0 ; i < testCount ; i++) { UtlString testString(testData[i].input) ; UtlString returnValue = testString.replace(testData[i].replaceSrc, \ testData[i].replaceTgt) ; TestUtilities::createMessage(3, &Message, prefix, testData[i].testDescription, \ suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), string(testData[i].expectedResult), \ string(testString.data())) ; TestUtilities::createMessage(3, &Message, prefix, testData[i].testDescription, \ suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), string(testData[i].expectedResult), \ string(returnValue.data())) ; } } /** Test the replace(pos, n, char*) * * Test data for this method * With a regular string, replace at nth suffixion (n < len) * a) any regular string upto position m. m < len * b) an alpha-num string upto position m. m < len * c) any string upto position m. m = len * d) any string upto position m. m > len * e) an empty string. n = 0 . m = len */ void testReplace_Middle() { struct TestReplaceDataStructure { const char* testDescription ; const char* input ; int startPosition ; int replaceLength ; const char* expectedValue; }; const char* prefix = "test replace(start, end, char*), where char* = " ; const char* suffix1 = ":- verify if replaced" ; const char* suffix2 = ":- verify return value" ; string Message ; const char* baseString = "string rep" ; const TestReplaceDataStructure testData[] = { \ {"an empty string. start = 0; last = 0 ", "", 0, 10, "" }, \ {"a regular string. start > 0; last < len(baseString) ", "Test Str", \ 2, 4, "stTest Str rep" }, \ {"a alpha-num string. start > 0; last < len(baseString) ", "Te12 $tr", \ 2, 4, "stTe12 $tr rep" }, \ {"a regular string. start > 0; last = total no. of remaining characters ", \ "Test Str", 2, 8, "stTest Str" }, \ {"a alpha-num string. start > 0 ; last > len(baseString)", "Te12 $tr", \ 2, 11, "stTe12 $tr" }, \ } ; const int testCount = sizeof(testData)/sizeof(testData[0]) ; // Using all the data that was created above, run the actual tests. for(int i = 0 ; i < testCount ; i++) { UtlString testString(baseString) ; UtlString returnString = testString.replace(testData[i].startPosition, \ testData[i].replaceLength, testData[i].input) ; // Verify if the selected text was replaced. TestUtilities::createMessage(3, &Message, prefix, testData[i].testDescription, \ suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), string(testData[i].expectedValue), \ string(testString.data())) ; // Verify return value TestUtilities::createMessage(3, &Message, prefix, testData[i].testDescription, \ suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), string(testData[i].expectedValue), \ string(returnString.data())) ; } } //testReplace_Middle /** Test the replace(pos, n, char*, len) where len = len(char*) * * The test data for this test case is the same as the testReplace_Middle() * test case */ void testReplace_Middle_SpecifyLengthAsSize() { utlTestReplace(true) ; } /** Test the replace(pos, n, char*, len) where len < len(char*) * * The test data for this case is the same as testReplace_Middle case */ void testReplace_Middle_SpecifySize() { utlTestReplace(false) ; } // Utility to test the replace method. void utlTestReplace(bool replaceAllofTarget) { struct TestReplaceSelectedDataStructure { const char* testDescription ; const char* input ; int startPosition ; int replaceLength ; int inputLength ; int charactersToCopy ; const char* expectedForCopyAll ; const char* expectedForCopyLimited ; }; const char* prefix = "test replace(start, end, char*, len), where char* = " ; const char* suffix1 ; const char* suffix2 ; if (replaceAllofTarget) { suffix1 = "size = len(targetString) :- verify if replaced" ; suffix2 = "size = len(targetString) :- verify return value"; } else { suffix1 = "size < len(targetString) -2 :- verify if replaced" ; suffix2 = "size < len(targetString) -2 :- verify return value"; } string Message ; const char* baseString = "string rep" ; TestReplaceSelectedDataStructure testData[] = { \ { "an empty string. start = 0; last = 0 ", \ "", 0, 10, 0, 0, "", "" }, \ { "a regular string. start > 0; last < len(baseString) ", \ "Test Str", 2, 4, 8, 4, "stTest Str rep", "stTest rep" }, \ { "a alpha-num string. start > 0; last < len(baseString) ", \ "Te12 $tr", 2, 4, 8, 4, "stTe12 $tr rep", "stTe12 rep" }, \ { "a regular string. start > 0; last = total no. of remaining characters", \ "Test Str", 2, 8, 8, 4, "stTest Str", "stTest" }, \ { "a alpha-num string. start > 0 ; last > len(baseString) ", \ "Te12 $tr", 2, 11, 8, 4, "stTe12 $tr", "stTe12" } \ } ; const int testCount = sizeof(testData)/sizeof(testData[0]) ; // Using all the data that was created above, run the actual tests. for(int i = 0 ; i < testCount ; i++) { UtlString ts1(baseString) ; UtlString ts2; const char* expected ; if (replaceAllofTarget) { ts2 = ts1.replace(testData[i].startPosition, testData[i].replaceLength, \ testData[i].input, testData[i].inputLength) ; expected = testData[i].expectedForCopyAll ; } else { ts2 = ts1.replace(testData[i].startPosition, testData[i].replaceLength, \ testData[i].input, testData[i].charactersToCopy) ; expected = testData[i].expectedForCopyLimited ; } // Verify if the selected text was replaced. TestUtilities::createMessage(3, &Message, prefix, testData[i].testDescription, \ suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), string(expected), string(ts1.data())) ; // Verify return value TestUtilities::createMessage(3, &Message, prefix, testData[i].testDescription, \ suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), string(expected), string(ts2.data())) ; } } //utlTestReplace /** Test the strip() to strip off trailing spaces. * * The different types of strings to be used for testing this case are * a) An Empty String * b) A regular string with trailing spaces c) A regular string with leading spaces * d) A regular string without spaces * e) An alphanumeric string with trailing spaces * f) An alphanumeric string without trailing spaces * g) An alphanumeric string with both spaces * h) Space only string */ void testStrip_Default() { KNOWN_EFENCE_BUG("Segmentation fault, EF_PROTECT_BELOW=1", "XPL-8"); utlTestStripSpaces(UtlString::trailing, false, false) ; } /** Test the strip() method by specifying the strip type explicitly * * This test is exactly similar to the testStrip_Default() one and * hence the test data is the same * Add another test here in which you explicitly specify that the * space character is to be striped. */ void testStrip_TrailingSpaces_SpecifyStripType() { KNOWN_EFENCE_BUG("Segmentation fault, EF_PROTECT_BELOW=1", "XPL-8"); utlTestStripSpaces(UtlString::trailing, true, false) ; utlTestStripSpaces(UtlString::trailing, true, true) ; } /** Test the strip() method for stripping off the leading spaces * * The different types of strings to be used for testing this case are * the same as in the testStrip_Default() method. */ void testStrip_LeadingSpaces() { utlTestStripSpaces(UtlString::leading, true, false) ; utlTestStripSpaces(UtlString::leading, true, true) ; } /** Test the strip() method for stripping off the leading spaces * * The different types of strings to be used for testing this case are * the same as in the testStrip_Default() method. */ void testStrip_AllSpaces() { utlTestStripSpaces(UtlString::both, true, false) ; utlTestStripSpaces(UtlString::both, true, true) ; } /** Utility to test striping of space characters. By altering the parameters * you can test the different strip flavours: * The first parameter controls whether you want to 'strip' leading characters, * trailing characters or both charactersr. The other two parameters are used to * test variants of testing spaces - viz. a) test when the type * of 'stripping' has been explicitly specified as trailing / nothing has specified. * and b) test when the character to be specified has been explicitly specifed as ' ' or * nothing has been specified. */ void utlTestStripSpaces(UtlString::StripType sType, \ bool specifyStripType, bool specifyChar) { // We need a string which has both leading and // trailing spaces. UtlString longStr(" ") ; longStr.append(longAlphaString) ; longStr.append(" ") ; // To evaluate the expected string resulting out of a strip(trail), // construct a string with only the longAlphaString and leading) spaces UtlString tmpStringForTrailing(" ") ; tmpStringForTrailing.append(longAlphaString) ; size_t tmpStrTrailLen = strlen( tmpStringForTrailing.data() ); // To evaluate the expected string resulting out of a strip(leading), // construct a string with only the longAlphaString and trailing spaces UtlString tmpStringForLeading(longAlphaString) ; tmpStringForLeading.append(" ") ; size_t tmpStrLeadLen = strlen( tmpStringForLeading.data() ); const char* expectedForLeading = tmpStringForLeading.data() ; const char* expectedForTrailing = tmpStringForTrailing.data() ; // If both sides are striped then the expected // string would just be longAlphaString const char* expectedForBoth = longAlphaString ; size_t tmpStrBothLen = strlen( expectedForBoth ) ; const TestStripDataStructure testData[] = { \ { "empty char*", "", ' ', \ "", "", "" }, \ { "regular char* w/o spaces", "A String", ' ', \ "A String", "A String", "A String" }, \ { "regular char* w trailing spaces", "A String ", ' ', \ "A String", "A String ", "A String" }, \ { "regular char* w leading spaces", " A String", ' ', \ " A String", "A String", "A String" }, \ { "alpha-num char* w/o spaces", "String12#2A", ' ',\ "String12#2A", "String12#2A", "String12#2A" }, \ { "alpha-num char* w trailing spaces", "String12#2A ", ' ', \ "String12#2A", "String12#2A ", "String12#2A" }, \ { "alpha-num char* w both spaces", " String12#2A ", ' ', \ " String12#2A", "String12#2A ", "String12#2A" }, \ { "space only char*", " ", ' ', \ "", "", ""} , \ { "Very long char*", longStr.data(), ' ', \ expectedForTrailing, expectedForLeading, expectedForBoth } \ } ; // create the first part of the message based on the type of striping to be done! UtlString prefix("Test the strip(") ; if (specifyStripType) { switch(sType) { case UtlString::trailing : prefix.append("trailing") ; break ; case UtlString::leading : prefix.append("leading") ; break ; case UtlString::both : prefix.append("both") ; break ; default: printf("\n Invalid sType: %d\n", sType ); CPPUNIT_ASSERT_MESSAGE( "Invalid sType", 0 ); break ; } } if (specifyChar) { prefix.append(", ' '") ; } prefix.append(") for a string made of ") ; const int testCount = sizeof(testData) / sizeof(testData[0]) ; for (int i = 0 ; i < testCount; i++) { UtlString testString(testData[i].input) ; size_t datalength = strlen( testData[i].input ); size_t utlTestStrLen = testString.length(); size_t utlTestCharLen = strlen( testString.data() ); CPPUNIT_ASSERT_EQUAL_MESSAGE("Test dataLen Not equal UtlString::Length", \ datalength, utlTestStrLen ) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Test UtlString::Length Not equal UtlString::data length", \ utlTestStrLen, utlTestCharLen ) ; UtlString returnString ; string Message ; if (specifyStripType) { if(specifyChar) { returnString = testString.strip(sType, ' '); } else { returnString = testString.strip(sType) ; } } else { KNOWN_EFENCE_BUG("Segmentation fault w/efence", "XPL-9"); returnString = testString.strip() ; } const char* expectedValue = ""; switch(sType) { case UtlString::trailing: expectedValue = testData[i].expectedForStripTrailing ; break ; case UtlString::leading: expectedValue = testData[i].expectedForStripLeading; break ; case UtlString::both: expectedValue = testData[i].expectedForStripBoth ; break ; } TestUtilities::createMessage(2, &Message, prefix.data(), \ testData[i].testDescription) ; if (strcmp(expectedValue, returnString.data())) { size_t expStrlen = strlen( expectedValue ); size_t actStrlen = strlen( returnString.data() ); printf("\nNon-matching strings[%d]:\n", i ); printf("[%d]%s\n", expStrlen, expectedValue ); printf("[%d]%s\n", actStrlen, returnString.data() ); printf("\n----------------\n"); printf("\n"); } CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), \ string(expectedValue), \ string(returnString.data())) ; } } //utlTestStripSpaces /** Test the strip() method for stripping of characters other than * spaces * Test data for this test case is :- * a) Empty string * b) String that has trailing 'c' s. * c) String that has leading 'c'. * d) String that has spaces on both ends * e) String that has 'c' on both ends * f) String w/o 'c' and w/o spaces. * g) String w/o 'c' but with spaces. */ void testStrip_Characters() { const char* prefix = "For a " ; const char* suffix1 = " :- test the strip(trailing, 'c') method" ; const char* suffix2 = " :- test the strip(leading, 'c') method" ; const char* suffix3 = " :- test the strip(both, 'c') method" ; string Message ; /* TestStripDataStructure : testDescription, input, characterToStrip, \ expectedForStripTrailing, expectedForStripLeading, expectedForStripBoth \ */ const TestStripDataStructure testData[] = { \ { "empty string", "", 'e',\ "", "", "" }, \ { "string that has trailing 'c's", "Test Stree", 'e', \ "Test Str", "Test Stree", "Test Str" }, \ { "string that has leading 'c's", "eeTest Str", 'e', \ "eeTest Str", "Test Str", "Test Str" }, \ { "string that has 'c's on both sides", "eeeTest Stre", 'e', \ "eeeTest Str", "Test Stre", "Test Str" }, \ { "string with no 'c's or spaces", "Test Str", 'e', \ "Test Str", "Test Str", "Test Str" }, \ { "string with no 'c's but has spaces", " Test Str ", 'e', \ " Test Str ", " Test Str ", " Test Str " } \ } ; const int testCount = sizeof(testData) / sizeof(testData[0]) ; // Test the case of striping trailing characters for (int i = 0 ; i < testCount ; i++) { UtlString::StripType sType = UtlString::trailing ; UtlString testString(testData[i].input) ; UtlString returnString = testString.strip(sType, \ testData[i].characterToStrip) ; TestUtilities::createMessage(3, &Message, prefix, \ testData[i].testDescription, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), \ string(testData[i].expectedForStripTrailing), string(returnString.data())) ; } // Test the case of striping leading characters for (int j = 0 ; j < testCount ; j++) { UtlString::StripType sType = UtlString::leading ; UtlString testString(testData[j].input) ; UtlString returnString = testString.strip(sType, \ testData[j].characterToStrip) ; TestUtilities::createMessage(3, &Message, prefix, testData[j].testDescription, \ suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), \ string(testData[j].expectedForStripLeading), string(returnString.data())) ; } // Test the case of striping characters on both ends for (int k = 0 ; k < testCount ; k++) { UtlString::StripType sType = UtlString::both ; UtlString testString(testData[k].input) ; UtlString returnString = testString.strip(sType, \ testData[k].characterToStrip) ; TestUtilities::createMessage(3, &Message, prefix, \ testData[k].testDescription, suffix3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), \ string(testData[k].expectedForStripBoth), string(returnString.data())) ; } } /** Test the resize() method for a string. * The test data for this test are :- * 1) When the string is empty, resize to 0 * 2) When the string is empty, resize to non-zero * 3) When the string is not empty, resize to n > current size * 4) When the string is not empty, resize to n = current size * 5) When the string is empty, resize to n < current size */ void testResize() { struct TestResizeStruct { const char* testDescription ; const char* stringData ; int resizeLength ; const char* expectedString ; int expectedLength ; } ; const char* prefix = "Test the resize(n) method for " ; const char* suffix1 = " - Verify modified string data" ; const char* suffix2 = " - Verify modified string length" ; string Message ; TestResizeStruct testData[] = { \ { "an empty string. Set n to 0", "", 0, "", 0 }, \ { "an empty string. Set n to > 0", "", 5, "", 5 }, \ { "a non-empty string. Set n > current size", "Test String", 14, \ "Test String", 14 }, \ { "a non-empty string. Set n = current size", "Test String", 11, \ "Test String", 11 }, \ { "a non-empty string. Set n < current size", "Test String", 6, \ "Test S", 6 } \ } ; int testCount = sizeof(testData)/sizeof(testData[0]) ; for (int i = 0 ; i < testCount; i++) { UtlString testString(testData[i].stringData) ; testString.resize(testData[i].resizeLength) ; //Verify target string's data TestUtilities::createMessage(3, &Message, prefix, testData[i].testDescription,\ suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), string(testData[i].expectedString), \ string(testString.data())) ; //Verify target string's length TestUtilities::createMessage(3, &Message, prefix, testData[i].testDescription,\ suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), testData[i].expectedLength, \ (int)testString.length()) ; } } }; CPPUNIT_TEST_SUITE_REGISTRATION(UtlStringTest_DestructiveManipulators); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlStringTest_NonMutating.cpp0000644000175000017500000020756112205613256030066 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2010 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include #ifdef WIN32 # define MEMBER_CONST #else # define MEMBER_CONST const #endif // The following variables have been defined in the base class // and will be used in all the string tests /** const int UtlStringTest::commonTestSetLength; const char* UtlStringTest::longAlphaString; const char* UtlStringTest::splCharString; const BasicStringVerifier UtlStringTest::commonTestSet[]; const int UtlStringTest::commonTestSetLength ; */ /** This class is used to test the UtlString class. * * PLEASE READ THE README FILE THAT CAN FOUND IN THE SAME DIRECTORY AS * THIS FILE. The Readme describes the organization / flow of tests and * without reading this file, the following class (and all unit tests) * may not make a lot of sense and might be difficult to comprehend. */ class UtlStringTest_NonMutating : public UtlStringTest { CPPUNIT_TEST_SUITE(UtlStringTest_NonMutating); CPPUNIT_TEST(testSubstring); CPPUNIT_TEST(testCompareTo_exactMatch); CPPUNIT_TEST(testCompareTo_ignoreCase); CPPUNIT_TEST(testIsEquals); CPPUNIT_TEST(testEqualityOperator); CPPUNIT_TEST(testEqualityOperator2); CPPUNIT_TEST(testIndex_EmptyString); CPPUNIT_TEST(testIndex_SearchFromStart); CPPUNIT_TEST(testIndex_DontStartFromStart); CPPUNIT_TEST(testIndex_CaseInsensitiveMatch); CPPUNIT_TEST(testIndex_char_SearchFromStart); CPPUNIT_TEST(testIndex_char_DontStartFromStart); CPPUNIT_TEST(testFirst_char); CPPUNIT_TEST(testFirst_charstar); CPPUNIT_TEST(testContains_charstar); CPPUNIT_TEST(testLast_char); CPPUNIT_TEST(testLength); CPPUNIT_TEST(testLength_NonNullTerminatedData); CPPUNIT_TEST(testIsNull); CPPUNIT_TEST(testLowerAndUpper); CPPUNIT_TEST(testPlusOperator); CPPUNIT_TEST(testIndexOperator); CPPUNIT_TEST(testCharAtOperator); CPPUNIT_TEST_SUITE_END(); private : struct TestCompareDataStructure { const char* testDescription; const char* compareData1; const char* compareData2; int expectedValue; }; struct TestCharstarIndexDataStructure { const char* testDescription; const char* searchString; int startPosition; // Specify -1 to ignore this parameter size_t expectedValue; }; struct TestCharIndexDataStructure { MEMBER_CONST char* testDescription; MEMBER_CONST char searchCharacter; int startPosition; // Specify -1 to ignore this parameter size_t expectedValue; }; public: UtlStringTest_NonMutating() { } void setUp() { } void tearDown() { } ~UtlStringTest_NonMutating() { } /** Sandbox method for experimenting with the API Under Test. * This method MUST be empty when the test drivers are being * checked in (final checkin) to the repository. */ void DynaTest() { } /*!a Test the (start, length) operator. */ void testSubstring() { // Note that the start and length are size_t's, though we // construct some of their values by casting negative numbers. struct TestSubstringStructure { const char* string; size_t start; size_t length; const char* expectedValue; }; const char* prefix = "Test the (start, len) operator, with "; string Message; TestSubstringStructure testData[] = { // String of 0 characters. { "", 0, 0, "" }, { "", 0, 1, "" }, { "", 0, 10, "" }, { "", 0, UtlString::UTLSTRING_TO_END, "" }, { "", 0, (size_t) (-2), "" }, { "", 1, 0, "" }, { "", 1, 1, "" }, { "", 1, 10, "" }, { "", 1, UtlString::UTLSTRING_TO_END, "" }, { "", 1, (size_t) (-2), "" }, { "", UtlString::UTLSTRING_TO_END, 0, "" }, { "", UtlString::UTLSTRING_TO_END, 1, "" }, { "", UtlString::UTLSTRING_TO_END, 10, "" }, { "", UtlString::UTLSTRING_TO_END, UtlString::UTLSTRING_TO_END, "" }, { "", UtlString::UTLSTRING_TO_END, (size_t) (-2), "" }, // Test (-2) as well as UtlString::UTLSTRING_TO_END, since -1 is a special value, (-2) // might be handled differently. { "", (size_t) (-2), 0, "" }, { "", (size_t) (-2), 1, "" }, { "", (size_t) (-2), 10, "" }, { "", (size_t) (-2), UtlString::UTLSTRING_TO_END, "" }, { "", (size_t) (-2), (size_t) (-2), "" }, // String of 1 character. { "a", 0, 0, "" }, { "b", 0, 1, "b" }, { "c", 0, 2, "" }, { "d", 0, 10, "" }, { "e", 0, UtlString::UTLSTRING_TO_END, "e" }, { "f", 0, (size_t) (-2), "" }, { "g", 1, 0, "" }, { "h", 1, 1, "" }, { "i", 1, 2, "" }, { "j", 1, 10, "" }, { "k", 1, UtlString::UTLSTRING_TO_END, "" }, { "l", 1, (size_t) (-2), "" }, { "g", 2, 0, "" }, { "h", 2, 1, "" }, { "i", 2, 2, "" }, { "j", 2, 10, "" }, { "k", 2, UtlString::UTLSTRING_TO_END, "" }, { "l", 2, (size_t) (-2), "" }, { "m", UtlString::UTLSTRING_TO_END, 0, "" }, { "n", UtlString::UTLSTRING_TO_END, 1, "" }, { "o", UtlString::UTLSTRING_TO_END, 2, "" }, { "p", UtlString::UTLSTRING_TO_END, 3, "" }, { "q", UtlString::UTLSTRING_TO_END, 10, "" }, { "r", UtlString::UTLSTRING_TO_END, UtlString::UTLSTRING_TO_END, "" }, { "s", UtlString::UTLSTRING_TO_END, (size_t) (-2), "" }, { "t", (size_t) (-2), 0, "" }, { "u", (size_t) (-2), 1, "" }, { "v", (size_t) (-2), 2, "" }, { "w", (size_t) (-2), 3, "" }, { "x", (size_t) (-2), 4, "" }, { "y", (size_t) (-2), 10, "" }, { "z", (size_t) (-2), UtlString::UTLSTRING_TO_END, "" }, { "A", (size_t) (-2), (size_t) (-2), "" }, // String of 2 characters. { "aQ", 0, 0, "" }, { "bW", 0, 1, "b" }, { "cE", 0, 2, "cE" }, { "cE", 0, 3, "" }, { "dR", 0, 10, "" }, { "eT", 0, UtlString::UTLSTRING_TO_END, "eT" }, { "fY", 0, (size_t) (-2), "" }, { "gU", 1, 0, "" }, { "hI", 1, 1, "I" }, { "iO", 1, 2, "" }, { "iO", 1, 3, "" }, { "jP", 1, 10, "" }, { "kA", 1, UtlString::UTLSTRING_TO_END, "A" }, { "lS", 1, (size_t) (-2), "" }, { "gU", 2, 0, "" }, { "hI", 2, 1, "" }, { "iO", 2, 2, "" }, { "jP", 2, 10, "" }, { "kA", 2, UtlString::UTLSTRING_TO_END, "" }, { "lS", 2, (size_t) (-2), "" }, { "gU", 3, 0, "" }, { "hI", 3, 1, "" }, { "iO", 3, 2, "" }, { "iO", 3, 3, "" }, { "jP", 3, 10, "" }, { "kA", 3, UtlString::UTLSTRING_TO_END, "" }, { "lS", 3, (size_t) (-2), "" }, { "mD", UtlString::UTLSTRING_TO_END, 0, "" }, { "nF", UtlString::UTLSTRING_TO_END, 1, "" }, { "oG", UtlString::UTLSTRING_TO_END, 2, "" }, { "pH", UtlString::UTLSTRING_TO_END, 3, "" }, { "pH", UtlString::UTLSTRING_TO_END, 4, "" }, { "qJ", UtlString::UTLSTRING_TO_END, 10, "" }, { "rK", UtlString::UTLSTRING_TO_END, UtlString::UTLSTRING_TO_END, "" }, { "sL", UtlString::UTLSTRING_TO_END, (size_t) (-2), "" }, { "tZ", (size_t) (-2), 0, "" }, { "uX", (size_t) (-2), 1, "" }, { "vC", (size_t) (-2), 2, "" }, { "wV", (size_t) (-2), 3, "" }, { "xB", (size_t) (-2), 4, "" }, { "xB", (size_t) (-2), 5, "" }, { "yN", (size_t) (-2), 10, "" }, { "zM", (size_t) (-2), UtlString::UTLSTRING_TO_END, "" }, { "Aq", (size_t) (-2), (size_t) (-2), "" }, // String of 3 characters. { "aQ0", 0, 0, "" }, { "bW1", 0, 1, "b" }, { "cE2", 0, 2, "cE" }, { "cE3", 0, 3, "cE3" }, { "cE3", 0, 4, "" }, { "dR4", 0, 10, "" }, { "eT5", 0, UtlString::UTLSTRING_TO_END, "eT5" }, { "fY6", 0, (size_t) (-2), "" }, { "gU7", 1, 0, "" }, { "hI8", 1, 1, "I" }, { "iO9", 1, 2, "O9" }, { "iO0", 1, 3, "" }, { "jP1", 1, 10, "" }, { "kA2", 1, UtlString::UTLSTRING_TO_END, "A2" }, { "lS3", 1, (size_t) (-2), "" }, { "gU7", 2, 0, "" }, { "hI8", 2, 1, "8" }, { "iO9", 2, 2, "" }, { "iO0", 2, 3, "" }, { "jP1", 2, 10, "" }, { "kA2", 2, UtlString::UTLSTRING_TO_END, "2" }, { "lS3", 2, (size_t) (-2), "" }, { "gU7", 3, 0, "" }, { "hI8", 3, 1, "" }, { "iO9", 3, 2, "" }, { "iO0", 3, 3, "" }, { "jP1", 3, 10, "" }, { "kA2", 3, UtlString::UTLSTRING_TO_END, "" }, { "lS3", 3, (size_t) (-2), "" }, { "gU7", 4, 0, "" }, { "hI8", 4, 1, "" }, { "iO9", 4, 2, "" }, { "iO0", 4, 3, "" }, { "jP1", 4, 10, "" }, { "kA2", 4, UtlString::UTLSTRING_TO_END, "" }, { "lS3", 4, (size_t) (-2), "" }, { "mD4", UtlString::UTLSTRING_TO_END, 0, "" }, { "nF5", UtlString::UTLSTRING_TO_END, 1, "" }, { "oG6", UtlString::UTLSTRING_TO_END, 2, "" }, { "pH7", UtlString::UTLSTRING_TO_END, 3, "" }, { "pH8", UtlString::UTLSTRING_TO_END, 4, "" }, { "pH8", UtlString::UTLSTRING_TO_END, 5, "" }, { "qJ9", UtlString::UTLSTRING_TO_END, 10, "" }, { "rK0", UtlString::UTLSTRING_TO_END, UtlString::UTLSTRING_TO_END, "" }, { "sL1", UtlString::UTLSTRING_TO_END, (size_t) (-2), "" }, { "tZ2", (size_t) (-2), 0, "" }, { "uX3", (size_t) (-2), 1, "" }, { "vC4", (size_t) (-2), 2, "" }, { "wV5", (size_t) (-2), 3, "" }, { "xB6", (size_t) (-2), 4, "" }, { "xB7", (size_t) (-2), 5, "" }, { "xB7", (size_t) (-2), 6, "" }, { "yN8", (size_t) (-2), 10, "" }, { "zM9", (size_t) (-2), UtlString::UTLSTRING_TO_END, "" }, { "Aq0", (size_t) (-2), (size_t) (-2), "" }, // String of 10 characters. { "pinesitaQ0", 0, 0, "" }, { "nssae > 1) + 1, ~(~((size_t) 0) >> 1) + 1, "" } }; // Go through the table of tests. for (unsigned i=0; i < sizeof(testData)/sizeof(testData[0]); i++) { // Get the test string as a UtlString. UtlString testString(testData[i].string); // Get the expected value as a UtlString. UtlString expectedValue(testData[i].expectedValue); // Assemble the test description. char description[80]; sprintf(description, "\"%s\"(%d, %d)", testData[i].string, testData[i].start, testData[i].length); // Execute the (start, length) operator. UtlString actualValue = testString((size_t) (testData[i].start), (size_t) (testData[i].length)); TestUtilities::createMessage(2, &Message, prefix, description); CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), expectedValue, actualValue); } }//testSubstring /** testCase for comparing the compareTo(char* ) / compareTo(UtlString) method * This test case checks the compareTo() method for a caseSensitive comparision * * The test data for this test case is :- * a) "lhs is empty. rhs is not", * b) "rhs is empty. lhs is not", * c) "lhs = rhs", * d) "lhs =~ rhs. The first character of lhs is lower case", * e) "lhs =~ rhs. The first character of lhs is upper case", * f) "lhs =~ rhs. The last character of lhs is lower case", * g) "lhs =~ rhs. The last character of lhs is upper case", * h) "lhs != rhs. The first character of the lhs is alphabetically first", * i) "lhs != rhs. The first character of the lhs is alphabetically second", * j) "lhs != rhs. After initial similarity in characters, the character(s) in the lhs are before those in the rhs" , * k) "lhs != rhs. After initial similarity in characters, the character(s) in the lhs are after those in the rhs", * l) "lhs != rhs. Text is alphanumeric. After initial similarity, the digit(s) in the lhs are before that in the rhs", * m) "lhs != rhs. Text is alphanumeric. After initial similarity, the digit(s) in the lhs are after that in the rhs", * n) "lhs != rhs. The text has special characters" * * Each of the above cases is verified for * 1) compareTo(char*) * 2) compareTo(char*, caseMatch=exactMatch) * 3) compareTo(UtlString) * 4) compareTo(UtlString, caseMatch=exactMatch) */ void testCompareTo_exactMatch() { const char* prefix = "Test the compareTo method when "; /* Composition of TestCompareDataStructure: testDescription, compareData1, compareData2, expectedValue; */ const TestCompareDataStructure testData[] = { \ { "lhs is empty. rhs is not", "", "test string", -1 },\ { "rhs is empty. lhs is not", "test string", "", 1 },\ { "rhs is empty. lhs is empty", "", "", 0 }, \ { "lhs == rhs", "test string", "test string", 0 },\ { "lhs =~ rhs. The first character of lhs is lower case", \ "Test string", "test string", -1 },\ { "lhs =~ rhs. The first character of lhs is upper case", \ "test string", "Test string", 1 },\ { "lhs =~ rhs. The last character of lhs is lower case", \ "test strinG", "test string", -1 }, \ { "lhs =~ rhs. The last character of lhs is upper case", \ "test string", "test strinG", 1 },\ { "lhs != rhs. The first character of the lhs is alphabetically first", \ "Hey dude", "No way", -1 },\ { "lhs != rhs. The first character of the lhs is alphabetically second", \ "Why is this", "May be not", 1 }, \ { "lhs != rhs. After initial similarity in characters, the character(s)" \ " in the lhs are before those in the rhs", \ "This is good", "This is sick", -1 },\ { "lhs != rhs. After initial similarity in characters, the character(s) in the lhs " \ "are after those in the rhs", \ "Are we right?", "Are we not?", 1 }, \ { "lhs != rhs. Text is alphanumeric. After initial similarity, the digit(s) in the lhs " \ "are before that in the rhs", \ "Number891", "Number93", -1 },\ { "lhs != rhs. Text is alphanumeric. After initial similarity, the digit(s) in the lhs " \ "are after that in the rhs", \ "Number765", "Number1234", 1 },\ { "lhs != rhs. The text has special characters", \ "T#ter", "T&ter", -1 }, // lhs < rhs { "lhs == rhs. The text has special characters", \ "TÜter", "TÜter", 0 } \ }; const int testCount = sizeof(testData)/sizeof(testData[0]); // Test the compare to method when the matchCase is not specified // and is assumed as default, The parameter passed is a char* utlTestCompareTo(prefix, testData, testCount, false, \ TYPE_CHARSTAR, UtlString::matchCase); // Test the compare to method when the matchCase is specified explicitly // The parameter passed is a char* utlTestCompareTo(prefix, testData, testCount, true, \ TYPE_CHARSTAR, UtlString::matchCase); // Test the compare to method when the matchCase is specified explicitly // The parameter passed is a UtlString utlTestCompareTo(prefix, testData, testCount, true, \ TYPE_UTLSTRING, UtlString::matchCase); } /** TestCase for comparing the compareTo(char*, CompareCase=ignoreCase) / compareTo (UtlString) This test case checks the compareTo() methods for a caseInsensitive comparision * * The test data for this test case is :- * a) "lhs is empty. rhs is not", * b) "rhs is empty. lhs is not", * c) "lhs == rhs", * d) "lhs =~ rhs. All the characters in the two strings have their case flipped", * e) "lhs =~ rhs. The characters are such that some have the same case, while others have 'em flipped", * f) "lhs != rhs. The first non-matching character is alphabetically first in the lhs (case doesnt matter)", * g) "lhs != rhs. The first non-matching character is alphabetically first in the rhs (case doesn't matter)", * h) "lhs != rhs. The strings are alpha-numeric", * i) "lhs != rhs. The strings have special characters", * j) "lhs == rhs. The strings have special characters" * */ void testCompareTo_ignoreCase() { const char* prefix = "Test the compareTo method when "; /* Composition of TestCompareDataStructure: testDescription, compareData1, compareData2, expectedValue; */ TestCompareDataStructure testData[] = { \ { "lhs is empty. rhs is not", "", "test string", -1}, \ { "rhs is empty. lhs is not", "test string", "", 1}, \ { "lhs == rhs", "test string", "test string", 0}, \ { "lhs =~ rhs. All the characters in the two strings have their case flipped", \ "TesT sTriNg", "tESt StRInG", 0}, \ { "lhs =~ rhs. The characters are such that some have the same case, while " \ "others have 'em flipped", "Test String", "TesT STring", 0}, \ { "lhs != rhs. The first non-matching character would make the lhs to appear " \ "before (case doesnt matter)", "Test String", "Test ttring", -1}, \ { "lhs != rhs. The first non-matching character would make the lhs to appear later " \ "(case doesn't matter)", "Test String", "Test bring", 1}, \ { "lhs != rhs. The strings are alpha-numeric", "Test234", "tEst1234", 1}, \ { "lhs != rhs. The strings have special characters", "Test^#", "test#^", 1}, \ { "lhs == rhs. The strings have special characters", "Test^#", "test^#", 0} \ }; const int testCount = sizeof(testData)/sizeof(testData[0]) ; utlTestCompareTo(prefix, testData, testCount, true, TYPE_CHARSTAR, \ UtlString::ignoreCase); utlTestCompareTo(prefix, testData, testCount, true, TYPE_UTLSTRING, \ UtlString::ignoreCase); } /** * utility used for testing the compareTo method. The type of test is controlled by the last * (optional) parameters. If specifyEnum is set to false, then the compareTo() function is * called without the CompareCase parameter (amounts to string.compareTo(char*) or * string.compareTo(string)). If set to true, then the method is called with the * argument(amoutns to string.compareTo(char*, enum) or string.compareTo(string, enum). * If the type parameter is set to 0, then the compareTo(char* ,..) is called. If set to 1, * then compareTo(UtlString, ..) is called */ void utlTestCompareTo(const char* prefix, const TestCompareDataStructure testData[], \ const int testCount, bool specifyEnum, StringType type, \ UtlString::CompareCase caseCompare) { const char* suffix; string Message; if (type == TYPE_CHARSTAR ) { if (specifyEnum) { if (caseCompare == UtlString::ignoreCase) { suffix = " :- compareTo(char*, CompareCase=ignore) "; } else { suffix = " :- compareTo(char*, CompareCase=exact) "; } } else { suffix = " :- compareTo(char*)"; } } // else type is to compareTo UtlString else { if (specifyEnum) { if (caseCompare == UtlString::ignoreCase) { suffix = " :- compareTo(UtlString, CompareCase=ignore) "; } else { suffix = " :- compareTo(UtlString, CompareCase=exact) "; } } else { suffix = " :- compareTo(UtlString) " ; } } for ( int i = 0; i < testCount; i++) { UtlString compareString1(testData[i].compareData1); UtlString compareString2(testData[i].compareData2); int cmpResult; if (type == TYPE_CHARSTAR) { if (specifyEnum) { cmpResult = compareString1.compareTo(testData[i].compareData2, caseCompare); } else { cmpResult = compareString1.compareTo(testData[i].compareData2); } } else { cmpResult = compareString1.compareTo(&compareString2, caseCompare); } // When string 'a' comes before string 'b', we are not concerned about // what is the integer returned when you call a.compareTo(b). We only want // to check if it returns any negative number and so on. bool testResult = false; if (testData[i].expectedValue == 0) { testResult = cmpResult == 0; } else if (testData[i].expectedValue == -1) { testResult = cmpResult < 0; } else { testResult = cmpResult > 0; } TestUtilities::createMessage(3, &Message, prefix, testData[i].testDescription, \ suffix); CPPUNIT_ASSERT_MESSAGE(Message.data(), testResult); } } //utlTestCompareTo /*! Test the isEquals method. * * The test data for this test is :- * a) Test two strings that*ARE* equal * b) Test two strings that would have been equal if the search were case sensitive. * c) Test two strings that are not equal. * d) Check an empty string with a non empty string * e) Check an empty string with an empty String * 6) Check a String with an Integer */ void testIsEquals() { const char* prefix = "Test the isEquals method for a string such that "; string Message; //Since the equals / compareTo methods are almost similar, use // the same data structure /* Composition of TestCompareDataStructure: testDescription, compareData1, compareData2, expectedValue; */ const TestCompareDataStructure testData[] = { \ { "the two strings *ARE* equal" , \ "Hello World", "Hello World", 1}, \ { "the two strings match for a case-insensitive search", \ "Hello World", "hello world", 0}, \ { "the two strings are not equal", \ "Hello World", "Different Universe", 0}, \ { "lhs is an empty string and rhs is not" , \ "", "Hello World", 0}, \ { "both the strings are empty strings" , "", "", 1 }, \ }; const int testCount = sizeof(testData)/sizeof(testData[0]); for(int i = 0; i < testCount; i++) { UtlString testString(testData[i].compareData1); UtlString compareString(testData[i].compareData2); bool actual = (TRUE == testString.isEqual(&compareString)); bool expected = (testData[i].expectedValue == 1); TestUtilities::createMessage(2, &Message, prefix, testData[i].testDescription); CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), expected, actual); } // Now check the case where a different type of collectable is compared to // a string UtlString testString("123"); UtlInt testInt(123); bool actual = (TRUE == testString.isEqual(&testInt)); TestUtilities::createMessage(2, &Message, prefix, "the target is not a UtlString"); CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), false, actual); } // testIsEqual(); /** * Test [not]equality operator on strings, left-hand and * right-hand variations. */ void testEqualityOperator() { struct EqualityOperatorTestData { MEMBER_CONST char rhs[128]; MEMBER_CONST char lhs[128]; bool isequal; }; const EqualityOperatorTestData data[] = { {"", "", true}, {"test", "test", true}, {"test", "tEst", false}, {"good", "bad", false}, {"abcd", "abcf", false} }; char msg[1024]; UtlString utlstr; int n = sizeof(data) / sizeof(data[0]); for (int i = 0; i < n; i++) { utlstr = data[i].rhs; sprintf(msg, "(UtlString)\"%s\" == (char *)\"%s\"", data[i].rhs, data[i].lhs); CPPUNIT_ASSERT_EQUAL_MESSAGE(msg, (int)data[i].isequal, (int)(utlstr == data[i].lhs)); sprintf(msg, "(UtlString)\"%s\" != (char *)\"%s\"", data[i].rhs, data[i].lhs); CPPUNIT_ASSERT_EQUAL_MESSAGE(msg, (int)!data[i].isequal, (int)(utlstr != data[i].lhs)); utlstr = data[i].lhs; sprintf(msg, "(char *)\"%s\" == (UtlString)\"%s\"", data[i].rhs, data[i].lhs); CPPUNIT_ASSERT_EQUAL_MESSAGE(msg, (int)data[i].isequal, (int)(data[i].rhs == utlstr)); sprintf(msg, "(char *)\"%s\" != (UtlString)\"%s\"", data[i].rhs, data[i].lhs); CPPUNIT_ASSERT_EQUAL_MESSAGE(msg, (int)!data[i].isequal, (int)(data[i].rhs != utlstr)); } } /** * Test == and != on a series of cases with a variety of type combinations. */ void testEqualityOperator2() { // Construct one-character test strings. const char* s_a1 = "a"; const char* s_a2 = "a"; const char* s_b = "b"; // Construct UtlStrings. const UtlString u_a1 = "a"; const UtlString u_a2 = "a"; const UtlString u_b = "b"; // Compare (const UtlString) to (const UtlString). CPPUNIT_ASSERT_MESSAGE("u_a1 == u_a1", (u_a1 == u_a1) == 1); CPPUNIT_ASSERT_MESSAGE("u_a1 == u_a2", (u_a1 == u_a2) == 1); CPPUNIT_ASSERT_MESSAGE("u_a1 == u_b", (u_a1 == u_b) == 0); CPPUNIT_ASSERT_MESSAGE("u_a1 != u_a1", (u_a1 != u_a1) == 0); CPPUNIT_ASSERT_MESSAGE("u_a1 != u_a2", (u_a1 != u_a2) == 0); CPPUNIT_ASSERT_MESSAGE("u_a1 != u_b", (u_a1 != u_b) == 1); // Compare (const UtlString) to (const char*). CPPUNIT_ASSERT_MESSAGE("u_a1 == s_a1", (u_a1 == s_a1) == 1); CPPUNIT_ASSERT_MESSAGE("u_a1 == s_a2", (u_a1 == s_a2) == 1); CPPUNIT_ASSERT_MESSAGE("u_a1 == s_b", (u_a1 == s_b) == 0); CPPUNIT_ASSERT_MESSAGE("u_a1 != s_a1", (u_a1 != s_a1) == 0); CPPUNIT_ASSERT_MESSAGE("u_a1 != s_a2", (u_a1 != s_a2) == 0); CPPUNIT_ASSERT_MESSAGE("u_a1 != s_b", (u_a1 != s_b) == 1); // Compare (const char*) to (const UtlString). CPPUNIT_ASSERT_MESSAGE("s_a1 == u_a1", (s_a1 == u_a1) == 1); CPPUNIT_ASSERT_MESSAGE("s_a1 == u_a2", (s_a1 == u_a2) == 1); CPPUNIT_ASSERT_MESSAGE("s_a1 == u_b", (s_a1 == u_b) == 0); CPPUNIT_ASSERT_MESSAGE("s_a1 != u_a1", (s_a1 != u_a1) == 0); CPPUNIT_ASSERT_MESSAGE("s_a1 != u_a2", (s_a1 != u_a2) == 0); CPPUNIT_ASSERT_MESSAGE("s_a1 != u_b", (s_a1 != u_b) == 1); // Compare (const UtlString) to (const char). // These operators do not exist. // Compare (const char) to (const UtlString). CPPUNIT_ASSERT_MESSAGE("u_a1[0] == u_a1", (u_a1[0] == u_a1) == 1); CPPUNIT_ASSERT_MESSAGE("u_a1[0] == u_a2", (u_a1[0] == u_a2) == 1); CPPUNIT_ASSERT_MESSAGE("u_a1[0] == u_b", (u_a1[0] == u_b) == 0); CPPUNIT_ASSERT_MESSAGE("u_a1[0] != u_a1", (u_a1[0] != u_a1) == 0); CPPUNIT_ASSERT_MESSAGE("u_a1[0] != u_a2", (u_a1[0] != u_a2) == 0); CPPUNIT_ASSERT_MESSAGE("u_a1[0] != u_b", (u_a1[0] != u_b) == 1); // Compare (const UtlString*) to (const UtlString*). // This is a pointer comparison, not a string comparison. CPPUNIT_ASSERT_MESSAGE("&u_a1 == &u_a1", (&u_a1 == &u_a1) == 1); CPPUNIT_ASSERT_MESSAGE("&u_a1 == &u_a2", (&u_a1 == &u_a2) == 0); CPPUNIT_ASSERT_MESSAGE("&u_a1 == &u_b", (&u_a1 == &u_b) == 0); CPPUNIT_ASSERT_MESSAGE("&u_a1 != &u_a1", (&u_a1 != &u_a1) == 0); CPPUNIT_ASSERT_MESSAGE("&u_a1 != &u_a2", (&u_a1 != &u_a2) == 1); CPPUNIT_ASSERT_MESSAGE("&u_a1 != &u_b", (&u_a1 != &u_b) == 1); } /*a! Test case for comparing the index(char*, ...) methods for an empty string * * The test data for this test case is :- * 1. When the String is empty * a) Test trying to find another empty string * b) Test trying to find a non empty string * // Verify with bob if we are hanlding the next case. * c) Test trying to find, starting off from a non-zero position, for a * non empty string * For (a) to (b) verify by both specifying position explicitly * as 0 / not providing at all */ void testIndex_EmptyString() { const char* prefix = "Test index method for an empty string. Find "; string Message; const TestCharstarIndexDataStructure testData[] = { \ { "Empty char* string", "", -1, 0 }, \ { "Non empty char* string", "Some", -1, UtlString::UTLSTRING_NOT_FOUND} \ }; UtlString testString(""); const int testCount = sizeof(testData) / sizeof(testData[0]); for (int i =0; i 0; end0, #include #include #include #include class UtlTokenizerTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlTokenizerTest); CPPUNIT_TEST(testBasic); CPPUNIT_TEST(testDelimsAtVariousPositions); CPPUNIT_TEST_SUITE_END(); public: void testBasic() { struct TestBasicStructure { const char* testDescription ; const char* expectedString ; bool expectedReturnValue ; } ; const char* prefix = "Test the next() method for " ; const char* suffix1 = " :-Verify token" ; const char* suffix2 = " :-Verify return value" ; string Message ; UtlTokenizer tokens("one two three"); const char* delim = " "; TestBasicStructure testData[] = { \ { "1st token inaccurate", "one", true }, \ { "2nd token inaccurate", "two", true }, \ { "3rd token inaccurate", "three", true }, \ { "Unexpected ending tokens", "", false } \ } ; int testCount = sizeof(testData) / sizeof(testData[0]) ; for (int i = 0 ; i < testCount ; i++ ) { UtlString token; UtlBoolean returnValue = tokens.next(token, delim); TestUtilities::createMessage(3, &Message, prefix, testData[i].testDescription, \ suffix1) ; ASSERT_STR_EQUAL_MESSAGE(Message.data(), testData[i].expectedString, token.data()); TestUtilities::createMessage(3, &Message, prefix, testData[i].testDescription, \ suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), testData[i].expectedReturnValue, \ (TRUE == returnValue)) ; } ; } void testDelimsAtVariousPositions() { struct TokenizerTestData { const char* testDescription ; const char* tokenizedString; int expectedCount; }; char msg[1024]; TokenizerTestData testSet[] = { { "string with multiple delims", \ "---X---XX---", 3}, { "string with one delim at the begining", \ "X---", 1}, { "string with no token", \ "---", 1}, { "string ending with delim", \ "---X", 1}, { "string begining with multiple delims", \ "XXX---", 1}, { "string with nothing but the delim", \ "XXX", 0} }; int n = sizeof(testSet) / sizeof(testSet[0]); for (int i = 0; i < n; i++) { UtlTokenizer toks(testSet[i].tokenizedString); int actualCount = 0; UtlBoolean done = FALSE; while (!done) { UtlString tok; UtlBoolean bSuccess = toks.next(tok, "X"); done = tok.isNull(); if (!done) { memset(msg, 0, sizeof(msg)); sprintf(msg, "For %s, verify token number %d", testSet[i].testDescription, actualCount); ASSERT_STR_EQUAL_MESSAGE(msg, "---", tok.data()); actualCount++; memset(msg, 0, sizeof(msg)); sprintf (msg, "For %s, verify return value for token number %d", testSet[i].testDescription, actualCount); CPPUNIT_ASSERT_MESSAGE(msg, (TRUE == bSuccess)) ; } else { memset(msg, 0, sizeof(msg)); sprintf (msg, "For %s, verify return value after all tokens", testSet[i].testDescription); CPPUNIT_ASSERT_MESSAGE(msg, !((TRUE == bSuccess))) ; } } memset(msg, 0, sizeof(msg)); sprintf(msg, "For %s, verify number of tokens", testSet[i].testDescription); CPPUNIT_ASSERT_EQUAL_MESSAGE(msg, testSet[i].expectedCount, actualCount); } } }; CPPUNIT_TEST_SUITE_REGISTRATION(UtlTokenizerTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/UtlVoidPtr.cpp0000644000175000017500000001577612205613256025031 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include /* PLEASE VERIFY WITH SCOTT */ /** This class is used to test the UtlVoidPtr utility class. * * PLEASE READ THE README FILE THAT CAN FOUND IN THE SAME DIRECTORY AS * THIS FILE. The Readme describes the organization / flow of tests and * without reading this file, the following class (and all unit tests) * may not make a lot of sense and might be difficult to comprehend. */ class UtlVoidPtrTests : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(UtlVoidPtrTests); CPPUNIT_TEST(testConstructor) ; CPPUNIT_TEST(testGetContainableType) ; CPPUNIT_TEST(testIsEqual) ; CPPUNIT_TEST(testSetValue) ; CPPUNIT_TEST_SUITE_END(); private: struct BasicIntVerifier { char* message ; int input ; int expectedValue ; } ; static const int INDEX_NOT_FOUND ; public: UtlVoidPtrTests() { } void setUp() { } void tearDown() { } ~UtlVoidPtrTests() { } /** Sandbox method for experimenting with the API Under Test. * This method MUST be empty when the test drivers are being * checked in (final checkin) to the repository. */ void DynaTest() { } /** Test the constructor * * Test data for this test is :- * a) test a default zero constructor * b) Test by passing some arbitary pointer. * c) Test by passing another containable object itself * */ void testConstructor() { // test that the default constructor creates a void ptr // with 0 as its volume. UtlVoidPtr testVoidObj1 ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Test the default constructor", \ (void*)0, (void*) testVoidObj1.getValue()) ; // Test that you can pass any void* object as the argument const char* testCharstar = "Hello ganeshji" ; UtlVoidPtr testVoidObj2((void*)testCharstar) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Test the one arg constructor by passing a char* " \ "pointer as the argument", (void*)testCharstar, (void*)testVoidObj2.getValue()) ; // Test that passing another UtlContainable* object itself doesn't // cause any confusions UtlString testString("New String") ; UtlVoidPtr testVoidObj3(&testString) ; CPPUNIT_ASSERT_EQUAL_MESSAGE("Test the one arg constructor by passing a UtlString* " \ "as the argument", (void*)&testString, (void*)testVoidObj3.getValue()) ; }//testConstructor() /** Test the getContainableType method * */ void testGetContainableType() { const char* message = "Test the getContainableType()" ; UtlVoidPtr testVoidObj((char*)"Hello ganeshji") ; CPPUNIT_ASSERT_EQUAL_MESSAGE(message, string("UtlVoidPtr"), \ string(testVoidObj.getContainableType())); } /** Test the hash() method * */ void testIsEqual() { UtlVoidPtr testVoidObj1 ; UtlVoidPtr testVoidObj1_clone ; UtlString testString = UtlString("Hello") ; UtlString testString_clone = UtlString("Hello") ; UtlVoidPtr testVoidObj2(&testString) ; UtlVoidPtr testVoidObj2_copy(&testString) ; UtlVoidPtr testVoidObj2_clone(&testString_clone) ; // For a UtlVoidPtr that has NULL as its value, any other VoidPtr with // NULL value should be Equal CPPUNIT_ASSERT_MESSAGE("Test the isEqual() method for a NULL pointer", \ testVoidObj1.isEqual(&testVoidObj1_clone)) ; // For a UtlVoidPtr, another object that contains the same ponter is // considered to be Equal CPPUNIT_ASSERT_MESSAGE("Test the isEqual() method for a regular voidPtr", \ testVoidObj2.isEqual(&testVoidObj2_copy)) ; // For a UtlVoidPtr, another objec that contains a 'similar (not same) pointer // is NOT considered to be equal CPPUNIT_ASSERT_MESSAGE("Test the isEqual() method for 2 voidPtr whose " \ "value is similar but not same", !testVoidObj2.isEqual(&testVoidObj2_clone)) ; }//testIsEqual() /** Test the setValue() method. * * The test data for this method is * a) For a NULL pointer set a different type * a) Set the value from one Non-NULL to another Non-NULL * d) set the value from Non-NULL to NULL */ void testSetValue() { const char* prefix ; const char* suffix1 = " : test return value" ; const char* suffix2 = " : test that value has been set" ; string Message ; UtlVoidPtr testVoidObj ; void* returnValue ; void* newValue ; void* oldValue = 0 ; newValue = (void*)"Hello world" ; returnValue = testVoidObj.setValue(newValue) ; prefix = "For a VoidPtr object which is not NULL, test setValue(void* value) " \ "where val is non NULL " ; Message = prefix; Message.append(suffix1); CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), (void*)oldValue, (void*)returnValue) ; Message = prefix; Message.append(suffix2); CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), (void*)newValue, \ (void*)testVoidObj.getValue()) ; oldValue = testVoidObj.getValue() ; prefix = "Test setValue(void* value) where value is not NULL and the " \ "existing object is not NULL" ; newValue = (void*)"Hello again world" ; returnValue = (void*)testVoidObj.setValue(newValue) ; Message = prefix; Message.append(suffix1); CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), (void*)oldValue, (void*)returnValue) ; Message = prefix; Message.append(suffix2); CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), (void*)newValue, \ (void*)testVoidObj.getValue()) ; oldValue = testVoidObj.getValue() ; prefix = "Test setValue(void* value) where value = NULL and existing object is not" ; newValue = 0 ; returnValue = (void*)testVoidObj.setValue(newValue) ; Message = prefix; Message.append(suffix1); CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), (void*)oldValue, (void*)returnValue); Message = prefix; Message.append(suffix1); CPPUNIT_ASSERT_EQUAL_MESSAGE(Message.data(), (void*)newValue, \ (void*)testVoidObj.getValue()) ; } //testSetValue }; const int UtlVoidPtrTests::INDEX_NOT_FOUND = -1 ; CPPUNIT_TEST_SUITE_REGISTRATION(UtlVoidPtrTests); sipxtapi-3.3.0~test17/sipXportLib/src/test/utl/XmlContentTest.cpp0000644000175000017500000001424412205613256025675 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include class XmlContentTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(XmlContentTest); CPPUNIT_TEST(testNamedEnt); CPPUNIT_TEST(testNumericEnt); CPPUNIT_TEST(testUnNamedEnt); CPPUNIT_TEST(testUnNumericEnt); CPPUNIT_TEST(testStringNoNewline); CPPUNIT_TEST(testDecimal); CPPUNIT_TEST_SUITE_END(); public: #define ESCAPE(input,correct) \ CPPUNIT_ASSERT_MESSAGE("XmlEscape failed\n" \ " Input: '" input "'\n" \ " Should be: '" correct "'\n", \ escape(input,correct) \ ); #define UNESCAPE(input,correct) \ CPPUNIT_ASSERT_MESSAGE("XmlUnEscape failed\n" \ " Input: '" input "'\n" \ " Should be: '" correct "'\n", \ unescape(input,correct) \ ); #define HANDCHECK 0 /* unconditionally print results */ UtlBoolean escape(const char* input, const char* correct) { UtlString in(input); UtlString out; XmlEscape(out,in); UtlBoolean result = (out == correct); if (!result || HANDCHECK) { printf("---- Escape\n" " In: '%s'\n" " Good:'%s'\n" " Out: '%s'\n", in.data(), correct, out.data() ); } return result; } UtlBoolean unescape(const char* input, const char* correct) { UtlString in(input); UtlString out; XmlUnEscape(out,in); UtlBoolean result = (out == correct); if (!result || HANDCHECK) { printf("---- UnEscape\n" " In: '%s'\n" " Good:'%s'\n" " Out: '%s'\n", in.data(), correct, out.data() ); } return result; } void testNamedEnt() { ESCAPE("zigzag","zigzag"); ESCAPE("zig&zag","zig&zag"); ESCAPE("zig&&zag","zig&&zag"); ESCAPE("zigzag&","zigzag&"); ESCAPE("zigzag&&","zigzag&&"); ESCAPE("&zigzag","&zigzag"); ESCAPE("&&zigzag","&&zigzag"); ESCAPE("&zigzag&","&zigzag&"); ESCAPE("&&zigzag&&","&&zigzag&&"); ESCAPE("&zig&zag&","&zig&zag&"); ESCAPE("&&zig&&zag&&","&&zig&&zag&&"); } void testNumericEnt() { ESCAPE("zigzag","zigzag"); ESCAPE("zig\x03zag","zigzag"); ESCAPE("zig\x03\x03zag","zigzag"); ESCAPE("zigzag\x03","zigzag"); ESCAPE("zigzag\x03\x03","zigzag"); ESCAPE("\x03zigzag","zigzag"); ESCAPE("\x03\x03zigzag","zigzag"); ESCAPE("\x03zigzag\x03","zigzag"); ESCAPE("\x03\x03zigzag\x03\x03","zigzag"); ESCAPE("\x03zig\x03zag\x03","zigzag"); ESCAPE("\x03\x03zig\x03\x03zag\x03\x03","zigzag"); } void testUnNamedEnt() { UNESCAPE("zigzag","zigzag"); UNESCAPE("zig&zag","zig&zag"); UNESCAPE("zig&&zag","zig&&zag"); UNESCAPE("zigzag&","zigzag&"); UNESCAPE("zigzag&&","zigzag&&"); UNESCAPE("&zigzag","&zigzag"); UNESCAPE("&&zigzag","&&zigzag"); UNESCAPE("&zigzag&","&zigzag&"); UNESCAPE("&&zigzag&&","&&zigzag&&"); UNESCAPE("&zig&zag&","&zig&zag&"); UNESCAPE("&&zig&&zag&&","&&zig&&zag&&"); } void testUnNumericEnt() { UNESCAPE("zigzag","zigzag"); UNESCAPE("zigzag","zig\x03zag"); UNESCAPE("zigzag","zig\x03\x03zag"); UNESCAPE("zigzag","zigzag\x03"); UNESCAPE("zigzag","zigzag\x03\x03"); UNESCAPE("zigzag","\x03zigzag"); UNESCAPE("zigzag","\x03\x03zigzag"); UNESCAPE("zigzag","\x03zigzag\x03"); UNESCAPE("zigzag","\x03\x03zigzag\x03\x03"); UNESCAPE("zigzag","\x03zig\x03zag\x03"); UNESCAPE("zigzag","\x03\x03zig\x03\x03zag\x03\x03"); } // Test that TiXmlDocument::Parse works on a string that does not end with newline. void testStringNoNewline() { const char* test_string = "\n"; TiXmlDocument doc; const char* result = doc.Parse(test_string); CPPUNIT_ASSERT_MESSAGE("Parse of test_string failed.", result != 0); } void testDecimal() { UtlString s; s = ""; XmlDecimal(s, 1); CPPUNIT_ASSERT_EQUAL(s, UtlString("1")); XmlDecimal(s, -1); CPPUNIT_ASSERT_EQUAL(s, UtlString("1-1")); XmlDecimal(s, 12); CPPUNIT_ASSERT_EQUAL(s, UtlString("1-112")); XmlDecimal(s, 1234567890); CPPUNIT_ASSERT_EQUAL(s, UtlString("1-1121234567890")); s = ""; XmlDecimal(s, 1, "%020d"); CPPUNIT_ASSERT_EQUAL(s, UtlString("00000000000000000001")); s = ""; XmlDecimal(s, (unsigned int) 0xFFFFFFFF, "%u"); CPPUNIT_ASSERT_EQUAL(s, UtlString("4294967295")); } }; CPPUNIT_TEST_SUITE_REGISTRATION(XmlContentTest); sipxtapi-3.3.0~test17/sipXportLib/src/test/README0000644000175000017500000002160312205613256022307 0ustar00danieldaniel00000000000000The following document describes the organization of CppUnit tests for the Utl Library. ________________________________________________________________________ 1. Test Methods :- ________________________________________________________________________ As in any CppUnit test, the tests are broken into different methods. Each test method tests one or two test case of the implementation under test. The name of the test method is self-explanatory as to what is being tested. _______________________________________________________________________ 2. Formal Methods of testing in arriving at the Test Data:- ________________________________________________________________________ To the extent possible, the formal methods of testing, namely, boundry value analysis / equivalence partitioning have been applied while arriving at the test data for the unit tests. For example, If the add method is being tested, for the class FOO the test data may be :- a) Test adding zero with zero. b) Test adding zero with a positive integer c) Test adding a positive integer with zero d) Test adding zero with a MAX_INT value ... and so on. Whenever possible these multiple test data are tested within the same method. (In the above case of add, it doesn't make sense to have one test method for add_zero_with_zero(), one for add_zero_with_positive(). Instead these methods are all tested within the testAdd() method itself. These multiple test data are organized as Arrays of Test Structures. For example, for the above case, the test arrays are :- struct TestDataStructure { int Lhs_Data ; int Rhs_Data ; int Expected_Result ; } TestDataStructure testData[] = { \ {0, 0, 0 } , \ {0, 9, 9 }, \ {8, 0, 8 }, \ {0, INT_MAX, INT_MAX} \ } ; By organizing the test data in such a fashion, the actual test procedure can be easily put into a loop. In the above case, for (i = 0 to end) { // Invoke the method being tested - "add" int result = foo_instance.add(testData[i].Lhs_Data, \ testData[i].Rhs_Data) ; // Now verify that the result of add was as expected. CPPUNIT_ASSERT_EQUAL(result == testData[i].Expected_Result ; } ________________________________________________________________________ 3. Mutliple Asserts for a test procedure ________________________________________________________________________ Some of the tests may have multiple CppUnit assert statements in them. This is usually the case when the call to a method may have more than a single impact. For example, a method call may require to return a particular value and modify the state of the instance. Or it may also be requried that the call has not altered the state inadvertently. For example, say that the append method of string takes in a second string as the argument, appends itself with the argument and returns the appended string. Then all of the following need to be verified a) The passed parameter is appended to 'this' string b) The return value represents the appended string AND c) The passed parameter is not changed. So instead of having three methods to test these, the single append method is made to have three CppUnit assert methods as shown below for ... { char* Old_Rhs_CharStar = testData[i].Rhs_Data.toString() ; string result = testString.append(testData[i].Rhs_Data) ; CPPUNIT_ASSERT_EQUAL(result ISEQUALTO testData[i].Expected_Result) ; CPPUNIT_ASSERT_EQUAL(testString.toString() ISEQUALTO \ testData[i].Expected_Result) ; CPPUNIT_ASSERT_EQUAL(testData[i].Rhs_Data.toString() ISEQUALTO \ Old_Rhs_CharStar) ; } ________________________________________________________________________ 4. Messages used while asserting ________________________________________________________________________ CppUnit offers a nice mechanism of providing messages to 'test assertion' This helps debugging should some of the tests fail. Instead of only looking at which line failed, you now have the ability to provide a message which states what exactly was being tested. Compare the test report which says, Failed at line 25! Expected = 9, Actual = 0 with Test the add method when zero is added to a posive integer, Line 25! Expected = 9, Actual = 0 Obviously the second line is more clear about what exactly went wrong. In the previous paragraphs, we have seen as to how the each test case has an array of multiple test data and multiple asserts. This obviously means that a message is constructed of at least 3 parts :- a) A common prefix :- For example, "Test the append() method " b) A message that is specific to the data being tested :- For example, "when the test instance is alphanumeric and RHS is numeric " AND c) A message that is specific to what is being verified :- For example, ":- Verify that the return value represents the concated string" OR ":- Verify that the original string is intact" Clearly (b) and (c) can assume one of many values depending on the test data / state being tested. To address this, message is constructed by having three variables, a) a prefix b) an array of messages. This array has the same number of elements as the test data array c) one or more suffix variables. The number depends on the number of asserts to be made. For example in case of the string, the values may be:- char* prefix = "Test the append() method " ; char* TestDataMessages[] = { \ "when the test instance is alpha and rhs is numeric ", \ "when the test instance is empty and rhs is alpha ", \ "when the test instance is empty and rhs is empty " \ } ; char* suffix1 = ":- Verify the return value" ; char* suffix2 = ":- Verify that the rhs *has* been appended to the test instances" ; char* suffix3 = ":- Verify that the original value has not been mutated" ; The message is then created by calling the utility method, TestUtility::createMessage(...) This method takes in the pointer to a string (besides other parameters) into which the composite message is written into . The full test snippet for the append tester would thus be -----------Code ---------------------- struct TestDataStructure { char* testDescription ; char* Lhs_Data ; char* Rhs_Data ; bool Expected_Result ; } TestDataStructure testData[] = { \ {"when the test instance is alpha and rhs is numeric ", \ "abc", "23", false } , \ {"when the test instance is empty and rhs is alpha ", \ "", "abc", false }, \ {"when the test instance is empty and rhs is empty ", \ "", "", false }, \ {"when the test instance is equal to rhs", \ "abc", "abc", true} \ } ; char* prefix = "Test the append() method " ; char* suffix1 = ":- Verify the return value" ; char* suffix2 = ":- Verify that the rhs *has* been appended to the test instances" ; char* suffix3 = ":- Verify that the original value has not been mutated" ; for 0 to test_count { char* Old_Rhs_CharStar = testData[i].Rhs_Data.toString() ; string result = testString.append(testData[i].Rhs_Data) ; string createdMessage; // define a string into which the message will be written to TestUtilities::createMessage(3, &createdMessage, prefix, \ testData[i].testDescription, suffix1) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(createdMessage.data(), result ISEQUALTO \ testData[i].Expected_Result) ; TestUtilities::createMessage(3, &createdMessage, prefix, \ testData[i].testDescription, suffix2) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(createdMessage.data(), testString.toString() \ ISEQUALTO testData[i].Expected_Result) ; TestUtilities::createMessage(3, &createdMessage, prefix, \ testData[i].testDescription, suffix3) ; CPPUNIT_ASSERT_EQUAL_MESSAGE(createdMessage.data(), \ testData[i].Rhs_Data.toString() \ ISEQUALTO Old_Rhs_CharStar) ; } -----------End Code ---------------------- ________________________________________________________________________ 5. Split testcases for the same method into multiple methods ________________________________________________________________________ Sometimes, the test case for the same method may be tested using more than one tester method. This is usually done if a) The test case requires a different setup for different test data b) If a test case is known to fail or has a high likelyhood of failing, then this may be put into the a different method so that this failure doesn't cause the other tests to fail. sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxunittests.h0000644000175000017500000000153312205613256024546 0ustar00danieldaniel00000000000000// // // Copyright (C) 2010 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ // Author: Daniel Petrie // dpetrie AT SIPez DOT com ////////////////////////////////////////////////////////////////////////////// #ifndef _sipxunittests_h_ #define _sipxunittests_h_ #if !defined(NO_CPPUNIT) && defined(ANDROID) #define NO_CPPUNIT 1 #endif #if defined(NO_CPPUNIT) #define SIPX_UNIT_BASE_CLASS SipxPortUnitTestClass #include #include #include typedef UtlString string; #else #define SIPX_UNIT_BASE_CLASS CppUnit::TestCase #include #include using namespace std; #endif #endif sipxtapi-3.3.0~test17/sipXportLib/src/test/Makefile.am0000644000175000017500000000716712205613305023467 0ustar00danieldaniel00000000000000 SUBDIRS = testplugin if BUILD_SIPXUNIT SUBDIRS += sipxunit endif if BUILD_SIPXPORTUNIT SUBDIRS += sipxportunit endif ## All tests under this GNU variable should run relatively quickly ## and of course require no setup # for performance numbers, add to TESTS: UtlListPerformance UtlHashMapPerformance TESTS = testsuite check_PROGRAMS = testsuite sandbox UtlListPerformance UtlHashMapPerformance ## To load source in gdb for libsipXport.la, type the 'share' at the ## gdb console just before stepping into function in sipXportLib testsuite_LDADD = \ @SIPX_UNIT_TARGET@/libsipXunit.la \ ../libsipXport.la testsuite_CXXFLAGS = \ -I$(top_srcdir)/sipXportLib/include \ @CPPUNIT_CFLAGS@ \ -I$(SIPXUNITINC) \ -DSIPX_TMPDIR=\"@SIPX_TMPDIR@\" \ -DTEST_DIR=\"@abs_builddir@\" \ -fno-gcse -O0 testsuite_CPPFLAGS = @CPPUNIT_CFLAGS@ # ORDER NOTE: the utl/UtlLinkTest and utl/UtlChainTest must be before # any test that uses any UtlContainer. testsuite_SOURCES = \ os/UnitTestLogHooks.cpp \ os/OsAdapterInfoTest.cpp \ os/OsCallbackTest.cpp \ os/OsConfigDbTest.cpp \ os/OsContactListTest.cpp \ os/OsContactTest.cpp \ os/OsDirTest.cpp \ os/OsEventTest.cpp \ os/OsFileIteratorTest.cpp \ os/OsFileSystemTest.cpp \ os/OsFileTest.cpp \ os/OsLockTest.cpp \ os/OsMsgQTest.cpp \ os/OsMsgDispatcherTest.cpp \ os/OsMutexTest.cpp \ os/OsNameDbTest.cpp \ os/OsPathTest.cpp \ os/OsProcessIteratorTest.cpp \ os/OsProcessMgrTest.cpp \ os/OsProcessTest.cpp \ os/OsSemTest.cpp \ os/OsServerTaskTest.cpp \ os/OsSharedLibMgrTest.cpp \ os/OsSocketTest.cpp \ os/OsTestUtilities.cpp \ os/OsTestUtilities.h \ os/OsTimerTaskTest.cpp \ os/OsTimerTest.cpp \ os/OsTimeTest.cpp \ utl/PluginHooksTest.cpp \ utl/TestPlugin.h \ utl/UtlChainTest.cpp \ utl/UtlContainableTestStub.cpp \ utl/UtlContainableTestStub.h \ utl/UtlCrc32Test.cpp \ utl/UtlCryptoTest.cpp \ utl/UtlDList.cpp \ utl/UtlDListIterator.cpp \ utl/UtlHashBag.cpp \ utl/UtlHashBagIterator.cpp \ utl/UtlHashMap.cpp \ utl/UtlHashMapIterator.cpp \ utl/UtlInt.cpp \ utl/UtlLinkTest.cpp \ utl/UtlLongLongInt.cpp \ utl/UtlRegex.cpp \ utl/UtlSList.cpp \ utl/UtlSListIteratorTest.cpp \ utl/UtlSortedList.cpp \ utl/UtlSortedListIteratorTest.cpp \ utl/UtlStringTest.cpp \ utl/UtlStringTest.h \ utl/UtlStringTest_ConstructiveManipulators.cpp \ utl/UtlStringTest_DestructiveManipulators.cpp \ utl/UtlStringTest_NonMutating.cpp \ utl/UtlTokenizerTest.cpp \ utl/UtlVoidPtr.cpp \ utl/XmlContentTest.cpp # [DEBUG ASSISTANT] List a single unittest to isoloate a unittest for # debugging or when developing a new unittest. As courtesy remove all # unittests before checking in, although forgetting to has no ill # effects. To build and run: # # cd src/test # make sandbox # ./sandbox # #sandbox_LDFLAGS = $(testsuite_LDFLAGS) sandbox_LDADD = $(testsuite_LDADD) sandbox_CXXFLAGS = $(testsuite_CXXFLAGS) sandbox_SOURCES = \ os/OsConfigDbTest.cpp \ utl/PluginHooksTest.cpp # Performance test of UtlList UtlListPerformance_SOURCES = \ utl/UtlListPerformance.cpp UtlListPerformance_CXXFLAGS = \ -I$(top_builddir)/config \ -I$(top_srcdir)/sipXportLib/include UtlListPerformance_LDADD = \ ../libsipXport.la # Performance test of UtlHashMap UtlHashMapPerformance_SOURCES = \ utl/UtlHashMapPerformance.cpp UtlHashMapPerformance_CXXFLAGS = \ -I$(top_builddir)/config \ -I$(top_srcdir)/sipXportLib/include UtlHashMapPerformance_LDADD = \ ../libsipXport.la EXTRA_DIST= noinst_HEADERS = sipxunittests.h sipxtapi-3.3.0~test17/sipXportLib/src/test/Makefile.in0000644000175000017500000047241612321445001023476 0ustar00danieldaniel00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @BUILD_SIPXUNIT_TRUE@am__append_1 = sipxunit @BUILD_SIPXPORTUNIT_TRUE@am__append_2 = sipxportunit TESTS = testsuite$(EXEEXT) check_PROGRAMS = testsuite$(EXEEXT) sandbox$(EXEEXT) \ UtlListPerformance$(EXEEXT) UtlHashMapPerformance$(EXEEXT) subdir = sipXportLib/src/test DIST_COMMON = README $(noinst_HEADERS) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/general.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/sipXlib.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am_UtlHashMapPerformance_OBJECTS = \ UtlHashMapPerformance-UtlHashMapPerformance.$(OBJEXT) UtlHashMapPerformance_OBJECTS = $(am_UtlHashMapPerformance_OBJECTS) UtlHashMapPerformance_DEPENDENCIES = ../libsipXport.la UtlHashMapPerformance_LINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) \ $(UtlHashMapPerformance_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_UtlListPerformance_OBJECTS = \ UtlListPerformance-UtlListPerformance.$(OBJEXT) UtlListPerformance_OBJECTS = $(am_UtlListPerformance_OBJECTS) UtlListPerformance_DEPENDENCIES = ../libsipXport.la UtlListPerformance_LINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) \ $(UtlListPerformance_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_sandbox_OBJECTS = sandbox-OsConfigDbTest.$(OBJEXT) \ sandbox-PluginHooksTest.$(OBJEXT) sandbox_OBJECTS = $(am_sandbox_OBJECTS) sandbox_DEPENDENCIES = $(testsuite_LDADD) sandbox_LINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CXXLD) $(sandbox_CXXFLAGS) $(CXXFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ am_testsuite_OBJECTS = testsuite-UnitTestLogHooks.$(OBJEXT) \ testsuite-OsAdapterInfoTest.$(OBJEXT) \ testsuite-OsCallbackTest.$(OBJEXT) \ testsuite-OsConfigDbTest.$(OBJEXT) \ testsuite-OsContactListTest.$(OBJEXT) \ testsuite-OsContactTest.$(OBJEXT) \ testsuite-OsDirTest.$(OBJEXT) testsuite-OsEventTest.$(OBJEXT) \ testsuite-OsFileIteratorTest.$(OBJEXT) \ testsuite-OsFileSystemTest.$(OBJEXT) \ testsuite-OsFileTest.$(OBJEXT) testsuite-OsLockTest.$(OBJEXT) \ testsuite-OsMsgQTest.$(OBJEXT) \ testsuite-OsMsgDispatcherTest.$(OBJEXT) \ testsuite-OsMutexTest.$(OBJEXT) \ testsuite-OsNameDbTest.$(OBJEXT) \ testsuite-OsPathTest.$(OBJEXT) \ testsuite-OsProcessIteratorTest.$(OBJEXT) \ testsuite-OsProcessMgrTest.$(OBJEXT) \ testsuite-OsProcessTest.$(OBJEXT) \ testsuite-OsSemTest.$(OBJEXT) \ testsuite-OsServerTaskTest.$(OBJEXT) \ testsuite-OsSharedLibMgrTest.$(OBJEXT) \ testsuite-OsSocketTest.$(OBJEXT) \ testsuite-OsTestUtilities.$(OBJEXT) \ testsuite-OsTimerTaskTest.$(OBJEXT) \ testsuite-OsTimerTest.$(OBJEXT) testsuite-OsTimeTest.$(OBJEXT) \ testsuite-PluginHooksTest.$(OBJEXT) \ testsuite-UtlChainTest.$(OBJEXT) \ testsuite-UtlContainableTestStub.$(OBJEXT) \ testsuite-UtlCrc32Test.$(OBJEXT) \ testsuite-UtlCryptoTest.$(OBJEXT) testsuite-UtlDList.$(OBJEXT) \ testsuite-UtlDListIterator.$(OBJEXT) \ testsuite-UtlHashBag.$(OBJEXT) \ testsuite-UtlHashBagIterator.$(OBJEXT) \ testsuite-UtlHashMap.$(OBJEXT) \ testsuite-UtlHashMapIterator.$(OBJEXT) \ testsuite-UtlInt.$(OBJEXT) testsuite-UtlLinkTest.$(OBJEXT) \ testsuite-UtlLongLongInt.$(OBJEXT) \ testsuite-UtlRegex.$(OBJEXT) testsuite-UtlSList.$(OBJEXT) \ testsuite-UtlSListIteratorTest.$(OBJEXT) \ testsuite-UtlSortedList.$(OBJEXT) \ testsuite-UtlSortedListIteratorTest.$(OBJEXT) \ testsuite-UtlStringTest.$(OBJEXT) \ testsuite-UtlStringTest_ConstructiveManipulators.$(OBJEXT) \ testsuite-UtlStringTest_DestructiveManipulators.$(OBJEXT) \ testsuite-UtlStringTest_NonMutating.$(OBJEXT) \ testsuite-UtlTokenizerTest.$(OBJEXT) \ testsuite-UtlVoidPtr.$(OBJEXT) \ testsuite-XmlContentTest.$(OBJEXT) testsuite_OBJECTS = $(am_testsuite_OBJECTS) testsuite_DEPENDENCIES = @SIPX_UNIT_TARGET@/libsipXunit.la \ ../libsipXport.la testsuite_LINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(testsuite_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) CXXLD = $(CXX) CXXLINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) CCLD = $(CC) LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ SOURCES = $(UtlHashMapPerformance_SOURCES) \ $(UtlListPerformance_SOURCES) $(sandbox_SOURCES) \ $(testsuite_SOURCES) DIST_SOURCES = $(UtlHashMapPerformance_SOURCES) \ $(UtlListPerformance_SOURCES) $(sandbox_SOURCES) \ $(testsuite_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ html-recursive info-recursive install-data-recursive \ install-dvi-recursive install-exec-recursive \ install-html-recursive install-info-recursive \ install-pdf-recursive install-ps-recursive install-recursive \ installcheck-recursive installdirs-recursive pdf-recursive \ ps-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac HEADERS = $(noinst_HEADERS) RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ distdir ETAGS = etags CTAGS = ctags am__tty_colors = \ red=; grn=; lgn=; blu=; std= DIST_SUBDIRS = testplugin sipxunit sipxportunit DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMRNB_INCLUDE = @AMRNB_INCLUDE@ AMRNB_LIB_ROOT = @AMRNB_LIB_ROOT@ AMRWB_INCLUDE = @AMRWB_INCLUDE@ AMRWB_LIB_ROOT = @AMRWB_LIB_ROOT@ AMRWB_TARGET = @AMRWB_TARGET@ AMR_TARGET = @AMR_TARGET@ AMTAR = @AMTAR@ ANT = @ANT@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CARBON_LIBS = @CARBON_LIBS@ CA_LIBS = @CA_LIBS@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPUNIT_CFLAGS = @CPPUNIT_CFLAGS@ CPPUNIT_CONFIG = @CPPUNIT_CONFIG@ CPPUNIT_LIBS = @CPPUNIT_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPS_PCRE_CFLAGS = @DEPS_PCRE_CFLAGS@ DEPS_PCRE_LIBS = @DEPS_PCRE_LIBS@ DLLTOOL = @DLLTOOL@ DOT = @DOT@ DOXYGEN = @DOXYGEN@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DYNEXT = @DYNEXT@ EAGC_LDFLAGS = @EAGC_LDFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EJBE_LDFLAGS = @EJBE_LDFLAGS@ EPLC_LDFLAGS = @EPLC_LDFLAGS@ EVAD_LDFLAGS = @EVAD_LDFLAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ G722_TARGET = @G722_TARGET@ G726_TARGET = @G726_TARGET@ GIPSINC = @GIPSINC@ GIPS_CE_OBJS = @GIPS_CE_OBJS@ GIPS_CPPFLAGS = @GIPS_CPPFLAGS@ GIPS_NEQ_OBJS = @GIPS_NEQ_OBJS@ GIPS_VE_OBJS = @GIPS_VE_OBJS@ GREP = @GREP@ GSM_CFLAGS = @GSM_CFLAGS@ GSM_CXXFLAGS = @GSM_CXXFLAGS@ GSM_LDFLAGS = @GSM_LDFLAGS@ GSM_LIBS = @GSM_LIBS@ GSM_TARGET = @GSM_TARGET@ ILBC_INCLUDE = @ILBC_INCLUDE@ ILBC_LIB_ROOT = @ILBC_LIB_ROOT@ ILBC_LIB_TARGET = @ILBC_LIB_TARGET@ ILBC_TARGET = @ILBC_TARGET@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTERFACE_FLAGS = @INTERFACE_FLAGS@ JAVA = @JAVA@ JAVAC_DEBUG = @JAVAC_DEBUG@ JAVAC_OPTIMIZED = @JAVAC_OPTIMIZED@ JAVA_HOME = @JAVA_HOME@ L16_TARGET = @L16_TARGET@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NAMED_PROGRAM = @NAMED_PROGRAM@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPUS_CFLAGS = @OPUS_CFLAGS@ OPUS_LIBS = @OPUS_LIBS@ OPUS_TARGET = @OPUS_TARGET@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PCMAPCMU_TARGET = @PCMAPCMU_TARGET@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ RTL_CXXFLAGS = @RTL_CXXFLAGS@ RTL_LDFLAGS = @RTL_LDFLAGS@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SIPXMEDIA_CE_LIBS = @SIPXMEDIA_CE_LIBS@ SIPXMEDIA_VE_LIBS = @SIPXMEDIA_VE_LIBS@ SIPXMEDIA_VE_STATIC_LIBS = @SIPXMEDIA_VE_STATIC_LIBS@ SIPXPBXUSER = @SIPXPBXUSER@ SIPXPHONECONF = @SIPXPHONECONF@ SIPXPHONEDATA = @SIPXPHONEDATA@ SIPXPHONELIB = @SIPXPHONELIB@ SIPX_BACKUPDIR = @SIPX_BACKUPDIR@ SIPX_BINDIR = @SIPX_BINDIR@ SIPX_CONFDIR = @SIPX_CONFDIR@ SIPX_CONFIGPHONEDIR = @SIPX_CONFIGPHONEDIR@ SIPX_DATADIR = @SIPX_DATADIR@ SIPX_DBDIR = @SIPX_DBDIR@ SIPX_DOCDIR = @SIPX_DOCDIR@ SIPX_INCDIR = @SIPX_INCDIR@ SIPX_LIBDIR = @SIPX_LIBDIR@ SIPX_LOGDIR = @SIPX_LOGDIR@ SIPX_PARKMUSICDIR = @SIPX_PARKMUSICDIR@ SIPX_RUNDIR = @SIPX_RUNDIR@ SIPX_SCHEMADIR = @SIPX_SCHEMADIR@ SIPX_TMPDIR = @SIPX_TMPDIR@ SIPX_UNIT_TARGET = @SIPX_UNIT_TARGET@ SIPX_VXMLDATADIR = @SIPX_VXMLDATADIR@ SPANDSP_CFLAGS = @SPANDSP_CFLAGS@ SPANDSP_CXXFLAGS = @SPANDSP_CXXFLAGS@ SPANDSP_LDFLAGS = @SPANDSP_LDFLAGS@ SPANDSP_LIBS = @SPANDSP_LIBS@ SPEEXDSP_CFLAGS = @SPEEXDSP_CFLAGS@ SPEEXDSP_LIBS = @SPEEXDSP_LIBS@ SPEEXDSP_STATIC_LIB = @SPEEXDSP_STATIC_LIB@ SPEEX_CFLAGS = @SPEEX_CFLAGS@ SPEEX_LIBS = @SPEEX_LIBS@ SPEEX_ROOT = @SPEEX_ROOT@ SPEEX_STATIC_LIB = @SPEEX_STATIC_LIB@ SPEEX_TARGET = @SPEEX_TARGET@ SS_LDFLAGS = @SS_LDFLAGS@ STATIC_CODEC_LIBS = @STATIC_CODEC_LIBS@ STRIP = @STRIP@ TONES_TARGET = @TONES_TARGET@ VERSION = @VERSION@ VIDEO_DEFINE = @VIDEO_DEFINE@ WXWIDGETS_CFLAGS = @WXWIDGETS_CFLAGS@ WXWIDGETS_CONFIG = @WXWIDGETS_CONFIG@ WXWIDGETS_CXXFLAGS = @WXWIDGETS_CXXFLAGS@ WXWIDGETS_LIBS = @WXWIDGETS_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ codeclibdir = @codeclibdir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ enable_dot = @enable_dot@ enable_html_docs = @enable_html_docs@ enable_latex_docs = @enable_latex_docs@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ jar = @jar@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ sipx_abs_srcdir = @sipx_abs_srcdir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ wwwdir = @wwwdir@ SUBDIRS = testplugin $(am__append_1) $(am__append_2) testsuite_LDADD = \ @SIPX_UNIT_TARGET@/libsipXunit.la \ ../libsipXport.la testsuite_CXXFLAGS = \ -I$(top_srcdir)/sipXportLib/include \ @CPPUNIT_CFLAGS@ \ -I$(SIPXUNITINC) \ -DSIPX_TMPDIR=\"@SIPX_TMPDIR@\" \ -DTEST_DIR=\"@abs_builddir@\" \ -fno-gcse -O0 testsuite_CPPFLAGS = @CPPUNIT_CFLAGS@ # ORDER NOTE: the utl/UtlLinkTest and utl/UtlChainTest must be before # any test that uses any UtlContainer. testsuite_SOURCES = \ os/UnitTestLogHooks.cpp \ os/OsAdapterInfoTest.cpp \ os/OsCallbackTest.cpp \ os/OsConfigDbTest.cpp \ os/OsContactListTest.cpp \ os/OsContactTest.cpp \ os/OsDirTest.cpp \ os/OsEventTest.cpp \ os/OsFileIteratorTest.cpp \ os/OsFileSystemTest.cpp \ os/OsFileTest.cpp \ os/OsLockTest.cpp \ os/OsMsgQTest.cpp \ os/OsMsgDispatcherTest.cpp \ os/OsMutexTest.cpp \ os/OsNameDbTest.cpp \ os/OsPathTest.cpp \ os/OsProcessIteratorTest.cpp \ os/OsProcessMgrTest.cpp \ os/OsProcessTest.cpp \ os/OsSemTest.cpp \ os/OsServerTaskTest.cpp \ os/OsSharedLibMgrTest.cpp \ os/OsSocketTest.cpp \ os/OsTestUtilities.cpp \ os/OsTestUtilities.h \ os/OsTimerTaskTest.cpp \ os/OsTimerTest.cpp \ os/OsTimeTest.cpp \ utl/PluginHooksTest.cpp \ utl/TestPlugin.h \ utl/UtlChainTest.cpp \ utl/UtlContainableTestStub.cpp \ utl/UtlContainableTestStub.h \ utl/UtlCrc32Test.cpp \ utl/UtlCryptoTest.cpp \ utl/UtlDList.cpp \ utl/UtlDListIterator.cpp \ utl/UtlHashBag.cpp \ utl/UtlHashBagIterator.cpp \ utl/UtlHashMap.cpp \ utl/UtlHashMapIterator.cpp \ utl/UtlInt.cpp \ utl/UtlLinkTest.cpp \ utl/UtlLongLongInt.cpp \ utl/UtlRegex.cpp \ utl/UtlSList.cpp \ utl/UtlSListIteratorTest.cpp \ utl/UtlSortedList.cpp \ utl/UtlSortedListIteratorTest.cpp \ utl/UtlStringTest.cpp \ utl/UtlStringTest.h \ utl/UtlStringTest_ConstructiveManipulators.cpp \ utl/UtlStringTest_DestructiveManipulators.cpp \ utl/UtlStringTest_NonMutating.cpp \ utl/UtlTokenizerTest.cpp \ utl/UtlVoidPtr.cpp \ utl/XmlContentTest.cpp # [DEBUG ASSISTANT] List a single unittest to isoloate a unittest for # debugging or when developing a new unittest. As courtesy remove all # unittests before checking in, although forgetting to has no ill # effects. To build and run: # # cd src/test # make sandbox # ./sandbox # #sandbox_LDFLAGS = $(testsuite_LDFLAGS) sandbox_LDADD = $(testsuite_LDADD) sandbox_CXXFLAGS = $(testsuite_CXXFLAGS) sandbox_SOURCES = \ os/OsConfigDbTest.cpp \ utl/PluginHooksTest.cpp # Performance test of UtlList UtlListPerformance_SOURCES = \ utl/UtlListPerformance.cpp UtlListPerformance_CXXFLAGS = \ -I$(top_builddir)/config \ -I$(top_srcdir)/sipXportLib/include UtlListPerformance_LDADD = \ ../libsipXport.la # Performance test of UtlHashMap UtlHashMapPerformance_SOURCES = \ utl/UtlHashMapPerformance.cpp UtlHashMapPerformance_CXXFLAGS = \ -I$(top_builddir)/config \ -I$(top_srcdir)/sipXportLib/include UtlHashMapPerformance_LDADD = \ ../libsipXport.la EXTRA_DIST = noinst_HEADERS = sipxunittests.h all: all-recursive .SUFFIXES: .SUFFIXES: .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu sipXportLib/src/test/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu sipXportLib/src/test/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list UtlHashMapPerformance$(EXEEXT): $(UtlHashMapPerformance_OBJECTS) $(UtlHashMapPerformance_DEPENDENCIES) $(EXTRA_UtlHashMapPerformance_DEPENDENCIES) @rm -f UtlHashMapPerformance$(EXEEXT) $(UtlHashMapPerformance_LINK) $(UtlHashMapPerformance_OBJECTS) $(UtlHashMapPerformance_LDADD) $(LIBS) UtlListPerformance$(EXEEXT): $(UtlListPerformance_OBJECTS) $(UtlListPerformance_DEPENDENCIES) $(EXTRA_UtlListPerformance_DEPENDENCIES) @rm -f UtlListPerformance$(EXEEXT) $(UtlListPerformance_LINK) $(UtlListPerformance_OBJECTS) $(UtlListPerformance_LDADD) $(LIBS) sandbox$(EXEEXT): $(sandbox_OBJECTS) $(sandbox_DEPENDENCIES) $(EXTRA_sandbox_DEPENDENCIES) @rm -f sandbox$(EXEEXT) $(sandbox_LINK) $(sandbox_OBJECTS) $(sandbox_LDADD) $(LIBS) testsuite$(EXEEXT): $(testsuite_OBJECTS) $(testsuite_DEPENDENCIES) $(EXTRA_testsuite_DEPENDENCIES) @rm -f testsuite$(EXEEXT) $(testsuite_LINK) $(testsuite_OBJECTS) $(testsuite_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/UtlHashMapPerformance-UtlHashMapPerformance.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/UtlListPerformance-UtlListPerformance.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sandbox-OsConfigDbTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sandbox-PluginHooksTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsAdapterInfoTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsCallbackTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsConfigDbTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsContactListTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsContactTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsDirTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsEventTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsFileIteratorTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsFileSystemTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsFileTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsLockTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsMsgDispatcherTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsMsgQTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsMutexTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsNameDbTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsPathTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsProcessIteratorTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsProcessMgrTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsProcessTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsSemTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsServerTaskTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsSharedLibMgrTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsSocketTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsTestUtilities.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsTimeTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsTimerTaskTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-OsTimerTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-PluginHooksTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UnitTestLogHooks.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlChainTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlContainableTestStub.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlCrc32Test.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlCryptoTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlDList.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlDListIterator.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlHashBag.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlHashBagIterator.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlHashMap.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlHashMapIterator.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlInt.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlLinkTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlLongLongInt.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlRegex.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlSList.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlSListIteratorTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlSortedList.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlSortedListIteratorTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlStringTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlStringTest_ConstructiveManipulators.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlStringTest_DestructiveManipulators.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlStringTest_NonMutating.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlTokenizerTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-UtlVoidPtr.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testsuite-XmlContentTest.Po@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< UtlHashMapPerformance-UtlHashMapPerformance.o: utl/UtlHashMapPerformance.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(UtlHashMapPerformance_CXXFLAGS) $(CXXFLAGS) -MT UtlHashMapPerformance-UtlHashMapPerformance.o -MD -MP -MF $(DEPDIR)/UtlHashMapPerformance-UtlHashMapPerformance.Tpo -c -o UtlHashMapPerformance-UtlHashMapPerformance.o `test -f 'utl/UtlHashMapPerformance.cpp' || echo '$(srcdir)/'`utl/UtlHashMapPerformance.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/UtlHashMapPerformance-UtlHashMapPerformance.Tpo $(DEPDIR)/UtlHashMapPerformance-UtlHashMapPerformance.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlHashMapPerformance.cpp' object='UtlHashMapPerformance-UtlHashMapPerformance.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(UtlHashMapPerformance_CXXFLAGS) $(CXXFLAGS) -c -o UtlHashMapPerformance-UtlHashMapPerformance.o `test -f 'utl/UtlHashMapPerformance.cpp' || echo '$(srcdir)/'`utl/UtlHashMapPerformance.cpp UtlHashMapPerformance-UtlHashMapPerformance.obj: utl/UtlHashMapPerformance.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(UtlHashMapPerformance_CXXFLAGS) $(CXXFLAGS) -MT UtlHashMapPerformance-UtlHashMapPerformance.obj -MD -MP -MF $(DEPDIR)/UtlHashMapPerformance-UtlHashMapPerformance.Tpo -c -o UtlHashMapPerformance-UtlHashMapPerformance.obj `if test -f 'utl/UtlHashMapPerformance.cpp'; then $(CYGPATH_W) 'utl/UtlHashMapPerformance.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlHashMapPerformance.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/UtlHashMapPerformance-UtlHashMapPerformance.Tpo $(DEPDIR)/UtlHashMapPerformance-UtlHashMapPerformance.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlHashMapPerformance.cpp' object='UtlHashMapPerformance-UtlHashMapPerformance.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(UtlHashMapPerformance_CXXFLAGS) $(CXXFLAGS) -c -o UtlHashMapPerformance-UtlHashMapPerformance.obj `if test -f 'utl/UtlHashMapPerformance.cpp'; then $(CYGPATH_W) 'utl/UtlHashMapPerformance.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlHashMapPerformance.cpp'; fi` UtlListPerformance-UtlListPerformance.o: utl/UtlListPerformance.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(UtlListPerformance_CXXFLAGS) $(CXXFLAGS) -MT UtlListPerformance-UtlListPerformance.o -MD -MP -MF $(DEPDIR)/UtlListPerformance-UtlListPerformance.Tpo -c -o UtlListPerformance-UtlListPerformance.o `test -f 'utl/UtlListPerformance.cpp' || echo '$(srcdir)/'`utl/UtlListPerformance.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/UtlListPerformance-UtlListPerformance.Tpo $(DEPDIR)/UtlListPerformance-UtlListPerformance.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlListPerformance.cpp' object='UtlListPerformance-UtlListPerformance.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(UtlListPerformance_CXXFLAGS) $(CXXFLAGS) -c -o UtlListPerformance-UtlListPerformance.o `test -f 'utl/UtlListPerformance.cpp' || echo '$(srcdir)/'`utl/UtlListPerformance.cpp UtlListPerformance-UtlListPerformance.obj: utl/UtlListPerformance.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(UtlListPerformance_CXXFLAGS) $(CXXFLAGS) -MT UtlListPerformance-UtlListPerformance.obj -MD -MP -MF $(DEPDIR)/UtlListPerformance-UtlListPerformance.Tpo -c -o UtlListPerformance-UtlListPerformance.obj `if test -f 'utl/UtlListPerformance.cpp'; then $(CYGPATH_W) 'utl/UtlListPerformance.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlListPerformance.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/UtlListPerformance-UtlListPerformance.Tpo $(DEPDIR)/UtlListPerformance-UtlListPerformance.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlListPerformance.cpp' object='UtlListPerformance-UtlListPerformance.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(UtlListPerformance_CXXFLAGS) $(CXXFLAGS) -c -o UtlListPerformance-UtlListPerformance.obj `if test -f 'utl/UtlListPerformance.cpp'; then $(CYGPATH_W) 'utl/UtlListPerformance.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlListPerformance.cpp'; fi` sandbox-OsConfigDbTest.o: os/OsConfigDbTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(sandbox_CXXFLAGS) $(CXXFLAGS) -MT sandbox-OsConfigDbTest.o -MD -MP -MF $(DEPDIR)/sandbox-OsConfigDbTest.Tpo -c -o sandbox-OsConfigDbTest.o `test -f 'os/OsConfigDbTest.cpp' || echo '$(srcdir)/'`os/OsConfigDbTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/sandbox-OsConfigDbTest.Tpo $(DEPDIR)/sandbox-OsConfigDbTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsConfigDbTest.cpp' object='sandbox-OsConfigDbTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(sandbox_CXXFLAGS) $(CXXFLAGS) -c -o sandbox-OsConfigDbTest.o `test -f 'os/OsConfigDbTest.cpp' || echo '$(srcdir)/'`os/OsConfigDbTest.cpp sandbox-OsConfigDbTest.obj: os/OsConfigDbTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(sandbox_CXXFLAGS) $(CXXFLAGS) -MT sandbox-OsConfigDbTest.obj -MD -MP -MF $(DEPDIR)/sandbox-OsConfigDbTest.Tpo -c -o sandbox-OsConfigDbTest.obj `if test -f 'os/OsConfigDbTest.cpp'; then $(CYGPATH_W) 'os/OsConfigDbTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsConfigDbTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/sandbox-OsConfigDbTest.Tpo $(DEPDIR)/sandbox-OsConfigDbTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsConfigDbTest.cpp' object='sandbox-OsConfigDbTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(sandbox_CXXFLAGS) $(CXXFLAGS) -c -o sandbox-OsConfigDbTest.obj `if test -f 'os/OsConfigDbTest.cpp'; then $(CYGPATH_W) 'os/OsConfigDbTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsConfigDbTest.cpp'; fi` sandbox-PluginHooksTest.o: utl/PluginHooksTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(sandbox_CXXFLAGS) $(CXXFLAGS) -MT sandbox-PluginHooksTest.o -MD -MP -MF $(DEPDIR)/sandbox-PluginHooksTest.Tpo -c -o sandbox-PluginHooksTest.o `test -f 'utl/PluginHooksTest.cpp' || echo '$(srcdir)/'`utl/PluginHooksTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/sandbox-PluginHooksTest.Tpo $(DEPDIR)/sandbox-PluginHooksTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/PluginHooksTest.cpp' object='sandbox-PluginHooksTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(sandbox_CXXFLAGS) $(CXXFLAGS) -c -o sandbox-PluginHooksTest.o `test -f 'utl/PluginHooksTest.cpp' || echo '$(srcdir)/'`utl/PluginHooksTest.cpp sandbox-PluginHooksTest.obj: utl/PluginHooksTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(sandbox_CXXFLAGS) $(CXXFLAGS) -MT sandbox-PluginHooksTest.obj -MD -MP -MF $(DEPDIR)/sandbox-PluginHooksTest.Tpo -c -o sandbox-PluginHooksTest.obj `if test -f 'utl/PluginHooksTest.cpp'; then $(CYGPATH_W) 'utl/PluginHooksTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/PluginHooksTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/sandbox-PluginHooksTest.Tpo $(DEPDIR)/sandbox-PluginHooksTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/PluginHooksTest.cpp' object='sandbox-PluginHooksTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(sandbox_CXXFLAGS) $(CXXFLAGS) -c -o sandbox-PluginHooksTest.obj `if test -f 'utl/PluginHooksTest.cpp'; then $(CYGPATH_W) 'utl/PluginHooksTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/PluginHooksTest.cpp'; fi` testsuite-UnitTestLogHooks.o: os/UnitTestLogHooks.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UnitTestLogHooks.o -MD -MP -MF $(DEPDIR)/testsuite-UnitTestLogHooks.Tpo -c -o testsuite-UnitTestLogHooks.o `test -f 'os/UnitTestLogHooks.cpp' || echo '$(srcdir)/'`os/UnitTestLogHooks.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UnitTestLogHooks.Tpo $(DEPDIR)/testsuite-UnitTestLogHooks.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/UnitTestLogHooks.cpp' object='testsuite-UnitTestLogHooks.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UnitTestLogHooks.o `test -f 'os/UnitTestLogHooks.cpp' || echo '$(srcdir)/'`os/UnitTestLogHooks.cpp testsuite-UnitTestLogHooks.obj: os/UnitTestLogHooks.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UnitTestLogHooks.obj -MD -MP -MF $(DEPDIR)/testsuite-UnitTestLogHooks.Tpo -c -o testsuite-UnitTestLogHooks.obj `if test -f 'os/UnitTestLogHooks.cpp'; then $(CYGPATH_W) 'os/UnitTestLogHooks.cpp'; else $(CYGPATH_W) '$(srcdir)/os/UnitTestLogHooks.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UnitTestLogHooks.Tpo $(DEPDIR)/testsuite-UnitTestLogHooks.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/UnitTestLogHooks.cpp' object='testsuite-UnitTestLogHooks.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UnitTestLogHooks.obj `if test -f 'os/UnitTestLogHooks.cpp'; then $(CYGPATH_W) 'os/UnitTestLogHooks.cpp'; else $(CYGPATH_W) '$(srcdir)/os/UnitTestLogHooks.cpp'; fi` testsuite-OsAdapterInfoTest.o: os/OsAdapterInfoTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsAdapterInfoTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsAdapterInfoTest.Tpo -c -o testsuite-OsAdapterInfoTest.o `test -f 'os/OsAdapterInfoTest.cpp' || echo '$(srcdir)/'`os/OsAdapterInfoTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsAdapterInfoTest.Tpo $(DEPDIR)/testsuite-OsAdapterInfoTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsAdapterInfoTest.cpp' object='testsuite-OsAdapterInfoTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsAdapterInfoTest.o `test -f 'os/OsAdapterInfoTest.cpp' || echo '$(srcdir)/'`os/OsAdapterInfoTest.cpp testsuite-OsAdapterInfoTest.obj: os/OsAdapterInfoTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsAdapterInfoTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsAdapterInfoTest.Tpo -c -o testsuite-OsAdapterInfoTest.obj `if test -f 'os/OsAdapterInfoTest.cpp'; then $(CYGPATH_W) 'os/OsAdapterInfoTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsAdapterInfoTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsAdapterInfoTest.Tpo $(DEPDIR)/testsuite-OsAdapterInfoTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsAdapterInfoTest.cpp' object='testsuite-OsAdapterInfoTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsAdapterInfoTest.obj `if test -f 'os/OsAdapterInfoTest.cpp'; then $(CYGPATH_W) 'os/OsAdapterInfoTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsAdapterInfoTest.cpp'; fi` testsuite-OsCallbackTest.o: os/OsCallbackTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsCallbackTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsCallbackTest.Tpo -c -o testsuite-OsCallbackTest.o `test -f 'os/OsCallbackTest.cpp' || echo '$(srcdir)/'`os/OsCallbackTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsCallbackTest.Tpo $(DEPDIR)/testsuite-OsCallbackTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsCallbackTest.cpp' object='testsuite-OsCallbackTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsCallbackTest.o `test -f 'os/OsCallbackTest.cpp' || echo '$(srcdir)/'`os/OsCallbackTest.cpp testsuite-OsCallbackTest.obj: os/OsCallbackTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsCallbackTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsCallbackTest.Tpo -c -o testsuite-OsCallbackTest.obj `if test -f 'os/OsCallbackTest.cpp'; then $(CYGPATH_W) 'os/OsCallbackTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsCallbackTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsCallbackTest.Tpo $(DEPDIR)/testsuite-OsCallbackTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsCallbackTest.cpp' object='testsuite-OsCallbackTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsCallbackTest.obj `if test -f 'os/OsCallbackTest.cpp'; then $(CYGPATH_W) 'os/OsCallbackTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsCallbackTest.cpp'; fi` testsuite-OsConfigDbTest.o: os/OsConfigDbTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsConfigDbTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsConfigDbTest.Tpo -c -o testsuite-OsConfigDbTest.o `test -f 'os/OsConfigDbTest.cpp' || echo '$(srcdir)/'`os/OsConfigDbTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsConfigDbTest.Tpo $(DEPDIR)/testsuite-OsConfigDbTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsConfigDbTest.cpp' object='testsuite-OsConfigDbTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsConfigDbTest.o `test -f 'os/OsConfigDbTest.cpp' || echo '$(srcdir)/'`os/OsConfigDbTest.cpp testsuite-OsConfigDbTest.obj: os/OsConfigDbTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsConfigDbTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsConfigDbTest.Tpo -c -o testsuite-OsConfigDbTest.obj `if test -f 'os/OsConfigDbTest.cpp'; then $(CYGPATH_W) 'os/OsConfigDbTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsConfigDbTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsConfigDbTest.Tpo $(DEPDIR)/testsuite-OsConfigDbTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsConfigDbTest.cpp' object='testsuite-OsConfigDbTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsConfigDbTest.obj `if test -f 'os/OsConfigDbTest.cpp'; then $(CYGPATH_W) 'os/OsConfigDbTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsConfigDbTest.cpp'; fi` testsuite-OsContactListTest.o: os/OsContactListTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsContactListTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsContactListTest.Tpo -c -o testsuite-OsContactListTest.o `test -f 'os/OsContactListTest.cpp' || echo '$(srcdir)/'`os/OsContactListTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsContactListTest.Tpo $(DEPDIR)/testsuite-OsContactListTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsContactListTest.cpp' object='testsuite-OsContactListTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsContactListTest.o `test -f 'os/OsContactListTest.cpp' || echo '$(srcdir)/'`os/OsContactListTest.cpp testsuite-OsContactListTest.obj: os/OsContactListTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsContactListTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsContactListTest.Tpo -c -o testsuite-OsContactListTest.obj `if test -f 'os/OsContactListTest.cpp'; then $(CYGPATH_W) 'os/OsContactListTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsContactListTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsContactListTest.Tpo $(DEPDIR)/testsuite-OsContactListTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsContactListTest.cpp' object='testsuite-OsContactListTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsContactListTest.obj `if test -f 'os/OsContactListTest.cpp'; then $(CYGPATH_W) 'os/OsContactListTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsContactListTest.cpp'; fi` testsuite-OsContactTest.o: os/OsContactTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsContactTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsContactTest.Tpo -c -o testsuite-OsContactTest.o `test -f 'os/OsContactTest.cpp' || echo '$(srcdir)/'`os/OsContactTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsContactTest.Tpo $(DEPDIR)/testsuite-OsContactTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsContactTest.cpp' object='testsuite-OsContactTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsContactTest.o `test -f 'os/OsContactTest.cpp' || echo '$(srcdir)/'`os/OsContactTest.cpp testsuite-OsContactTest.obj: os/OsContactTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsContactTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsContactTest.Tpo -c -o testsuite-OsContactTest.obj `if test -f 'os/OsContactTest.cpp'; then $(CYGPATH_W) 'os/OsContactTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsContactTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsContactTest.Tpo $(DEPDIR)/testsuite-OsContactTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsContactTest.cpp' object='testsuite-OsContactTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsContactTest.obj `if test -f 'os/OsContactTest.cpp'; then $(CYGPATH_W) 'os/OsContactTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsContactTest.cpp'; fi` testsuite-OsDirTest.o: os/OsDirTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsDirTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsDirTest.Tpo -c -o testsuite-OsDirTest.o `test -f 'os/OsDirTest.cpp' || echo '$(srcdir)/'`os/OsDirTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsDirTest.Tpo $(DEPDIR)/testsuite-OsDirTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsDirTest.cpp' object='testsuite-OsDirTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsDirTest.o `test -f 'os/OsDirTest.cpp' || echo '$(srcdir)/'`os/OsDirTest.cpp testsuite-OsDirTest.obj: os/OsDirTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsDirTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsDirTest.Tpo -c -o testsuite-OsDirTest.obj `if test -f 'os/OsDirTest.cpp'; then $(CYGPATH_W) 'os/OsDirTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsDirTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsDirTest.Tpo $(DEPDIR)/testsuite-OsDirTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsDirTest.cpp' object='testsuite-OsDirTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsDirTest.obj `if test -f 'os/OsDirTest.cpp'; then $(CYGPATH_W) 'os/OsDirTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsDirTest.cpp'; fi` testsuite-OsEventTest.o: os/OsEventTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsEventTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsEventTest.Tpo -c -o testsuite-OsEventTest.o `test -f 'os/OsEventTest.cpp' || echo '$(srcdir)/'`os/OsEventTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsEventTest.Tpo $(DEPDIR)/testsuite-OsEventTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsEventTest.cpp' object='testsuite-OsEventTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsEventTest.o `test -f 'os/OsEventTest.cpp' || echo '$(srcdir)/'`os/OsEventTest.cpp testsuite-OsEventTest.obj: os/OsEventTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsEventTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsEventTest.Tpo -c -o testsuite-OsEventTest.obj `if test -f 'os/OsEventTest.cpp'; then $(CYGPATH_W) 'os/OsEventTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsEventTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsEventTest.Tpo $(DEPDIR)/testsuite-OsEventTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsEventTest.cpp' object='testsuite-OsEventTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsEventTest.obj `if test -f 'os/OsEventTest.cpp'; then $(CYGPATH_W) 'os/OsEventTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsEventTest.cpp'; fi` testsuite-OsFileIteratorTest.o: os/OsFileIteratorTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsFileIteratorTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsFileIteratorTest.Tpo -c -o testsuite-OsFileIteratorTest.o `test -f 'os/OsFileIteratorTest.cpp' || echo '$(srcdir)/'`os/OsFileIteratorTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsFileIteratorTest.Tpo $(DEPDIR)/testsuite-OsFileIteratorTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsFileIteratorTest.cpp' object='testsuite-OsFileIteratorTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsFileIteratorTest.o `test -f 'os/OsFileIteratorTest.cpp' || echo '$(srcdir)/'`os/OsFileIteratorTest.cpp testsuite-OsFileIteratorTest.obj: os/OsFileIteratorTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsFileIteratorTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsFileIteratorTest.Tpo -c -o testsuite-OsFileIteratorTest.obj `if test -f 'os/OsFileIteratorTest.cpp'; then $(CYGPATH_W) 'os/OsFileIteratorTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsFileIteratorTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsFileIteratorTest.Tpo $(DEPDIR)/testsuite-OsFileIteratorTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsFileIteratorTest.cpp' object='testsuite-OsFileIteratorTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsFileIteratorTest.obj `if test -f 'os/OsFileIteratorTest.cpp'; then $(CYGPATH_W) 'os/OsFileIteratorTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsFileIteratorTest.cpp'; fi` testsuite-OsFileSystemTest.o: os/OsFileSystemTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsFileSystemTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsFileSystemTest.Tpo -c -o testsuite-OsFileSystemTest.o `test -f 'os/OsFileSystemTest.cpp' || echo '$(srcdir)/'`os/OsFileSystemTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsFileSystemTest.Tpo $(DEPDIR)/testsuite-OsFileSystemTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsFileSystemTest.cpp' object='testsuite-OsFileSystemTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsFileSystemTest.o `test -f 'os/OsFileSystemTest.cpp' || echo '$(srcdir)/'`os/OsFileSystemTest.cpp testsuite-OsFileSystemTest.obj: os/OsFileSystemTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsFileSystemTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsFileSystemTest.Tpo -c -o testsuite-OsFileSystemTest.obj `if test -f 'os/OsFileSystemTest.cpp'; then $(CYGPATH_W) 'os/OsFileSystemTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsFileSystemTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsFileSystemTest.Tpo $(DEPDIR)/testsuite-OsFileSystemTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsFileSystemTest.cpp' object='testsuite-OsFileSystemTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsFileSystemTest.obj `if test -f 'os/OsFileSystemTest.cpp'; then $(CYGPATH_W) 'os/OsFileSystemTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsFileSystemTest.cpp'; fi` testsuite-OsFileTest.o: os/OsFileTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsFileTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsFileTest.Tpo -c -o testsuite-OsFileTest.o `test -f 'os/OsFileTest.cpp' || echo '$(srcdir)/'`os/OsFileTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsFileTest.Tpo $(DEPDIR)/testsuite-OsFileTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsFileTest.cpp' object='testsuite-OsFileTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsFileTest.o `test -f 'os/OsFileTest.cpp' || echo '$(srcdir)/'`os/OsFileTest.cpp testsuite-OsFileTest.obj: os/OsFileTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsFileTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsFileTest.Tpo -c -o testsuite-OsFileTest.obj `if test -f 'os/OsFileTest.cpp'; then $(CYGPATH_W) 'os/OsFileTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsFileTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsFileTest.Tpo $(DEPDIR)/testsuite-OsFileTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsFileTest.cpp' object='testsuite-OsFileTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsFileTest.obj `if test -f 'os/OsFileTest.cpp'; then $(CYGPATH_W) 'os/OsFileTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsFileTest.cpp'; fi` testsuite-OsLockTest.o: os/OsLockTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsLockTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsLockTest.Tpo -c -o testsuite-OsLockTest.o `test -f 'os/OsLockTest.cpp' || echo '$(srcdir)/'`os/OsLockTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsLockTest.Tpo $(DEPDIR)/testsuite-OsLockTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsLockTest.cpp' object='testsuite-OsLockTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsLockTest.o `test -f 'os/OsLockTest.cpp' || echo '$(srcdir)/'`os/OsLockTest.cpp testsuite-OsLockTest.obj: os/OsLockTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsLockTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsLockTest.Tpo -c -o testsuite-OsLockTest.obj `if test -f 'os/OsLockTest.cpp'; then $(CYGPATH_W) 'os/OsLockTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsLockTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsLockTest.Tpo $(DEPDIR)/testsuite-OsLockTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsLockTest.cpp' object='testsuite-OsLockTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsLockTest.obj `if test -f 'os/OsLockTest.cpp'; then $(CYGPATH_W) 'os/OsLockTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsLockTest.cpp'; fi` testsuite-OsMsgQTest.o: os/OsMsgQTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsMsgQTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsMsgQTest.Tpo -c -o testsuite-OsMsgQTest.o `test -f 'os/OsMsgQTest.cpp' || echo '$(srcdir)/'`os/OsMsgQTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsMsgQTest.Tpo $(DEPDIR)/testsuite-OsMsgQTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsMsgQTest.cpp' object='testsuite-OsMsgQTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsMsgQTest.o `test -f 'os/OsMsgQTest.cpp' || echo '$(srcdir)/'`os/OsMsgQTest.cpp testsuite-OsMsgQTest.obj: os/OsMsgQTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsMsgQTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsMsgQTest.Tpo -c -o testsuite-OsMsgQTest.obj `if test -f 'os/OsMsgQTest.cpp'; then $(CYGPATH_W) 'os/OsMsgQTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsMsgQTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsMsgQTest.Tpo $(DEPDIR)/testsuite-OsMsgQTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsMsgQTest.cpp' object='testsuite-OsMsgQTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsMsgQTest.obj `if test -f 'os/OsMsgQTest.cpp'; then $(CYGPATH_W) 'os/OsMsgQTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsMsgQTest.cpp'; fi` testsuite-OsMsgDispatcherTest.o: os/OsMsgDispatcherTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsMsgDispatcherTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsMsgDispatcherTest.Tpo -c -o testsuite-OsMsgDispatcherTest.o `test -f 'os/OsMsgDispatcherTest.cpp' || echo '$(srcdir)/'`os/OsMsgDispatcherTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsMsgDispatcherTest.Tpo $(DEPDIR)/testsuite-OsMsgDispatcherTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsMsgDispatcherTest.cpp' object='testsuite-OsMsgDispatcherTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsMsgDispatcherTest.o `test -f 'os/OsMsgDispatcherTest.cpp' || echo '$(srcdir)/'`os/OsMsgDispatcherTest.cpp testsuite-OsMsgDispatcherTest.obj: os/OsMsgDispatcherTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsMsgDispatcherTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsMsgDispatcherTest.Tpo -c -o testsuite-OsMsgDispatcherTest.obj `if test -f 'os/OsMsgDispatcherTest.cpp'; then $(CYGPATH_W) 'os/OsMsgDispatcherTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsMsgDispatcherTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsMsgDispatcherTest.Tpo $(DEPDIR)/testsuite-OsMsgDispatcherTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsMsgDispatcherTest.cpp' object='testsuite-OsMsgDispatcherTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsMsgDispatcherTest.obj `if test -f 'os/OsMsgDispatcherTest.cpp'; then $(CYGPATH_W) 'os/OsMsgDispatcherTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsMsgDispatcherTest.cpp'; fi` testsuite-OsMutexTest.o: os/OsMutexTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsMutexTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsMutexTest.Tpo -c -o testsuite-OsMutexTest.o `test -f 'os/OsMutexTest.cpp' || echo '$(srcdir)/'`os/OsMutexTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsMutexTest.Tpo $(DEPDIR)/testsuite-OsMutexTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsMutexTest.cpp' object='testsuite-OsMutexTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsMutexTest.o `test -f 'os/OsMutexTest.cpp' || echo '$(srcdir)/'`os/OsMutexTest.cpp testsuite-OsMutexTest.obj: os/OsMutexTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsMutexTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsMutexTest.Tpo -c -o testsuite-OsMutexTest.obj `if test -f 'os/OsMutexTest.cpp'; then $(CYGPATH_W) 'os/OsMutexTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsMutexTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsMutexTest.Tpo $(DEPDIR)/testsuite-OsMutexTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsMutexTest.cpp' object='testsuite-OsMutexTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsMutexTest.obj `if test -f 'os/OsMutexTest.cpp'; then $(CYGPATH_W) 'os/OsMutexTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsMutexTest.cpp'; fi` testsuite-OsNameDbTest.o: os/OsNameDbTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsNameDbTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsNameDbTest.Tpo -c -o testsuite-OsNameDbTest.o `test -f 'os/OsNameDbTest.cpp' || echo '$(srcdir)/'`os/OsNameDbTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsNameDbTest.Tpo $(DEPDIR)/testsuite-OsNameDbTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsNameDbTest.cpp' object='testsuite-OsNameDbTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsNameDbTest.o `test -f 'os/OsNameDbTest.cpp' || echo '$(srcdir)/'`os/OsNameDbTest.cpp testsuite-OsNameDbTest.obj: os/OsNameDbTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsNameDbTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsNameDbTest.Tpo -c -o testsuite-OsNameDbTest.obj `if test -f 'os/OsNameDbTest.cpp'; then $(CYGPATH_W) 'os/OsNameDbTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsNameDbTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsNameDbTest.Tpo $(DEPDIR)/testsuite-OsNameDbTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsNameDbTest.cpp' object='testsuite-OsNameDbTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsNameDbTest.obj `if test -f 'os/OsNameDbTest.cpp'; then $(CYGPATH_W) 'os/OsNameDbTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsNameDbTest.cpp'; fi` testsuite-OsPathTest.o: os/OsPathTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsPathTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsPathTest.Tpo -c -o testsuite-OsPathTest.o `test -f 'os/OsPathTest.cpp' || echo '$(srcdir)/'`os/OsPathTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsPathTest.Tpo $(DEPDIR)/testsuite-OsPathTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsPathTest.cpp' object='testsuite-OsPathTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsPathTest.o `test -f 'os/OsPathTest.cpp' || echo '$(srcdir)/'`os/OsPathTest.cpp testsuite-OsPathTest.obj: os/OsPathTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsPathTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsPathTest.Tpo -c -o testsuite-OsPathTest.obj `if test -f 'os/OsPathTest.cpp'; then $(CYGPATH_W) 'os/OsPathTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsPathTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsPathTest.Tpo $(DEPDIR)/testsuite-OsPathTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsPathTest.cpp' object='testsuite-OsPathTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsPathTest.obj `if test -f 'os/OsPathTest.cpp'; then $(CYGPATH_W) 'os/OsPathTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsPathTest.cpp'; fi` testsuite-OsProcessIteratorTest.o: os/OsProcessIteratorTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsProcessIteratorTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsProcessIteratorTest.Tpo -c -o testsuite-OsProcessIteratorTest.o `test -f 'os/OsProcessIteratorTest.cpp' || echo '$(srcdir)/'`os/OsProcessIteratorTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsProcessIteratorTest.Tpo $(DEPDIR)/testsuite-OsProcessIteratorTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsProcessIteratorTest.cpp' object='testsuite-OsProcessIteratorTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsProcessIteratorTest.o `test -f 'os/OsProcessIteratorTest.cpp' || echo '$(srcdir)/'`os/OsProcessIteratorTest.cpp testsuite-OsProcessIteratorTest.obj: os/OsProcessIteratorTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsProcessIteratorTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsProcessIteratorTest.Tpo -c -o testsuite-OsProcessIteratorTest.obj `if test -f 'os/OsProcessIteratorTest.cpp'; then $(CYGPATH_W) 'os/OsProcessIteratorTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsProcessIteratorTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsProcessIteratorTest.Tpo $(DEPDIR)/testsuite-OsProcessIteratorTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsProcessIteratorTest.cpp' object='testsuite-OsProcessIteratorTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsProcessIteratorTest.obj `if test -f 'os/OsProcessIteratorTest.cpp'; then $(CYGPATH_W) 'os/OsProcessIteratorTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsProcessIteratorTest.cpp'; fi` testsuite-OsProcessMgrTest.o: os/OsProcessMgrTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsProcessMgrTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsProcessMgrTest.Tpo -c -o testsuite-OsProcessMgrTest.o `test -f 'os/OsProcessMgrTest.cpp' || echo '$(srcdir)/'`os/OsProcessMgrTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsProcessMgrTest.Tpo $(DEPDIR)/testsuite-OsProcessMgrTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsProcessMgrTest.cpp' object='testsuite-OsProcessMgrTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsProcessMgrTest.o `test -f 'os/OsProcessMgrTest.cpp' || echo '$(srcdir)/'`os/OsProcessMgrTest.cpp testsuite-OsProcessMgrTest.obj: os/OsProcessMgrTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsProcessMgrTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsProcessMgrTest.Tpo -c -o testsuite-OsProcessMgrTest.obj `if test -f 'os/OsProcessMgrTest.cpp'; then $(CYGPATH_W) 'os/OsProcessMgrTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsProcessMgrTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsProcessMgrTest.Tpo $(DEPDIR)/testsuite-OsProcessMgrTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsProcessMgrTest.cpp' object='testsuite-OsProcessMgrTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsProcessMgrTest.obj `if test -f 'os/OsProcessMgrTest.cpp'; then $(CYGPATH_W) 'os/OsProcessMgrTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsProcessMgrTest.cpp'; fi` testsuite-OsProcessTest.o: os/OsProcessTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsProcessTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsProcessTest.Tpo -c -o testsuite-OsProcessTest.o `test -f 'os/OsProcessTest.cpp' || echo '$(srcdir)/'`os/OsProcessTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsProcessTest.Tpo $(DEPDIR)/testsuite-OsProcessTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsProcessTest.cpp' object='testsuite-OsProcessTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsProcessTest.o `test -f 'os/OsProcessTest.cpp' || echo '$(srcdir)/'`os/OsProcessTest.cpp testsuite-OsProcessTest.obj: os/OsProcessTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsProcessTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsProcessTest.Tpo -c -o testsuite-OsProcessTest.obj `if test -f 'os/OsProcessTest.cpp'; then $(CYGPATH_W) 'os/OsProcessTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsProcessTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsProcessTest.Tpo $(DEPDIR)/testsuite-OsProcessTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsProcessTest.cpp' object='testsuite-OsProcessTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsProcessTest.obj `if test -f 'os/OsProcessTest.cpp'; then $(CYGPATH_W) 'os/OsProcessTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsProcessTest.cpp'; fi` testsuite-OsSemTest.o: os/OsSemTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsSemTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsSemTest.Tpo -c -o testsuite-OsSemTest.o `test -f 'os/OsSemTest.cpp' || echo '$(srcdir)/'`os/OsSemTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsSemTest.Tpo $(DEPDIR)/testsuite-OsSemTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsSemTest.cpp' object='testsuite-OsSemTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsSemTest.o `test -f 'os/OsSemTest.cpp' || echo '$(srcdir)/'`os/OsSemTest.cpp testsuite-OsSemTest.obj: os/OsSemTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsSemTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsSemTest.Tpo -c -o testsuite-OsSemTest.obj `if test -f 'os/OsSemTest.cpp'; then $(CYGPATH_W) 'os/OsSemTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsSemTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsSemTest.Tpo $(DEPDIR)/testsuite-OsSemTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsSemTest.cpp' object='testsuite-OsSemTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsSemTest.obj `if test -f 'os/OsSemTest.cpp'; then $(CYGPATH_W) 'os/OsSemTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsSemTest.cpp'; fi` testsuite-OsServerTaskTest.o: os/OsServerTaskTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsServerTaskTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsServerTaskTest.Tpo -c -o testsuite-OsServerTaskTest.o `test -f 'os/OsServerTaskTest.cpp' || echo '$(srcdir)/'`os/OsServerTaskTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsServerTaskTest.Tpo $(DEPDIR)/testsuite-OsServerTaskTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsServerTaskTest.cpp' object='testsuite-OsServerTaskTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsServerTaskTest.o `test -f 'os/OsServerTaskTest.cpp' || echo '$(srcdir)/'`os/OsServerTaskTest.cpp testsuite-OsServerTaskTest.obj: os/OsServerTaskTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsServerTaskTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsServerTaskTest.Tpo -c -o testsuite-OsServerTaskTest.obj `if test -f 'os/OsServerTaskTest.cpp'; then $(CYGPATH_W) 'os/OsServerTaskTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsServerTaskTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsServerTaskTest.Tpo $(DEPDIR)/testsuite-OsServerTaskTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsServerTaskTest.cpp' object='testsuite-OsServerTaskTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsServerTaskTest.obj `if test -f 'os/OsServerTaskTest.cpp'; then $(CYGPATH_W) 'os/OsServerTaskTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsServerTaskTest.cpp'; fi` testsuite-OsSharedLibMgrTest.o: os/OsSharedLibMgrTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsSharedLibMgrTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsSharedLibMgrTest.Tpo -c -o testsuite-OsSharedLibMgrTest.o `test -f 'os/OsSharedLibMgrTest.cpp' || echo '$(srcdir)/'`os/OsSharedLibMgrTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsSharedLibMgrTest.Tpo $(DEPDIR)/testsuite-OsSharedLibMgrTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsSharedLibMgrTest.cpp' object='testsuite-OsSharedLibMgrTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsSharedLibMgrTest.o `test -f 'os/OsSharedLibMgrTest.cpp' || echo '$(srcdir)/'`os/OsSharedLibMgrTest.cpp testsuite-OsSharedLibMgrTest.obj: os/OsSharedLibMgrTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsSharedLibMgrTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsSharedLibMgrTest.Tpo -c -o testsuite-OsSharedLibMgrTest.obj `if test -f 'os/OsSharedLibMgrTest.cpp'; then $(CYGPATH_W) 'os/OsSharedLibMgrTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsSharedLibMgrTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsSharedLibMgrTest.Tpo $(DEPDIR)/testsuite-OsSharedLibMgrTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsSharedLibMgrTest.cpp' object='testsuite-OsSharedLibMgrTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsSharedLibMgrTest.obj `if test -f 'os/OsSharedLibMgrTest.cpp'; then $(CYGPATH_W) 'os/OsSharedLibMgrTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsSharedLibMgrTest.cpp'; fi` testsuite-OsSocketTest.o: os/OsSocketTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsSocketTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsSocketTest.Tpo -c -o testsuite-OsSocketTest.o `test -f 'os/OsSocketTest.cpp' || echo '$(srcdir)/'`os/OsSocketTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsSocketTest.Tpo $(DEPDIR)/testsuite-OsSocketTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsSocketTest.cpp' object='testsuite-OsSocketTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsSocketTest.o `test -f 'os/OsSocketTest.cpp' || echo '$(srcdir)/'`os/OsSocketTest.cpp testsuite-OsSocketTest.obj: os/OsSocketTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsSocketTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsSocketTest.Tpo -c -o testsuite-OsSocketTest.obj `if test -f 'os/OsSocketTest.cpp'; then $(CYGPATH_W) 'os/OsSocketTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsSocketTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsSocketTest.Tpo $(DEPDIR)/testsuite-OsSocketTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsSocketTest.cpp' object='testsuite-OsSocketTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsSocketTest.obj `if test -f 'os/OsSocketTest.cpp'; then $(CYGPATH_W) 'os/OsSocketTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsSocketTest.cpp'; fi` testsuite-OsTestUtilities.o: os/OsTestUtilities.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsTestUtilities.o -MD -MP -MF $(DEPDIR)/testsuite-OsTestUtilities.Tpo -c -o testsuite-OsTestUtilities.o `test -f 'os/OsTestUtilities.cpp' || echo '$(srcdir)/'`os/OsTestUtilities.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsTestUtilities.Tpo $(DEPDIR)/testsuite-OsTestUtilities.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTestUtilities.cpp' object='testsuite-OsTestUtilities.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsTestUtilities.o `test -f 'os/OsTestUtilities.cpp' || echo '$(srcdir)/'`os/OsTestUtilities.cpp testsuite-OsTestUtilities.obj: os/OsTestUtilities.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsTestUtilities.obj -MD -MP -MF $(DEPDIR)/testsuite-OsTestUtilities.Tpo -c -o testsuite-OsTestUtilities.obj `if test -f 'os/OsTestUtilities.cpp'; then $(CYGPATH_W) 'os/OsTestUtilities.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsTestUtilities.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsTestUtilities.Tpo $(DEPDIR)/testsuite-OsTestUtilities.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTestUtilities.cpp' object='testsuite-OsTestUtilities.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsTestUtilities.obj `if test -f 'os/OsTestUtilities.cpp'; then $(CYGPATH_W) 'os/OsTestUtilities.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsTestUtilities.cpp'; fi` testsuite-OsTimerTaskTest.o: os/OsTimerTaskTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsTimerTaskTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsTimerTaskTest.Tpo -c -o testsuite-OsTimerTaskTest.o `test -f 'os/OsTimerTaskTest.cpp' || echo '$(srcdir)/'`os/OsTimerTaskTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsTimerTaskTest.Tpo $(DEPDIR)/testsuite-OsTimerTaskTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTimerTaskTest.cpp' object='testsuite-OsTimerTaskTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsTimerTaskTest.o `test -f 'os/OsTimerTaskTest.cpp' || echo '$(srcdir)/'`os/OsTimerTaskTest.cpp testsuite-OsTimerTaskTest.obj: os/OsTimerTaskTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsTimerTaskTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsTimerTaskTest.Tpo -c -o testsuite-OsTimerTaskTest.obj `if test -f 'os/OsTimerTaskTest.cpp'; then $(CYGPATH_W) 'os/OsTimerTaskTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsTimerTaskTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsTimerTaskTest.Tpo $(DEPDIR)/testsuite-OsTimerTaskTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTimerTaskTest.cpp' object='testsuite-OsTimerTaskTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsTimerTaskTest.obj `if test -f 'os/OsTimerTaskTest.cpp'; then $(CYGPATH_W) 'os/OsTimerTaskTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsTimerTaskTest.cpp'; fi` testsuite-OsTimerTest.o: os/OsTimerTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsTimerTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsTimerTest.Tpo -c -o testsuite-OsTimerTest.o `test -f 'os/OsTimerTest.cpp' || echo '$(srcdir)/'`os/OsTimerTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsTimerTest.Tpo $(DEPDIR)/testsuite-OsTimerTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTimerTest.cpp' object='testsuite-OsTimerTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsTimerTest.o `test -f 'os/OsTimerTest.cpp' || echo '$(srcdir)/'`os/OsTimerTest.cpp testsuite-OsTimerTest.obj: os/OsTimerTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsTimerTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsTimerTest.Tpo -c -o testsuite-OsTimerTest.obj `if test -f 'os/OsTimerTest.cpp'; then $(CYGPATH_W) 'os/OsTimerTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsTimerTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsTimerTest.Tpo $(DEPDIR)/testsuite-OsTimerTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTimerTest.cpp' object='testsuite-OsTimerTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsTimerTest.obj `if test -f 'os/OsTimerTest.cpp'; then $(CYGPATH_W) 'os/OsTimerTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsTimerTest.cpp'; fi` testsuite-OsTimeTest.o: os/OsTimeTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsTimeTest.o -MD -MP -MF $(DEPDIR)/testsuite-OsTimeTest.Tpo -c -o testsuite-OsTimeTest.o `test -f 'os/OsTimeTest.cpp' || echo '$(srcdir)/'`os/OsTimeTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsTimeTest.Tpo $(DEPDIR)/testsuite-OsTimeTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTimeTest.cpp' object='testsuite-OsTimeTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsTimeTest.o `test -f 'os/OsTimeTest.cpp' || echo '$(srcdir)/'`os/OsTimeTest.cpp testsuite-OsTimeTest.obj: os/OsTimeTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-OsTimeTest.obj -MD -MP -MF $(DEPDIR)/testsuite-OsTimeTest.Tpo -c -o testsuite-OsTimeTest.obj `if test -f 'os/OsTimeTest.cpp'; then $(CYGPATH_W) 'os/OsTimeTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsTimeTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-OsTimeTest.Tpo $(DEPDIR)/testsuite-OsTimeTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='os/OsTimeTest.cpp' object='testsuite-OsTimeTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-OsTimeTest.obj `if test -f 'os/OsTimeTest.cpp'; then $(CYGPATH_W) 'os/OsTimeTest.cpp'; else $(CYGPATH_W) '$(srcdir)/os/OsTimeTest.cpp'; fi` testsuite-PluginHooksTest.o: utl/PluginHooksTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-PluginHooksTest.o -MD -MP -MF $(DEPDIR)/testsuite-PluginHooksTest.Tpo -c -o testsuite-PluginHooksTest.o `test -f 'utl/PluginHooksTest.cpp' || echo '$(srcdir)/'`utl/PluginHooksTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-PluginHooksTest.Tpo $(DEPDIR)/testsuite-PluginHooksTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/PluginHooksTest.cpp' object='testsuite-PluginHooksTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-PluginHooksTest.o `test -f 'utl/PluginHooksTest.cpp' || echo '$(srcdir)/'`utl/PluginHooksTest.cpp testsuite-PluginHooksTest.obj: utl/PluginHooksTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-PluginHooksTest.obj -MD -MP -MF $(DEPDIR)/testsuite-PluginHooksTest.Tpo -c -o testsuite-PluginHooksTest.obj `if test -f 'utl/PluginHooksTest.cpp'; then $(CYGPATH_W) 'utl/PluginHooksTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/PluginHooksTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-PluginHooksTest.Tpo $(DEPDIR)/testsuite-PluginHooksTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/PluginHooksTest.cpp' object='testsuite-PluginHooksTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-PluginHooksTest.obj `if test -f 'utl/PluginHooksTest.cpp'; then $(CYGPATH_W) 'utl/PluginHooksTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/PluginHooksTest.cpp'; fi` testsuite-UtlChainTest.o: utl/UtlChainTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlChainTest.o -MD -MP -MF $(DEPDIR)/testsuite-UtlChainTest.Tpo -c -o testsuite-UtlChainTest.o `test -f 'utl/UtlChainTest.cpp' || echo '$(srcdir)/'`utl/UtlChainTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlChainTest.Tpo $(DEPDIR)/testsuite-UtlChainTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlChainTest.cpp' object='testsuite-UtlChainTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlChainTest.o `test -f 'utl/UtlChainTest.cpp' || echo '$(srcdir)/'`utl/UtlChainTest.cpp testsuite-UtlChainTest.obj: utl/UtlChainTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlChainTest.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlChainTest.Tpo -c -o testsuite-UtlChainTest.obj `if test -f 'utl/UtlChainTest.cpp'; then $(CYGPATH_W) 'utl/UtlChainTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlChainTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlChainTest.Tpo $(DEPDIR)/testsuite-UtlChainTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlChainTest.cpp' object='testsuite-UtlChainTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlChainTest.obj `if test -f 'utl/UtlChainTest.cpp'; then $(CYGPATH_W) 'utl/UtlChainTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlChainTest.cpp'; fi` testsuite-UtlContainableTestStub.o: utl/UtlContainableTestStub.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlContainableTestStub.o -MD -MP -MF $(DEPDIR)/testsuite-UtlContainableTestStub.Tpo -c -o testsuite-UtlContainableTestStub.o `test -f 'utl/UtlContainableTestStub.cpp' || echo '$(srcdir)/'`utl/UtlContainableTestStub.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlContainableTestStub.Tpo $(DEPDIR)/testsuite-UtlContainableTestStub.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlContainableTestStub.cpp' object='testsuite-UtlContainableTestStub.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlContainableTestStub.o `test -f 'utl/UtlContainableTestStub.cpp' || echo '$(srcdir)/'`utl/UtlContainableTestStub.cpp testsuite-UtlContainableTestStub.obj: utl/UtlContainableTestStub.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlContainableTestStub.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlContainableTestStub.Tpo -c -o testsuite-UtlContainableTestStub.obj `if test -f 'utl/UtlContainableTestStub.cpp'; then $(CYGPATH_W) 'utl/UtlContainableTestStub.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlContainableTestStub.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlContainableTestStub.Tpo $(DEPDIR)/testsuite-UtlContainableTestStub.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlContainableTestStub.cpp' object='testsuite-UtlContainableTestStub.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlContainableTestStub.obj `if test -f 'utl/UtlContainableTestStub.cpp'; then $(CYGPATH_W) 'utl/UtlContainableTestStub.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlContainableTestStub.cpp'; fi` testsuite-UtlCrc32Test.o: utl/UtlCrc32Test.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlCrc32Test.o -MD -MP -MF $(DEPDIR)/testsuite-UtlCrc32Test.Tpo -c -o testsuite-UtlCrc32Test.o `test -f 'utl/UtlCrc32Test.cpp' || echo '$(srcdir)/'`utl/UtlCrc32Test.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlCrc32Test.Tpo $(DEPDIR)/testsuite-UtlCrc32Test.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlCrc32Test.cpp' object='testsuite-UtlCrc32Test.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlCrc32Test.o `test -f 'utl/UtlCrc32Test.cpp' || echo '$(srcdir)/'`utl/UtlCrc32Test.cpp testsuite-UtlCrc32Test.obj: utl/UtlCrc32Test.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlCrc32Test.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlCrc32Test.Tpo -c -o testsuite-UtlCrc32Test.obj `if test -f 'utl/UtlCrc32Test.cpp'; then $(CYGPATH_W) 'utl/UtlCrc32Test.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlCrc32Test.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlCrc32Test.Tpo $(DEPDIR)/testsuite-UtlCrc32Test.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlCrc32Test.cpp' object='testsuite-UtlCrc32Test.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlCrc32Test.obj `if test -f 'utl/UtlCrc32Test.cpp'; then $(CYGPATH_W) 'utl/UtlCrc32Test.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlCrc32Test.cpp'; fi` testsuite-UtlCryptoTest.o: utl/UtlCryptoTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlCryptoTest.o -MD -MP -MF $(DEPDIR)/testsuite-UtlCryptoTest.Tpo -c -o testsuite-UtlCryptoTest.o `test -f 'utl/UtlCryptoTest.cpp' || echo '$(srcdir)/'`utl/UtlCryptoTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlCryptoTest.Tpo $(DEPDIR)/testsuite-UtlCryptoTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlCryptoTest.cpp' object='testsuite-UtlCryptoTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlCryptoTest.o `test -f 'utl/UtlCryptoTest.cpp' || echo '$(srcdir)/'`utl/UtlCryptoTest.cpp testsuite-UtlCryptoTest.obj: utl/UtlCryptoTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlCryptoTest.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlCryptoTest.Tpo -c -o testsuite-UtlCryptoTest.obj `if test -f 'utl/UtlCryptoTest.cpp'; then $(CYGPATH_W) 'utl/UtlCryptoTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlCryptoTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlCryptoTest.Tpo $(DEPDIR)/testsuite-UtlCryptoTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlCryptoTest.cpp' object='testsuite-UtlCryptoTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlCryptoTest.obj `if test -f 'utl/UtlCryptoTest.cpp'; then $(CYGPATH_W) 'utl/UtlCryptoTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlCryptoTest.cpp'; fi` testsuite-UtlDList.o: utl/UtlDList.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlDList.o -MD -MP -MF $(DEPDIR)/testsuite-UtlDList.Tpo -c -o testsuite-UtlDList.o `test -f 'utl/UtlDList.cpp' || echo '$(srcdir)/'`utl/UtlDList.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlDList.Tpo $(DEPDIR)/testsuite-UtlDList.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlDList.cpp' object='testsuite-UtlDList.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlDList.o `test -f 'utl/UtlDList.cpp' || echo '$(srcdir)/'`utl/UtlDList.cpp testsuite-UtlDList.obj: utl/UtlDList.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlDList.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlDList.Tpo -c -o testsuite-UtlDList.obj `if test -f 'utl/UtlDList.cpp'; then $(CYGPATH_W) 'utl/UtlDList.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlDList.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlDList.Tpo $(DEPDIR)/testsuite-UtlDList.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlDList.cpp' object='testsuite-UtlDList.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlDList.obj `if test -f 'utl/UtlDList.cpp'; then $(CYGPATH_W) 'utl/UtlDList.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlDList.cpp'; fi` testsuite-UtlDListIterator.o: utl/UtlDListIterator.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlDListIterator.o -MD -MP -MF $(DEPDIR)/testsuite-UtlDListIterator.Tpo -c -o testsuite-UtlDListIterator.o `test -f 'utl/UtlDListIterator.cpp' || echo '$(srcdir)/'`utl/UtlDListIterator.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlDListIterator.Tpo $(DEPDIR)/testsuite-UtlDListIterator.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlDListIterator.cpp' object='testsuite-UtlDListIterator.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlDListIterator.o `test -f 'utl/UtlDListIterator.cpp' || echo '$(srcdir)/'`utl/UtlDListIterator.cpp testsuite-UtlDListIterator.obj: utl/UtlDListIterator.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlDListIterator.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlDListIterator.Tpo -c -o testsuite-UtlDListIterator.obj `if test -f 'utl/UtlDListIterator.cpp'; then $(CYGPATH_W) 'utl/UtlDListIterator.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlDListIterator.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlDListIterator.Tpo $(DEPDIR)/testsuite-UtlDListIterator.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlDListIterator.cpp' object='testsuite-UtlDListIterator.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlDListIterator.obj `if test -f 'utl/UtlDListIterator.cpp'; then $(CYGPATH_W) 'utl/UtlDListIterator.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlDListIterator.cpp'; fi` testsuite-UtlHashBag.o: utl/UtlHashBag.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlHashBag.o -MD -MP -MF $(DEPDIR)/testsuite-UtlHashBag.Tpo -c -o testsuite-UtlHashBag.o `test -f 'utl/UtlHashBag.cpp' || echo '$(srcdir)/'`utl/UtlHashBag.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlHashBag.Tpo $(DEPDIR)/testsuite-UtlHashBag.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlHashBag.cpp' object='testsuite-UtlHashBag.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlHashBag.o `test -f 'utl/UtlHashBag.cpp' || echo '$(srcdir)/'`utl/UtlHashBag.cpp testsuite-UtlHashBag.obj: utl/UtlHashBag.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlHashBag.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlHashBag.Tpo -c -o testsuite-UtlHashBag.obj `if test -f 'utl/UtlHashBag.cpp'; then $(CYGPATH_W) 'utl/UtlHashBag.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlHashBag.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlHashBag.Tpo $(DEPDIR)/testsuite-UtlHashBag.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlHashBag.cpp' object='testsuite-UtlHashBag.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlHashBag.obj `if test -f 'utl/UtlHashBag.cpp'; then $(CYGPATH_W) 'utl/UtlHashBag.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlHashBag.cpp'; fi` testsuite-UtlHashBagIterator.o: utl/UtlHashBagIterator.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlHashBagIterator.o -MD -MP -MF $(DEPDIR)/testsuite-UtlHashBagIterator.Tpo -c -o testsuite-UtlHashBagIterator.o `test -f 'utl/UtlHashBagIterator.cpp' || echo '$(srcdir)/'`utl/UtlHashBagIterator.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlHashBagIterator.Tpo $(DEPDIR)/testsuite-UtlHashBagIterator.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlHashBagIterator.cpp' object='testsuite-UtlHashBagIterator.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlHashBagIterator.o `test -f 'utl/UtlHashBagIterator.cpp' || echo '$(srcdir)/'`utl/UtlHashBagIterator.cpp testsuite-UtlHashBagIterator.obj: utl/UtlHashBagIterator.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlHashBagIterator.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlHashBagIterator.Tpo -c -o testsuite-UtlHashBagIterator.obj `if test -f 'utl/UtlHashBagIterator.cpp'; then $(CYGPATH_W) 'utl/UtlHashBagIterator.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlHashBagIterator.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlHashBagIterator.Tpo $(DEPDIR)/testsuite-UtlHashBagIterator.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlHashBagIterator.cpp' object='testsuite-UtlHashBagIterator.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlHashBagIterator.obj `if test -f 'utl/UtlHashBagIterator.cpp'; then $(CYGPATH_W) 'utl/UtlHashBagIterator.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlHashBagIterator.cpp'; fi` testsuite-UtlHashMap.o: utl/UtlHashMap.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlHashMap.o -MD -MP -MF $(DEPDIR)/testsuite-UtlHashMap.Tpo -c -o testsuite-UtlHashMap.o `test -f 'utl/UtlHashMap.cpp' || echo '$(srcdir)/'`utl/UtlHashMap.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlHashMap.Tpo $(DEPDIR)/testsuite-UtlHashMap.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlHashMap.cpp' object='testsuite-UtlHashMap.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlHashMap.o `test -f 'utl/UtlHashMap.cpp' || echo '$(srcdir)/'`utl/UtlHashMap.cpp testsuite-UtlHashMap.obj: utl/UtlHashMap.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlHashMap.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlHashMap.Tpo -c -o testsuite-UtlHashMap.obj `if test -f 'utl/UtlHashMap.cpp'; then $(CYGPATH_W) 'utl/UtlHashMap.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlHashMap.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlHashMap.Tpo $(DEPDIR)/testsuite-UtlHashMap.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlHashMap.cpp' object='testsuite-UtlHashMap.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlHashMap.obj `if test -f 'utl/UtlHashMap.cpp'; then $(CYGPATH_W) 'utl/UtlHashMap.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlHashMap.cpp'; fi` testsuite-UtlHashMapIterator.o: utl/UtlHashMapIterator.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlHashMapIterator.o -MD -MP -MF $(DEPDIR)/testsuite-UtlHashMapIterator.Tpo -c -o testsuite-UtlHashMapIterator.o `test -f 'utl/UtlHashMapIterator.cpp' || echo '$(srcdir)/'`utl/UtlHashMapIterator.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlHashMapIterator.Tpo $(DEPDIR)/testsuite-UtlHashMapIterator.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlHashMapIterator.cpp' object='testsuite-UtlHashMapIterator.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlHashMapIterator.o `test -f 'utl/UtlHashMapIterator.cpp' || echo '$(srcdir)/'`utl/UtlHashMapIterator.cpp testsuite-UtlHashMapIterator.obj: utl/UtlHashMapIterator.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlHashMapIterator.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlHashMapIterator.Tpo -c -o testsuite-UtlHashMapIterator.obj `if test -f 'utl/UtlHashMapIterator.cpp'; then $(CYGPATH_W) 'utl/UtlHashMapIterator.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlHashMapIterator.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlHashMapIterator.Tpo $(DEPDIR)/testsuite-UtlHashMapIterator.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlHashMapIterator.cpp' object='testsuite-UtlHashMapIterator.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlHashMapIterator.obj `if test -f 'utl/UtlHashMapIterator.cpp'; then $(CYGPATH_W) 'utl/UtlHashMapIterator.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlHashMapIterator.cpp'; fi` testsuite-UtlInt.o: utl/UtlInt.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlInt.o -MD -MP -MF $(DEPDIR)/testsuite-UtlInt.Tpo -c -o testsuite-UtlInt.o `test -f 'utl/UtlInt.cpp' || echo '$(srcdir)/'`utl/UtlInt.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlInt.Tpo $(DEPDIR)/testsuite-UtlInt.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlInt.cpp' object='testsuite-UtlInt.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlInt.o `test -f 'utl/UtlInt.cpp' || echo '$(srcdir)/'`utl/UtlInt.cpp testsuite-UtlInt.obj: utl/UtlInt.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlInt.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlInt.Tpo -c -o testsuite-UtlInt.obj `if test -f 'utl/UtlInt.cpp'; then $(CYGPATH_W) 'utl/UtlInt.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlInt.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlInt.Tpo $(DEPDIR)/testsuite-UtlInt.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlInt.cpp' object='testsuite-UtlInt.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlInt.obj `if test -f 'utl/UtlInt.cpp'; then $(CYGPATH_W) 'utl/UtlInt.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlInt.cpp'; fi` testsuite-UtlLinkTest.o: utl/UtlLinkTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlLinkTest.o -MD -MP -MF $(DEPDIR)/testsuite-UtlLinkTest.Tpo -c -o testsuite-UtlLinkTest.o `test -f 'utl/UtlLinkTest.cpp' || echo '$(srcdir)/'`utl/UtlLinkTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlLinkTest.Tpo $(DEPDIR)/testsuite-UtlLinkTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlLinkTest.cpp' object='testsuite-UtlLinkTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlLinkTest.o `test -f 'utl/UtlLinkTest.cpp' || echo '$(srcdir)/'`utl/UtlLinkTest.cpp testsuite-UtlLinkTest.obj: utl/UtlLinkTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlLinkTest.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlLinkTest.Tpo -c -o testsuite-UtlLinkTest.obj `if test -f 'utl/UtlLinkTest.cpp'; then $(CYGPATH_W) 'utl/UtlLinkTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlLinkTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlLinkTest.Tpo $(DEPDIR)/testsuite-UtlLinkTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlLinkTest.cpp' object='testsuite-UtlLinkTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlLinkTest.obj `if test -f 'utl/UtlLinkTest.cpp'; then $(CYGPATH_W) 'utl/UtlLinkTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlLinkTest.cpp'; fi` testsuite-UtlLongLongInt.o: utl/UtlLongLongInt.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlLongLongInt.o -MD -MP -MF $(DEPDIR)/testsuite-UtlLongLongInt.Tpo -c -o testsuite-UtlLongLongInt.o `test -f 'utl/UtlLongLongInt.cpp' || echo '$(srcdir)/'`utl/UtlLongLongInt.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlLongLongInt.Tpo $(DEPDIR)/testsuite-UtlLongLongInt.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlLongLongInt.cpp' object='testsuite-UtlLongLongInt.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlLongLongInt.o `test -f 'utl/UtlLongLongInt.cpp' || echo '$(srcdir)/'`utl/UtlLongLongInt.cpp testsuite-UtlLongLongInt.obj: utl/UtlLongLongInt.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlLongLongInt.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlLongLongInt.Tpo -c -o testsuite-UtlLongLongInt.obj `if test -f 'utl/UtlLongLongInt.cpp'; then $(CYGPATH_W) 'utl/UtlLongLongInt.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlLongLongInt.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlLongLongInt.Tpo $(DEPDIR)/testsuite-UtlLongLongInt.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlLongLongInt.cpp' object='testsuite-UtlLongLongInt.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlLongLongInt.obj `if test -f 'utl/UtlLongLongInt.cpp'; then $(CYGPATH_W) 'utl/UtlLongLongInt.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlLongLongInt.cpp'; fi` testsuite-UtlRegex.o: utl/UtlRegex.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlRegex.o -MD -MP -MF $(DEPDIR)/testsuite-UtlRegex.Tpo -c -o testsuite-UtlRegex.o `test -f 'utl/UtlRegex.cpp' || echo '$(srcdir)/'`utl/UtlRegex.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlRegex.Tpo $(DEPDIR)/testsuite-UtlRegex.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlRegex.cpp' object='testsuite-UtlRegex.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlRegex.o `test -f 'utl/UtlRegex.cpp' || echo '$(srcdir)/'`utl/UtlRegex.cpp testsuite-UtlRegex.obj: utl/UtlRegex.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlRegex.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlRegex.Tpo -c -o testsuite-UtlRegex.obj `if test -f 'utl/UtlRegex.cpp'; then $(CYGPATH_W) 'utl/UtlRegex.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlRegex.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlRegex.Tpo $(DEPDIR)/testsuite-UtlRegex.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlRegex.cpp' object='testsuite-UtlRegex.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlRegex.obj `if test -f 'utl/UtlRegex.cpp'; then $(CYGPATH_W) 'utl/UtlRegex.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlRegex.cpp'; fi` testsuite-UtlSList.o: utl/UtlSList.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlSList.o -MD -MP -MF $(DEPDIR)/testsuite-UtlSList.Tpo -c -o testsuite-UtlSList.o `test -f 'utl/UtlSList.cpp' || echo '$(srcdir)/'`utl/UtlSList.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlSList.Tpo $(DEPDIR)/testsuite-UtlSList.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlSList.cpp' object='testsuite-UtlSList.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlSList.o `test -f 'utl/UtlSList.cpp' || echo '$(srcdir)/'`utl/UtlSList.cpp testsuite-UtlSList.obj: utl/UtlSList.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlSList.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlSList.Tpo -c -o testsuite-UtlSList.obj `if test -f 'utl/UtlSList.cpp'; then $(CYGPATH_W) 'utl/UtlSList.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlSList.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlSList.Tpo $(DEPDIR)/testsuite-UtlSList.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlSList.cpp' object='testsuite-UtlSList.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlSList.obj `if test -f 'utl/UtlSList.cpp'; then $(CYGPATH_W) 'utl/UtlSList.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlSList.cpp'; fi` testsuite-UtlSListIteratorTest.o: utl/UtlSListIteratorTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlSListIteratorTest.o -MD -MP -MF $(DEPDIR)/testsuite-UtlSListIteratorTest.Tpo -c -o testsuite-UtlSListIteratorTest.o `test -f 'utl/UtlSListIteratorTest.cpp' || echo '$(srcdir)/'`utl/UtlSListIteratorTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlSListIteratorTest.Tpo $(DEPDIR)/testsuite-UtlSListIteratorTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlSListIteratorTest.cpp' object='testsuite-UtlSListIteratorTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlSListIteratorTest.o `test -f 'utl/UtlSListIteratorTest.cpp' || echo '$(srcdir)/'`utl/UtlSListIteratorTest.cpp testsuite-UtlSListIteratorTest.obj: utl/UtlSListIteratorTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlSListIteratorTest.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlSListIteratorTest.Tpo -c -o testsuite-UtlSListIteratorTest.obj `if test -f 'utl/UtlSListIteratorTest.cpp'; then $(CYGPATH_W) 'utl/UtlSListIteratorTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlSListIteratorTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlSListIteratorTest.Tpo $(DEPDIR)/testsuite-UtlSListIteratorTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlSListIteratorTest.cpp' object='testsuite-UtlSListIteratorTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlSListIteratorTest.obj `if test -f 'utl/UtlSListIteratorTest.cpp'; then $(CYGPATH_W) 'utl/UtlSListIteratorTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlSListIteratorTest.cpp'; fi` testsuite-UtlSortedList.o: utl/UtlSortedList.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlSortedList.o -MD -MP -MF $(DEPDIR)/testsuite-UtlSortedList.Tpo -c -o testsuite-UtlSortedList.o `test -f 'utl/UtlSortedList.cpp' || echo '$(srcdir)/'`utl/UtlSortedList.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlSortedList.Tpo $(DEPDIR)/testsuite-UtlSortedList.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlSortedList.cpp' object='testsuite-UtlSortedList.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlSortedList.o `test -f 'utl/UtlSortedList.cpp' || echo '$(srcdir)/'`utl/UtlSortedList.cpp testsuite-UtlSortedList.obj: utl/UtlSortedList.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlSortedList.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlSortedList.Tpo -c -o testsuite-UtlSortedList.obj `if test -f 'utl/UtlSortedList.cpp'; then $(CYGPATH_W) 'utl/UtlSortedList.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlSortedList.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlSortedList.Tpo $(DEPDIR)/testsuite-UtlSortedList.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlSortedList.cpp' object='testsuite-UtlSortedList.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlSortedList.obj `if test -f 'utl/UtlSortedList.cpp'; then $(CYGPATH_W) 'utl/UtlSortedList.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlSortedList.cpp'; fi` testsuite-UtlSortedListIteratorTest.o: utl/UtlSortedListIteratorTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlSortedListIteratorTest.o -MD -MP -MF $(DEPDIR)/testsuite-UtlSortedListIteratorTest.Tpo -c -o testsuite-UtlSortedListIteratorTest.o `test -f 'utl/UtlSortedListIteratorTest.cpp' || echo '$(srcdir)/'`utl/UtlSortedListIteratorTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlSortedListIteratorTest.Tpo $(DEPDIR)/testsuite-UtlSortedListIteratorTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlSortedListIteratorTest.cpp' object='testsuite-UtlSortedListIteratorTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlSortedListIteratorTest.o `test -f 'utl/UtlSortedListIteratorTest.cpp' || echo '$(srcdir)/'`utl/UtlSortedListIteratorTest.cpp testsuite-UtlSortedListIteratorTest.obj: utl/UtlSortedListIteratorTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlSortedListIteratorTest.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlSortedListIteratorTest.Tpo -c -o testsuite-UtlSortedListIteratorTest.obj `if test -f 'utl/UtlSortedListIteratorTest.cpp'; then $(CYGPATH_W) 'utl/UtlSortedListIteratorTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlSortedListIteratorTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlSortedListIteratorTest.Tpo $(DEPDIR)/testsuite-UtlSortedListIteratorTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlSortedListIteratorTest.cpp' object='testsuite-UtlSortedListIteratorTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlSortedListIteratorTest.obj `if test -f 'utl/UtlSortedListIteratorTest.cpp'; then $(CYGPATH_W) 'utl/UtlSortedListIteratorTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlSortedListIteratorTest.cpp'; fi` testsuite-UtlStringTest.o: utl/UtlStringTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlStringTest.o -MD -MP -MF $(DEPDIR)/testsuite-UtlStringTest.Tpo -c -o testsuite-UtlStringTest.o `test -f 'utl/UtlStringTest.cpp' || echo '$(srcdir)/'`utl/UtlStringTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlStringTest.Tpo $(DEPDIR)/testsuite-UtlStringTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlStringTest.cpp' object='testsuite-UtlStringTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlStringTest.o `test -f 'utl/UtlStringTest.cpp' || echo '$(srcdir)/'`utl/UtlStringTest.cpp testsuite-UtlStringTest.obj: utl/UtlStringTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlStringTest.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlStringTest.Tpo -c -o testsuite-UtlStringTest.obj `if test -f 'utl/UtlStringTest.cpp'; then $(CYGPATH_W) 'utl/UtlStringTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlStringTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlStringTest.Tpo $(DEPDIR)/testsuite-UtlStringTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlStringTest.cpp' object='testsuite-UtlStringTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlStringTest.obj `if test -f 'utl/UtlStringTest.cpp'; then $(CYGPATH_W) 'utl/UtlStringTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlStringTest.cpp'; fi` testsuite-UtlStringTest_ConstructiveManipulators.o: utl/UtlStringTest_ConstructiveManipulators.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlStringTest_ConstructiveManipulators.o -MD -MP -MF $(DEPDIR)/testsuite-UtlStringTest_ConstructiveManipulators.Tpo -c -o testsuite-UtlStringTest_ConstructiveManipulators.o `test -f 'utl/UtlStringTest_ConstructiveManipulators.cpp' || echo '$(srcdir)/'`utl/UtlStringTest_ConstructiveManipulators.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlStringTest_ConstructiveManipulators.Tpo $(DEPDIR)/testsuite-UtlStringTest_ConstructiveManipulators.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlStringTest_ConstructiveManipulators.cpp' object='testsuite-UtlStringTest_ConstructiveManipulators.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlStringTest_ConstructiveManipulators.o `test -f 'utl/UtlStringTest_ConstructiveManipulators.cpp' || echo '$(srcdir)/'`utl/UtlStringTest_ConstructiveManipulators.cpp testsuite-UtlStringTest_ConstructiveManipulators.obj: utl/UtlStringTest_ConstructiveManipulators.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlStringTest_ConstructiveManipulators.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlStringTest_ConstructiveManipulators.Tpo -c -o testsuite-UtlStringTest_ConstructiveManipulators.obj `if test -f 'utl/UtlStringTest_ConstructiveManipulators.cpp'; then $(CYGPATH_W) 'utl/UtlStringTest_ConstructiveManipulators.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlStringTest_ConstructiveManipulators.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlStringTest_ConstructiveManipulators.Tpo $(DEPDIR)/testsuite-UtlStringTest_ConstructiveManipulators.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlStringTest_ConstructiveManipulators.cpp' object='testsuite-UtlStringTest_ConstructiveManipulators.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlStringTest_ConstructiveManipulators.obj `if test -f 'utl/UtlStringTest_ConstructiveManipulators.cpp'; then $(CYGPATH_W) 'utl/UtlStringTest_ConstructiveManipulators.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlStringTest_ConstructiveManipulators.cpp'; fi` testsuite-UtlStringTest_DestructiveManipulators.o: utl/UtlStringTest_DestructiveManipulators.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlStringTest_DestructiveManipulators.o -MD -MP -MF $(DEPDIR)/testsuite-UtlStringTest_DestructiveManipulators.Tpo -c -o testsuite-UtlStringTest_DestructiveManipulators.o `test -f 'utl/UtlStringTest_DestructiveManipulators.cpp' || echo '$(srcdir)/'`utl/UtlStringTest_DestructiveManipulators.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlStringTest_DestructiveManipulators.Tpo $(DEPDIR)/testsuite-UtlStringTest_DestructiveManipulators.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlStringTest_DestructiveManipulators.cpp' object='testsuite-UtlStringTest_DestructiveManipulators.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlStringTest_DestructiveManipulators.o `test -f 'utl/UtlStringTest_DestructiveManipulators.cpp' || echo '$(srcdir)/'`utl/UtlStringTest_DestructiveManipulators.cpp testsuite-UtlStringTest_DestructiveManipulators.obj: utl/UtlStringTest_DestructiveManipulators.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlStringTest_DestructiveManipulators.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlStringTest_DestructiveManipulators.Tpo -c -o testsuite-UtlStringTest_DestructiveManipulators.obj `if test -f 'utl/UtlStringTest_DestructiveManipulators.cpp'; then $(CYGPATH_W) 'utl/UtlStringTest_DestructiveManipulators.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlStringTest_DestructiveManipulators.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlStringTest_DestructiveManipulators.Tpo $(DEPDIR)/testsuite-UtlStringTest_DestructiveManipulators.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlStringTest_DestructiveManipulators.cpp' object='testsuite-UtlStringTest_DestructiveManipulators.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlStringTest_DestructiveManipulators.obj `if test -f 'utl/UtlStringTest_DestructiveManipulators.cpp'; then $(CYGPATH_W) 'utl/UtlStringTest_DestructiveManipulators.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlStringTest_DestructiveManipulators.cpp'; fi` testsuite-UtlStringTest_NonMutating.o: utl/UtlStringTest_NonMutating.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlStringTest_NonMutating.o -MD -MP -MF $(DEPDIR)/testsuite-UtlStringTest_NonMutating.Tpo -c -o testsuite-UtlStringTest_NonMutating.o `test -f 'utl/UtlStringTest_NonMutating.cpp' || echo '$(srcdir)/'`utl/UtlStringTest_NonMutating.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlStringTest_NonMutating.Tpo $(DEPDIR)/testsuite-UtlStringTest_NonMutating.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlStringTest_NonMutating.cpp' object='testsuite-UtlStringTest_NonMutating.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlStringTest_NonMutating.o `test -f 'utl/UtlStringTest_NonMutating.cpp' || echo '$(srcdir)/'`utl/UtlStringTest_NonMutating.cpp testsuite-UtlStringTest_NonMutating.obj: utl/UtlStringTest_NonMutating.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlStringTest_NonMutating.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlStringTest_NonMutating.Tpo -c -o testsuite-UtlStringTest_NonMutating.obj `if test -f 'utl/UtlStringTest_NonMutating.cpp'; then $(CYGPATH_W) 'utl/UtlStringTest_NonMutating.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlStringTest_NonMutating.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlStringTest_NonMutating.Tpo $(DEPDIR)/testsuite-UtlStringTest_NonMutating.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlStringTest_NonMutating.cpp' object='testsuite-UtlStringTest_NonMutating.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlStringTest_NonMutating.obj `if test -f 'utl/UtlStringTest_NonMutating.cpp'; then $(CYGPATH_W) 'utl/UtlStringTest_NonMutating.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlStringTest_NonMutating.cpp'; fi` testsuite-UtlTokenizerTest.o: utl/UtlTokenizerTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlTokenizerTest.o -MD -MP -MF $(DEPDIR)/testsuite-UtlTokenizerTest.Tpo -c -o testsuite-UtlTokenizerTest.o `test -f 'utl/UtlTokenizerTest.cpp' || echo '$(srcdir)/'`utl/UtlTokenizerTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlTokenizerTest.Tpo $(DEPDIR)/testsuite-UtlTokenizerTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlTokenizerTest.cpp' object='testsuite-UtlTokenizerTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlTokenizerTest.o `test -f 'utl/UtlTokenizerTest.cpp' || echo '$(srcdir)/'`utl/UtlTokenizerTest.cpp testsuite-UtlTokenizerTest.obj: utl/UtlTokenizerTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlTokenizerTest.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlTokenizerTest.Tpo -c -o testsuite-UtlTokenizerTest.obj `if test -f 'utl/UtlTokenizerTest.cpp'; then $(CYGPATH_W) 'utl/UtlTokenizerTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlTokenizerTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlTokenizerTest.Tpo $(DEPDIR)/testsuite-UtlTokenizerTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlTokenizerTest.cpp' object='testsuite-UtlTokenizerTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlTokenizerTest.obj `if test -f 'utl/UtlTokenizerTest.cpp'; then $(CYGPATH_W) 'utl/UtlTokenizerTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlTokenizerTest.cpp'; fi` testsuite-UtlVoidPtr.o: utl/UtlVoidPtr.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlVoidPtr.o -MD -MP -MF $(DEPDIR)/testsuite-UtlVoidPtr.Tpo -c -o testsuite-UtlVoidPtr.o `test -f 'utl/UtlVoidPtr.cpp' || echo '$(srcdir)/'`utl/UtlVoidPtr.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlVoidPtr.Tpo $(DEPDIR)/testsuite-UtlVoidPtr.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlVoidPtr.cpp' object='testsuite-UtlVoidPtr.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlVoidPtr.o `test -f 'utl/UtlVoidPtr.cpp' || echo '$(srcdir)/'`utl/UtlVoidPtr.cpp testsuite-UtlVoidPtr.obj: utl/UtlVoidPtr.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-UtlVoidPtr.obj -MD -MP -MF $(DEPDIR)/testsuite-UtlVoidPtr.Tpo -c -o testsuite-UtlVoidPtr.obj `if test -f 'utl/UtlVoidPtr.cpp'; then $(CYGPATH_W) 'utl/UtlVoidPtr.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlVoidPtr.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-UtlVoidPtr.Tpo $(DEPDIR)/testsuite-UtlVoidPtr.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/UtlVoidPtr.cpp' object='testsuite-UtlVoidPtr.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-UtlVoidPtr.obj `if test -f 'utl/UtlVoidPtr.cpp'; then $(CYGPATH_W) 'utl/UtlVoidPtr.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/UtlVoidPtr.cpp'; fi` testsuite-XmlContentTest.o: utl/XmlContentTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-XmlContentTest.o -MD -MP -MF $(DEPDIR)/testsuite-XmlContentTest.Tpo -c -o testsuite-XmlContentTest.o `test -f 'utl/XmlContentTest.cpp' || echo '$(srcdir)/'`utl/XmlContentTest.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-XmlContentTest.Tpo $(DEPDIR)/testsuite-XmlContentTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/XmlContentTest.cpp' object='testsuite-XmlContentTest.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-XmlContentTest.o `test -f 'utl/XmlContentTest.cpp' || echo '$(srcdir)/'`utl/XmlContentTest.cpp testsuite-XmlContentTest.obj: utl/XmlContentTest.cpp @am__fastdepCXX_TRUE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -MT testsuite-XmlContentTest.obj -MD -MP -MF $(DEPDIR)/testsuite-XmlContentTest.Tpo -c -o testsuite-XmlContentTest.obj `if test -f 'utl/XmlContentTest.cpp'; then $(CYGPATH_W) 'utl/XmlContentTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/XmlContentTest.cpp'; fi` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/testsuite-XmlContentTest.Tpo $(DEPDIR)/testsuite-XmlContentTest.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='utl/XmlContentTest.cpp' object='testsuite-XmlContentTest.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testsuite_CPPFLAGS) $(CPPFLAGS) $(testsuite_CXXFLAGS) $(CXXFLAGS) -c -o testsuite-XmlContentTest.obj `if test -f 'utl/XmlContentTest.cpp'; then $(CYGPATH_W) 'utl/XmlContentTest.cpp'; else $(CYGPATH_W) '$(srcdir)/utl/XmlContentTest.cpp'; fi` mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run `make' without going through this Makefile. # To change the values of `make' variables: instead of editing Makefiles, # (1) if the variable is set in `config.status', edit `config.status' # (which will cause the Makefiles to be regenerated when you run `make'); # (2) otherwise, pass the desired values on the `make' command line. $(RECURSIVE_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ list='$(SUBDIRS)'; for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" $(RECURSIVE_CLEAN_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ rev=''; for subdir in $$list; do \ if test "$$subdir" = "."; then :; else \ rev="$$subdir $$rev"; \ fi; \ done; \ rev="$$rev ."; \ target=`echo $@ | sed s/-recursive//`; \ for subdir in $$rev; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done && test -z "$$fail" tags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ done ctags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ done ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags check-TESTS: $(TESTS) @failed=0; all=0; xfail=0; xpass=0; skip=0; \ srcdir=$(srcdir); export srcdir; \ list=' $(TESTS) '; \ $(am__tty_colors); \ if test -n "$$list"; then \ for tst in $$list; do \ if test -f ./$$tst; then dir=./; \ elif test -f $$tst; then dir=; \ else dir="$(srcdir)/"; fi; \ if $(TESTS_ENVIRONMENT) $${dir}$$tst; then \ all=`expr $$all + 1`; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$tst[\ \ ]*) \ xpass=`expr $$xpass + 1`; \ failed=`expr $$failed + 1`; \ col=$$red; res=XPASS; \ ;; \ *) \ col=$$grn; res=PASS; \ ;; \ esac; \ elif test $$? -ne 77; then \ all=`expr $$all + 1`; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$tst[\ \ ]*) \ xfail=`expr $$xfail + 1`; \ col=$$lgn; res=XFAIL; \ ;; \ *) \ failed=`expr $$failed + 1`; \ col=$$red; res=FAIL; \ ;; \ esac; \ else \ skip=`expr $$skip + 1`; \ col=$$blu; res=SKIP; \ fi; \ echo "$${col}$$res$${std}: $$tst"; \ done; \ if test "$$all" -eq 1; then \ tests="test"; \ All=""; \ else \ tests="tests"; \ All="All "; \ fi; \ if test "$$failed" -eq 0; then \ if test "$$xfail" -eq 0; then \ banner="$$All$$all $$tests passed"; \ else \ if test "$$xfail" -eq 1; then failures=failure; else failures=failures; fi; \ banner="$$All$$all $$tests behaved as expected ($$xfail expected $$failures)"; \ fi; \ else \ if test "$$xpass" -eq 0; then \ banner="$$failed of $$all $$tests failed"; \ else \ if test "$$xpass" -eq 1; then passes=pass; else passes=passes; fi; \ banner="$$failed of $$all $$tests did not behave as expected ($$xpass unexpected $$passes)"; \ fi; \ fi; \ dashes="$$banner"; \ skipped=""; \ if test "$$skip" -ne 0; then \ if test "$$skip" -eq 1; then \ skipped="($$skip test was not run)"; \ else \ skipped="($$skip tests were not run)"; \ fi; \ test `echo "$$skipped" | wc -c` -le `echo "$$banner" | wc -c` || \ dashes="$$skipped"; \ fi; \ report=""; \ if test "$$failed" -ne 0 && test -n "$(PACKAGE_BUGREPORT)"; then \ report="Please report to $(PACKAGE_BUGREPORT)"; \ test `echo "$$report" | wc -c` -le `echo "$$banner" | wc -c` || \ dashes="$$report"; \ fi; \ dashes=`echo "$$dashes" | sed s/./=/g`; \ if test "$$failed" -eq 0; then \ col="$$grn"; \ else \ col="$$red"; \ fi; \ echo "$${col}$$dashes$${std}"; \ echo "$${col}$$banner$${std}"; \ test -z "$$skipped" || echo "$${col}$$skipped$${std}"; \ test -z "$$report" || echo "$${col}$$report$${std}"; \ echo "$${col}$$dashes$${std}"; \ test "$$failed" -eq 0; \ else :; fi distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-recursive all-am: Makefile $(HEADERS) installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ mostlyclean-am distclean: distclean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) check-am \ ctags-recursive install-am install-strip tags-recursive .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ all all-am check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool ctags \ ctags-recursive distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-recursive uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: sipxtapi-3.3.0~test17/sipXportLib/src/test/testplugin/0000755000175000017500000000000012321445024023616 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/src/test/testplugin/Makefile.am0000644000175000017500000000335112205613305025654 0ustar00danieldaniel00000000000000## Process this file with automake to produce Makefile.in include $(top_srcdir)/config/sipXcommon.am.inc ## HACK ## We don't need these libraries installed, so we declare them noinst_ ## but that has the unfortunate side effect that automake then assumes ## (reasonably) that there is no point in making them shared, which ## is wrong because the PluginTest needs to dlopen them... noinst_LTLIBRARIES = libtestpluginA.la libtestpluginB.la ## So... we explicitly add the -rpath that automake would normally provide ## when building a shared library. libtestpluginA_la_LDFLAGS = \ -rpath @abs_builddir@ \ -version-info ${version_Current}:${version_Revision}:${version_Age} libtestpluginB_la_LDFLAGS = $(libtestpluginA_la_LDFLAGS) INCLUDES = \ -I$(top_srcdir)/sipXportLib/include \ -I$(top_srcdir)/sipXportLib/src/test/utl ## Libtool version info - update only immediately before a release # Current - increment if any interfaces are added, removed, or changed version_Current=1 # Revision - set to 0 if Current was incremented # increment if any implementation has changed version_Revision=0 # Age - set to 0 of any interfaces have been removed # increment if any interfaces have been added version_Age=0 libtestpluginA_la_LIBADD = \ -ldl \ -lpthread \ -lstdc++ libtestpluginB_la_LIBADD = $(libtestpluginA_la_LIBADD) ## Compile the same source twice, changing the resulting class name ## to create two different plugins libtestpluginA_la_CXXFLAGS = \ -DLIBRARY_NAME=\"TestPluginA\" \ -DTestPlugin=TestPluginA libtestpluginB_la_CXXFLAGS = \ -DLIBRARY_NAME=\"TestPluginB\" \ -DTestPlugin=TestPluginB libtestpluginA_la_SOURCES = \ TestPlugin.cpp libtestpluginB_la_SOURCES = $(libtestpluginA_la_SOURCES) sipxtapi-3.3.0~test17/sipXportLib/src/test/testplugin/Makefile.in0000644000175000017500000006156312321445001025671 0ustar00danieldaniel00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # -*-makefile-*- VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ $(top_srcdir)/config/sipXcommon.am.inc subdir = sipXportLib/src/test/testplugin ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/general.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/sipXlib.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libtestpluginA_la_DEPENDENCIES = am_libtestpluginA_la_OBJECTS = libtestpluginA_la-TestPlugin.lo libtestpluginA_la_OBJECTS = $(am_libtestpluginA_la_OBJECTS) libtestpluginA_la_LINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) \ $(libtestpluginA_la_CXXFLAGS) $(CXXFLAGS) \ $(libtestpluginA_la_LDFLAGS) $(LDFLAGS) -o $@ am__DEPENDENCIES_1 = libtestpluginB_la_DEPENDENCIES = $(am__DEPENDENCIES_1) am__objects_1 = libtestpluginB_la-TestPlugin.lo am_libtestpluginB_la_OBJECTS = $(am__objects_1) libtestpluginB_la_OBJECTS = $(am_libtestpluginB_la_OBJECTS) libtestpluginB_la_LINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) \ $(libtestpluginB_la_CXXFLAGS) $(CXXFLAGS) \ $(libtestpluginB_la_LDFLAGS) $(LDFLAGS) -o $@ DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) CXXLD = $(CXX) CXXLINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ SOURCES = $(libtestpluginA_la_SOURCES) $(libtestpluginB_la_SOURCES) DIST_SOURCES = $(libtestpluginA_la_SOURCES) \ $(libtestpluginB_la_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMRNB_INCLUDE = @AMRNB_INCLUDE@ AMRNB_LIB_ROOT = @AMRNB_LIB_ROOT@ AMRWB_INCLUDE = @AMRWB_INCLUDE@ AMRWB_LIB_ROOT = @AMRWB_LIB_ROOT@ AMRWB_TARGET = @AMRWB_TARGET@ AMR_TARGET = @AMR_TARGET@ AMTAR = @AMTAR@ ANT = @ANT@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CARBON_LIBS = @CARBON_LIBS@ CA_LIBS = @CA_LIBS@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPUNIT_CFLAGS = @CPPUNIT_CFLAGS@ CPPUNIT_CONFIG = @CPPUNIT_CONFIG@ CPPUNIT_LIBS = @CPPUNIT_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPS_PCRE_CFLAGS = @DEPS_PCRE_CFLAGS@ DEPS_PCRE_LIBS = @DEPS_PCRE_LIBS@ DLLTOOL = @DLLTOOL@ DOT = @DOT@ DOXYGEN = @DOXYGEN@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DYNEXT = @DYNEXT@ EAGC_LDFLAGS = @EAGC_LDFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EJBE_LDFLAGS = @EJBE_LDFLAGS@ EPLC_LDFLAGS = @EPLC_LDFLAGS@ EVAD_LDFLAGS = @EVAD_LDFLAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ G722_TARGET = @G722_TARGET@ G726_TARGET = @G726_TARGET@ GIPSINC = @GIPSINC@ GIPS_CE_OBJS = @GIPS_CE_OBJS@ GIPS_CPPFLAGS = @GIPS_CPPFLAGS@ GIPS_NEQ_OBJS = @GIPS_NEQ_OBJS@ GIPS_VE_OBJS = @GIPS_VE_OBJS@ GREP = @GREP@ GSM_CFLAGS = @GSM_CFLAGS@ GSM_CXXFLAGS = @GSM_CXXFLAGS@ GSM_LDFLAGS = @GSM_LDFLAGS@ GSM_LIBS = @GSM_LIBS@ GSM_TARGET = @GSM_TARGET@ ILBC_INCLUDE = @ILBC_INCLUDE@ ILBC_LIB_ROOT = @ILBC_LIB_ROOT@ ILBC_LIB_TARGET = @ILBC_LIB_TARGET@ ILBC_TARGET = @ILBC_TARGET@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTERFACE_FLAGS = @INTERFACE_FLAGS@ JAVA = @JAVA@ JAVAC_DEBUG = @JAVAC_DEBUG@ JAVAC_OPTIMIZED = @JAVAC_OPTIMIZED@ JAVA_HOME = @JAVA_HOME@ L16_TARGET = @L16_TARGET@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NAMED_PROGRAM = @NAMED_PROGRAM@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPUS_CFLAGS = @OPUS_CFLAGS@ OPUS_LIBS = @OPUS_LIBS@ OPUS_TARGET = @OPUS_TARGET@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PCMAPCMU_TARGET = @PCMAPCMU_TARGET@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ RTL_CXXFLAGS = @RTL_CXXFLAGS@ RTL_LDFLAGS = @RTL_LDFLAGS@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SIPXMEDIA_CE_LIBS = @SIPXMEDIA_CE_LIBS@ SIPXMEDIA_VE_LIBS = @SIPXMEDIA_VE_LIBS@ SIPXMEDIA_VE_STATIC_LIBS = @SIPXMEDIA_VE_STATIC_LIBS@ SIPXPBXUSER = @SIPXPBXUSER@ SIPXPHONECONF = @SIPXPHONECONF@ SIPXPHONEDATA = @SIPXPHONEDATA@ SIPXPHONELIB = @SIPXPHONELIB@ SIPX_BACKUPDIR = @SIPX_BACKUPDIR@ SIPX_BINDIR = @SIPX_BINDIR@ SIPX_CONFDIR = @SIPX_CONFDIR@ SIPX_CONFIGPHONEDIR = @SIPX_CONFIGPHONEDIR@ SIPX_DATADIR = @SIPX_DATADIR@ SIPX_DBDIR = @SIPX_DBDIR@ SIPX_DOCDIR = @SIPX_DOCDIR@ SIPX_INCDIR = @SIPX_INCDIR@ SIPX_LIBDIR = @SIPX_LIBDIR@ SIPX_LOGDIR = @SIPX_LOGDIR@ SIPX_PARKMUSICDIR = @SIPX_PARKMUSICDIR@ SIPX_RUNDIR = @SIPX_RUNDIR@ SIPX_SCHEMADIR = @SIPX_SCHEMADIR@ SIPX_TMPDIR = @SIPX_TMPDIR@ SIPX_UNIT_TARGET = @SIPX_UNIT_TARGET@ SIPX_VXMLDATADIR = @SIPX_VXMLDATADIR@ SPANDSP_CFLAGS = @SPANDSP_CFLAGS@ SPANDSP_CXXFLAGS = @SPANDSP_CXXFLAGS@ SPANDSP_LDFLAGS = @SPANDSP_LDFLAGS@ SPANDSP_LIBS = @SPANDSP_LIBS@ SPEEXDSP_CFLAGS = @SPEEXDSP_CFLAGS@ SPEEXDSP_LIBS = @SPEEXDSP_LIBS@ SPEEXDSP_STATIC_LIB = @SPEEXDSP_STATIC_LIB@ SPEEX_CFLAGS = @SPEEX_CFLAGS@ SPEEX_LIBS = @SPEEX_LIBS@ SPEEX_ROOT = @SPEEX_ROOT@ SPEEX_STATIC_LIB = @SPEEX_STATIC_LIB@ SPEEX_TARGET = @SPEEX_TARGET@ SS_LDFLAGS = @SS_LDFLAGS@ STATIC_CODEC_LIBS = @STATIC_CODEC_LIBS@ STRIP = @STRIP@ TONES_TARGET = @TONES_TARGET@ VERSION = @VERSION@ VIDEO_DEFINE = @VIDEO_DEFINE@ WXWIDGETS_CFLAGS = @WXWIDGETS_CFLAGS@ WXWIDGETS_CONFIG = @WXWIDGETS_CONFIG@ WXWIDGETS_CXXFLAGS = @WXWIDGETS_CXXFLAGS@ WXWIDGETS_LIBS = @WXWIDGETS_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ codeclibdir = @codeclibdir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ enable_dot = @enable_dot@ enable_html_docs = @enable_html_docs@ enable_latex_docs = @enable_latex_docs@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ jar = @jar@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ sipx_abs_srcdir = @sipx_abs_srcdir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ wwwdir = @wwwdir@ ConfigureArgs = $(shell sed \ -e '/^ *\$$ .*\/configure/!d' \ -e 's/^ *\$$ .*\/configure *//' \ $(top_builddir)/config.log \ ) LocalizeSipXconfig = sed \ -e 's,@PACKAGE\@,@PACKAGE@,g' \ -e 's,@VERSION\@,@VERSION@,g' \ -e 's,@abs_builddir\@,@abs_builddir@,g' \ -e 's,@abs_srcdir\@,@abs_srcdir@,g' \ -e 's,@abs_top_srcdir\@,@abs_top_srcdir@,g' \ -e 's,@sipx_abs_srcdir\@,@sipx_abs_srcdir@,g' \ -e 's!@CONFIGURE_OPTIONS@!$(ConfigureArgs)!g' \ -e 's,@bindir\@,$(bindir),g' \ -e 's,@datadir\@,$(datadir),g' \ -e 's,@htmldir\@,@htmldir@,g' \ -e 's,@INSTALL\@,@INSTALL@,g' \ -e 's,@install_sh\@,@install_sh@,g' \ -e 's,@libdir\@,$(libdir),g' \ -e 's,@localstatedir\@,$(localstatedir),g' \ -e 's,@pkgdatadir\@,@pkgdatadir@,g' \ -e 's,@prefix\@,$(prefix),g' \ -e 's,@profiledir\@,@profiledir@,g' \ -e 's,@wwwdir\@,@wwwdir@,g' \ -e 's,@host\@,@host@,g' \ -e 's,@PERL\@,@PERL@,g' \ -e 's,@APACHE2_HTTPD\@,@APACHE2_HTTPD@,g' \ -e 's,@APACHE2_MOD\@,@APACHE2_MOD@,g' \ -e 's,@CLOVER_HOME\@,@CLOVER_HOME@,g' \ -e 's,@JAVAC_DEBUG\@,@JAVAC_DEBUG@,g' \ -e 's,@JAVAC_OPTIMIZED\@,@JAVAC_OPTIMIZED@,g' \ -e 's,@JAVA\@,@JAVA@,g' \ -e 's,@JAVA_HOME\@,@JAVA_HOME@,g' \ -e 's,@JBOSS_HOME\@,@JBOSS_HOME@,g' \ -e 's,@JBOSS_SERVER_CONF\@,@JBOSS_SERVER_CONF@,g' \ -e 's,@SIPFOUNDRY_ORG\@,@SIPFOUNDRY_ORG@,g' \ -e 's,@SIPXCONFIG_LIBDIR\@,@SIPXCONFIG_LIBDIR@,g' \ -e 's,@SIPXPBXUSER\@,@SIPXPBXUSER@,g' \ -e 's,@SIPX_BINDIR\@,@SIPX_BINDIR@,g' \ -e 's,@SIPX_CONFDIR\@,@SIPX_CONFDIR@,g' \ -e 's,@SIPX_CONFIGPHONEDIR\@,@SIPX_CONFIGPHONEDIR@,g' \ -e 's,@SIPX_BACKUPDIR\@,@SIPX_BACKUPDIR@,g' \ -e 's,@SIPX_DATADIR\@,@SIPX_DATADIR@,g' \ -e 's,@SIPX_DBDIR\@,@SIPX_DBDIR@,g' \ -e 's,@SIPX_DOCDIR\@,@SIPX_DOCDIR@,g' \ -e 's,@SIPX_LOGDIR\@,@SIPX_LOGDIR@,g' \ -e 's,@SIPX_RUNDIR\@,@SIPX_RUNDIR@,g' \ -e 's,@SIPX_TMPDIR\@,@SIPX_TMPDIR@,g' \ -e 's,@SIPX_INCDIR\@,@SIPX_INCDIR@,g' \ -e 's,@SIPX_LIBDIR\@,@SIPX_LIBDIR@,g' \ -e 's,@SIPX_SCHEMADIR\@,@SIPX_SCHEMADIR@,g' \ -e 's,@SIPX_VXMLDATADIR\@,@SIPX_VXMLDATADIR@,g' \ -e 's,@SIPX_PARKMUSICDIR\@,@SIPX_PARKMUSICDIR@,g' \ -e 's,@SPRING_HOME\@,@SPRING_HOME@,g' \ -e 's,@XPRESSA_BUILD_NUMBER\@,@XPRESSA_BUILD_NUMBER@,g' \ -e 's,@XPRESSA_BUILD_COMMENT\@,@XPRESSA_BUILD_COMMENT@,g' \ -e 's,@SIPXPHONELIB\@,@SIPXPHONELIB@,g' \ -e 's,@SIPXPHONEDATA\@,@SIPXPHONEDATA@,g' \ -e 's,@SIPXPHONECONF\@,@SIPXPHONECONF@,g' \ -e 's,@NAMED_PROGRAM\@,@NAMED_PROGRAM@,g' noinst_LTLIBRARIES = libtestpluginA.la libtestpluginB.la libtestpluginA_la_LDFLAGS = \ -rpath @abs_builddir@ \ -version-info ${version_Current}:${version_Revision}:${version_Age} libtestpluginB_la_LDFLAGS = $(libtestpluginA_la_LDFLAGS) INCLUDES = \ -I$(top_srcdir)/sipXportLib/include \ -I$(top_srcdir)/sipXportLib/src/test/utl # Current - increment if any interfaces are added, removed, or changed version_Current = 1 # Revision - set to 0 if Current was incremented # increment if any implementation has changed version_Revision = 0 # Age - set to 0 of any interfaces have been removed # increment if any interfaces have been added version_Age = 0 libtestpluginA_la_LIBADD = \ -ldl \ -lpthread \ -lstdc++ libtestpluginB_la_LIBADD = $(libtestpluginA_la_LIBADD) libtestpluginA_la_CXXFLAGS = \ -DLIBRARY_NAME=\"TestPluginA\" \ -DTestPlugin=TestPluginA libtestpluginB_la_CXXFLAGS = \ -DLIBRARY_NAME=\"TestPluginB\" \ -DTestPlugin=TestPluginB libtestpluginA_la_SOURCES = \ TestPlugin.cpp libtestpluginB_la_SOURCES = $(libtestpluginA_la_SOURCES) all: all-am .SUFFIXES: .SUFFIXES: .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(top_srcdir)/config/sipXcommon.am.inc $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu sipXportLib/src/test/testplugin/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu sipXportLib/src/test/testplugin/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/config/sipXcommon.am.inc: $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; for p in $$list; do \ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ test "$$dir" != "$$p" || dir=.; \ echo "rm -f \"$${dir}/so_locations\""; \ rm -f "$${dir}/so_locations"; \ done libtestpluginA.la: $(libtestpluginA_la_OBJECTS) $(libtestpluginA_la_DEPENDENCIES) $(EXTRA_libtestpluginA_la_DEPENDENCIES) $(libtestpluginA_la_LINK) $(libtestpluginA_la_OBJECTS) $(libtestpluginA_la_LIBADD) $(LIBS) libtestpluginB.la: $(libtestpluginB_la_OBJECTS) $(libtestpluginB_la_DEPENDENCIES) $(EXTRA_libtestpluginB_la_DEPENDENCIES) $(libtestpluginB_la_LINK) $(libtestpluginB_la_OBJECTS) $(libtestpluginB_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libtestpluginA_la-TestPlugin.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libtestpluginB_la-TestPlugin.Plo@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< libtestpluginA_la-TestPlugin.lo: TestPlugin.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestpluginA_la_CXXFLAGS) $(CXXFLAGS) -MT libtestpluginA_la-TestPlugin.lo -MD -MP -MF $(DEPDIR)/libtestpluginA_la-TestPlugin.Tpo -c -o libtestpluginA_la-TestPlugin.lo `test -f 'TestPlugin.cpp' || echo '$(srcdir)/'`TestPlugin.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libtestpluginA_la-TestPlugin.Tpo $(DEPDIR)/libtestpluginA_la-TestPlugin.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='TestPlugin.cpp' object='libtestpluginA_la-TestPlugin.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestpluginA_la_CXXFLAGS) $(CXXFLAGS) -c -o libtestpluginA_la-TestPlugin.lo `test -f 'TestPlugin.cpp' || echo '$(srcdir)/'`TestPlugin.cpp libtestpluginB_la-TestPlugin.lo: TestPlugin.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestpluginB_la_CXXFLAGS) $(CXXFLAGS) -MT libtestpluginB_la-TestPlugin.lo -MD -MP -MF $(DEPDIR)/libtestpluginB_la-TestPlugin.Tpo -c -o libtestpluginB_la-TestPlugin.lo `test -f 'TestPlugin.cpp' || echo '$(srcdir)/'`TestPlugin.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libtestpluginB_la-TestPlugin.Tpo $(DEPDIR)/libtestpluginB_la-TestPlugin.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='TestPlugin.cpp' object='libtestpluginB_la-TestPlugin.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libtestpluginB_la_CXXFLAGS) $(CXXFLAGS) -c -o libtestpluginB_la-TestPlugin.lo `test -f 'TestPlugin.cpp' || echo '$(srcdir)/'`TestPlugin.cpp mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ clean-libtool clean-noinstLTLIBRARIES ctags distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: sipxtapi-3.3.0~test17/sipXportLib/src/test/testplugin/TestPlugin.cpp0000644000175000017500000000454012205613256026430 0ustar00danieldaniel00000000000000// // Copyright (C) 2005 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlString.h" #include "os/OsConfigDb.h" #include "TestPlugin.h" // DEFINES //#define TEST_DEBUG // if defined, adds logging // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * A test hook for use with PluginTest * * This is compiled twice by the Makefile to produce two different shared libraries. * The only differences between those compilations are the command line definitions: * - For TestPluginA: * @code * -DLIBRARY_NAME=\"TestPluginA\" -DTestPlugin=TestPluginA * @endcode * - For TestPluginB: * @code * -DLIBRARY_NAME=\"TestPluginB\" -DTestPlugin=TestPluginB * @endcode * This makes the classes have unique names, so they are invoked correctly when constructed. */ const char* TestPlugin::LibraryName = LIBRARY_NAME; const char* TestPlugin::FactoryName = "getTestPlugin"; /// Read (or re-read) whatever configuration the hook requires. void TestPlugin::readConfig( OsConfigDb& configDb ) { UtlString key; UtlString value; if (mConfigured) { mConfiguration.destroyAll(); } UtlString place; for (; configDb.getNext(place, key, value) == OS_SUCCESS; place = key) { mConfiguration.insertKeyAndValue(new UtlString(key), new UtlString(value)); } mConfigured = true; } /// Return the integer value for a given configuration key bool TestPlugin::getConfiguredValueFor(const UtlString& key, UtlString& value) const { assert(mConfigured); UtlString* found = static_cast(mConfiguration.findValue(&key)); if (found) { value = *found; } return found != NULL; } /// Set to the unique library name void TestPlugin::pluginName(UtlString& name) const { assert(mConfigured); name.remove(0); name.append(LibraryName); name.append("::"); name.append(mInstanceName); } /// The constructor is called from getTestPlugin below TestPlugin::TestPlugin(const UtlString& name) : Plugin(name), mConfigured(false) { } TestPlugin::~TestPlugin() { mConfiguration.destroyAll(); } extern "C" TestPlugin* getTestPlugin(const UtlString& name) { return new TestPlugin(name); } sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxunit/0000755000175000017500000000000012321445024023303 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxunit/TestUtilities.h0000644000175000017500000001346312205613256026303 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2010 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2010 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _TestUtilities_h_ #define _TestUtilities_h_ #if defined(NO_CPPUNIT) #include typedef UtlString string; #else #include #include #include using namespace std ; // MACROS #define MAX_BUG_MESSAGE_LEN 1024 /** * Assert 2 character strings match character for character, NULLs ok */ #define ASSERT_STR_EQUAL(expected, actual) \ ( TestUtilities::assertEquals((expected), (actual), \ CPPUNIT_SOURCELINE(), "")) /** * Assert 2 character strings match character for character, NULLs ok * and include message to report if they aren't */ #define ASSERT_STR_EQUAL_MESSAGE(message, expected, actual) \ ( TestUtilities::assertEquals((expected), (actual), \ CPPUNIT_SOURCELINE(), (message))) /** * Call this just before a crash is known to happen. Obvisouly * you've attempted to fix the bug, but this is for bugs you cannot * fix for a very good reason, in which case you log a bug in JIRA * and you enter that bug number here. BUG NUMBER MANDATORY!!! * * THIS MACRO WILL NOT RETURN, Assertion Exception will be thrown * and handled by framework. * * Example: * // see bug for more details * KNOWN_FATAL_BUG("Segmentation Fault", "XPL-34"); * CPPUNIT_ASSERT_EQUAL(3, db->getRowCount()); * */ #define KNOWN_FATAL_BUG(message, bugNo) \ ( TestUtilities::knownFatalBug((message), (bugNo), \ CPPUNIT_SOURCELINE())) /** * Call this just before an assertion is known to fail. Obvisouly * you've attempted to fix the bug, but this is for bugs you cannot * fix for a very good reason, in which case you log a bug in JIRA * and you enter that bug number here. BUG NUMBER MANDATORY!!! * * Example: * KNOWN_BUG("Will be zero until Joe can finish module", "XPL-36"); * CPPUNIT_ASSERT_EQUAL(3, db->getRowCount()); */ #define KNOWN_BUG(message, bugNo) \ ( TestUtilities::knownBug((message), (bugNo), \ CPPUNIT_SOURCELINE())) /** * Fatal bugs you only get when running Electric Fence. This will be * fatal if efence on, otherwise non-fatal bug. (Experimental) */ #define KNOWN_EFENCE_BUG(message, bugNo) \ ( TestUtilities::knownEfenceBug((message), (bugNo), \ CPPUNIT_SOURCELINE())) #endif /* NO_CPPUNIT */ // FORWARD DECLARATIONS /** * Common utility functions for unittests */ class TestUtilities { public: /** Create a message using the arguments passed. The message is created by * by appending all the arguments (which have to be of the type char*) starting * off from the 3rd argument. * * @param * For example, if this method is called as
* createMessage(4, &msg, "Composite of ", "one ", "and two ", " as strings") * this would cause the variable msg to have the following string:- * Composite of one and two as strings */ #if defined(NO_CPPUNIT) static void createMessage(int num, /**< Number of char* messages that have been passed as arguments */ UtlString* outMsg, /**< string instance into which the generated message is written. * It is the responsibility of the caller to create the string */ ... /**< variable list arguments of char* which represents the fragments * of the message */ ) ; #else static void createMessage(int num, /**< Number of char* messages that have been passed as arguments */ std::string* outMsg, /**< string instance into which the generated message is written. * It is the responsibility of the caller to create the string */ ... /**< variable list arguments of char* which represents the fragments * of the message */ ) ; /** Use macro, do not this call directly. */ static void assertEquals(const char* expected, const char* actual, CppUnit::SourceLine sourceLine, const std::string &message); /** Use macro, do not this call directly. */ static bool testingKnownBug(); /** Last known non-fatal bug messages return here, valid until next test starts */ static const char *getKnownBugMessage(); /** Called by unittest framework after exiting a test method */ static void resetKnownBugTesting(); /** * Prints quotes around strings, work when w/trailing whitespaces * important. Also will print NULL (no quotes) when sz is NULL. **/ static std::string printString(const char* sz); /** Use macro, do not this call directly. */ static void knownFatalBug(const char* message, const char* bugNo, CppUnit::SourceLine sourceLine); /** Use macro, do not this call directly. */ static void knownBug(const char* message, const char* bugNo, CppUnit::SourceLine sourceLine); /** Use macro, do not this call directly. */ static void knownEfenceBug(const char* message, const char* bugNo, CppUnit::SourceLine sourceLine); private: static std::string printBug(const char* message, const char *bugNo); static bool m_testingKnownBug; static char m_bugMessage[MAX_BUG_MESSAGE_LEN]; #endif /* NO_CPPUNIT */ }; #endif sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxunit/Makefile.am0000644000175000017500000000126412205613305025342 0ustar00danieldaniel00000000000000 INCLUDES = \ -I$(top_srcdir)/sipXportLib/src/test \ -I$(top_srcdir)/sipXportLib/include lib_LTLIBRARIES = libsipXunit.la libsipXunit_la_LDFLAGS = -static # no version info for static libs libsipXunit_la_CFLAGS = @CPPUNIT_CFLAGS@ libsipXunit_la_CPPFLAGS = @CPPUNIT_CFLAGS@ libsipXunit_la_SOURCES = \ unitmain.cpp \ TestUtilities.cpp \ TestRunner.cpp \ TestRunner.h \ TestMonitor.cpp \ TestMonitor.h \ TestOutputter.cpp \ TestOutputter.h \ TestOsSysLogListener.cpp \ TestOsSysLogListener.h \ TestTemplate.cpp libsipXunit_la_LIBADD = \ @CPPUNIT_LIBS@ sipxincludedir = $(pkgincludedir)/sipxunit sipxinclude_HEADERS = \ TestUtilities.h sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxunit/Makefile.in0000644000175000017500000007577412321445001025367 0ustar00danieldaniel00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = sipXportLib/src/test/sipxunit DIST_COMMON = $(sipxinclude_HEADERS) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/general.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/sipXlib.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(sipxincludedir)" LTLIBRARIES = $(lib_LTLIBRARIES) libsipXunit_la_DEPENDENCIES = am_libsipXunit_la_OBJECTS = libsipXunit_la-unitmain.lo \ libsipXunit_la-TestUtilities.lo libsipXunit_la-TestRunner.lo \ libsipXunit_la-TestMonitor.lo libsipXunit_la-TestOutputter.lo \ libsipXunit_la-TestOsSysLogListener.lo \ libsipXunit_la-TestTemplate.lo libsipXunit_la_OBJECTS = $(am_libsipXunit_la_OBJECTS) libsipXunit_la_LINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(libsipXunit_la_LDFLAGS) $(LDFLAGS) -o $@ DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) CXXLD = $(CXX) CXXLINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) CCLD = $(CC) LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ SOURCES = $(libsipXunit_la_SOURCES) DIST_SOURCES = $(libsipXunit_la_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac HEADERS = $(sipxinclude_HEADERS) ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMRNB_INCLUDE = @AMRNB_INCLUDE@ AMRNB_LIB_ROOT = @AMRNB_LIB_ROOT@ AMRWB_INCLUDE = @AMRWB_INCLUDE@ AMRWB_LIB_ROOT = @AMRWB_LIB_ROOT@ AMRWB_TARGET = @AMRWB_TARGET@ AMR_TARGET = @AMR_TARGET@ AMTAR = @AMTAR@ ANT = @ANT@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CARBON_LIBS = @CARBON_LIBS@ CA_LIBS = @CA_LIBS@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPUNIT_CFLAGS = @CPPUNIT_CFLAGS@ CPPUNIT_CONFIG = @CPPUNIT_CONFIG@ CPPUNIT_LIBS = @CPPUNIT_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPS_PCRE_CFLAGS = @DEPS_PCRE_CFLAGS@ DEPS_PCRE_LIBS = @DEPS_PCRE_LIBS@ DLLTOOL = @DLLTOOL@ DOT = @DOT@ DOXYGEN = @DOXYGEN@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DYNEXT = @DYNEXT@ EAGC_LDFLAGS = @EAGC_LDFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EJBE_LDFLAGS = @EJBE_LDFLAGS@ EPLC_LDFLAGS = @EPLC_LDFLAGS@ EVAD_LDFLAGS = @EVAD_LDFLAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ G722_TARGET = @G722_TARGET@ G726_TARGET = @G726_TARGET@ GIPSINC = @GIPSINC@ GIPS_CE_OBJS = @GIPS_CE_OBJS@ GIPS_CPPFLAGS = @GIPS_CPPFLAGS@ GIPS_NEQ_OBJS = @GIPS_NEQ_OBJS@ GIPS_VE_OBJS = @GIPS_VE_OBJS@ GREP = @GREP@ GSM_CFLAGS = @GSM_CFLAGS@ GSM_CXXFLAGS = @GSM_CXXFLAGS@ GSM_LDFLAGS = @GSM_LDFLAGS@ GSM_LIBS = @GSM_LIBS@ GSM_TARGET = @GSM_TARGET@ ILBC_INCLUDE = @ILBC_INCLUDE@ ILBC_LIB_ROOT = @ILBC_LIB_ROOT@ ILBC_LIB_TARGET = @ILBC_LIB_TARGET@ ILBC_TARGET = @ILBC_TARGET@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTERFACE_FLAGS = @INTERFACE_FLAGS@ JAVA = @JAVA@ JAVAC_DEBUG = @JAVAC_DEBUG@ JAVAC_OPTIMIZED = @JAVAC_OPTIMIZED@ JAVA_HOME = @JAVA_HOME@ L16_TARGET = @L16_TARGET@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NAMED_PROGRAM = @NAMED_PROGRAM@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPUS_CFLAGS = @OPUS_CFLAGS@ OPUS_LIBS = @OPUS_LIBS@ OPUS_TARGET = @OPUS_TARGET@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PCMAPCMU_TARGET = @PCMAPCMU_TARGET@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ RTL_CXXFLAGS = @RTL_CXXFLAGS@ RTL_LDFLAGS = @RTL_LDFLAGS@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SIPXMEDIA_CE_LIBS = @SIPXMEDIA_CE_LIBS@ SIPXMEDIA_VE_LIBS = @SIPXMEDIA_VE_LIBS@ SIPXMEDIA_VE_STATIC_LIBS = @SIPXMEDIA_VE_STATIC_LIBS@ SIPXPBXUSER = @SIPXPBXUSER@ SIPXPHONECONF = @SIPXPHONECONF@ SIPXPHONEDATA = @SIPXPHONEDATA@ SIPXPHONELIB = @SIPXPHONELIB@ SIPX_BACKUPDIR = @SIPX_BACKUPDIR@ SIPX_BINDIR = @SIPX_BINDIR@ SIPX_CONFDIR = @SIPX_CONFDIR@ SIPX_CONFIGPHONEDIR = @SIPX_CONFIGPHONEDIR@ SIPX_DATADIR = @SIPX_DATADIR@ SIPX_DBDIR = @SIPX_DBDIR@ SIPX_DOCDIR = @SIPX_DOCDIR@ SIPX_INCDIR = @SIPX_INCDIR@ SIPX_LIBDIR = @SIPX_LIBDIR@ SIPX_LOGDIR = @SIPX_LOGDIR@ SIPX_PARKMUSICDIR = @SIPX_PARKMUSICDIR@ SIPX_RUNDIR = @SIPX_RUNDIR@ SIPX_SCHEMADIR = @SIPX_SCHEMADIR@ SIPX_TMPDIR = @SIPX_TMPDIR@ SIPX_UNIT_TARGET = @SIPX_UNIT_TARGET@ SIPX_VXMLDATADIR = @SIPX_VXMLDATADIR@ SPANDSP_CFLAGS = @SPANDSP_CFLAGS@ SPANDSP_CXXFLAGS = @SPANDSP_CXXFLAGS@ SPANDSP_LDFLAGS = @SPANDSP_LDFLAGS@ SPANDSP_LIBS = @SPANDSP_LIBS@ SPEEXDSP_CFLAGS = @SPEEXDSP_CFLAGS@ SPEEXDSP_LIBS = @SPEEXDSP_LIBS@ SPEEXDSP_STATIC_LIB = @SPEEXDSP_STATIC_LIB@ SPEEX_CFLAGS = @SPEEX_CFLAGS@ SPEEX_LIBS = @SPEEX_LIBS@ SPEEX_ROOT = @SPEEX_ROOT@ SPEEX_STATIC_LIB = @SPEEX_STATIC_LIB@ SPEEX_TARGET = @SPEEX_TARGET@ SS_LDFLAGS = @SS_LDFLAGS@ STATIC_CODEC_LIBS = @STATIC_CODEC_LIBS@ STRIP = @STRIP@ TONES_TARGET = @TONES_TARGET@ VERSION = @VERSION@ VIDEO_DEFINE = @VIDEO_DEFINE@ WXWIDGETS_CFLAGS = @WXWIDGETS_CFLAGS@ WXWIDGETS_CONFIG = @WXWIDGETS_CONFIG@ WXWIDGETS_CXXFLAGS = @WXWIDGETS_CXXFLAGS@ WXWIDGETS_LIBS = @WXWIDGETS_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ codeclibdir = @codeclibdir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ enable_dot = @enable_dot@ enable_html_docs = @enable_html_docs@ enable_latex_docs = @enable_latex_docs@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ jar = @jar@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ sipx_abs_srcdir = @sipx_abs_srcdir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ wwwdir = @wwwdir@ INCLUDES = \ -I$(top_srcdir)/sipXportLib/src/test \ -I$(top_srcdir)/sipXportLib/include lib_LTLIBRARIES = libsipXunit.la libsipXunit_la_LDFLAGS = -static # no version info for static libs libsipXunit_la_CFLAGS = @CPPUNIT_CFLAGS@ libsipXunit_la_CPPFLAGS = @CPPUNIT_CFLAGS@ libsipXunit_la_SOURCES = \ unitmain.cpp \ TestUtilities.cpp \ TestRunner.cpp \ TestRunner.h \ TestMonitor.cpp \ TestMonitor.h \ TestOutputter.cpp \ TestOutputter.h \ TestOsSysLogListener.cpp \ TestOsSysLogListener.h \ TestTemplate.cpp libsipXunit_la_LIBADD = \ @CPPUNIT_LIBS@ sipxincludedir = $(pkgincludedir)/sipxunit sipxinclude_HEADERS = \ TestUtilities.h all: all-am .SUFFIXES: .SUFFIXES: .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu sipXportLib/src/test/sipxunit/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu sipXportLib/src/test/sipxunit/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ test "$$dir" != "$$p" || dir=.; \ echo "rm -f \"$${dir}/so_locations\""; \ rm -f "$${dir}/so_locations"; \ done libsipXunit.la: $(libsipXunit_la_OBJECTS) $(libsipXunit_la_DEPENDENCIES) $(EXTRA_libsipXunit_la_DEPENDENCIES) $(libsipXunit_la_LINK) -rpath $(libdir) $(libsipXunit_la_OBJECTS) $(libsipXunit_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXunit_la-TestMonitor.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXunit_la-TestOsSysLogListener.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXunit_la-TestOutputter.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXunit_la-TestRunner.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXunit_la-TestTemplate.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXunit_la-TestUtilities.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXunit_la-unitmain.Plo@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< libsipXunit_la-unitmain.lo: unitmain.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libsipXunit_la-unitmain.lo -MD -MP -MF $(DEPDIR)/libsipXunit_la-unitmain.Tpo -c -o libsipXunit_la-unitmain.lo `test -f 'unitmain.cpp' || echo '$(srcdir)/'`unitmain.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXunit_la-unitmain.Tpo $(DEPDIR)/libsipXunit_la-unitmain.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='unitmain.cpp' object='libsipXunit_la-unitmain.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libsipXunit_la-unitmain.lo `test -f 'unitmain.cpp' || echo '$(srcdir)/'`unitmain.cpp libsipXunit_la-TestUtilities.lo: TestUtilities.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libsipXunit_la-TestUtilities.lo -MD -MP -MF $(DEPDIR)/libsipXunit_la-TestUtilities.Tpo -c -o libsipXunit_la-TestUtilities.lo `test -f 'TestUtilities.cpp' || echo '$(srcdir)/'`TestUtilities.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXunit_la-TestUtilities.Tpo $(DEPDIR)/libsipXunit_la-TestUtilities.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='TestUtilities.cpp' object='libsipXunit_la-TestUtilities.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libsipXunit_la-TestUtilities.lo `test -f 'TestUtilities.cpp' || echo '$(srcdir)/'`TestUtilities.cpp libsipXunit_la-TestRunner.lo: TestRunner.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libsipXunit_la-TestRunner.lo -MD -MP -MF $(DEPDIR)/libsipXunit_la-TestRunner.Tpo -c -o libsipXunit_la-TestRunner.lo `test -f 'TestRunner.cpp' || echo '$(srcdir)/'`TestRunner.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXunit_la-TestRunner.Tpo $(DEPDIR)/libsipXunit_la-TestRunner.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='TestRunner.cpp' object='libsipXunit_la-TestRunner.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libsipXunit_la-TestRunner.lo `test -f 'TestRunner.cpp' || echo '$(srcdir)/'`TestRunner.cpp libsipXunit_la-TestMonitor.lo: TestMonitor.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libsipXunit_la-TestMonitor.lo -MD -MP -MF $(DEPDIR)/libsipXunit_la-TestMonitor.Tpo -c -o libsipXunit_la-TestMonitor.lo `test -f 'TestMonitor.cpp' || echo '$(srcdir)/'`TestMonitor.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXunit_la-TestMonitor.Tpo $(DEPDIR)/libsipXunit_la-TestMonitor.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='TestMonitor.cpp' object='libsipXunit_la-TestMonitor.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libsipXunit_la-TestMonitor.lo `test -f 'TestMonitor.cpp' || echo '$(srcdir)/'`TestMonitor.cpp libsipXunit_la-TestOutputter.lo: TestOutputter.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libsipXunit_la-TestOutputter.lo -MD -MP -MF $(DEPDIR)/libsipXunit_la-TestOutputter.Tpo -c -o libsipXunit_la-TestOutputter.lo `test -f 'TestOutputter.cpp' || echo '$(srcdir)/'`TestOutputter.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXunit_la-TestOutputter.Tpo $(DEPDIR)/libsipXunit_la-TestOutputter.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='TestOutputter.cpp' object='libsipXunit_la-TestOutputter.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libsipXunit_la-TestOutputter.lo `test -f 'TestOutputter.cpp' || echo '$(srcdir)/'`TestOutputter.cpp libsipXunit_la-TestOsSysLogListener.lo: TestOsSysLogListener.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libsipXunit_la-TestOsSysLogListener.lo -MD -MP -MF $(DEPDIR)/libsipXunit_la-TestOsSysLogListener.Tpo -c -o libsipXunit_la-TestOsSysLogListener.lo `test -f 'TestOsSysLogListener.cpp' || echo '$(srcdir)/'`TestOsSysLogListener.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXunit_la-TestOsSysLogListener.Tpo $(DEPDIR)/libsipXunit_la-TestOsSysLogListener.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='TestOsSysLogListener.cpp' object='libsipXunit_la-TestOsSysLogListener.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libsipXunit_la-TestOsSysLogListener.lo `test -f 'TestOsSysLogListener.cpp' || echo '$(srcdir)/'`TestOsSysLogListener.cpp libsipXunit_la-TestTemplate.lo: TestTemplate.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libsipXunit_la-TestTemplate.lo -MD -MP -MF $(DEPDIR)/libsipXunit_la-TestTemplate.Tpo -c -o libsipXunit_la-TestTemplate.lo `test -f 'TestTemplate.cpp' || echo '$(srcdir)/'`TestTemplate.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXunit_la-TestTemplate.Tpo $(DEPDIR)/libsipXunit_la-TestTemplate.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='TestTemplate.cpp' object='libsipXunit_la-TestTemplate.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libsipXunit_la-TestTemplate.lo `test -f 'TestTemplate.cpp' || echo '$(srcdir)/'`TestTemplate.cpp mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-sipxincludeHEADERS: $(sipxinclude_HEADERS) @$(NORMAL_INSTALL) @list='$(sipxinclude_HEADERS)'; test -n "$(sipxincludedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(sipxincludedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(sipxincludedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(sipxincludedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(sipxincludedir)" || exit $$?; \ done uninstall-sipxincludeHEADERS: @$(NORMAL_UNINSTALL) @list='$(sipxinclude_HEADERS)'; test -n "$(sipxincludedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(sipxincludedir)'; $(am__uninstall_files_from_dir) ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) $(HEADERS) installdirs: for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(sipxincludedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-sipxincludeHEADERS install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-libLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-libLTLIBRARIES uninstall-sipxincludeHEADERS .MAKE: install-am install-strip .PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ clean-libLTLIBRARIES clean-libtool ctags distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am \ install-libLTLIBRARIES install-man install-pdf install-pdf-am \ install-ps install-ps-am install-sipxincludeHEADERS \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags uninstall uninstall-am \ uninstall-libLTLIBRARIES uninstall-sipxincludeHEADERS # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxunit/unitmain.cpp0000644000175000017500000000474612205613256025653 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include "os/OsIntTypes.h" #include #include #if defined(_VXWORKS) #include #endif // // External API into Device code #if defined(_VXWORKS) #ifdef __cplusplus extern "C" { #endif int cpptest_main( void ); int cpptestvx( void ); #ifdef __cplusplus } #endif #endif /** * include this in your project and it will find all Suite's that have been * registered with the CppUnit TextFactoryRegistry and run them */ #if defined(_VXWORKS) // // spawning task to use LARGE stack size, 20K was not enough!!! // int cpptestvx( void ) { int gCppTestTaskID = taskSpawn( "UnitTest", 100, 0, (512*1024), (FUNCPTR)cpptest_main, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); assert(gCppTestTaskID != ERROR); return gCppTestTaskID; } #endif #if defined(_VXWORKS) int cpptest_main( void ) #else #if defined(WINCE) int main( int argc, char* argv[] ); #if defined(WINCE6) int wmain(int argc, wchar_t* argv[]) { printf( "entering wmain( )\n" ); int iRet = 1; iRet = main( 0, NULL ); printf( " main( ) returned %d\n", iRet ); return iRet; } #endif // wWinMain is not defined in winbase.h. //extern "C" int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd); //**************************************************************** int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd ) { printf( "entering WinMain( ) - lpCmdLine is *%s*\n", lpCmdLine ); wchar_t *pW = NULL; int iRet = 1; iRet = main( 0, NULL ); printf( " main( ) returned %d\n", iRet ); return iRet; } #endif int main( int argc, char* argv[] ) #endif { TestRunner runner; CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry(); runner.addTest(registry.makeTest()); bool wasSucessful = runner.run(); #if defined(_VXWORKS) // check the stack size using vxworks built-in function // ti( taskIdSelf() ); taskDelay(100); // check all stack sizes checkStack(0); #endif return !wasSucessful; } void forceUnitTest( ) { } sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxunit/TestUtilities.cpp0000644000175000017500000001007312205613256026630 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2010 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2010 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #if !defined(NO_CPPUNIT) #include #include #include #include #include #include #include #include #include // Application Includes #include #include // Static initializers bool TestUtilities::m_testingKnownBug = false; char TestUtilities::m_bugMessage[MAX_BUG_MESSAGE_LEN]; #else #include #include #include #include #endif #if defined(NO_CPPUNIT) /* ========================= UTILITY METHODS ================================= */ void TestUtilities::createMessage(int count, UtlString* createdMessage, ...) { createdMessage -> remove(0) ; va_list arguments ; va_start(arguments, createdMessage) ; for(int i = 0 ; i < count ; i++) { const char* strTemp = va_arg(arguments, const char*) ; createdMessage -> append(strTemp) ; } } #else /* CPPUNIT */ /* ========================= UTILITY METHODS ================================= */ void TestUtilities::createMessage(int count, std::string* createdMessage, ...) { createdMessage -> erase() ; va_list arguments ; va_start(arguments, createdMessage) ; for(int i = 0 ; i < count ; i++) { const char* strTemp = va_arg(arguments, const char*) ; createdMessage -> append(strTemp) ; } } std::string TestUtilities::printString(const char* sz) { std::string str; if (sz == NULL) { str.append("NULL"); } else { str.append("\"").append(sz).append("\""); } return std::string(str); } void TestUtilities::assertEquals(const char* expected, const char* actual, CppUnit::SourceLine sourceLine, const std::string &message) { if (strcmp(expected, actual) != 0) { CppUnit::Asserter::failNotEqual(printString(expected), printString(actual), sourceLine, message); } } void TestUtilities::knownBug(const char* message, const char* bugNo, CppUnit::SourceLine sourceLine) { m_testingKnownBug = true; CppUnit::Message msg(printBug(message, bugNo)); CppUnit::Exception err(msg, sourceLine); strncpy(m_bugMessage, err.what(), MAX_BUG_MESSAGE_LEN); // return after and allow non-fatal error to occur } void TestUtilities::knownFatalBug(const char* message, const char* bugNo, CppUnit::SourceLine sourceLine) { m_testingKnownBug = true; std::string bugMsg = printBug(message, bugNo); // throw an assertion so as so avoid fatal code that would normally // follow this call CppUnit::Asserter::fail(bugMsg, sourceLine); } void TestUtilities::knownEfenceBug(const char* message, const char* bugNo, CppUnit::SourceLine sourceLine) { // Electric fence causes segfaults at location of error so all tests die // so effectively efence on will avoid error. #ifdef HAVE_EFENCE knownFatalBug(message, bugNo, sourceLine); #endif } std::string TestUtilities::printBug(const char* message, const char *bugNo) { std::string bugMsg("BUG "); bugMsg += bugNo; bugMsg += ": "; bugMsg += message; return bugMsg; } const char *TestUtilities::getKnownBugMessage() { return (const char*)m_bugMessage; } bool TestUtilities::testingKnownBug() { return m_testingKnownBug; } void TestUtilities::resetKnownBugTesting() { m_testingKnownBug = false; m_bugMessage[0] = 0; } #endif /* !NO_CPPUNIT */ sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxunit/TestRunner.cpp0000644000175000017500000000255412205613256026133 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // The cppunit/TestRunner.h file has to be included twice // once before cppunit/TestResult.h for cppunit 1.11 #include "os/OsIntTypes.h" #include #include // once after cppunit/TestResult.h for cppunit 1.10 #include #include #include #include TestRunner::TestRunner() : CppUnit::TestRunner() { m_monitor = new TestMonitor(); m_outputter = new TestOutputter(m_monitor); m_result = new CppUnit::TestResult(); m_logger = new TestOsSysLogListener(); m_result->addListener(m_monitor); // To disable the use of OsSysLog during unit tests, comment out the following line m_result->addListener(m_logger); } TestRunner::~TestRunner() { delete m_result; delete m_outputter; delete m_monitor; delete m_logger; } bool TestRunner::run() { CppUnit::TestRunner *pthis = this; pthis->run(*m_result); m_outputter->write(); return m_monitor->wasSuccessful(); } sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxunit/TestRunner.h0000644000175000017500000000154712205613256025601 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _TestRunner_h_ #define _TestRunner_h_ #include #include #include class CppUnit::TestResult; class TestMonitor; /** * Instantiates nec. objects for running a test suite for main method */ class TestRunner : public CppUnit::TestRunner { public: TestRunner(); virtual ~TestRunner(); bool run(); private: TestMonitor *m_monitor; TestOsSysLogListener *m_logger; CppUnit::TestResult *m_result; TestOutputter *m_outputter; }; #endif sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxunit/TestMonitor.cpp0000644000175000017500000000316212205613256026305 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include #include #include #include TestMonitor::TestMonitor() : CppUnit::TestResultCollector() { m_wasSuccessful = true; m_verbose = true; } TestMonitor::~TestMonitor() { } void TestMonitor::startTest(CppUnit::Test *test) { // set static context, assumes tests run in serial TestUtilities::resetKnownBugTesting(); if (m_verbose) { std::cout << "[TEST]:" << test->getName() << std::endl; } TestResultCollector::startTest(test); } void TestMonitor::addFailure(const CppUnit::TestFailure &failure) { // query static context, assumes tests run in serial if (!TestUtilities::testingKnownBug()) { m_wasSuccessful = false; } // Add bug details to final message if (strlen(TestUtilities::getKnownBugMessage()) != 0) { CppUnit::Message msg = failure.thrownException()->message(); msg.addDetail(TestUtilities::getKnownBugMessage()); failure.thrownException()->setMessage(msg); } TestResultCollector::addFailure(failure); } bool TestMonitor::wasSuccessful() const { return m_wasSuccessful; } sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxunit/TestMonitor.h0000644000175000017500000000212012205613256025743 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _TestMonitor_h_ #define _TestMonitor_h_ #include class CppUnit::Test; class CppUnit::TestFailure; /** * Monitors each test and prints, accumulated test results and various * other operations between individual test runs */ class TestMonitor : public CppUnit::TestResultCollector { public: TestMonitor(); virtual ~TestMonitor(); /** Overridden */ virtual void startTest(CppUnit::Test *test); /** Overridden */ virtual void addFailure(const CppUnit::TestFailure &failure); /** Overriden */ virtual bool wasSuccessful() const; /** * Sends waring message to the error stream */ static void warning(const char *message); private: bool m_verbose; bool m_wasSuccessful; }; #endif sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxunit/TestOutputter.cpp0000644000175000017500000000162712205613256026675 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include TestOutputter::TestOutputter(CppUnit::TestResultCollector *collector) : CppUnit::TextOutputter(collector, std::cout) { // Default implementation doesn't send ALL failure out // to stderr so use this delegate for failure outputting m_err = new CppUnit::TextOutputter(collector, std::cerr); } TestOutputter::~TestOutputter() { delete m_err; } void TestOutputter::printFailures() { m_err->printFailures(); } void TestOutputter::printFailureWarning() { m_err->printFailureWarning(); } sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxunit/TestOutputter.h0000644000175000017500000000151612205613256026337 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _TestOutputter_h_ #define _TestOutputter_h_ #include #include #include class CppUnit::TestResultCollector; /** * Handle actually printing to stdout, stderr and report file */ class TestOutputter : public CppUnit::TextOutputter { public: TestOutputter(CppUnit::TestResultCollector *collector); virtual ~TestOutputter(); protected: void printFailures(); void printFailureWarning(); private: CppUnit::TextOutputter *m_err; }; #endif sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxunit/TestOsSysLogListener.cpp0000644000175000017500000000372212205613256030110 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPfoundry Inc. // License by SIPfoundry under the LGPL license. // // Copyright (C) 2007 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPez, LLC. // Licensed to SIPfoundry under a Contributor Agreement. // ////////////////////////////////////////////////////////////////////////////// #include "os/OsIntTypes.h" #include #ifdef __pingtel_on_posix__ # include #endif #include "TestOsSysLogListener.h" #include #include "os/OsSysLog.h" #include "os/OsFileSystem.h" /// constructor TestOsSysLogListener::TestOsSysLogListener() { }; UtlString TestOsSysLogListener::getLogFilename(const UtlString& testName) { UtlString tn(testName); tn.replace(':','_').append(".log"); return tn; } void TestOsSysLogListener::startTest(CPPUNIT_NS::Test* test) { UtlString testLogFile = getLogFilename(test->getName().c_str()); OsSysLog::initialize(0,"UnitTest"); OsSysLog::setLoggingPriority(PRI_DEBUG); OsFileSystem::remove(testLogFile, FALSE, TRUE); OsSysLog::setOutputFile(0,testLogFile); } void TestOsSysLogListener::endTest(CPPUNIT_NS::Test* test) { // Flush and shutdown logging, so the log file is closed and able to be removed. OsSysLog::flush(); OsSysLog::shutdown(); // Remove the log file if it is an empty one. UtlString testLogFile = getLogFilename(test->getName().c_str()); OsPath testLogFilePath(testLogFile); OsFileInfo tLogFInfo; OsStatus stat = OsFileSystem::getFileInfo(testLogFilePath, tLogFInfo); if (stat == OS_SUCCESS) { unsigned long logSz = 0; stat = tLogFInfo.getSize(logSz); if (stat == OS_SUCCESS && (logSz == 0)) { stat = OsFileSystem::remove(testLogFile, FALSE, TRUE); if (stat != OS_SUCCESS) { printf("Failed to remove file %s\n", testLogFile.data()); } } } } /// destructor TestOsSysLogListener::~TestOsSysLogListener() { }; sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxunit/TestOsSysLogListener.h0000644000175000017500000000245412205613256027556 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPfoundry Inc. // License by SIPfoundry under the LGPL license. // // Copyright (C) 2007 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // ////////////////////////////////////////////////////////////////////////////// #ifndef _TESTOSSYSLOGLISTENER_H_ #define _TESTOSSYSLOGLISTENER_H_ // SYSTEM INCLUDES #include #include #include // APPLICATION INCLUDES // DEFINES // CONSTANTS // TYPEDEFS // FORWARD DECLARATIONS class Test; /// One line description /** * Long description */ class TestOsSysLogListener : public CPPUNIT_NS::TestListener { public: /*! Constructs a TextTestProgressListener object. */ TestOsSysLogListener(); /// Destructor. virtual ~TestOsSysLogListener(); static UtlString getLogFilename(const UtlString& testName); virtual void startTest( CPPUNIT_NS::Test *test ); virtual void endTest( CPPUNIT_NS::Test *test ); private: // @cond INCLUDENOCOPY /// There is no copy constructor. TestOsSysLogListener(const TestOsSysLogListener& nocopyconstructor); /// There is no assignment operator. TestOsSysLogListener& operator=(const TestOsSysLogListener& noassignmentoperator); // @endcond }; #endif // _TESTOSSYSLOGLISTENER_H_ sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxunit/TestTemplate.cpp0000644000175000017500000000161712205613256026434 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include class TestTemplate : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(TestTemplate); CPPUNIT_TEST(testMethod); CPPUNIT_TEST_SUITE_END(); public: void testMethod() { // a few of the more handy assertions CPPUNIT_ASSERT(true || false); CPPUNIT_ASSERT_EQUAL(1, 3 - 2); CPPUNIT_ASSERT_MESSAGE("description", true || false); CPPUNIT_ASSERT_EQUAL_MESSAGE("description", 1, 3 - 2); //CPPUNIT_FAIL("failed"); } }; CPPUNIT_TEST_SUITE_REGISTRATION(TestTemplate); sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxportunit/0000755000175000017500000000000012321445024024210 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxportunit/com_sipez_unit_UnitTestActivity.h0000644000175000017500000000113612205613256032772 0ustar00danieldaniel00000000000000/* DO NOT EDIT THIS FILE - it is machine generated */ #include /* Header for class com_sipez_unit_UnitTestActivity */ #ifndef _Included_com_sipez_unit_UnitTestActivity #define _Included_com_sipez_unit_UnitTestActivity #ifdef __cplusplus extern "C" { #endif #undef com_sipez_unit_UnitTestActivity_MESSAGE_LOG_TEXT #define com_sipez_unit_UnitTestActivity_MESSAGE_LOG_TEXT 1001L /* * Class: com_sipez_unit_UnitTestActivity * Method: runTests * Signature: ()I */ JNIEXPORT jint JNICALL Java_com_sipez_unit_UnitTestActivity_runTests (JNIEnv *, jclass); #ifdef __cplusplus } #endif #endif sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxportunit/SipxPortUnitTestAsserts.h0000644000175000017500000001275212205613256031232 0ustar00danieldaniel00000000000000// // // Copyright (C) 2010 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ // Author: Daniel Petrie // dpetrie AT SIPez DOT com ////////////////////////////////////////////////////////////////////////////// #ifndef _SipxPortUnitTestAsserts_h_ #define _SipxPortUnitTestAsserts_h_ // SYSTEM INCLUDES #include // APPLICATION INCLUDES // DEFINES // MACROS // As some point these ASSERT macros should all be more specific so they // provide more information on the test operands. However for now until // things are refined, they are all based upon the general // CPPUNIT_ASSERT_MESSAGE macro #define KNOWN_BUG(BUG_MSG, BUG_NUMBER) \ CPPUNIT_ASSERT_MESSAGE("KNOWN_BUG: " BUG_MSG " " BUG_NUMBER, 0) #define KNOWN_EFENCE_BUG(EFENCE_MSG, BUG_NUM) \ CPPUNIT_ASSERT_MESSAGE("EFENCE_BUG: " EFENCE_MSG " " BUG_NUM, 0) #define ASSERT_STR_EQUAL(STRING1, STRING2) \ ASSERT_STR_EQUAL_MESSAGE("", STRING1, STRING2) #define ASSERT_STR_EQUAL_MESSAGE(STR_NOT_EQ_MSG, STR1, STR2) \ CPPUNIT_ASSERT_EQUAL_MESSAGE(STR_NOT_EQ_MSG, STR1, STR2) #define CPPUNIT_ASSERT_EQUAL(EQUAL_ARG1, EQUAL_ARG2) \ CPPUNIT_ASSERT_EQUAL_MESSAGE("", EQUAL_ARG1, EQUAL_ARG2) #define CPPUNIT_ASSERT_EQUAL_MESSAGE(NOT_EQ_MSG, EQ_ARG1, EQ_ARG2) \ { \ SipxPortUnitTestClass* currentTestClass = 0; \ if((currentTestClass = SipxPortUnitTestEnvironment::getCurrentTestClass())) \ { \ currentTestClass->incrementTestPointIndex(); \ currentTestClass->setTestPointLine(__LINE__); \ currentTestClass->setTestPointFilename(__FILE__); \ if(SipxPortUnitTestEnvironment::areEqual(EQ_ARG1,EQ_ARG2)) \ { \ currentTestClass->incrementTestPointsPassed(); \ } \ else \ { \ currentTestClass->incrementTestPointsFailed(); \ char _sipxportunit_message[SIPX_PORT_UNIT_MAX_ERROR_MESSAGE_SIZE]; \ const char* className = currentTestClass->getClassName(); \ const char* methodName = currentTestClass->getCurrentMethodName(); /* spMethodNames[getCurrentMethodIndex()]; */ \ int testPoint = currentTestClass->getTestPointIndex(); \ SipxPortUnitTestEnvironment::makeAssertNotEqualMessage(_sipxportunit_message, ((char*)NOT_EQ_MSG), #EQ_ARG1, #EQ_ARG2, \ __FILE__, className, methodName, testPoint, __LINE__, EQ_ARG1, EQ_ARG2); \ SipxPortUnitTestEnvironment::printOut(_sipxportunit_message); \ currentTestClass->addFailedTestPoint(__FILE__, \ className, \ methodName, \ testPoint, \ __LINE__, \ _sipxportunit_message); \ } \ } \ assert(currentTestClass); \ } #define CPPUNIT_ASSERT(ASSERT_VAL) \ CPPUNIT_ASSERT_MESSAGE("", ASSERT_VAL) #define CPPUNIT_FAIL(FAIL_MSG) \ CPPUNIT_ASSERT_MESSAGE(FAIL_MSG, 0) #define CPPUNIT_ASSERT_MESSAGE(ERROR_MESSAGE, TRUE_VALUE) \ { \ SipxPortUnitTestClass* currentTestClass = 0; \ if((currentTestClass = SipxPortUnitTestEnvironment::getCurrentTestClass())) \ { \ currentTestClass->incrementTestPointIndex(); \ currentTestClass->setTestPointLine(__LINE__); \ currentTestClass->setTestPointFilename(__FILE__); \ if(TRUE_VALUE) \ { \ currentTestClass->incrementTestPointsPassed(); \ } \ else \ { \ currentTestClass->incrementTestPointsFailed(); \ char _sipxportunit_message[SIPX_PORT_UNIT_MAX_ERROR_MESSAGE_SIZE]; \ const char* className = currentTestClass->getClassName(); \ const char* methodName = currentTestClass->getCurrentMethodName(); /* spMethodNames[getCurrentMethodIndex()]; */ \ int testPoint = currentTestClass->getTestPointIndex(); \ snprintf(_sipxportunit_message, SIPX_PORT_UNIT_MAX_ERROR_MESSAGE_SIZE - 1, \ "%s, \"%s\" is not true, file: %s %s::%s test point: %d line: %d\n", \ ((char*)ERROR_MESSAGE), #TRUE_VALUE, \ __FILE__, className, methodName, testPoint, __LINE__); \ SipxPortUnitTestEnvironment::printOut(_sipxportunit_message); \ currentTestClass->addFailedTestPoint(__FILE__, \ className, \ methodName, \ testPoint, \ __LINE__, \ _sipxportunit_message); \ } \ } \ assert(currentTestClass); \ } // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS #endif // _SipxPortUnitTestAsserts_h_ sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxportunit/SipxPortUnitTestClass.h0000644000175000017500000003252512321267455030660 0ustar00danieldaniel00000000000000// // // Copyright (C) 2010 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ // Author: Daniel Petrie // dpetrie AT SIPez DOT com ////////////////////////////////////////////////////////////////////////////// #ifndef _SipxPortUnitTestClass_h_ #define _SipxPortUnitTestClass_h_ // SYSTEM INCLUDES #include #include // APPLICATION INCLUDES #include // DEFINES // MACROS #define CPPUNIT_TEST_SUB_SUITE(CHILD_CLASS_NAME, PARENT_CLASS_NAME) \ CPPUNIT_TEST_SUITE(CHILD_CLASS_NAME) #define CPPUNIT_TEST_SUITE(CLASS_NAME) \ public: \ /* Not implemented here so actual tests can code constructor and destructors CLASS_NAME() : \ SipxPortUnitTestClass(#CLASS_NAME) \ { \ } \ \ ~ CLASS_NAME() \ { \ char buffer[256]; \ sprintf(buffer, "Entering ~%s\n", \ #CLASS_NAME); \ SipxPortUnitTestEnvironment::printOut(buffer); \ \ } */\ \ static int getMethodCount() \ { \ initializeStatics(); \ return(sMethodCount); \ } \ virtual const char* getCurrentMethodName() const\ { \ assert(spMethodNames); \ return(mCurrentMethodIndex >= 0 && \ mCurrentMethodIndex < sMethodCount ? \ spMethodNames[mCurrentMethodIndex] : \ 0); \ } \ \ virtual void incrementTestPointsPassed() \ { \ sTestPointsPassed++; \ SipxPortUnitTestEnvironment::incrementTestPointsPassed(); \ } \ \ static int getPassedTestPointCount() \ { \ return(sTestPointsPassed); \ } \ \ static int getFailedTestPointCount() \ { \ return(sTestPointsFailed); \ } \ \ virtual void incrementTestPointsFailed() \ { \ sTestPointsFailed++; \ SipxPortUnitTestEnvironment::incrementTestPointsFailed(); \ } \ \ static int getFailureCount() \ { \ return(sTestPointFailureCount); \ } \ \ static SipxPortUnitTestPointFailure* getFailure(int failureIndex) \ { \ assert(failureIndex >= 0); \ assert(failureIndex < SIPX_PORT_UNIT_MAX_TEST_ERRORS_PER_CLASS); \ return(sTestPointFailures[failureIndex]); \ } \ \ static bool addFailure(SipxPortUnitTestPointFailure* failure) \ { \ bool wasAdded = false; \ if(sTestPointFailureCount < SIPX_PORT_UNIT_MAX_TEST_ERRORS_PER_CLASS) \ { \ sTestPointFailures[sTestPointFailureCount] = failure; \ sTestPointFailureCount++; \ wasAdded = true; \ } \ else \ { \ char message[SIPX_PORT_UNIT_MAX_ERROR_MESSAGE_SIZE]; \ sprintf(message, "WARNING: maximum failures of %d excedded for class: %s, failure not added: %s\n", \ SIPX_PORT_UNIT_MAX_TEST_ERRORS_PER_CLASS, \ failure->getClassName(), failure->getMessage()); \ SipxPortUnitTestEnvironment::printOut(message); \ } \ return(wasAdded); \ } \ \ private: \ static int sInitialized; \ static int sInitializedSignature; \ static int sMethodCount; \ static char** spMethodNames; \ static SipxPortTestMethodState* spMethodStates; \ static int sTestPointsPassed; \ static int sTestPointsFailed; \ static int sTestPointFailureCount; \ static SipxPortUnitTestPointFailure* sTestPointFailures[SIPX_PORT_UNIT_MAX_TEST_ERRORS_PER_CLASS]; \ \ void runAllMethodsFrom(int startMethodIndex) \ { \ forEachTestMethod(RUN_ALL_FROM, this, startMethodIndex); \ } \ \ void addFailedTestPoint(const char* fileName, \ const char* className, \ const char* methodName, \ int testPoint, \ int lineNumber, \ const char* message) \ { \ SipxPortUnitTestPointFailure* failure = \ new SipxPortUnitTestPointFailure(fileName, \ className, \ methodName, \ testPoint, \ lineNumber, \ message); \ if(!addFailure(failure)) \ { \ /* not added. array is full, so clean up */ \ delete failure; \ failure = 0; \ } \ } \ \ static void initializeStatics() \ { \ if(!sInitialized || \ sInitializedSignature != SIPX_PORT_UNIT_TEST_SIGNATURE) \ { \ sInitialized = false; \ sMethodCount = -1; \ spMethodNames = 0; \ spMethodStates = 0; \ sTestPointsPassed = 0; \ sTestPointsFailed = 0; \ sTestPointFailureCount = 0; \ for(int failureIndex = 0; failureIndex < SIPX_PORT_UNIT_MAX_TEST_ERRORS_PER_CLASS; failureIndex++) \ { \ sTestPointFailures[failureIndex] = 0; \ } \ \ forEachTestMethod(INIT_TEST_METHOD_INFO, 0, 0); \ \ sInitialized = true; \ sInitializedSignature = SIPX_PORT_UNIT_TEST_SIGNATURE; \ } \ } \ \ static void forEachTestMethod(SipxPortTestMethodOperation operation, \ CLASS_NAME* testInstance, \ int methodIndexStart) \ { \ if(operation == INIT_TEST_METHOD_INFO && sMethodCount == -1) \ { \ forEachTestMethod(SET_METHOD_COUNT, 0, 0); \ } \ \ int methodIndex = 0; \ char buffer[SIPX_PORT_UNIT_MAX_ERROR_MESSAGE_SIZE]; \ #define CPPUNIT_TEST(METHOD_NAME) \ switch(operation) \ { \ case SET_METHOD_COUNT: \ break; \ \ case INIT_TEST_METHOD_INFO: \ { \ assert(methodIndex >= 0 && \ methodIndex < sMethodCount); \ assert(spMethodNames[methodIndex] == 0); \ spMethodNames[methodIndex] = \ SipxPortUnitTestEnvironment::newCopyString(#METHOD_NAME) ; \ } \ break; \ \ case RUN_ALL_FROM: \ assert(testInstance); \ if(methodIndex >= methodIndexStart) \ { \ testInstance->setCurrentMethodIndex(methodIndex); \ testInstance->resetTestPointIndex(); \ spMethodStates[methodIndex] = RUNNING; \ snprintf(buffer, SIPX_PORT_UNIT_MAX_ERROR_MESSAGE_SIZE - 1, \ "[TEST]: %s::%s\n", testInstance->getClassName(), \ #METHOD_NAME); \ buffer[SIPX_PORT_UNIT_MAX_ERROR_MESSAGE_SIZE - 1] = '\0'; \ SipxPortUnitTestEnvironment::printOut(buffer); \ testInstance->setUp(); \ testInstance->METHOD_NAME(); \ testInstance->tearDown(); \ spMethodStates[methodIndex] = COMPLETED; \ } \ break; \ \ /* Invalid operation id */ \ default: \ assert(0); \ break; \ } \ methodIndex++; \ #define CPPUNIT_TEST_SUITE_END() \ if(operation == SET_METHOD_COUNT) \ { \ sMethodCount = methodIndex; \ spMethodNames = new char*[sMethodCount]; \ spMethodStates = new SipxPortTestMethodState[sMethodCount]; \ for(int mIndex = 0; mIndex < sMethodCount; mIndex++) \ { \ spMethodNames[mIndex] = 0; \ spMethodStates[mIndex] = NOT_RUN; \ } \ } \ } \ #define CPPUNIT_TEST_SUITE_REGISTRATION(CLASS_NAME) \ int CLASS_NAME::sInitialized = false; \ int CLASS_NAME::sInitializedSignature = 0; \ int CLASS_NAME::sMethodCount = -1; \ char** CLASS_NAME::spMethodNames = 0; \ SipxPortUnitTestClass::SipxPortTestMethodState* CLASS_NAME::spMethodStates = 0; \ int CLASS_NAME::sTestPointsPassed = 0; \ int CLASS_NAME::sTestPointsFailed = 0; \ int CLASS_NAME::sTestPointFailureCount = 0; /* num pointers in following array */ \ SipxPortUnitTestPointFailure* CLASS_NAME::sTestPointFailures[SIPX_PORT_UNIT_MAX_TEST_ERRORS_PER_CLASS]; \ \ class CLASS_NAME##Constructor : public SipxPortUnitTestConstructor \ { \ public: \ CLASS_NAME##Constructor() : \ SipxPortUnitTestConstructor(#CLASS_NAME) \ { \ } \ \ /* virtual ~ CLASS_NAME##Constructor() \ { \ Should never get destroyed \ assert(0); \ } */ \ \ void constructTestClass() \ { \ if(mpTestClass == 0) \ { \ mpTestClass = new CLASS_NAME(); \ mpTestClass->setClassName(#CLASS_NAME); \ } \ } \ \ int getTestMethodCount() \ { \ return(CLASS_NAME::getMethodCount()); \ } \ \ void addTestClassFailure(const char* className, \ const char* message) \ { \ SipxPortUnitTestPointFailure* failure = \ new SipxPortUnitTestPointFailure("", \ className, \ "", \ -1, \ -1, \ message); \ if(!CLASS_NAME::addFailure(failure)) \ { \ /* no room to add, clean up */ \ delete failure; \ failure = 0; \ } \ } \ \ int getPassedTestPointCount() const \ { \ return(CLASS_NAME::getPassedTestPointCount()); \ } \ \ int getFailedTestPointCount() const \ { \ return(CLASS_NAME::getFailedTestPointCount()); \ } \ \ int getFailureCount() const\ { \ return(CLASS_NAME::getFailureCount()); \ } \ \ SipxPortUnitTestPointFailure* getFailure(int failureIndex) \ { \ return(CLASS_NAME::getFailure(failureIndex)); \ } \ }; \ \ static CLASS_NAME##Constructor* instance##CLASS_NAME##Constructor = new CLASS_NAME##Constructor(); \ // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS // //! Abstract class that all unit test classes should derive from /*! * */ class SipxPortUnitTestClass { /* ============================= P U B L I C ============================== */ public: typedef enum { SET_METHOD_COUNT = 0, INIT_TEST_METHOD_INFO, RUN_ALL_FROM } SipxPortTestMethodOperation; typedef enum { NOT_RUN = 0, RUNNING, ABORTED, COMPLETED } SipxPortTestMethodState; /* ============================ C R E A T O R S =========================== */ //! Constructor SipxPortUnitTestClass(const char* testClassName = 0); //! Destructor virtual ~SipxPortUnitTestClass(); /* ======================== M A N I P U L A T O R S ======================= */ virtual void runAllMethodsFrom(int methodIndex) = 0; /// User overridable initialization to be done before each test method is invoked virtual void setUp(); /// User overridable clean up to be done after each test method is invoked virtual void tearDown(); /// Helper method to create a failure entry for the class virtual void addFailedTestPoint(const char* fileName, const char* className, const char* methodName, int testPoint, int lineNumber, const char* message) = 0; /* ========================== A C C E S S O R S =========================== */ void setClassName(const char* className); const char* getClassName(); void setCurrentMethodIndex(int methodIndex); int getCurrentMethodIndex() const; virtual const char* getCurrentMethodName() const = 0; void resetTestPointIndex(); void incrementTestPointIndex(); int getTestPointIndex() const; virtual void incrementTestPointsPassed() = 0; virtual void incrementTestPointsFailed() = 0; void setTestPointLine(int lineNumber); int getTestPointLine() const; void setTestPointFilename(const char* testFilename); const char* getTestPointFilename() const; /* ============================ I N Q U I R Y ============================= */ //__________________________________________________________________________// /* ========================== P R O T E C T E D =========================== */ protected: char* mpClassName; int mCurrentMethodIndex; int mPriorTestPointIndex; int mPriorTestPointLine; char mPriorTestPointFileName[SIPX_PORT_UNIT_MAX_TEST_FILENAME_LENGTH]; //__________________________________________________________________________// /* ============================ P R I V A T E ============================= */ private: //! Disabled copy constructor SipxPortUnitTestClass(const SipxPortUnitTestClass& rSipxPortUnitTestClass); //! Disabled assignment operator SipxPortUnitTestClass& operator=(const SipxPortUnitTestClass& rhs); }; #endif // _SipxPortUnitTestClass_h_ sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxportunit/SipxPortUnitTestConstructor.h0000644000175000017500000000702112205613256032124 0ustar00danieldaniel00000000000000// // // Copyright (C) 2010 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ // Author: Daniel Petrie // dpetrie AT SIPez DOT com ////////////////////////////////////////////////////////////////////////////// #ifndef _SipxPortUnitTestConstructor_h_ #define _SipxPortUnitTestConstructor_h_ // SYSTEM INCLUDES //#include <...> // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class SipxPortUnitTestClass; class SipxPortUnitTestPointFailure; // //! Factory/helper container for a test class /*! * */ class SipxPortUnitTestConstructor { /* ============================= P U B L I C ============================== */ public: /* ============================ C R E A T O R S =========================== */ //! Constructor SipxPortUnitTestConstructor(const char* testClassName); //! Destructor virtual ~SipxPortUnitTestConstructor(); /* ======================== M A N I P U L A T O R S ======================= */ /// Run all test metods for the class starting at the given method index void runAllMethodsFrom(int methodIndex); /**< * @param[in] methodIndex - Hense skipping methods 0 through methodIndex-1 */ /// Construct an instance of the test class virtual void constructTestClass() = 0; /// Destro the test class instance void releaseTestClass(); /// Log a failure as we caught a signal while this test class was running void addSignalCaughtFailure(int signalNumber); /// Log a general class failure virtual void addTestClassFailure(const char* className, const char* message) = 0; /* ========================== A C C E S S O R S =========================== */ /// get test class name for SipxPortUnitTestClass const char* getClassName() const; /// Returns the number of test methods for the test class virtual int getTestMethodCount() = 0; /// Return test point success count virtual int getPassedTestPointCount() const = 0; /// Return test point failure count virtual int getFailedTestPointCount() const = 0; /// Return test point failure count virtual int getFailureCount() const = 0; /// Returns a test point failure object virtual SipxPortUnitTestPointFailure* getFailure(int failureIndex) = 0; /// Get the last known line position for the running test int getTestPointLine() const; /// Get the last know file name of the source for the running test const char* getTestPointFilename() const; /* ============================ I N Q U I R Y ============================= */ //__________________________________________________________________________// /* ========================== P R O T E C T E D =========================== */ protected: char* mpClassName; SipxPortUnitTestClass* mpTestClass; //__________________________________________________________________________// /* ============================ P R I V A T E ============================= */ private: /// Diable default constructor SipxPortUnitTestConstructor(); //! Disabled copy constructor SipxPortUnitTestConstructor(const SipxPortUnitTestConstructor& rSipxPortUnitTestConstructor); //! Disabled assignment operator SipxPortUnitTestConstructor& operator=(const SipxPortUnitTestConstructor& rhs); }; #endif // _SipxPortUnitTestConstructor_h_ sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxportunit/SipxPortUnitTestEnvironment.h0000644000175000017500000001715212205613256032111 0ustar00danieldaniel00000000000000// // // Copyright (C) 2010-2012 SIPez LLC All rights reserved. // // $$ // Author: Daniel Petrie // dpetrie AT SIPez DOT com ////////////////////////////////////////////////////////////////////////////// #ifndef _SipxPortUnitTestEnvironment_h_ #define _SipxPortUnitTestEnvironment_h_ // SYSTEM INCLUDES #include // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define SIPX_PORT_UNIT_TEST_SIGNATURE 20100108 // For now we hardcode some limits #define SIPX_PORT_UNIT_MAX_TEST_CLASSES 2048 #define SIPX_PORT_UNIT_MAX_TEST_METHODS 512 #define SIPX_PORT_UNIT_MAX_TEST_ERRORS_PER_CLASS 100 #define SIPX_PORT_UNIT_MAX_ERROR_MESSAGE_SIZE 4096 #define SIPX_PORT_UNIT_MAX_TEST_FILENAME_LENGTH 1024 #define SIPX_PORT_UNIT_MAX_STACK_TRACE_SIZE 32 // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class SipxPortUnitTestConstructor; class SipxPortUnitTestClass; class UtlContainable; // //! Top level unit test class and envrionment container /*! This is the top level class that runs the unt tests, keeps track of * results and state. All unit tests to be run get registered with this * class. This unit test framework was created as CPPUNIT does not port * well to may environments, especially on embeded systems and platforms * where exceptions, RTTI, stdlib and templates are not well supported. * * * \par Concepts * * The unit tests for a suite are broken down into the the following * primatives: * -# Test Class * A test class is a C++ class that defines a set of method to * be run as part of the test suit. Typically a test class will test a * specific class or subsystem. * -# Test Method * A test method is a C++ method defined in a test class. It will * typically contain a number of test points. The test points usually * are a set of related test assertions for the test class. * -# Test Point * A test point is a single test check or assertion. It tests the * value or state of a variable or object. Test points are implemented * using a set of macros. * * \par Aborts * * The test framework attempts to catch signals from SEGV, FPE, etc. * and continue the running of the remaining tests. It also attempts * to dump the stack when signals are caught. If you do not want it * to catch signals and instead have it dump core so that you can debug * the stack, simply comment out the calls to signal in * SipxPortUnitTestEnvironment.cpp. To get function names in the * stack dump you will want to compile with the -rdynamic option. * */ typedef void (*SipxUnitStringOutputter)(const char* logMesage); class SipxPortUnitTestEnvironment { /* ============================= P U B L I C ============================== */ public: /* ============================ C R E A T O R S =========================== */ /* ======================== M A N I P U L A T O R S ======================= */ static void initializeEnvironment(); static void resetExceptionState(); static void registerTestConstructor(SipxPortUnitTestConstructor* testClassToAdd); static void runTests(); static void reportResults(); static void printOut(const char* messageText); static void defaultPrintOut(const char* messageText); static bool areEqual(long arg1, long arg2); static bool areEqual(const UtlString& arg1, const UtlString& arg2); static bool areEqual(const UtlContainable& arg1, const UtlContainable& arg2); static bool areEqual(const UtlContainable* arg1, const UtlContainable* arg2); static bool areEqual(void* arg1, void* arg2); static void makeAssertNotEqualMessage(char* messageBuffer, const char* notEqualMessage, const char* arg1String, const char* arg2String, const char* fileName, const char* className, const char* methodName, int testPoint, int lineNum, int arg1, int arg2); static void makeAssertNotEqualMessage(char* messageBuffer, const char* notEqualMessage, const char* arg1String, const char* arg2String, const char* fileName, const char* className, const char* methodName, int testPoint, int lineNum, const char* arg1, const char* arg2); static void makeAssertNotEqualMessage(char* messageBuffer, const char* notEqualMessage, const char* arg1String, const char* arg2String, const char* fileName, const char* className, const char* methodName, int testPoint, int lineNum, const UtlContainable* arg1, const UtlContainable* arg2); static void makeAssertNotEqualMessage(char* messageBuffer, const char* notEqualMessage, const char* arg1String, const char* arg2String, const char* fileName, const char* className, const char* methodName, int testPoint, int lineNum, const void* arg1, const void* arg2); /* ========================== A C C E S S O R S =========================== */ static char* newCopyString(const char* stringToCopy); static void incrementMethodsRun(); static void setMethodIndex(int methodIndex); static void resetTestPointIndex(); static void incrementTestPointIndex(); static void incrementTestPointsPassed(); static void incrementTestPointsFailed(); static int getTestPointFailureCount(); static int getTestAbortCount(); static void dumpCurrentTestState(); static SipxPortUnitTestClass* getCurrentTestClass(); static void setCurrentTestClass(SipxPortUnitTestClass* currentClass); static void setStringOutMethod(SipxUnitStringOutputter outputMethod); static void setLogHookBegin(void (*logBeginFunc)(const char* testClassName)); static void setLogHookEnd(void (*logEndFunc)(const char* testClassName)); /* ============================ I N Q U I R Y ============================= */ //__________________________________________________________________________// /* ========================== P R O T E C T E D =========================== */ protected: static void signalHandler(int signalCaught); //__________________________________________________________________________// /* ============================ P R I V A T E ============================= */ private: //! Constructor SipxPortUnitTestEnvironment(); //! Destructor virtual ~SipxPortUnitTestEnvironment(); //! Disabled copy constructor SipxPortUnitTestEnvironment(const SipxPortUnitTestEnvironment& rSipxPortUnitTestEnvironment); //! Disabled assignment operator SipxPortUnitTestEnvironment& operator=(const SipxPortUnitTestEnvironment& rhs); static bool sInitialized; static int sInitializedSignature; /// simple lock static int sInitializing; static int sCurrentTestClassIndex; static int sCurrentTestMethodIndex; static int sCurrentTestPointIndex; static SipxPortUnitTestClass* spCurrentTestClass; static int sTotalTestMethodCount; static int sTestMethodsRun; static int sTestPointsPassed; static int sTestPointsFailed; static int sTotalTestClassCount; static SipxPortUnitTestConstructor** sTestClassesToRun; // Note the term exceptions is used loosely here // really we are talking about signal events that we are // able to recover from static int sNumExceptionsCaught; static int sLastExceptionsCaught; static int sLastExceptionClassIndex; static int sNumExceptionsForSameClass; static int sLastExceptionMethodIndex; static int sLastExceptionTestPointIndex; static SipxUnitStringOutputter sStringOutputMethod; static void (*sLogHookBegin)(const char* testName); static void (*sLogHookEnd)(const char* testName); }; #endif // _SipxPortUnitTestEnvironment_h_ sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxportunit/SipxPortUnitTest.h0000644000175000017500000000155612205617431027664 0ustar00danieldaniel00000000000000// // // Copyright (C) 2010 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ // Author: Daniel Petrie // dpetrie AT SIPez DOT com ////////////////////////////////////////////////////////////////////////////// #ifndef _SipxPortUnitTest_h_ #define _SipxPortUnitTest_h_ // SYSTEM INCLUDES #include #include #include // APPLICATION INCLUDES #include #include #include #include #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS // #endif // _SipxPortUnitTest_h_ sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxportunit/SipxPortUnitTestPointFailure.h0000644000175000017500000000471112205613256032203 0ustar00danieldaniel00000000000000// // // Copyright (C) 2010 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ // Author: Daniel Petrie // dpetrie AT SIPez DOT com ////////////////////////////////////////////////////////////////////////////// #ifndef _SipxPortUnitTestPointFailure_h_ #define _SipxPortUnitTestPointFailure_h_ // SYSTEM INCLUDES //#include <...> // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS // //! Container for information about a failed test point /*! * */ class SipxPortUnitTestPointFailure { /* ============================= P U B L I C ============================== */ public: /* ============================ C R E A T O R S =========================== */ //! Constructor SipxPortUnitTestPointFailure(const char* fileName, const char* className, const char* methodName, int testPointIndex, int lineNumber, const char* message); //! Destructor virtual ~SipxPortUnitTestPointFailure(); /* ======================== M A N I P U L A T O R S ======================= */ /* ========================== A C C E S S O R S =========================== */ const char* getClassName() const; const char* getMessage() const; /* ============================ I N Q U I R Y ============================= */ //__________________________________________________________________________// /* ========================== P R O T E C T E D =========================== */ protected: char* mSourceFilename; char* mClassName; char* mMethodName; int mTestPointIndex; int mLineNumber; char* mTestPointMessage; //__________________________________________________________________________// /* ============================ P R I V A T E ============================= */ private: /// Disable default constructor SipxPortUnitTestPointFailure(); //! Disabled copy constructor SipxPortUnitTestPointFailure(const SipxPortUnitTestPointFailure& rSipxPortUnitTestPointFailure); //! Disabled assignment operator SipxPortUnitTestPointFailure& operator=(const SipxPortUnitTestPointFailure& rhs); }; #endif // _SipxPortUnitTestPointFailure_h_ sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxportunit/Makefile.am0000644000175000017500000000147512205613305026253 0ustar00danieldaniel00000000000000 INCLUDES = \ -I$(top_srcdir)/sipXportLib/src/test \ -I$(top_srcdir)/sipXportLib/include lib_LTLIBRARIES = libsipXunit.la libsipXunit_la_LDFLAGS = -static # no version info for static libs libsipXunit_la_CFLAGS = @CPPUNIT_CFLAGS@ libsipXunit_la_CPPFLAGS = @CPPUNIT_CFLAGS@ libsipXunit_la_SOURCES = \ SipxPortUnitTestClass.cpp \ SipxPortUnitTestConstructor.cpp \ SipxPortUnitTestEnvironment.cpp \ SipxPortUnitTestPointFailure.cpp \ main.cpp \ ../sipxunit/TestUtilities.cpp libsipXunit_la_LIBADD = \ @CPPUNIT_LIBS@ sipxincludedir = $(includedir)/sipxportunit sipxinclude_HEADERS = \ com_sipez_unit_UnitTestActivity.h \ SipxPortUnitTestAsserts.h \ SipxPortUnitTestClass.h \ SipxPortUnitTestConstructor.h \ SipxPortUnitTestEnvironment.h \ SipxPortUnitTest.h \ SipxPortUnitTestPointFailure.h sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxportunit/Makefile.in0000644000175000017500000007444212321445001026263 0ustar00danieldaniel00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = sipXportLib/src/test/sipxportunit DIST_COMMON = $(sipxinclude_HEADERS) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/general.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/sipXlib.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(sipxincludedir)" LTLIBRARIES = $(lib_LTLIBRARIES) libsipXunit_la_DEPENDENCIES = am_libsipXunit_la_OBJECTS = libsipXunit_la-SipxPortUnitTestClass.lo \ libsipXunit_la-SipxPortUnitTestConstructor.lo \ libsipXunit_la-SipxPortUnitTestEnvironment.lo \ libsipXunit_la-SipxPortUnitTestPointFailure.lo \ libsipXunit_la-main.lo libsipXunit_la-TestUtilities.lo libsipXunit_la_OBJECTS = $(am_libsipXunit_la_OBJECTS) libsipXunit_la_LINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(libsipXunit_la_LDFLAGS) $(LDFLAGS) -o $@ DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) CXXLD = $(CXX) CXXLINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ SOURCES = $(libsipXunit_la_SOURCES) DIST_SOURCES = $(libsipXunit_la_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac HEADERS = $(sipxinclude_HEADERS) ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMRNB_INCLUDE = @AMRNB_INCLUDE@ AMRNB_LIB_ROOT = @AMRNB_LIB_ROOT@ AMRWB_INCLUDE = @AMRWB_INCLUDE@ AMRWB_LIB_ROOT = @AMRWB_LIB_ROOT@ AMRWB_TARGET = @AMRWB_TARGET@ AMR_TARGET = @AMR_TARGET@ AMTAR = @AMTAR@ ANT = @ANT@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CARBON_LIBS = @CARBON_LIBS@ CA_LIBS = @CA_LIBS@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPUNIT_CFLAGS = @CPPUNIT_CFLAGS@ CPPUNIT_CONFIG = @CPPUNIT_CONFIG@ CPPUNIT_LIBS = @CPPUNIT_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPS_PCRE_CFLAGS = @DEPS_PCRE_CFLAGS@ DEPS_PCRE_LIBS = @DEPS_PCRE_LIBS@ DLLTOOL = @DLLTOOL@ DOT = @DOT@ DOXYGEN = @DOXYGEN@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DYNEXT = @DYNEXT@ EAGC_LDFLAGS = @EAGC_LDFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EJBE_LDFLAGS = @EJBE_LDFLAGS@ EPLC_LDFLAGS = @EPLC_LDFLAGS@ EVAD_LDFLAGS = @EVAD_LDFLAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ G722_TARGET = @G722_TARGET@ G726_TARGET = @G726_TARGET@ GIPSINC = @GIPSINC@ GIPS_CE_OBJS = @GIPS_CE_OBJS@ GIPS_CPPFLAGS = @GIPS_CPPFLAGS@ GIPS_NEQ_OBJS = @GIPS_NEQ_OBJS@ GIPS_VE_OBJS = @GIPS_VE_OBJS@ GREP = @GREP@ GSM_CFLAGS = @GSM_CFLAGS@ GSM_CXXFLAGS = @GSM_CXXFLAGS@ GSM_LDFLAGS = @GSM_LDFLAGS@ GSM_LIBS = @GSM_LIBS@ GSM_TARGET = @GSM_TARGET@ ILBC_INCLUDE = @ILBC_INCLUDE@ ILBC_LIB_ROOT = @ILBC_LIB_ROOT@ ILBC_LIB_TARGET = @ILBC_LIB_TARGET@ ILBC_TARGET = @ILBC_TARGET@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTERFACE_FLAGS = @INTERFACE_FLAGS@ JAVA = @JAVA@ JAVAC_DEBUG = @JAVAC_DEBUG@ JAVAC_OPTIMIZED = @JAVAC_OPTIMIZED@ JAVA_HOME = @JAVA_HOME@ L16_TARGET = @L16_TARGET@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NAMED_PROGRAM = @NAMED_PROGRAM@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPUS_CFLAGS = @OPUS_CFLAGS@ OPUS_LIBS = @OPUS_LIBS@ OPUS_TARGET = @OPUS_TARGET@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PCMAPCMU_TARGET = @PCMAPCMU_TARGET@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ RTL_CXXFLAGS = @RTL_CXXFLAGS@ RTL_LDFLAGS = @RTL_LDFLAGS@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SIPXMEDIA_CE_LIBS = @SIPXMEDIA_CE_LIBS@ SIPXMEDIA_VE_LIBS = @SIPXMEDIA_VE_LIBS@ SIPXMEDIA_VE_STATIC_LIBS = @SIPXMEDIA_VE_STATIC_LIBS@ SIPXPBXUSER = @SIPXPBXUSER@ SIPXPHONECONF = @SIPXPHONECONF@ SIPXPHONEDATA = @SIPXPHONEDATA@ SIPXPHONELIB = @SIPXPHONELIB@ SIPX_BACKUPDIR = @SIPX_BACKUPDIR@ SIPX_BINDIR = @SIPX_BINDIR@ SIPX_CONFDIR = @SIPX_CONFDIR@ SIPX_CONFIGPHONEDIR = @SIPX_CONFIGPHONEDIR@ SIPX_DATADIR = @SIPX_DATADIR@ SIPX_DBDIR = @SIPX_DBDIR@ SIPX_DOCDIR = @SIPX_DOCDIR@ SIPX_INCDIR = @SIPX_INCDIR@ SIPX_LIBDIR = @SIPX_LIBDIR@ SIPX_LOGDIR = @SIPX_LOGDIR@ SIPX_PARKMUSICDIR = @SIPX_PARKMUSICDIR@ SIPX_RUNDIR = @SIPX_RUNDIR@ SIPX_SCHEMADIR = @SIPX_SCHEMADIR@ SIPX_TMPDIR = @SIPX_TMPDIR@ SIPX_UNIT_TARGET = @SIPX_UNIT_TARGET@ SIPX_VXMLDATADIR = @SIPX_VXMLDATADIR@ SPANDSP_CFLAGS = @SPANDSP_CFLAGS@ SPANDSP_CXXFLAGS = @SPANDSP_CXXFLAGS@ SPANDSP_LDFLAGS = @SPANDSP_LDFLAGS@ SPANDSP_LIBS = @SPANDSP_LIBS@ SPEEXDSP_CFLAGS = @SPEEXDSP_CFLAGS@ SPEEXDSP_LIBS = @SPEEXDSP_LIBS@ SPEEXDSP_STATIC_LIB = @SPEEXDSP_STATIC_LIB@ SPEEX_CFLAGS = @SPEEX_CFLAGS@ SPEEX_LIBS = @SPEEX_LIBS@ SPEEX_ROOT = @SPEEX_ROOT@ SPEEX_STATIC_LIB = @SPEEX_STATIC_LIB@ SPEEX_TARGET = @SPEEX_TARGET@ SS_LDFLAGS = @SS_LDFLAGS@ STATIC_CODEC_LIBS = @STATIC_CODEC_LIBS@ STRIP = @STRIP@ TONES_TARGET = @TONES_TARGET@ VERSION = @VERSION@ VIDEO_DEFINE = @VIDEO_DEFINE@ WXWIDGETS_CFLAGS = @WXWIDGETS_CFLAGS@ WXWIDGETS_CONFIG = @WXWIDGETS_CONFIG@ WXWIDGETS_CXXFLAGS = @WXWIDGETS_CXXFLAGS@ WXWIDGETS_LIBS = @WXWIDGETS_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ codeclibdir = @codeclibdir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ enable_dot = @enable_dot@ enable_html_docs = @enable_html_docs@ enable_latex_docs = @enable_latex_docs@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ jar = @jar@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ sipx_abs_srcdir = @sipx_abs_srcdir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ wwwdir = @wwwdir@ INCLUDES = \ -I$(top_srcdir)/sipXportLib/src/test \ -I$(top_srcdir)/sipXportLib/include lib_LTLIBRARIES = libsipXunit.la libsipXunit_la_LDFLAGS = -static # no version info for static libs libsipXunit_la_CFLAGS = @CPPUNIT_CFLAGS@ libsipXunit_la_CPPFLAGS = @CPPUNIT_CFLAGS@ libsipXunit_la_SOURCES = \ SipxPortUnitTestClass.cpp \ SipxPortUnitTestConstructor.cpp \ SipxPortUnitTestEnvironment.cpp \ SipxPortUnitTestPointFailure.cpp \ main.cpp \ ../sipxunit/TestUtilities.cpp libsipXunit_la_LIBADD = \ @CPPUNIT_LIBS@ sipxincludedir = $(includedir)/sipxportunit sipxinclude_HEADERS = \ com_sipez_unit_UnitTestActivity.h \ SipxPortUnitTestAsserts.h \ SipxPortUnitTestClass.h \ SipxPortUnitTestConstructor.h \ SipxPortUnitTestEnvironment.h \ SipxPortUnitTest.h \ SipxPortUnitTestPointFailure.h all: all-am .SUFFIXES: .SUFFIXES: .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu sipXportLib/src/test/sipxportunit/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu sipXportLib/src/test/sipxportunit/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ test "$$dir" != "$$p" || dir=.; \ echo "rm -f \"$${dir}/so_locations\""; \ rm -f "$${dir}/so_locations"; \ done libsipXunit.la: $(libsipXunit_la_OBJECTS) $(libsipXunit_la_DEPENDENCIES) $(EXTRA_libsipXunit_la_DEPENDENCIES) $(libsipXunit_la_LINK) -rpath $(libdir) $(libsipXunit_la_OBJECTS) $(libsipXunit_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXunit_la-SipxPortUnitTestClass.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXunit_la-SipxPortUnitTestConstructor.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXunit_la-SipxPortUnitTestEnvironment.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXunit_la-SipxPortUnitTestPointFailure.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXunit_la-TestUtilities.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libsipXunit_la-main.Plo@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LTCXXCOMPILE) -c -o $@ $< libsipXunit_la-SipxPortUnitTestClass.lo: SipxPortUnitTestClass.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libsipXunit_la-SipxPortUnitTestClass.lo -MD -MP -MF $(DEPDIR)/libsipXunit_la-SipxPortUnitTestClass.Tpo -c -o libsipXunit_la-SipxPortUnitTestClass.lo `test -f 'SipxPortUnitTestClass.cpp' || echo '$(srcdir)/'`SipxPortUnitTestClass.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXunit_la-SipxPortUnitTestClass.Tpo $(DEPDIR)/libsipXunit_la-SipxPortUnitTestClass.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='SipxPortUnitTestClass.cpp' object='libsipXunit_la-SipxPortUnitTestClass.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libsipXunit_la-SipxPortUnitTestClass.lo `test -f 'SipxPortUnitTestClass.cpp' || echo '$(srcdir)/'`SipxPortUnitTestClass.cpp libsipXunit_la-SipxPortUnitTestConstructor.lo: SipxPortUnitTestConstructor.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libsipXunit_la-SipxPortUnitTestConstructor.lo -MD -MP -MF $(DEPDIR)/libsipXunit_la-SipxPortUnitTestConstructor.Tpo -c -o libsipXunit_la-SipxPortUnitTestConstructor.lo `test -f 'SipxPortUnitTestConstructor.cpp' || echo '$(srcdir)/'`SipxPortUnitTestConstructor.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXunit_la-SipxPortUnitTestConstructor.Tpo $(DEPDIR)/libsipXunit_la-SipxPortUnitTestConstructor.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='SipxPortUnitTestConstructor.cpp' object='libsipXunit_la-SipxPortUnitTestConstructor.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libsipXunit_la-SipxPortUnitTestConstructor.lo `test -f 'SipxPortUnitTestConstructor.cpp' || echo '$(srcdir)/'`SipxPortUnitTestConstructor.cpp libsipXunit_la-SipxPortUnitTestEnvironment.lo: SipxPortUnitTestEnvironment.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libsipXunit_la-SipxPortUnitTestEnvironment.lo -MD -MP -MF $(DEPDIR)/libsipXunit_la-SipxPortUnitTestEnvironment.Tpo -c -o libsipXunit_la-SipxPortUnitTestEnvironment.lo `test -f 'SipxPortUnitTestEnvironment.cpp' || echo '$(srcdir)/'`SipxPortUnitTestEnvironment.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXunit_la-SipxPortUnitTestEnvironment.Tpo $(DEPDIR)/libsipXunit_la-SipxPortUnitTestEnvironment.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='SipxPortUnitTestEnvironment.cpp' object='libsipXunit_la-SipxPortUnitTestEnvironment.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libsipXunit_la-SipxPortUnitTestEnvironment.lo `test -f 'SipxPortUnitTestEnvironment.cpp' || echo '$(srcdir)/'`SipxPortUnitTestEnvironment.cpp libsipXunit_la-SipxPortUnitTestPointFailure.lo: SipxPortUnitTestPointFailure.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libsipXunit_la-SipxPortUnitTestPointFailure.lo -MD -MP -MF $(DEPDIR)/libsipXunit_la-SipxPortUnitTestPointFailure.Tpo -c -o libsipXunit_la-SipxPortUnitTestPointFailure.lo `test -f 'SipxPortUnitTestPointFailure.cpp' || echo '$(srcdir)/'`SipxPortUnitTestPointFailure.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXunit_la-SipxPortUnitTestPointFailure.Tpo $(DEPDIR)/libsipXunit_la-SipxPortUnitTestPointFailure.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='SipxPortUnitTestPointFailure.cpp' object='libsipXunit_la-SipxPortUnitTestPointFailure.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libsipXunit_la-SipxPortUnitTestPointFailure.lo `test -f 'SipxPortUnitTestPointFailure.cpp' || echo '$(srcdir)/'`SipxPortUnitTestPointFailure.cpp libsipXunit_la-main.lo: main.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libsipXunit_la-main.lo -MD -MP -MF $(DEPDIR)/libsipXunit_la-main.Tpo -c -o libsipXunit_la-main.lo `test -f 'main.cpp' || echo '$(srcdir)/'`main.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXunit_la-main.Tpo $(DEPDIR)/libsipXunit_la-main.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='main.cpp' object='libsipXunit_la-main.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libsipXunit_la-main.lo `test -f 'main.cpp' || echo '$(srcdir)/'`main.cpp libsipXunit_la-TestUtilities.lo: ../sipxunit/TestUtilities.cpp @am__fastdepCXX_TRUE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -MT libsipXunit_la-TestUtilities.lo -MD -MP -MF $(DEPDIR)/libsipXunit_la-TestUtilities.Tpo -c -o libsipXunit_la-TestUtilities.lo `test -f '../sipxunit/TestUtilities.cpp' || echo '$(srcdir)/'`../sipxunit/TestUtilities.cpp @am__fastdepCXX_TRUE@ $(am__mv) $(DEPDIR)/libsipXunit_la-TestUtilities.Tpo $(DEPDIR)/libsipXunit_la-TestUtilities.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ source='../sipxunit/TestUtilities.cpp' object='libsipXunit_la-TestUtilities.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libsipXunit_la_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) -c -o libsipXunit_la-TestUtilities.lo `test -f '../sipxunit/TestUtilities.cpp' || echo '$(srcdir)/'`../sipxunit/TestUtilities.cpp mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-sipxincludeHEADERS: $(sipxinclude_HEADERS) @$(NORMAL_INSTALL) @list='$(sipxinclude_HEADERS)'; test -n "$(sipxincludedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(sipxincludedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(sipxincludedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(sipxincludedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(sipxincludedir)" || exit $$?; \ done uninstall-sipxincludeHEADERS: @$(NORMAL_UNINSTALL) @list='$(sipxinclude_HEADERS)'; test -n "$(sipxincludedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(sipxincludedir)'; $(am__uninstall_files_from_dir) ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) $(HEADERS) installdirs: for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(sipxincludedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-sipxincludeHEADERS install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-libLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-libLTLIBRARIES uninstall-sipxincludeHEADERS .MAKE: install-am install-strip .PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ clean-libLTLIBRARIES clean-libtool ctags distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am \ install-libLTLIBRARIES install-man install-pdf install-pdf-am \ install-ps install-ps-am install-sipxincludeHEADERS \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags uninstall uninstall-am \ uninstall-libLTLIBRARIES uninstall-sipxincludeHEADERS # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxportunit/SipxPortUnitTestClass.cpp0000644000175000017500000000753712205613256031213 0ustar00danieldaniel00000000000000// // // Copyright (C) 2010 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ // Author: Daniel Petrie // dpetrie AT SIPez DOT com ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #include // APPLICATION INCLUDES #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS //__________________________________________________________________________// /* ============================= P U B L I C ============================== */ /* ============================ C R E A T O R S =========================== */ // Constructor SipxPortUnitTestClass::SipxPortUnitTestClass(const char* name) : mpClassName(SipxPortUnitTestEnvironment::newCopyString(name)), mCurrentMethodIndex(-1), mPriorTestPointIndex(-1), mPriorTestPointLine(-1) { mPriorTestPointFileName[0] = '\0'; } SipxPortUnitTestClass::~SipxPortUnitTestClass() { /* char buffer[SIPX_PORT_UNIT_MAX_ERROR_MESSAGE_SIZE]; sprintf(buffer, "~SipxPortUnitTestClass destroying: %s\n", mpClassName); SipxPortUnitTestEnvironment::printOut(buffer); */ } /* ======================== M A N I P U L A T O R S ======================= */ void SipxPortUnitTestClass::setUp() { //SipxPortUnitTestEnvironment::printOut("Default setUp\n"); } void SipxPortUnitTestClass::tearDown() { //SipxPortUnitTestEnvironment::printOut("Default tearDown\n"); } /* ========================== A C C E S S O R S =========================== */ void SipxPortUnitTestClass::setClassName(const char* className) { assert(mpClassName == 0); mpClassName = SipxPortUnitTestEnvironment::newCopyString(className); } const char* SipxPortUnitTestClass::getClassName() { return(mpClassName); } void SipxPortUnitTestClass::setCurrentMethodIndex(int methodIndex) { assert(methodIndex >= 0); mCurrentMethodIndex = methodIndex; SipxPortUnitTestEnvironment::setMethodIndex(methodIndex); SipxPortUnitTestEnvironment::incrementMethodsRun(); } int SipxPortUnitTestClass::getCurrentMethodIndex() const { return(mCurrentMethodIndex); } void SipxPortUnitTestClass::resetTestPointIndex() { mPriorTestPointIndex = -1; SipxPortUnitTestEnvironment::resetTestPointIndex(); } void SipxPortUnitTestClass::incrementTestPointIndex() { mPriorTestPointIndex++; SipxPortUnitTestEnvironment::incrementTestPointIndex(); } int SipxPortUnitTestClass::getTestPointIndex() const { return(mPriorTestPointIndex); } void SipxPortUnitTestClass::setTestPointLine(int lineNumber) { mPriorTestPointLine = lineNumber; } int SipxPortUnitTestClass::getTestPointLine() const { return(mPriorTestPointLine); } void SipxPortUnitTestClass::setTestPointFilename(const char* filename) { strncpy(mPriorTestPointFileName, filename, SIPX_PORT_UNIT_MAX_TEST_FILENAME_LENGTH - 1); // Make sure string is always null terminated mPriorTestPointFileName[SIPX_PORT_UNIT_MAX_TEST_FILENAME_LENGTH - 1] = '\0'; } const char* SipxPortUnitTestClass::getTestPointFilename() const { return(mPriorTestPointFileName); } /* ============================ I N Q U I R Y ============================= */ //__________________________________________________________________________// /* ========================== P R O T E C T E D =========================== */ //__________________________________________________________________________// /* ============================ P R I V A T E ============================= */ /* ========================== F U N C T I O N S =========================== */ //__________________________________________________________________________// sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxportunit/SipxPortUnitTestConstructor.cpp0000644000175000017500000001071312205613256032461 0ustar00danieldaniel00000000000000// // // Copyright (C) 2010 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ // Author: Daniel Petrie // dpetrie AT SIPez DOT com ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include // APPLICATION INCLUDES #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS //__________________________________________________________________________// /* ============================= P U B L I C ============================== */ /* ============================ C R E A T O R S =========================== */ // Constructor SipxPortUnitTestConstructor::SipxPortUnitTestConstructor(const char* testClassName) : mpClassName(SipxPortUnitTestEnvironment::newCopyString(testClassName)), mpTestClass(0) { // Register this test to be run SipxPortUnitTestEnvironment::registerTestConstructor(this); } SipxPortUnitTestConstructor::~SipxPortUnitTestConstructor() { // SipxPortUnitTestConstructor should never get destroyed assert(0); if(mpClassName != 0) { delete[] mpClassName; mpClassName = 0; } } /* ======================== M A N I P U L A T O R S ======================= */ void SipxPortUnitTestConstructor::runAllMethodsFrom(int methodIndex) { if(mpTestClass == 0) { constructTestClass(); assert(mpTestClass); } SipxPortUnitTestEnvironment::setCurrentTestClass(mpTestClass); mpTestClass->runAllMethodsFrom(methodIndex); } void SipxPortUnitTestConstructor::releaseTestClass() { /* char buffer[256]; sprintf(buffer, "SipxPortUnitTestConstructor::releaseTestClass: %s\n", mpTestClass->getClassName()); SipxPortUnitTestEnvironment::printOut(buffer); */ assert(mpTestClass); delete mpTestClass; mpTestClass = 0; } void SipxPortUnitTestConstructor::addSignalCaughtFailure(int signalNumber) { char message[SIPX_PORT_UNIT_MAX_ERROR_MESSAGE_SIZE]; if(mpTestClass) { const char* fileName = mpTestClass->getTestPointFilename(); const char* methodName = mpTestClass->getCurrentMethodName(); int testPoint = mpTestClass->getTestPointIndex(); int lineNumber = mpTestClass->getTestPointLine(); sprintf(message, "ABORT: due to signal: %d caught while in file: %s %s::%s test point: %d between line: %d and next test point\n", signalNumber, fileName, mpClassName, methodName, testPoint, lineNumber); mpTestClass->addFailedTestPoint(fileName, mpClassName, methodName, testPoint, lineNumber, message); } // no class, something bad must have happened during construction or // initialization. Log a general class test failure else { sprintf(message, "ABORT: due to signal %d caught while constructing or initializing test class: %s. ALL test methods skipped.\n", signalNumber, mpClassName); addTestClassFailure(mpClassName, message); } } /* ========================== A C C E S S O R S =========================== */ const char* SipxPortUnitTestConstructor::getClassName() const { return(mpClassName); } int SipxPortUnitTestConstructor::getTestPointLine() const { return(mpTestClass ? mpTestClass->getTestPointLine() : -1); } const char* SipxPortUnitTestConstructor::getTestPointFilename() const { return(mpTestClass ? mpTestClass->getTestPointFilename() : 0); } /* ============================ I N Q U I R Y ============================= */ //__________________________________________________________________________// /* ========================== P R O T E C T E D =========================== */ //__________________________________________________________________________// /* ============================ P R I V A T E ============================= */ /* ========================== F U N C T I O N S =========================== */ //__________________________________________________________________________// sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxportunit/SipxPortUnitTestEnvironment.cpp0000644000175000017500000004526412205617431032450 0ustar00danieldaniel00000000000000// // // Copyright (C) 2010-2012 SIPez LLC All rights reserved. // // $$ // Author: Daniel Petrie // dpetrie AT SIPez DOT com ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #include #include #include #if !defined(ANDROID) && !defined(_WIN32) # include #endif #if defined(_WIN32) #define siglongjmp longjmp #define sigsetjmp(BUF, OPT) setjmp(BUF) #endif // APPLICATION INCLUDES #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS //#define DONT_CATCH_SIGNALS // STATIC VARIABLE INITIALIZATIONS bool SipxPortUnitTestEnvironment::sInitialized = 0; int SipxPortUnitTestEnvironment::sInitializedSignature = 0; int SipxPortUnitTestEnvironment::sInitializing = 0; int SipxPortUnitTestEnvironment::sCurrentTestClassIndex = -1; int SipxPortUnitTestEnvironment::sCurrentTestMethodIndex = -1; int SipxPortUnitTestEnvironment::sCurrentTestPointIndex = -1; SipxPortUnitTestClass* SipxPortUnitTestEnvironment::spCurrentTestClass = 0; int SipxPortUnitTestEnvironment::sTotalTestMethodCount = 0; int SipxPortUnitTestEnvironment::sTestMethodsRun = 0; int SipxPortUnitTestEnvironment::sTestPointsPassed = 0; int SipxPortUnitTestEnvironment::sTestPointsFailed = 0; int SipxPortUnitTestEnvironment::sTotalTestClassCount = 0; SipxPortUnitTestConstructor** SipxPortUnitTestEnvironment::sTestClassesToRun = NULL; int SipxPortUnitTestEnvironment::sNumExceptionsCaught = 0; int SipxPortUnitTestEnvironment::sLastExceptionsCaught = 0; int SipxPortUnitTestEnvironment::sLastExceptionClassIndex = -1; int SipxPortUnitTestEnvironment::sNumExceptionsForSameClass = 0; int SipxPortUnitTestEnvironment::sLastExceptionMethodIndex = -1; int SipxPortUnitTestEnvironment::sLastExceptionTestPointIndex = -1; void (*SipxPortUnitTestEnvironment::sLogHookBegin)(const char* testName) = NULL; void (*SipxPortUnitTestEnvironment::sLogHookEnd)(const char* testName) = NULL; SipxUnitStringOutputter SipxPortUnitTestEnvironment::sStringOutputMethod = defaultPrintOut; // Stack to recover to if something bad happens in a test jmp_buf sLongJumpStack; //__________________________________________________________________________// /* ============================= P U B L I C ============================== */ /* ============================ C R E A T O R S =========================== */ // Constructor SipxPortUnitTestEnvironment::SipxPortUnitTestEnvironment() { } SipxPortUnitTestEnvironment::~SipxPortUnitTestEnvironment() { } /* ======================== M A N I P U L A T O R S ======================= */ void SipxPortUnitTestEnvironment::initializeEnvironment() { if(!sInitialized || sInitializedSignature != SIPX_PORT_UNIT_TEST_SIGNATURE) { if(sInitializing != SIPX_PORT_UNIT_TEST_SIGNATURE) { sInitializing = SIPX_PORT_UNIT_TEST_SIGNATURE; sCurrentTestClassIndex = -1; sCurrentTestMethodIndex = -1; sCurrentTestPointIndex = -1; spCurrentTestClass = 0; sTotalTestMethodCount = 0; sTestMethodsRun = 0; sTestPointsPassed = 0; sTestPointsFailed = 0; sTotalTestClassCount = 0; sTestClassesToRun = new SipxPortUnitTestConstructor*[SIPX_PORT_UNIT_MAX_TEST_CLASSES]; sNumExceptionsCaught = -1; sLastExceptionsCaught = 0; resetExceptionState(); sInitializing = 0; sInitializedSignature = SIPX_PORT_UNIT_TEST_SIGNATURE; sInitialized = 1; } } } void SipxPortUnitTestEnvironment::dumpCurrentTestState() { char buffer[SIPX_PORT_UNIT_MAX_ERROR_MESSAGE_SIZE]; sprintf(buffer, "current class index: %d\ncurrent method index: %d\ncurrent test point index: %d\n", sCurrentTestClassIndex, sCurrentTestMethodIndex, sCurrentTestPointIndex); printOut(buffer); } void SipxPortUnitTestEnvironment::resetExceptionState() { initializeEnvironment(); //printOut("SipxPortUnitTestEnvironment::resetExceptionState\n"); sNumExceptionsCaught++; if(sLastExceptionClassIndex == sCurrentTestClassIndex) { sNumExceptionsForSameClass++; } else { sNumExceptionsForSameClass = 0; } sLastExceptionClassIndex = sCurrentTestClassIndex; sLastExceptionMethodIndex = sCurrentTestMethodIndex; sLastExceptionTestPointIndex = sCurrentTestPointIndex; } void SipxPortUnitTestEnvironment::registerTestConstructor(SipxPortUnitTestConstructor* testClassToAdd) { initializeEnvironment(); assert(testClassToAdd); sTestClassesToRun[sTotalTestClassCount] = testClassToAdd; sTotalTestClassCount++; } void SipxPortUnitTestEnvironment::signalHandler(int signalCaught) { char buffer[256]; sprintf(buffer, "ABORT: due to caught signal: %d", signalCaught); printOut(buffer); assert(sCurrentTestClassIndex >= 0); assert(sCurrentTestClassIndex < sTotalTestClassCount); assert(sCurrentTestClassIndex < SIPX_PORT_UNIT_MAX_TEST_CLASSES); sprintf(buffer, " while in %s test class: %s between line: %d and next test point\n", sTestClassesToRun[sCurrentTestClassIndex]->getTestPointFilename(), sTestClassesToRun[sCurrentTestClassIndex]->getClassName(), sTestClassesToRun[sCurrentTestClassIndex]->getTestPointLine()); printOut(buffer); sTestClassesToRun[sCurrentTestClassIndex]->addSignalCaughtFailure(signalCaught); #if !defined(ANDROID) && !defined(_WIN32) // Try to get a back trace, but we loose the top function call due to // being in the signal handler void* traceStack[SIPX_PORT_UNIT_MAX_STACK_TRACE_SIZE]; int stackSize = backtrace(traceStack, SIPX_PORT_UNIT_MAX_STACK_TRACE_SIZE); char** entryPointArray = backtrace_symbols(traceStack, stackSize); printOut("stack: =========\n"); for(int stackIndex = 0; stackIndex < stackSize; stackIndex++) { sprintf(buffer, " %d] %s\n", stackIndex + 1, entryPointArray[stackIndex]); printOut(buffer); } #endif resetExceptionState(); sLastExceptionsCaught = signalCaught; siglongjmp(sLongJumpStack, 1); } void SipxPortUnitTestEnvironment::runTests() { initializeEnvironment(); // Prepare to run tests and catch signals if something bad happends #ifndef DONT_CATCH_SIGNALS signal(SIGFPE, SipxPortUnitTestEnvironment::signalHandler); signal(SIGSEGV, SipxPortUnitTestEnvironment::signalHandler); signal(SIGILL, SipxPortUnitTestEnvironment::signalHandler); #endif // Render test inforation for each test class first time this gets run // This will be run more than once if we catch a signal and are able // to recover. if(sigsetjmp(sLongJumpStack, 1) == 0 /*sCurrentTestClassIndex == -1i*/) { sCurrentTestClassIndex = 0; sTotalTestMethodCount = 0; for(int testIndex = 0; testIndex < sTotalTestClassCount; testIndex++) { assert(sTestClassesToRun[testIndex]); sTotalTestMethodCount += (sTestClassesToRun[testIndex])->getTestMethodCount(); } } // We are recovering from an exception/signal that was caught else { if(sCurrentTestMethodIndex == -1) { // caught signal before running first method of test class // something must be wrong with the initialization or // constuction of the test class. So skip the whole test // class sCurrentTestClassIndex++; char buffer[256]; sprintf(buffer, "initialization or construction of: %s failed skipping to class: %s\n", sTestClassesToRun[sCurrentTestClassIndex-1]->getClassName(), sTestClassesToRun[sCurrentTestClassIndex]->getClassName()); printOut(buffer); } else { printOut("recovered from failure, starting next test method\n"); // Move to the next test method as something went bad sCurrentTestMethodIndex++; } dumpCurrentTestState(); } for(;sCurrentTestClassIndex < sTotalTestClassCount; sCurrentTestClassIndex++) { assert(sTestClassesToRun[sCurrentTestClassIndex]); if(sLogHookBegin) { sLogHookBegin(sTestClassesToRun[sCurrentTestClassIndex]->getClassName()); } sTestClassesToRun[sCurrentTestClassIndex]->runAllMethodsFrom(sCurrentTestMethodIndex); // Can now free up the test class, but we keep the test class //constructor around so we can get at the stats sTestClassesToRun[sCurrentTestClassIndex]->releaseTestClass(); if(sLogHookEnd) { sLogHookEnd(sTestClassesToRun[sCurrentTestClassIndex]->getClassName()); } sCurrentTestMethodIndex = 0; sCurrentTestPointIndex = 0; } // Now that we are done with the tests, we do not want the signal // handler to catch stuff any more #ifndef DONT_CATCH_SIGNALS signal(SIGFPE, SIG_DFL); signal(SIGSEGV, SIG_DFL); #endif } void SipxPortUnitTestEnvironment::reportResults() { initializeEnvironment(); printOut("\nTEST SUMMARY:\n"); char buffer[SIPX_PORT_UNIT_MAX_ERROR_MESSAGE_SIZE]; sprintf(buffer, "Total: %d test class(es), %d test method(s), ?? test points\n", sTotalTestClassCount, sTotalTestMethodCount); printOut(buffer); sprintf(buffer, "Ran: %d test class(es), %d test method(s), %d test points\n", sCurrentTestClassIndex, sTestMethodsRun, sTestPointsPassed + sTestPointsFailed); printOut(buffer); sprintf(buffer, "%d test points passed, %d test points failed, %d tests aborted\n", sTestPointsPassed, sTestPointsFailed, sNumExceptionsCaught); printOut(buffer); // Detail successes printOut("\n=============================================\nSuccess tallies:\n"); for(int classIndex = 0; classIndex < sTotalTestClassCount; classIndex++) { SipxPortUnitTestConstructor* classConstr = sTestClassesToRun[classIndex]; assert(classConstr); int passed = classConstr->getPassedTestPointCount(); sprintf(buffer, "%s: %d test methods, %d/%d test points succeeded\n", classConstr->getClassName(), classConstr->getTestMethodCount(), passed, (passed + classConstr->getFailedTestPointCount())); printOut(buffer); } // Dig out all the failure messages for all of the classes if(sTestPointsFailed || sNumExceptionsCaught) { sprintf(buffer, "\n=============================================\n%d FAILURE(S), %d ABORT(S):\n", sTestPointsFailed, sNumExceptionsCaught); printOut(buffer); } int failureIndex = 0; SipxPortUnitTestPointFailure* failure = 0; for(int classIndex = 0; classIndex < sTotalTestClassCount; classIndex++) { SipxPortUnitTestConstructor* classConstr = sTestClassesToRun[classIndex]; assert(classConstr); failureIndex = 0; while(failureIndex < SIPX_PORT_UNIT_MAX_TEST_ERRORS_PER_CLASS && (failure = classConstr->getFailure(failureIndex))) { // If first failure for this test class label it if(failureIndex == 0) { sprintf(buffer, "\n%s %d failure(s):\n", classConstr->getClassName(), classConstr->getFailureCount()); printOut(buffer); } sprintf(buffer, " %d) ", failureIndex + 1); printOut(buffer); printOut(failure->getMessage()); failureIndex++; } if(failureIndex == SIPX_PORT_UNIT_MAX_TEST_ERRORS_PER_CLASS) { sprintf(buffer, "WARNING: maximum failures (%d) reached for test class: %s\n", SIPX_PORT_UNIT_MAX_TEST_ERRORS_PER_CLASS, classConstr->getClassName()); printOut(buffer); } } } void SipxPortUnitTestEnvironment::defaultPrintOut(const char* messageText) { printf("%s", messageText); } void SipxPortUnitTestEnvironment::printOut(const char* messageText) { if(sStringOutputMethod) { (sStringOutputMethod)(messageText); } } bool SipxPortUnitTestEnvironment::areEqual(long arg1, long arg2) { return(arg1 == arg2); } bool SipxPortUnitTestEnvironment::areEqual(const UtlString& arg1, const UtlString& arg2) { return(arg1.compareTo(arg2) == 0); } bool SipxPortUnitTestEnvironment::areEqual(const UtlContainable& arg1, const UtlContainable& arg2) { return(arg1.isEqual(&arg2)); } bool SipxPortUnitTestEnvironment::areEqual(const UtlContainable* arg1, const UtlContainable* arg2) { return(arg1 == arg2 || (arg1 && arg2 && arg1->isEqual(arg2))); } bool SipxPortUnitTestEnvironment::areEqual(void* arg1, void* arg2) { return(arg1 == arg2); } void SipxPortUnitTestEnvironment::makeAssertNotEqualMessage(char* messageBuffer, const char* notEqualMessage, const char* arg1String, const char* arg2String, const char* fileName, const char* className, const char* methodName, int testPoint, int lineNum, int arg1, int arg2) { snprintf(messageBuffer, SIPX_PORT_UNIT_MAX_ERROR_MESSAGE_SIZE - 1, "%s, \"%s\" is not equal to \"%s\", file: %s %s::%s test point: %d line: %d\n\t%s=%d\n\t%s=%d\n", notEqualMessage, arg1String, arg2String, fileName, className, methodName, testPoint, lineNum, arg1String, arg1, arg2String, arg2); } void SipxPortUnitTestEnvironment::makeAssertNotEqualMessage(char* messageBuffer, const char* notEqualMessage, const char* arg1String, const char* arg2String, const char* fileName, const char* className, const char* methodName, int testPoint, int lineNum, const char* arg1, const char* arg2) { snprintf(messageBuffer, SIPX_PORT_UNIT_MAX_ERROR_MESSAGE_SIZE - 1, "%s, \"%s\" is not equal to \"%s\", file: %s %s::%s test point: %d line: %d\n\t%s=\"%s\"\n\t%s=\"%s\"\n", notEqualMessage, arg1String, arg2String, fileName, className, methodName, testPoint, lineNum, arg1String, arg1, arg2String, arg2); } void SipxPortUnitTestEnvironment::makeAssertNotEqualMessage(char* messageBuffer, const char* notEqualMessage, const char* arg1String, const char* arg2String, const char* fileName, const char* className, const char* methodName, int testPoint, int lineNum, const void* arg1, const void* arg2) { snprintf(messageBuffer, SIPX_PORT_UNIT_MAX_ERROR_MESSAGE_SIZE - 1, "%s, \"%s\" is not equal to \"%s\", file: %s %s::%s test point: %d line: %d\n\t%s=%p\n\t%s=%p\n", notEqualMessage, arg1String, arg2String, fileName, className, methodName, testPoint, lineNum, arg1String, arg1, arg2String, arg2); } void SipxPortUnitTestEnvironment::makeAssertNotEqualMessage(char* messageBuffer, const char* notEqualMessage, const char* arg1String, const char* arg2String, const char* fileName, const char* className, const char* methodName, int testPoint, int lineNum, const UtlContainable* arg1, const UtlContainable* arg2) { // No generic way to get value of UtlContainable so we do not print it snprintf(messageBuffer, SIPX_PORT_UNIT_MAX_ERROR_MESSAGE_SIZE - 1, "%s, \"%s\" is not equal to \"%s\", file: %s %s::%s test point: %d line: %d\n", notEqualMessage, arg1String, arg2String, fileName, className, methodName, testPoint, lineNum); //, arg1String, arg1, arg2String, arg2); } /* ========================== A C C E S S O R S =========================== */ char* SipxPortUnitTestEnvironment::newCopyString(const char* stringToCopy) { char* stringCopy = 0; if(stringToCopy) { int nameLength = strlen(stringToCopy); stringCopy = new char[nameLength + 1]; strcpy(stringCopy, stringToCopy); } return(stringCopy); } void SipxPortUnitTestEnvironment::incrementMethodsRun() { sTestMethodsRun++; } void SipxPortUnitTestEnvironment::setMethodIndex(int methodIndex) { sCurrentTestMethodIndex = methodIndex; } void SipxPortUnitTestEnvironment::resetTestPointIndex() { sCurrentTestPointIndex = -1; } void SipxPortUnitTestEnvironment::incrementTestPointIndex() { sCurrentTestPointIndex++; } void SipxPortUnitTestEnvironment::incrementTestPointsPassed() { sTestPointsPassed++; } void SipxPortUnitTestEnvironment::incrementTestPointsFailed() { sTestPointsFailed++; } int SipxPortUnitTestEnvironment::getTestPointFailureCount() { return(sTestPointsFailed); } int SipxPortUnitTestEnvironment::getTestAbortCount() { return(sNumExceptionsCaught); } SipxPortUnitTestClass* SipxPortUnitTestEnvironment::getCurrentTestClass() { return(spCurrentTestClass); } void SipxPortUnitTestEnvironment::setCurrentTestClass(SipxPortUnitTestClass* currentClass) { spCurrentTestClass = currentClass; } void SipxPortUnitTestEnvironment::setStringOutMethod(SipxUnitStringOutputter newOutputMethod) { sStringOutputMethod = newOutputMethod; } void SipxPortUnitTestEnvironment::setLogHookBegin(void (*logBeginFunc)(const char* testClassName)) { sLogHookBegin = logBeginFunc; } void SipxPortUnitTestEnvironment::setLogHookEnd(void (*logEndFunc)(const char* testClassName)) { sLogHookEnd = logEndFunc; } /* ============================ I N Q U I R Y ============================= */ //__________________________________________________________________________// /* ========================== P R O T E C T E D =========================== */ //__________________________________________________________________________// /* ============================ P R I V A T E ============================= */ /* ========================== F U N C T I O N S =========================== */ //__________________________________________________________________________// sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxportunit/SipxPortUnitTestPointFailure.cpp0000644000175000017500000000515712205613256032543 0ustar00danieldaniel00000000000000// // // Copyright (C) 2010 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ // Author: Daniel Petrie // dpetrie AT SIPez DOT com ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS //__________________________________________________________________________// /* ============================= P U B L I C ============================== */ /* ============================ C R E A T O R S =========================== */ // Constructor SipxPortUnitTestPointFailure::SipxPortUnitTestPointFailure(const char* fileName, const char* className, const char* methodName, int testPointIndex, int lineNumber, const char* message) : mSourceFilename(SipxPortUnitTestEnvironment::newCopyString(fileName)), mClassName(SipxPortUnitTestEnvironment::newCopyString(className)), mMethodName(SipxPortUnitTestEnvironment::newCopyString(methodName)), mTestPointIndex(testPointIndex), mLineNumber(lineNumber), mTestPointMessage(SipxPortUnitTestEnvironment::newCopyString(message)) { } // Destructor SipxPortUnitTestPointFailure::~SipxPortUnitTestPointFailure() { } /* ======================== M A N I P U L A T O R S ======================= */ /* ========================== A C C E S S O R S =========================== */ const char* SipxPortUnitTestPointFailure::getClassName() const { return(mClassName); } const char* SipxPortUnitTestPointFailure::getMessage() const { return(mTestPointMessage); } /* ============================ I N Q U I R Y ============================= */ //__________________________________________________________________________// /* ========================== P R O T E C T E D =========================== */ //__________________________________________________________________________// /* ============================ P R I V A T E ============================= */ /* ========================== F U N C T I O N S =========================== */ //__________________________________________________________________________// sipxtapi-3.3.0~test17/sipXportLib/src/test/sipxportunit/main.cpp0000644000175000017500000000130512205613256025644 0ustar00danieldaniel00000000000000// // // Copyright (C) 2010 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2010 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ // Author: Daniel Petrie // dpetrie AT SIPez DOT com ////////////////////////////////////////////////////////////////////////////// #include int main(int arc, char* argv[]) { int result = 0; SipxPortUnitTestEnvironment::runTests(); SipxPortUnitTestEnvironment::reportResults(); result = SipxPortUnitTestEnvironment::getTestPointFailureCount(); result += SipxPortUnitTestEnvironment::getTestAbortCount(); return(result); } sipxtapi-3.3.0~test17/sipXportLib/include/0000755000175000017500000000000012321445025021276 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/include/os/0000755000175000017500000000000012321445025021717 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/0000755000175000017500000000000012321445025023056 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/host_address.h0000644000175000017500000000101612205613256025713 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifdef __linux__ #ifdef __cplusplus extern "C" { #endif unsigned int getExternalHostAddressLinux(void); void getEthernetHWAddrLinux(char * address, int length); #ifdef __cplusplus } #endif #endif /* __linux__ */ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/AdapterInfo.h0000644000175000017500000000172012205613256025427 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef getDNSServers_h_ #define getDNSServers_h_ #ifdef __cplusplus #include /// Return this host's IP addresses. extern "C" bool getAllLocalHostIps(const class HostAdapterAddress* localHostAddresses[], int &numAddresses); /**< * Does not include the "loopback" address. */ /// Return a generated adapter name associated with the IP address. extern "C" bool getContactAdapterName(UtlString &adapterName, const UtlString &ipAddress, bool unusedHere); #endif #endif // getDNSServers_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/OsBSemLinux.h0000644000175000017500000000447512205613256025415 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsBSemLinux_h_ #define _OsBSemLinux_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsBSem.h" #include "os/linux/OsLinuxDefs.h" #include "os/linux/pt_csem.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Binary semaphore for Linux class OsBSemLinux : public OsBSemBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsBSemLinux(const int queueOptions, const int initState); //:Constructor virtual ~OsBSemLinux(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsStatus acquire(const OsTime& rTimeout = OsTime::OS_INFINITY); //:Block the task until the semaphore is acquired or the timeout expires virtual OsStatus tryAcquire(void); //:Conditionally acquire the semaphore (i.e., don't block) // Return OS_BUSY if the semaphore is held by some other task virtual OsStatus release(void); //:Release the semaphore /* ============================ ACCESSORS ================================= */ virtual void OsBSemShow(void); //:Print semaphore information to the console /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: pt_sem_t mSemImp; // Pingtel-Linux counting semaphore OsBSemLinux(); //:Default constructor (not implemented for this class) OsBSemLinux(const OsBSemLinux& rOsBSemLinux); //:Copy constructor (not implemented for this class) OsBSemLinux& operator=(const OsBSemLinux& rhs); //:Assignment operator (not implemented for this class) }; /* ============================ INLINE METHODS ============================ */ #endif // _OsBSemLinux_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/OsCSemLinux.h0000644000175000017500000000502012205613256025401 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsCSemLinux_h_ #define _OsCSemLinux_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsCSem.h" #include "os/linux/OsLinuxDefs.h" #include "os/linux/pt_csem.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Counting semaphore for Linux class OsCSemLinux : public OsCSemBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsCSemLinux(const int queueOptions, const int maxCount); //:Constructor setting the initial and max semaphore values to maxCount OsCSemLinux(const int queueOptions, const int maxCount, const int initCount); //:Constructor allowing different initial and maximum semaphore values virtual ~OsCSemLinux(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsStatus acquire(const OsTime& rTimeout = OsTime::OS_INFINITY); //:Block the task until the semaphore is acquired or the timeout expires virtual OsStatus tryAcquire(void); //:Conditionally acquire the semaphore (i.e., don't block) // Return OS_BUSY if the semaphore is held by some other task virtual OsStatus release(void); //:Release the semaphore /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: pt_sem_t mSemImp; // Pingtel-Linux counting semaphore OsCSemLinux(); //:Default constructor (not implemented for this class) OsCSemLinux(const OsCSemLinux& rOsCSemLinux); //:Copy constructor (not implemented for this class) OsCSemLinux& operator=(const OsCSemLinux& rhs); //:Assignment operator (not implemented for this class) void init(void); //:Common initialization shared by all (non-copy) constructors }; /* ============================ INLINE METHODS ============================ */ #endif // _OsCSemLinux_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/OsDateTimeLinux.h0000644000175000017500000000667012205613256026262 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsDateTimeLinux_h_ #define _OsDateTimeLinux_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsDateTime.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:DateTime management functions for Linux class OsDateTimeLinux : public OsDateTimeBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsDateTimeLinux(); //:Default constructor OsDateTimeLinux(const unsigned short year, ///< 4-digit year const unsigned char month, const unsigned char day, const unsigned char hour, const unsigned char minute, const unsigned char second, const unsigned int microsecond); //:Constructor OsDateTimeLinux(const OsDateTimeLinux& rOsDateTimeLinux); //:Copy constructor /// Convert an OsTime to an OsDateTime OsDateTimeLinux(const OsTime& toTime); virtual ~OsDateTimeLinux(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsDateTimeLinux& operator=(const OsDateTimeLinux& rhs); //:Assignment operator static void setTime(struct timespec gmt, int tzOffsetSecs, DstRule dstRule); //:Set the system time //!param: (in) gmt - time relative to the beginning of 1970 (GMT) //!param: (in) tzOffsetSecs - local time offset (seconds relative to GMT) //!param: (in) dstRule - daylight savings time rule static void setTimeZone(int tzOffsetSecs, DstRule dstRule); //:Set the time zone and daylight savings time information //!param: (in) tzOffsetSecs - local time offset (seconds relative to GMT) //!param: (in) dstRule - daylight savings time rule /* ============================ ACCESSORS ================================= */ virtual OsStatus cvtToTimeSinceBoot(OsTime& rTime) const; //:Convert the OsDateTimeBase value to an OsTime value // The OsTime value is relative to when the system was booted. static void getCurTime(OsDateTimeLinux& rDateTime); //:Return the current time as an OsDateTime value /// Return the current time as an OsTime value static void getCurTime(OsTime& rTime); static void getCurTimeSinceBoot(OsTime& rTime); //:Return the current time as an OsTime value // The OsTime value is relative to when the system was booted. static unsigned long getSecsSinceEpoch(void); //:Current time as the number of seconds since midnight (0 hour) 01/01/70 static double secondsSinceBoot(void); //:Get seconds since boot under Linux using /proc/uptime /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _OsDateTimeLinux_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/OsDirLinux.h0000644000175000017500000000470112205613256025275 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsDir_h_ #define _OsDir_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsStatus.h" #include "os/OsDefs.h" #include "os/OsFS.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsFileInfoBase; class OsDirBase; class OsPathLinux; class OsFileInfoLinux; //:Abstraction class to hande directory manipulations class OsDirLinux : public OsDirBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsDirLinux(const char* pathname); OsDirLinux(const OsPathLinux& rOsPath); OsDirLinux(const OsDirLinux& rOsDir); //:Copy constructor virtual ~OsDirLinux(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsStatus create(int permissions = 0755) const; //: Create the path specified by this object // Returns OS_SUCCESS if successful, or OS_INVALID OsStatus rename(const char* name); //: Renames the current directory to the name specified // Returns: // OS_SUCCESS if successful // OS_INVALID if failed /* ============================ ACCESSORS ================================= */ OsStatus getFileInfo(OsFileInfoBase& rFileInfo) const; //: Returns the file information for this objects path (see //: OsFileInfo for more detail) // Returns: // OS_SUCCESS if successful // OS_INVALID if failed /* ============================ INQUIRY =================================== */ UtlBoolean exists(); //: Returns TRUE if the directory specified by this object exists /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsDirLinux(); //:Default constructor OsDirLinux& operator=(const OsDirLinux& rhs); //:Assignment operator /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _OsDir_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/OsFileInfoLinux.h0000644000175000017500000000374412205613256026260 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsFileInfo_h_ #define _OsFileInfo_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsTime.h" #include "os/OsFileInfoBase.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsPathLinux; class OsFileInfoBase; //:Class short description which may consist of multiple lines (note the ':') // Class detailed description which may extend to multiple lines class OsFileInfoLinux : public OsFileInfoBase { friend class OsDirBase; friend class OsFileBase; friend class OsFileSystem; friend class OsDirLinux; friend class OsFileLinux; friend class OsFileSystemLinux; /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsFileInfoLinux(); //:Default constructor OsFileInfoLinux(const OsFileInfoLinux& rOsFileInfo); //:Copy constructor virtual ~OsFileInfoLinux(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsFileInfoLinux& operator=(const OsFileInfoLinux& rhs); //:Assignment operator /* ============================ INQUIRY =================================== */ UtlBoolean isReadOnly() const; //: return TRUE if entry is readonly /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _OsFileInfo_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/OsFileIteratorLinux.h0000644000175000017500000000423012205613256027145 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsFileIterator_h_ #define _OsFileIterator_h_ // SYSTEM INCLUDES #include #include #include #include #include // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsFS.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsFileInfoLinux; class OsPathLinux; class OsFileIteratorBase; //:Abstraction class to iterate through files and/or directories class OsFileIteratorLinux : public OsFileIteratorBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsFileIteratorLinux(); OsFileIteratorLinux(const OsPathLinux& rPathName); virtual ~OsFileIteratorLinux(); //:Destructor /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ //: Returns total files enumerated thus far. /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: DIR* mSearchHandle; OsStatus getNextEntryName(UtlString &rName, OsFileType &rFileType); //: Platform dependant call for getting entry OsStatus getFirstEntryName(UtlString &rName, OsFileType &rFileType); //: Platform dependant call for getting entry OsFileType mMatchAttrib; //: Attributes for file matching long mFileCount; //: How many file did this class find }; /* ============================ INLINE METHODS ============================ */ #endif // _OsFileIterator_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/OsFileLinux.h0000644000175000017500000000554012205613256025440 0ustar00danieldaniel00000000000000// // Copyright (C) 2005, 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004, 2005 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsFileLinux_h_ #define _OsFileLinux_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsFileInfoBase; class OsFileInfoLinux; class OsPathLinux; //:OS class for creating,reading, writing, manipulating files. class OsFileLinux : public OsFileBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsFileLinux(const OsPathBase& filename); //:Default constructor virtual ~OsFileLinux(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsStatus filelock(const bool wait); //: Cross-process locks this file, optionally waiting for the lock. //: Returns: //: OS_SUCCESS if successful //: OS_FAILED if unsuccessful //: Notes: This method should only be called by OsFileBase::open()! OsStatus fileunlock(); //: Cross-process unlocks this file. //: Notes: This method should only be called by OsFileBase::close()! OsStatus setLength(unsigned long newLength); //: Sets the length of the file specified by the object to the new size //: Sets the length of the file specified by the object to the new size //: Shrinking or Growing the file as needed. OsStatus setReadOnly(UtlBoolean isReadOnly); //: Sets the file to the new state //: Returns: //: OS_SUCCESS if successful //: OS_INVALID if failed OsStatus touch(); //: Updates the date and time on the file. Creates if needed. /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ UtlBoolean isReadonly() const; //: Returns TRUE if file is readonly virtual OsStatus getFileInfo(OsFileInfoBase& rFileinfo) const; //: Returns all the relevant info on this file /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsFileLinux(const OsFileLinux& rOsFileLinux); //:Copy constructor OsFileLinux& operator=(const OsFileLinux& rhs); //:Assignment operator /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _OsFileLinux_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/OsLinuxDefs.h0000644000175000017500000000173112205613256025440 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsLinuxDefs_h_ #define _OsLinuxDefs_h_ // SYSTEM INCLUDES #include #include #include #ifdef __cplusplus extern "C" { #endif // APPLICATION INCLUDES // DEFINES // Change the VxWorks defines that interfere with names used by our // own abstraction layer. // Not sure if these are present under other OS's but it can't hurt :) #undef NO_WAIT #undef OK #undef WAIT_FOREVER #define POSIX_OK 0 #define POSIX_NO_WAIT 0 #define POSIX_WAIT_FOREVER (-1) // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS #ifdef __cplusplus } #endif #endif // _OsLinuxDefs_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/OsMutexLinux.h0000644000175000017500000000535212205613256025664 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsMutexLinux_h_ #define _OsMutexLinux_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsMutex.h" #include "os/linux/OsLinuxDefs.h" #include "os/linux/pt_mutex.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Mutual exclusion semaphore (mutex) for Linux // The mutual-exclusion semaphore is a specialized version of the binary // semaphore, designed to address issues inherent in mutual exclusion, such // as recursive access to resources, priority inversion, and deletion safety // The fundamental behavior of the mutual-exclusion semaphore is identical to // except for the following restrictions: it can only be used for mutual // exclusion and it can only be released by the task that acquired it. class OsMutexLinux : public OsMutexBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsMutexLinux(const unsigned options); //:Constructor virtual ~OsMutexLinux(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsStatus acquire(const OsTime& rTimeout = OsTime::OS_INFINITY); //:Block the task until the semaphore is acquired or the timeout expires virtual OsStatus tryAcquire(void); //:Conditionally acquire the mutex (i.e., don't block) // Return OS_BUSY if the mutex is held by some other task virtual OsStatus release(void); //:Release the semaphore /* ============================ ACCESSORS ================================= */ virtual void OsMutexShow(void); //:Print mutex information to the console. /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: pt_mutex_t mMutexImp; // Pingtel-Linux mutex OsMutexLinux(); //:Default constructor (not implemented for this class) OsMutexLinux(const OsMutexLinux& rOsMutexLinux); //:Copy constructor (not implemented for this class) OsMutexLinux& operator=(const OsMutexLinux& rhs); //:Assignment operator (not implemented for this class) }; /* ============================ INLINE METHODS ============================ */ #endif // _OsMutexLinux_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/OsPathLinux.h0000644000175000017500000000402412205613256025451 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsPathLinux_h_ #define _OsPathLinux_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsPathBase.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsPathBase; //:OS generic path class. Will massage any input string so separators are correct. //:Also provided functions to class OsPathLinux : public OsPathBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsPathLinux(); //:Default constructor OsPathLinux(const OsPathLinux& rOsPathLinux); //:Copy constructor virtual ~OsPathLinux(); //:Destructor OsPathLinux(const UtlString& rPath); //: Copy contructor OsPathLinux(const char* pPath); //: Construct OsPathLinux from char* OsPathLinux(const UtlString& rVolume, const UtlString& rDirName, const UtlString& rFileName, const UtlString& rExtension); //: Forms a OsPathLinux from discrete parts /* ============================ MANIPULATORS ============================== */ OsPathLinux& operator=(const OsPathLinux& rhs); //:Assignment operator /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _OsPathLinux_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/OsProcessIteratorLinux.h0000644000175000017500000000443612205613256027714 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsProcessIteratorLinux_h_ #define _OsProcessIteratorLinux_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsProcess.h" #include "os/OsProcessIterator.h" #include "os/OsFS.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsProcessBase; class OsProcessIteratorBase; //: Used to enumerate running processes class OsProcessIteratorLinux : OsProcessIteratorBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: friend class OsProcessLinux; /* ============================ CREATORS ================================== */ OsProcessIteratorLinux(); //:Default constructor OsProcessIteratorLinux(const char* filterExp); //:Return processes filtered by name virtual ~OsProcessIteratorLinux(); //:Destructor /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ OsStatus findFirst(OsProcess &rProcess); //: Start enumeration of running processes //: Returns OS_SUCCESS if found //: Returns OS_FAILED if none found. OsStatus findNext(OsProcess &rProcess); //: Continues enumeration of running processes //: Returns OS_SUCCESS if found //: Returns OS_FAILED if none found. /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsStatus readProcFile(OsPath &procDirname, OsProcess & rProcess); OsProcessLinux mProcess; int hProcessSnapshot; OsFileIterator *mpFileIterator; //:Last process found by this class }; /* ============================ INLINE METHODS ============================ */ #endif // _OsProcessIteratorLinux_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/OsProcessLinux.h0000644000175000017500000000730212205613256026175 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsProcessLinux_h_ #define _OsProcessLinux_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsProcess.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //: This encapsulates a pid, and allows querying, killing and all the //: other cool things you want to do to a process. class OsProcessLinux : public OsProcessBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsProcessLinux(); //:Default constructor virtual ~OsProcessLinux(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsStatus launch(UtlString &rAppName, UtlString parameters[], OsPath &startupDir, OsProcessPriorityClass prio = NormalPriorityClass, UtlBoolean bExeclusive = FALSE); //: Pass the appname and parameters to start the process //: Returns TRUE if process started ok. //: If bExclusive is TRUE and another process by the same name already //: is running the return is OS_FAILED virtual OsStatus kill(); //: Kills the process specified by pid virtual OsStatus setPriority(int prio); //: Changes the process priority. Must own the process for this to be legal. static OsStatus getByPID(PID pid, OsProcessLinux &rProcess); //: Given a PID, this method will fill in the process passed in so the user //: can then manipulate it virtual OsStatus setIORedirect(OsPath &rStdInputFilename, OsPath &rStdOutputFilename, OsPath &rStdErrorFilename); //: Sets the standard input, output and/or stderror /* ============================ ACCESSORS ================================= */ static PID getCurrentPID(); //: Returns the current process id. virtual OsStatus getPriority(int &rPrio); //: Returns the process priority. Must own the process for this to be legal. virtual OsStatus getPriorityClass(OsProcessPriorityClass &rPrioClass); //: Returns the Priority Class for this process. Priority is a function of the class. virtual OsStatus getMinPriority(int &rMinPrio); //: Returns the min priority base on which class is selected virtual OsStatus getMaxPriority(int &rMaxPrio); //: Returns the max priority base on which class is selected virtual OsStatus getInfo(OsProcessInfo &rProcessInfo); //: Returns full information on process, including priority. //: See OsProcessInfo for more information virtual OsStatus getUpTime(OsTime &rUpTime); //: How long has this process been runnign for? /* ============================ INQUIRY =================================== */ virtual UtlBoolean isRunning () const ; //: Returns TRUE if process is still active int wait(int WaitInSecs); //: waits n seconds for the process to terminate. //: if you pass 0 then it waits indefinately /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: static void cleanZombieProcess(int signal); //: Clean zombie child processes when they die }; /* ============================ INLINE METHODS ============================ */ #endif // _OsProcessLinux_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/OsRWMutexLinux.h0000644000175000017500000001000712205613256026126 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsRWMutexLinux_h_ #define _OsRWMutexLinux_h_ // SYSTEM INCLUDES #include #include // APPLICATION INCLUDES #include "os/OsRWMutex.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS #ifdef ANDROID // [ // Bionic's pthreads implementation does not provide support for RW-locks. // As a first attempt we simply replaced RW-locks with usual mutexes. // I think this way is good way to go, because RW-locks for ARM-based device // is an overkill. But if we discover any problems with this solution, we can // switch to our own RW-locks implementation in sipXportLib/src/shared/OsRWMutexShared.cpp. typedef pthread_mutex_t pthread_rwlock_t; # define pthread_rwlock_init pthread_mutex_init # define pthread_rwlock_destroy pthread_mutex_destroy # define pthread_rwlock_rdlock pthread_mutex_lock # define pthread_rwlock_wrlock pthread_mutex_lock # define pthread_rwlock_tryrdlock pthread_mutex_trylock # define pthread_rwlock_trywrlock pthread_mutex_trylock # define pthread_rwlock_unlock pthread_mutex_unlock #endif // ANDROID ] // FORWARD DECLARATIONS //:Mutual exclusion semaphore handling multiple readers and writers // Two kinds of concurrent tasks, called "readers" and "writers", share a // single resource. The readers can use the resource simultaneously, but each // writer must have exclusive access to it. When a writer is ready to use the // resource, it should be enabled to do so as soon as possible. class OsRWMutexLinux { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum QueueOptions { Q_FIFO = 0x0, // queue blocked tasks on a first-in, first-out basis Q_PRIORITY = 0x1 // queue blocked tasks based on their priority }; /* ============================ CREATORS ================================== */ /// Default constructor OsRWMutexLinux(const int queueOptions); /// Destructor ~OsRWMutexLinux(); /* ============================ MANIPULATORS ============================== */ OsStatus acquireRead(); //:Block (if necessary) until the task acquires the resource for reading // Multiple simultaneous readers are allowed. OsStatus acquireWrite(); //:Block (if necessary) until the task acquires the resource for writing // Only one writer at a time is allowed (and no readers). OsStatus tryAcquireRead(); //:Conditionally acquire the resource for reading (i.e., don't block) // Multiple simultaneous readers are allowed. // Return OS_BUSY if the resource is held for writing by some other task OsStatus tryAcquireWrite(); //:Conditionally acquire the resource for writing (i.e., don't block). // Only one writer at a time is allowed (and no readers). // Return OS_BUSY if the resource is held for writing by some other task // or if there are running readers. OsStatus releaseRead(); //:Release the resource for reading OsStatus releaseWrite(); //:Release the resource for writing /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: pthread_rwlock_t mLockImp; /// Copy constructor (not implemented for this class) OsRWMutexLinux(const OsRWMutexLinux& rhs); /// Assignment operator (not implemented for this class) OsRWMutexLinux& operator=(const OsRWMutexLinux& rhs); }; /* ============================ INLINE METHODS ============================ */ #endif // _OsRWMutexLinux_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/OsSharedLibMgrLinux.h0000644000175000017500000000531712205613256027066 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsSharedLibMgrLinux_h_ #define _OsSharedLibMgrLinux_h_ // SYSTEM INCLUDES //#include <...> // APPLICATION INCLUDES #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Class short description which may consist of multiple lines (note the ':') // Class detailed description which may extend to multiple lines class OsSharedLibMgrLinux : public OsSharedLibMgrBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ friend class OsSharedLibMgrBase; public: /* ============================ CREATORS ================================== */ virtual ~OsSharedLibMgrLinux(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsStatus loadSharedLib(const char* libName); //: Loads the given shared library //!param: libName - name of library, may include absolute or relative path virtual OsStatus getSharedLibSymbol(const char* libName, const char* symbolName, void*& symbolAddress); //: Gets the address of a symbol in the shared lib //!param: (in) libName - name of library, may include absolute or relative path //!param: (in) symbolName - name of the variable or function exported in the shared lib //!param: (out) symbolAddress - the address of the function or variable virtual OsStatus unloadSharedLib(const char* libName); //: Unloads the given shared library // Before unloading library make sure that no one else use it! //!param: libName - name of library, may include absolute or relative path /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsSharedLibMgrLinux(); //:Default constructor disallowed, use getOsSharedLibMgr /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsSharedLibMgrLinux(const OsSharedLibMgrLinux& rOsSharedLibMgrLinux); //:Copy constructor OsSharedLibMgrLinux& operator=(const OsSharedLibMgrLinux& rhs); //:Assignment operator }; /* ============================ INLINE METHODS ============================ */ #endif // _OsSharedLibMgrLinux_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/OsTaskLinux.h0000644000175000017500000002645212205617431025467 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsTaskLinux_h_ #define _OsTaskLinux_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsMutex.h" #include "os/OsRWMutex.h" #include "os/OsStatus.h" #include "os/OsTask.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsTime; //:Task abstraction for Linux // A task represents a thread of execution. All tasks run within the same // address space but have their own stack and program counter. Tasks may be // created and deleted dynamically. // // Users create tasks by: // 1) Deriving a new class based on OsTask or one of its descendants, // and overriding the run() method in the derived class. // 2) Calling the constructor for the derived class. // 3) Invoking the start() method for the derived class. This creates the // corresponding low-level OS task and associates it with the class. // // Note: Many of the methods in this class are only applicable once the // start() method for the object has been called and the corresponding // low-level task has been created. Accordingly, before a successful call // to start(), most of the methods in this class return the // OS_TASK_NOT_STARTED status. class OsTaskLinux : public OsTaskBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum LinuxPriorities { RT_NO = 0, // Non-realtime priority, does not use realtime scheduling RT_LOW = 1, // Lowest realtime priority RT_NORMAL = 2, RT_HIGH = 3, RT_HIGHEST = 4 // Highest realtime priority }; /* ============================ CREATORS ================================== */ OsTaskLinux(const UtlString& name="", void* pArg=NULL, const int priority=DEF_PRIO, const int options=DEF_OPTIONS, const int stackSize=DEF_STACKSIZE); //:Constructor virtual ~OsTaskLinux(); //:Destructor -- delete the task virtual OsStatus deleteForce(void); //:Delete the task even if the task is protected from deletion // After calling this method, the user will still need to delete the // corresponding OsTask object to reclaim its storage. /* ============================ MANIPULATORS ============================== */ virtual UtlBoolean restart(void); //:Restart the task // The task is first terminated, and then reinitialized with the same // name, priority, options, stack size, original entry point, and // parameters it had when it was terminated. // Return TRUE if the restart of the task is successful. virtual OsStatus resume(void); //:Resume the task // This routine resumes the task. The task suspension is cleared, and // the task operates in the remaining state. virtual int run(void* pArg) = 0; //:The entry point for the task. // Derive new tasks as subclasses of OsTask, overriding this method. virtual UtlBoolean start(void); //:Spawn a new task and invoke its run() method. // Return TRUE if the spawning of the new task is successful. // Return FALSE if the task spawn fails or if the task has already // been started. virtual OsStatus suspend(void); //:Suspend the task // This routine suspends the task. Suspension is additive: thus, tasks // can be delayed and suspended, or pended and suspended. Suspended, // delayed tasks whose delays expire remain suspended. Likewise, // suspended, pended tasks that unblock remain suspended only. virtual OsStatus setErrno(int errno); //:Set the errno status for the task virtual OsStatus setOptions(int options); //:Set the execution options for the task // The only option that can be changed after a task has been created // is whether to allow breakpoint debugging. virtual OsStatus setPriority(int priority); //:Set the priority of the task // Priorities range from 0, the highest priority, to 255, the lowest // priority. virtual OsStatus varAdd(int* pVar); //:Add a task variable to the task // This routine adds a specified variable pVar (4-byte memory // location) to its task's context. After calling this routine, the // variable is private to the task. The task can access and modify // the variable, but the modifications are not visible to other tasks, // and other tasks' modifications to that variable do not affect the // value seen by the task. This is accomplished by saving and restoring // the variable's value each time a task switch occurs to or from the // calling task. virtual OsStatus varDelete(int* pVar); //:Remove a task variable from the task // This routine removes a specified task variable, pVar, from its // task's context. The private value of that variable is lost. virtual OsStatus varSet(int* pVar, int value); //:Set the value of a private task variable // This routine sets the private value of the task variable for a // specified task. The specified task is usually not the calling task, // which can set its private value by directly modifying the variable. // This routine is provided primarily for debugging purposes. static OsStatus delay(const int milliSecs); //:Delay a task from executing for the specified number of milliseconds // This routine causes the calling task to relinquish the CPU for the // duration specified. This is commonly referred to as manual // rescheduling, but it is also useful when waiting for some external // condition that does not have an interrupt associated with it. static OsStatus safe(void); //:Make the calling task safe from deletion // This routine protects the calling task from deletion. Tasks that // attempt to delete a protected task will block until the task is // made unsafe, using unsafe(). When a task becomes unsafe, the // deleter will be unblocked and allowed to delete the task. // The safe() primitive utilizes a count to keep track of // nested calls for task protection. When nesting occurs, // the task becomes unsafe only after the outermost unsafe() // is executed. static OsStatus unsafe(void); //:Make the calling task unsafe from deletion // This routine removes the calling task's protection from deletion. // Tasks that attempt to delete a protected task will block until the // task is unsafe. When a task becomes unsafe, the deleter will be // unblocked and allowed to delete the task. // The unsafe() primitive utilizes a count to keep track of nested // calls for task protection. When nesting occurs, the task becomes // unsafe only after the outermost unsafe() is executed. static void yield(void); //:Yield the CPU if a task of equal or higher priority is ready to run. /* ============================ ACCESSORS ================================= */ static OsTaskLinux* getCurrentTask(void); //:Return a pointer to the OsTask object for the currently executing task // Return NULL if none exists. static OsStatus getCurrentTaskId(OsTaskId_t &rid); //:Return an Id of the currently executing task static OsTaskLinux* getTaskByName(const UtlString& taskName); //:Return a pointer to the OsTask object corresponding to the named task // Return NULL if there is no task object with that name. static OsTaskLinux* getTaskById(const pthread_t taskId); //:Return a pointer to the OsTask object corresponding to taskId // Return NULL is there is no task object with that id. virtual OsStatus getErrno(int& rErrno); //:Get the errno status for the task virtual int getOptions(void); //:Return the execution options for the task virtual OsStatus getPriority(int& rPriority); //:Return the priority of the task virtual OsStatus varGet(void); //:Get the value of a task variable // This routine returns the private value of a task variable for its // task. The task is usually not the calling task, which can get its // private value by directly accessing the variable. This routine is // provided primarily for debugging purposes. static void getIdString_d(UtlString&, OsTaskId_t); static void getIdString_x(UtlString&, OsTaskId_t); static void getIdString_X(UtlString&, OsTaskId_t); //: Relatively portable way to do what was being done wrong before. /* ============================ INQUIRY =================================== */ virtual OsStatus id(OsTaskId_t &rId); //:Get the task ID for this task virtual UtlBoolean isSuspended(void); //:Check if the task is suspended // Return TRUE is the task is suspended, otherwise FALSE. /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsTaskId_t mTaskId; // Linux unique ID for task OsRWMutex mDeleteGuard; // RWMutex guard to prevent unwanted task deletion int mSuspendCnt; // Counts the nesting level of suspend() calls pthread_mutex_t mStartupSyncMutex; // Mutex, used with next two conditional // variables to synchronize thread startup. pthread_cond_t mTaskInitializedEvent; // Conditional variable, signaling // that this OsTask object initialization is completed // and thread could go on. pthread_cond_t mTaskStartedEvent; // Conditional variable, signaling // that thread is started and doLinuxCreateTask() could // return to caller. enum { OS_TASK_THREAD_STARTUP_TIMEOUT=5 // Time to wait for thread startup // (in seconds). }; // saved initialization information (used for task restarts) int mOptions; int mPriority; int mStackSize; UtlBoolean doLinuxCreateTask(const char* pTaskName); //:Do the real work associated with creating a new Linux task. // The mDataGuard lock should be held upon entry into this method. // // This method is blocking. It finishes only when thread is really // started up. This is needed to avoid bad racing conditions. E.g. // when thread may be stopped before really started, causing deadlock. void doLinuxTerminateTask(UtlBoolean doForce); //:Do the real work associated with terminating a Linux task. // The mDataGuard lock should be held upon entry into this method. /** * taskUnregister * remove mapping from the OsNameDb for this thread id */ void taskUnregister(void); static void * taskEntry(void* arg); //:Function that serves as the starting address for a Linux task OsTaskLinux(const OsTaskLinux& rOsTaskLinux); //:Copy constructor (not implemented for this class) OsTaskLinux& operator=(const OsTaskLinux& rhs); //:Assignment operator (not implemented for this class) }; /* ============================ INLINE METHODS ============================ */ #endif // _OsTaskLinux_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/OsUtilLinux.h0000644000175000017500000000546012205613256025477 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsUtilLinux_h_ #define _OsUtilLinux_h_ // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsTime.h" #include "os/linux/OsLinuxDefs.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS typedef void (*sighandler_t)(int); // FORWARD DECLARATIONS //:Static methods that are useful when running on top of Linux class OsUtilLinux { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ static int cvtOsPrioToLinuxPrio(const int osPrio); //:Convert an abstraction layer task priority to a Linux task priority static int cvtOsPrioToLinuxRtPrio(const int osPrio); //:Convert an abstraction layer task priority to a Linux task priority static int cvtLinuxPrioToOsPrio(const int linuxPrio); //:Convert a Linux task priority to an abstraction layer task priority static void cvtOsTimeToTimespec(OsTime time1, struct timespec * time2); //:Convert an OsTime class relative to the current time to a struct // timespec relative to epoch static sighandler_t signal(int signum, sighandler_t handler); //:Replacement for ::signal() that works better /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsUtilLinux(); //:Default constructor (not implemented for this class) // We identify this as a protected method so that gcc doesn't complain // that the class only defines a private constructor and has no friends. virtual ~OsUtilLinux(); //:Destructor (not implemented for this class) // We identify this as a protected method so that gcc doesn't complain // that the class only defines a private destructor and has no friends. /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsUtilLinux(const OsUtilLinux& rOsUtilLinux); //:Copy constructor (not implemented for this class) OsUtilLinux& operator=(const OsUtilLinux& rhs); //:Assignment operator (not implemented for this class) }; /* ============================ INLINE METHODS ============================ */ #endif // _OsUtilLinux_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/pt_csem.h0000644000175000017500000000521112205613256024664 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// /* SIPX_USE_NATIVE_PTHREADS define enable use of standard pthread implementation * of synchonization primitives instead of sipX re-implementation of them. This * re-implementation was created to work around the fact that the LinuxThreads * implementation of pthreads did not have a timed version of semaphore wait * (sem_timedwait()). These days NPTL is widely adopted, thus solving this * problem more efficiently. So, if you're not forced to use a pthreads * implementation without sem_timedwait() (e.g. on OS X) it is better to * define SIPX_USE_NATIVE_PTHREADS. * See the original comment about the sipX implementation below #else. */ #ifndef _PT_CSEM_H #define _PT_CSEM_H #if !defined(__APPLE__) && !defined(ANDROID) /* Also see pt_mutex.h */ #define SIPX_USE_NATIVE_PTHREADS //#undef SIPX_USE_NATIVE_PTHREADS #endif #ifdef SIPX_USE_NATIVE_PTHREADS // [ #include #define pt_sem_t sem_t #define pt_sem_init(sem, max, count) sem_init((sem), 0, (count)) #define pt_sem_wait(sem) sem_wait((sem)) #define pt_sem_timedwait(sem, timeout) sem_timedwait((sem), (timeout)) #define pt_sem_trywait(sem) sem_trywait((sem)) #define pt_sem_post(sem) sem_post((sem)) #define pt_sem_getvalue(sem) sem_getvalue((sem)) #define pt_sem_destroy(sem) sem_destroy((sem)) #else // SIPX_USE_NATIVE_PTHREADS ][ /* The default LinuxThreads implementation does not have support for timing * out while waiting for a synchronization object. Since I've already ported * the rest of the OS dependent files to that interface, we can just drop in a * mostly-compatible replacement written in C (like pthreads itself) that uses * the pthread_cond_timedwait function and a mutex to build all the other * synchronization objecs with timeout capabilities. */ #include #ifdef __cplusplus extern "C" { #endif typedef struct pt_sem { unsigned int count; unsigned int max; pthread_mutex_t mutex; pthread_cond_t cond; } pt_sem_t; int pt_sem_init(pt_sem_t *sem, unsigned int max, unsigned int count); int pt_sem_wait(pt_sem_t *sem); int pt_sem_timedwait(pt_sem_t *sem,const struct timespec *timeout); int pt_sem_trywait(pt_sem_t *sem); int pt_sem_post(pt_sem_t *sem); int pt_sem_getvalue(pt_sem_t *sem); int pt_sem_destroy(pt_sem_t *sem); #ifdef __cplusplus } #endif #endif // SIPX_USE_NATIVE_PTHREADS ] #endif /* _PT_CSEM_H */ sipxtapi-3.3.0~test17/sipXportLib/include/os/linux/pt_mutex.h0000644000175000017500000000600012205613256025074 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// /* SIPX_USE_NATIVE_PTHREADS define enable use of standard pthread implementation * of synchonization primitives instead of sipX re-implementation of them. This * re-implementation was created to work around the fact that the LinuxThreads * implementation of pthreads did not have a timed version of semaphore wait * (sem_timedwait()). These days NPTL is widely adopted, thus solving this * problem more efficiently. So, if you're not forced to use a pthreads * implementation without sem_timedwait() (e.g. on OS X) it is better to * define SIPX_USE_NATIVE_PTHREADS. * See the original comment about the sipX implementation below #else. */ #ifndef _PT_MUTEX_H #define _PT_MUTEX_H #if !defined(__APPLE__) && !defined(ANDROID) /* Also see pt_csem.h */ #define SIPX_USE_NATIVE_PTHREADS //#undef SIPX_USE_NATIVE_PTHREADS #endif #include #ifdef SIPX_USE_NATIVE_PTHREADS // [ #define pt_mutex_t pthread_mutex_t #if defined(__linux__) && !defined(PTHREAD_MUTEX_RECURSIVE) # define PTHREAD_MUTEX_RECURSIVE PTHREAD_MUTEX_RECURSIVE_NP #endif //#define pt_mutex_init(mutex) pthread_mutex_init((mutex), NULL) static inline int pt_mutex_init(pthread_mutex_t *mutex) { pthread_mutexattr_t a; pthread_mutexattr_init(&a); pthread_mutexattr_settype(&a,PTHREAD_MUTEX_RECURSIVE); return pthread_mutex_init(mutex, &a); } #define pt_mutex_lock(mutex) pthread_mutex_lock((mutex)) #define pt_mutex_timedlock(mutex, timeout) pthread_mutex_timedlock((mutex), (timeout)) #define pt_mutex_trylock(mutex) pthread_mutex_trylock((mutex)) #define pt_mutex_unlock(mutex) pthread_mutex_unlock((mutex)) #define pt_mutex_destroy(mutex) pthread_mutex_destroy((mutex)) #else // SIPX_USE_NATIVE_PTHREADS ][ /* The default LinuxThreads implementation does not have support for timing * out while waiting for a synchronization object. Since I've already ported * the rest of the OS dependent files to that interface, we can just drop in a * mostly-compatible replacement written in C (like pthreads itself) that uses * the pthread_cond_timedwait function and a mutex to build all the other * synchronization objecs with timeout capabilities. */ #ifdef __cplusplus extern "C" { #endif typedef struct pt_mutex { unsigned int count; pthread_t thread; pthread_mutex_t mutex; pthread_cond_t cond; } pt_mutex_t; void dumpPtMutex(pt_mutex_t* mutex); int pt_mutex_init(pt_mutex_t *mutex); int pt_mutex_lock(pt_mutex_t *mutex); int pt_mutex_timedlock(pt_mutex_t *mutex,const struct timespec *timeout); int pt_mutex_trylock(pt_mutex_t *mutex); int pt_mutex_unlock(pt_mutex_t *mutex); int pt_mutex_destroy(pt_mutex_t *mutex); #ifdef __cplusplus } #endif #endif // SIPX_USE_NATIVE_PTHREADS ] #endif /* _PT_MUTEX_H */ sipxtapi-3.3.0~test17/sipXportLib/include/os/shared/0000755000175000017500000000000012321445025023165 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/include/os/shared/OsMsgQShared.h0000644000175000017500000001445012205613256025646 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsMsgQShared_h_ #define _OsMsgQShared_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsCSem.h" #include "os/OsDefs.h" #include "os/OsMsg.h" #include "os/OsMsgQ.h" #include "os/OsMutex.h" #include "os/OsTime.h" #include "utl/UtlDList.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS class UtlString; // FORWARD DECLARATIONS // #define OS_MSGQ_DEBUG // #define OS_MSGQ_REPORTING // debug class class DebugMutex { public: DebugMutex(OsMutex& mutex, const char* label) { printf("DebugMutex %s:\n", label); mutex.OsMutexShow(); }; private: DebugMutex(); }; /** * Message queue implementation for OS's with no native message queue support * * Two kinds of concurrent tasks, called "senders" and "receivers", * communicate using a message queue. When the queue is empty, receivers are * blocked until there are messages to receive. When the queue is full, * senders are blocked until some of the queued messages are received -- * freeing up space in the queue for more messages. * * This implementation is based on the description from the book "Operating * Systems Principles" by Per Brinch Hansen, 1973. This solution uses: *
*    - a counting semaphore (mEmpty) to control the delay of the sender in
*      the following way:
*        initially:      the "empty" semaphore count is set to maxMsgs
*        before send:    acquire(empty)
*        after receive:  release(empty)
*    - a counting semaphore (mFull) to control the delay of the receiver in
*      the following way:
*        initially:      the "full" semaphore count is set to 0
*        before receive: acquire(full)
*        after send:     release(full)
*    - a binary semaphore (mGuard) to ensure against concurrent access to
*      internal object data
*  
*/ class OsMsgQShared : public OsMsgQBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /// Constructor OsMsgQShared( const int maxMsgs=DEF_MAX_MSGS, ///< Max number of messages. const int maxMsgLen=DEF_MAX_MSG_LEN, ///< Max msg length (bytes). const int options=Q_PRIORITY, ///< How to queue blocked tasks. const UtlString& name="" ///< Global name for this queue. ); /**< * If name is specified but is already in use, throw an exception. */ /// Destructor virtual ~OsMsgQShared(); /* ============================ MANIPULATORS ============================== */ /// @copydoc OsMsgQBase::send() virtual OsStatus send(const OsMsg& rMsg, const OsTime& rTimeout=OsTime::OS_INFINITY); /// @copydoc OsMsgQBase::sendNoCopy() virtual OsStatus sendNoCopy(OsMsg *pMsg, const OsTime& rTimeout=OsTime::OS_INFINITY); /// @copydoc OsMsgQBase::sendUrgent() virtual OsStatus sendUrgent(const OsMsg& rMsg, const OsTime& rTimeout=OsTime::OS_INFINITY); /// @copydoc OsMsgQBase::sendFromISR() virtual OsStatus sendFromISR(OsMsg& rMsg); /// @copydoc OsMsgQBase::receive() virtual OsStatus receive(OsMsg*& rpMsg, const OsTime& rTimeout=OsTime::OS_INFINITY); /* ============================ ACCESSORS ================================= */ #ifdef OS_MSGQ_DEBUG int getFullCount() { return mFull.getValue();} int getEmptyCount() { return mEmpty.getValue();} UtlDList& getList() { return mDlist;} #endif /// @copydoc OsMsgQBase::numMsgs() virtual int numMsgs(); #ifdef MSGQ_IS_VALID_CHECK /// Print information on the message queue to the console virtual void show(); #endif /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: #ifdef MSGQ_IS_VALID_CHECK virtual void testMessageQ(); #endif /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsMutex mGuard; ///< Mutex used to synchronize access to the msg queue. OsCSem mEmpty; ///< Counting semaphore used to coordinate sending msgs to ///< the queue and blocking senders to keep the number ///< of messages less than or equal to maxMsgs. OsCSem mFull; ///< Counting semaphore used to coordinate receiving msgs ///< from the queue and blocking receivers when there are ///< no messages to receive. UtlDList mDlist; ///< Doubly-linked list used to store messages. #ifdef MSGQ_IS_VALID_CHECK int mOptions; ///< Message queue options. int mHighCnt; ///< High water mark for the number of msgs in the queue. #endif #ifdef OS_MSGQ_REPORTING int mIncreaseLevel; ///< Emit a message to the log when the number ///< of messages reaches the mIncreaseLevel. int mDecreaseLevel; ///< Emit a message to the log when the number ///< of messages goes below the mDecreaseLevel. int mIncrementLevel; ///< When the mIncreaseLevel or mDecreaseLevels ///< are reached, increment/decrement the level ///< by mIncrementLevel. #endif /// Helper function for sending messages OsStatus doSend(const OsMsg& rMsg, const OsTime& rTimeout, const UtlBoolean isUrgent, const UtlBoolean needCopy); /// Helper function for removing a message from the head of the queue OsStatus doReceive(OsMsg*& rpMsg, const OsTime& rTimeout); /// Copy constructor (not implemented for this class) OsMsgQShared(const OsMsgQShared& rOsMsgQShared); /// Assignment operator (not implemented for this class) OsMsgQShared& operator=(const OsMsgQShared& rhs); }; /* ============================ INLINE METHODS ============================ */ #endif // _OsMsgQShared_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/shared/OsTimerMessage.h0000644000175000017500000000572012205613256026235 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsTimerMessage_h_ #define _OsTimerMessage_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsBSem.h" #include "os/OsTimer.h" #include "os/OsMsg.h" #include "os/OsStatus.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Message used to send timer operation requests class OsTimerMessage : public OsMsg { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum MsgSubType { UNSPECIFIED, // Not yet initialized ADD, // Add a new timer REMOVE, // Remove an existing timer SHUTDOWN // Shutdown the timer thread }; //!enumcode: UNSPECIFIED - not yet initialized //!enumcode: ADD - add a new timer. //!enumcode: REMOVE - remove an existing timer //!enumcode: SHUTDOWN - shutdown the timer thread /* ============================ CREATORS ================================== */ OsTimerMessage(OsTimer* pTimer, OsBSem* pSem); //:Constructor for ADD messages OsTimerMessage(int ID, OsBSem* pSem); //:Constructor for REMOVE messages OsTimerMessage(OsBSem* pSem); //:Constructor for SHUTDOWN messages OsTimerMessage(const OsTimerMessage& rOsTimerMessage); //:Copy constructor virtual OsMsg* createCopy(void) const; //:Create a copy of this msg object (which may be of a derived type) virtual ~OsTimerMessage(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsTimerMessage& operator=(const OsTimerMessage& rhs); //:Assignment operator /* ============================ ACCESSORS ================================= */ virtual int getMsgSize(void) const; //:Return the size of the message in bytes // This is a virtual method so that it will return the accurate size for // the message object even if that object has been upcast to the type of // an ancestor class. int getTimerID(void); //:Get the timer ID (for REMOVE messages) OsTimer* getTimer(void); //:Get the OsTimer (for ADD messages) OsBSem* getSynchSem(void); //:Get the synchronization semaphore (for ADD and REMOVE messages) /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: int mID; OsTimer* mpTimer; OsBSem* mpSynchSem; }; /* ============================ INLINE METHODS ============================ */ #endif // _OsTimerMessage_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/0000755000175000017500000000000012321445025022527 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/getWindowsDNSServers.h0000644000175000017500000001774512205613256026773 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef getWindowsDNSServers_h_ #define getWindowsDNSServers_h_ #ifdef WIN32 #define MAXIPLEN 40 #include #include #ifdef __cplusplus # include #endif // Definitions and structures used by getnetworkparams and getadaptersinfo apis #define MAX_ADAPTER_DESCRIPTION_LENGTH 128 // arb. #define MAX_ADAPTER_NAME_LENGTH 256 // arb. #define MAX_ADAPTER_ADDRESS_LENGTH 8 // arb. #define DEFAULT_MINIMUM_ENTITIES 32 // arb. #define MAX_HOSTNAME_LEN 128 // arb. #define MAX_DOMAIN_NAME_LEN 128 // arb. #define MAX_SCOPE_ID_LEN 256 // arb. #define MAX_ADAPTER_NAME 128 // // types // // Node Type #define BROADCAST_NODETYPE 1 #define PEER_TO_PEER_NODETYPE 2 #define MIXED_NODETYPE 4 #define HYBRID_NODETYPE 8 // Adapter Type #define IF_OTHER_ADAPTERTYPE 0 #define IF_ETHERNET_ADAPTERTYPE 1 #define IF_TOKEN_RING_ADAPTERTYPE 2 #define IF_FDDI_ADAPTERTYPE 3 #define IF_PPP_ADAPTERTYPE 4 #define IF_LOOPBACK_ADAPTERTYPE 5 #define IF_SLIP_ADAPTERTYPE 6 typedef enum { IfOperStatusUp = 1, IfOperStatusDown, IfOperStatusTesting, IfOperStatusUnknown, IfOperStatusDormant, IfOperStatusNotPresent, IfOperStatusLowerLayerDown } IF_OPER_STATUS; // // IP_ADDRESS_STRING - store an IP address as a dotted decimal string // typedef struct { char String[4 * 4]; } IP_ADDRESS_STRING, *PIP_ADDRESS_STRING, IP_MASK_STRING, *PIP_MASK_STRING; // // IP_ADDR_STRING - store an IP address with its corresponding subnet mask, // both as dotted decimal strings // typedef struct _IP_ADDR_STRING { struct _IP_ADDR_STRING* Next; IP_ADDRESS_STRING IpAddress; IP_MASK_STRING IpMask; DWORD Context; } IP_ADDR_STRING, *PIP_ADDR_STRING; // // ADAPTER_INFO - per-adapter information. All IP addresses are stored as // strings // typedef struct _IP_ADAPTER_INFO { struct _IP_ADAPTER_INFO* Next; DWORD ComboIndex; char AdapterName[MAX_ADAPTER_NAME_LENGTH + 4]; char Description[MAX_ADAPTER_DESCRIPTION_LENGTH + 4]; UINT AddressLength; BYTE Address[MAX_ADAPTER_ADDRESS_LENGTH]; DWORD Index; UINT Type; UINT DhcpEnabled; PIP_ADDR_STRING CurrentIpAddress; IP_ADDR_STRING IpAddressList; IP_ADDR_STRING GatewayList; IP_ADDR_STRING DhcpServer; BOOL HaveWins; IP_ADDR_STRING PrimaryWinsServer; IP_ADDR_STRING SecondaryWinsServer; time_t LeaseObtained; time_t LeaseExpires; } IP_ADAPTER_INFO, *PIP_ADAPTER_INFO; // // IP_PER_ADAPTER_INFO - per-adapter IP information such as DNS server list. // typedef struct _IP_PER_ADAPTER_INFO { UINT AutoconfigEnabled; UINT AutoconfigActive; PIP_ADDR_STRING CurrentDnsServer; IP_ADDR_STRING DnsServerList; } IP_PER_ADAPTER_INFO, *PIP_PER_ADAPTER_INFO; // // FIXED_INFO - the set of IP-related information which does not depend on DHCP // typedef enum { IpPrefixOriginOther = 0, IpPrefixOriginManual, IpPrefixOriginWellKnown, IpPrefixOriginDhcp, IpPrefixOriginRouterAdvertisement } IP_PREFIX_ORIGIN; typedef enum { IpSuffixOriginOther = 0, IpSuffixOriginManual, IpSuffixOriginWellKnown, IpSuffixOriginDhcp, IpSuffixOriginLinkLayerAddress, IpSuffixOriginRandom } IP_SUFFIX_ORIGIN; typedef enum { IpDadStateInvalid = 0, IpDadStateTentative, IpDadStateDuplicate, IpDadStateDeprecated, IpDadStatePreferred } IP_DAD_STATE; typedef struct SOCKET_ADDRESS_XYZ { LPSOCKADDR lpSockaddr ; INT iSockaddrLength ; } SOCKET_ADDRESS_XYZ, *PSOCKET_ADDRESS_XYZ, FAR * LPSOCKET_ADDRESS_XYZ ; typedef struct _IP_ADAPTER_UNICAST_ADDRESS { union { ULONGLONG Alignment; struct { ULONG Length; DWORD Flags; }; }; struct _IP_ADAPTER_UNICAST_ADDRESS *Next; SOCKET_ADDRESS_XYZ Address; IP_PREFIX_ORIGIN PrefixOrigin; IP_SUFFIX_ORIGIN SuffixOrigin; IP_DAD_STATE DadState; ULONG ValidLifetime; ULONG PreferredLifetime; ULONG LeaseLifetime; } IP_ADAPTER_UNICAST_ADDRESS, *PIP_ADAPTER_UNICAST_ADDRESS; typedef struct _IP_ADAPTER_ANYCAST_ADDRESS { union { ULONGLONG Alignment; struct { ULONG Length; DWORD Flags; }; }; struct _IP_ADAPTER_ANYCAST_ADDRESS *Next; SOCKET_ADDRESS_XYZ Address; } IP_ADAPTER_ANYCAST_ADDRESS, *PIP_ADAPTER_ANYCAST_ADDRESS; typedef struct _IP_ADAPTER_MULTICAST_ADDRESS { union { ULONGLONG Alignment; struct { ULONG Length; DWORD Flags; }; }; struct _IP_ADAPTER_MULTICAST_ADDRESS *Next; SOCKET_ADDRESS_XYZ Address; } IP_ADAPTER_MULTICAST_ADDRESS, *PIP_ADAPTER_MULTICAST_ADDRESS; typedef struct { char HostName[MAX_HOSTNAME_LEN + 4] ; char DomainName[MAX_DOMAIN_NAME_LEN + 4]; PIP_ADDR_STRING CurrentDnsServer; IP_ADDR_STRING DnsServerList; UINT NodeType; char ScopeId[MAX_SCOPE_ID_LEN + 4]; UINT EnableRouting; UINT EnableProxy; UINT EnableDns; } FIXED_INFO, *PFIXED_INFO; typedef struct _IP_ADAPTER_DNS_SERVER_ADDRESS { union { ULONGLONG Alignment; struct { ULONG Length; DWORD Reserved; }; }; struct _IP_ADAPTER_DNS_SERVER_ADDRESS *Next; SOCKET_ADDRESS_XYZ Address; } IP_ADAPTER_DNS_SERVER_ADDRESS, *PIP_ADAPTER_DNS_SERVER_ADDRESS; typedef struct _IP_ADAPTER_PREFIX { union { ULONGLONG Alignment; struct { ULONG Length; DWORD Flags; }; }; struct _IP_ADAPTER_PREFIX *Next; SOCKET_ADDRESS_XYZ Address; ULONG PrefixLength; } IP_ADAPTER_PREFIX, *PIP_ADAPTER_PREFIX; typedef struct _IP_ADAPTER_ADDRESSES { union { ULONGLONG Alignment; struct { ULONG Length; DWORD IfIndex; }; }; struct _IP_ADAPTER_ADDRESSES *Next; PCHAR AdapterName; PIP_ADAPTER_UNICAST_ADDRESS FirstUnicastAddress; PIP_ADAPTER_ANYCAST_ADDRESS FirstAnycastAddress; PIP_ADAPTER_MULTICAST_ADDRESS FirstMulticastAddress; PIP_ADAPTER_DNS_SERVER_ADDRESS FirstDnsServerAddress; PWCHAR DnsSuffix; PWCHAR Description; PWCHAR FriendlyName; BYTE PhysicalAddress[MAX_ADAPTER_ADDRESS_LENGTH]; DWORD PhysicalAddressLength; DWORD Flags; DWORD Mtu; DWORD IfType; IF_OPER_STATUS OperStatus; DWORD Ipv6IfIndex; DWORD ZoneIndices[16]; PIP_ADAPTER_PREFIX FirstPrefix; } IP_ADAPTER_ADDRESSES, *PIP_ADAPTER_ADDRESSES; typedef struct _IP_ADAPTER_INDEX_MAP { ULONG Index; WCHAR Name[MAX_ADAPTER_NAME]; } IP_ADAPTER_INDEX_MAP, *PIP_ADAPTER_INDEX_MAP; typedef struct _IP_INTERFACE_INFO { LONG NumAdapters; IP_ADAPTER_INDEX_MAP Adapter[1]; } IP_INTERFACE_INFO,*PIP_INTERFACE_INFO; #ifdef __cplusplus extern "C" int getWindowsDNSServers(char DNSServers[][MAXIPLEN], int max, const char* szLocalIp); /// Get this host's IP addresses. extern "C" bool getAllLocalHostIps(const class HostAdapterAddress* localHostAddresses[], int &numAddresses); /**< * @param localHostAddresses Preallocated array for determined IP addresses. * @param numAddresses Input: Size of the preallocated array. * Output: Number of IPs found by the system. */ extern "C" bool getContactAdapterName(UtlString &adapterName, const UtlString &ipAddress, bool trueName); //: Returns a generated adapter name associated with the IP address #else int getWindowsDNSServers(char DNSServers[][MAXIPLEN], int max, const char* szLocalIp); #endif #endif //WIN32 #endif // getWindowsDNSServers_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/OsBSemWnt.h0000644000175000017500000000444712205613256024536 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsBSemWnt_h_ #define _OsBSemWnt_h_ // SYSTEM INCLUDES #define WIN32_LEAN_AND_MEAN #include // APPLICATION INCLUDES #include "os/OsBSem.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS typedef HANDLE WinSemaphore; // FORWARD DECLARATIONS //:Binary semaphore for Windows NT class OsBSemWnt : public OsBSemBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsBSemWnt(const int queueOptions, const int initState); //:Constructor virtual ~OsBSemWnt(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsStatus acquire(const OsTime& rTimeout = OsTime::OS_INFINITY); //:Block the task until the semaphore is acquired or the timeout expires virtual OsStatus tryAcquire(void); //:Conditionally acquire the semaphore (i.e., don't block) // Return OS_BUSY if the semaphore is held by some other task virtual OsStatus release(void); //:Release the semaphore /* ============================ ACCESSORS ================================= */ virtual void OsBSemShow(void); //:Print semaphore information to the console /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: WinSemaphore mSemImp; // Windows NT semaphore OsBSemWnt(); //:Default constructor (not implemented for this class) OsBSemWnt(const OsBSemWnt& rOsBSemWnt); //:Copy constructor (not implemented for this class) OsBSemWnt& operator=(const OsBSemWnt& rhs); //:Assignment operator (not implemented for this class) }; /* ============================ INLINE METHODS ============================ */ #endif // _OsBSemWnt_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/OsCSemWnt.h0000644000175000017500000000500112205613256024522 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsCSemWnt_h_ #define _OsCSemWnt_h_ // SYSTEM INCLUDES #define WIN32_LEAN_AND_MEAN #include // APPLICATION INCLUDES #include "os/OsCSem.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS typedef HANDLE WinSemaphore; // FORWARD DECLARATIONS //:Counting semaphore for Windows NT class OsCSemWnt : public OsCSemBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsCSemWnt(const int queueOptions, const int maxCount); //:Constructor setting the initial and max semaphore values to maxCount OsCSemWnt(const int queueOptions, const int maxCount, const int initCount); //:Constructor allowing different initial and maximum semaphore values virtual ~OsCSemWnt(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsStatus acquire(const OsTime& rTimeout = OsTime::OS_INFINITY); //:Block the task until the semaphore is acquired or the timeout expires virtual OsStatus tryAcquire(void); //:Conditionally acquire the semaphore (i.e., don't block) // Return OS_BUSY if the semaphore is held by some other task virtual OsStatus release(void); //:Release the semaphore /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: WinSemaphore mSemImp; // Windows NT semaphore OsCSemWnt(); //:Default constructor (not implemented for this class) OsCSemWnt(const OsCSemWnt& rOsCSemWnt); //:Copy constructor (not implemented for this class) OsCSemWnt& operator=(const OsCSemWnt& rhs); //:Assignment operator (not implemented for this class) void init(void); //:Common initialization shared by all (non-copy) constructors }; /* ============================ INLINE METHODS ============================ */ #endif // _OsCSemWnt_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/OsDateTimeWnt.h0000644000175000017500000000653212205613256025401 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsDateTimeWnt_h_ #define _OsDateTimeWnt_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsDateTime.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:DateTime management functions for Windows NT class OsDateTimeWnt : public OsDateTimeBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsDateTimeWnt(); //:Default constructor OsDateTimeWnt(const unsigned short year, const unsigned char month, const unsigned char day, const unsigned char hour, const unsigned char minute, const unsigned char second, const unsigned int microsecond); //:Constructor OsDateTimeWnt(const OsDateTimeWnt& rOsDateTimeWnt); //:Copy constructor /// Convert an OsTime to an OsDateTime OsDateTimeWnt(const OsTime& toTime); virtual ~OsDateTimeWnt(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsDateTimeWnt& operator=(const OsDateTimeWnt& rhs); //:Assignment operator static void setTime(struct timespec gmt, int tzOffsetSecs, DstRule dstRule); //:Set the system time. For now, this is a no-op for Windows platforms. //!param: (in) gmt - time relative to the beginning of 1970 (GMT) //!param: (in) tzOffsetSecs - local time offset (seconds relative to GMT) //!param: (in) dstRule - daylight savings time rule static void setTimeZone(int tzOffsetSecs, DstRule dstRule); //:Set the time zone and daylight savings time information //!param: (in) tzOffsetSecs - local time offset (seconds relative to GMT) //!param: (in) dstRule - daylight savings time rule /* ============================ ACCESSORS ================================= */ virtual OsStatus cvtToTimeSinceBoot(OsTime& rTime) const; //:Convert the OsDateTimeBase value to an OsTime value // The OsTime value is relative to when the system was booted. static void getCurTime(OsDateTimeWnt& rDateTime); //:Return the current time as an OsDateTime value static void getCurTime(OsTime& rTime); //:Return the current time as an OsTime value static void getCurTimeSinceBoot(OsTime& rTime); //:Return the current time as an OsTime value // The OsTime value is relative to when the system was booted. static unsigned long getSecsSinceEpoch(void); //:Current time as the number of seconds since midnight (0 hour) 01/01/70 /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _OsDateTimeWnt_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/OsDirWnt.h0000644000175000017500000000472212205613256024422 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsDir_h_ #define _OsDir_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "os/OsStatus.h" #include "os/OsDefs.h" #include "os/OsDirBase.h" #include "os/wnt/OsPathWnt.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsFileInfoBase; class OsDirBase; class OsPathWnt; class OsFileInfoWnt; //:Abstraction class to handle directory manipulations class OsDirWnt : public OsDirBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsDirWnt(const char* pathname); OsDirWnt(const OsPathWnt& rOsPath); OsDirWnt(const OsDirWnt& rOsDir); //:Copy constructor virtual ~OsDirWnt(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsStatus create() const; //: Create the path specified by this object // Returns OS_SUCCESS if successful, or OS_INVALID OsStatus rename(const char* name); //: Renames the current directory to the name specified // Returns: // OS_SUCCESS if successful // OS_INVALID if failed /* ============================ ACCESSORS ================================= */ OsStatus getFileInfo(OsFileInfoBase& rFileInfo) const; //: Returns the file information for this objects path (see //: OsFileInfo for more detail) // Returns: // OS_SUCCESS if successful // OS_INVALID if failed /* ============================ INQUIRY =================================== */ UtlBoolean exists(); //: Returns TRUE if the directory specified by this object exists /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsDirWnt(); //:Default constructor OsDirWnt& operator=(const OsDirWnt& rhs); //:Assignment operator /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _OsDir_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/OsFileInfoWnt.h0000644000175000017500000000375012205613256025377 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsFileInfo_h_ #define _OsFileInfo_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsTime.h" #include "os/OsFileInfoBase.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsPathWnt; class OsFileInfoBase; //:Class short description which may consist of multiple lines (note the ':') // Class detailed description which may extend to multiple lines class OsFileInfoWnt : public OsFileInfoBase { friend class OsDirBase; friend class OsFileBase; friend class OsFileSystem; friend class OsDirWnt; friend class OsFileWnt; friend class OsFileSystemWnt; /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsFileInfoWnt(); //:Default constructor OsFileInfoWnt(const OsFileInfoWnt& rOsFileInfo); //:Copy constructor virtual ~OsFileInfoWnt(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsFileInfoWnt& operator=(const OsFileInfoWnt& rhs); //:Assignment operator /* ============================ INQUIRY =================================== */ UtlBoolean isReadOnly() const; //: return TRUE if entry is readonly /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _OsFileInfo_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/OsFileIteratorWnt.h0000644000175000017500000000375512205613256026302 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsFileIterator_h_ #define _OsFileIterator_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsFS.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsFileInfoWnt; class OsPathWnt; class OsFileIteratorBase; class UtlString; //:Abstraction class to iterate through files and/or directories class OsFileIteratorWnt : public OsFileIteratorBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsFileIteratorWnt(); OsFileIteratorWnt(const OsPathWnt& rPathName); virtual ~OsFileIteratorWnt(); //:Destructor /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ //: Returns total files enumerated thus far. /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: // Override this function for releasing mSearchHandle. virtual void Release(); /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsStatus getNextEntryName(UtlString &rName, OsFileType &rFileType); //: Platform dependant call for getting entry OsStatus getFirstEntryName(UtlString &rName, OsFileType &rFileType); //: Platform dependant call for getting entry }; /* ============================ INLINE METHODS ============================ */ #endif // _OsFileIterator_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/OsFileSystemWnt.h0000644000175000017500000000715312205613256025771 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsFileSystemWnt_h_ #define _OsFileSystemWnt_h_ // SYSTEM INCLUDES #include #if defined(_WIN32) #ifndef WINCE # include # include # include #endif #elif defined(_VXWORKS) # include # include #elif defined(__pingtel_on_posix__) # include # include # define O_BINARY 0 // There is no notion of a "not binary" file under POSIX, // so we just set O_BINARY used below to no bits in the mask. #else # error Unsupported target platform. #endif #ifndef WINCE # include # include # include #endif #ifndef WINCE #include #endif // APPLICATION INCLUDES #include "os/OsFS.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsPathWnt; class OsFileInfoWnt; //:Helper class that constructs OsDir and OsFile objects //:for you. This may be expanded to include enumerating versions //:of these functions. class OsFileSystemWnt { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ OsFileSystemWnt& operator=(const OsFileSystemWnt& rhs); //:Assignment operator static OsStatus copy(const OsPathWnt& rSource, const OsPathWnt& rOsPath); //: Returns TRUE if file moved ok static OsStatus rename(const OsPathWnt& rSourceFile, const OsPathWnt& rDestFile); //: Renames the directory or file specified by path static OsStatus change(const OsPathWnt& rOsPath); //: Change the current working directory to the specified location static OsStatus createDir(const OsPathWnt& rOsPath); //: Creates the specified directory //: Fails if a file by the same name already exists in the directory static OsStatus setReadOnly(const OsPathWnt& rOsPath, UtlBoolean bState); //: Sets the specifed file or path to readonly /* ============================ ACCESSORS ================================= */ static OsStatus getFileInfo(OsPathBase& filespec, OsFileInfoBase& rfileInfo); //: Retrieve system info for specified directory of file static OsStatus OsFileSystemWnt::getWorkingDirectory(OsPathWnt& rPath); //: returns the current working directory for the process /* ============================ ACCESSORS ================================= */ static OsStatus OsFileSystemWnt::getFileInfo(OsPathWnt& rFilespec, OsFileInfoWnt& rFileInfo); //: Retrieve system info for specified directory of file /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsFileSystemWnt(const OsFileSystemWnt& rOsFileSystemWnt); //:Copy constructor OsFileSystemWnt(); //:Default constructor virtual ~OsFileSystemWnt(); //:Destructor /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _OsFileSystemWnt_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/OsFileWnt.h0000644000175000017500000000607012205613256024561 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsFileWnt_h_ #define _OsFileWnt_h_ // SYSTEM INCLUDES #include "os/OsStatus.h" // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsFileInfoBase; class OsFileInfoWnt; class OsPathWnt; //:OS class for creating,reading, writing, manipulating files. class OsFileWnt : public OsFileBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsFileWnt(const OsPathBase& filename); //:Default constructor virtual ~OsFileWnt(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsStatus fileunlock(); //: Cross-process unlocks this file. //: Notes: This method should only be called by OsFileBase::close()! OsStatus filelock(const bool wait); //: Cross-process locks this file, optionally waiting for the lock. //: Returns: //: OS_SUCCESS if successful //: OS_FAILED if unsuccessful //: Notes: This method should only be called by OsFileBase::open()! OsStatus setLength(unsigned long newLength); //: Sets the length of the file specified by the object to the new size //: Sets the length of the file specified by the object to the new size //: Shrinking or Growing the file as needed. OsStatus touch(); //: Updates the date and time on the file. Creates if needed. /* ============================ ACCESSORS ================================= */ /// Convert Windows FILETIME to an OsTime. static OsTime OsFileWnt::fileTimeToOsTime(FILETIME ft); /**< * This static function converts a windows FILETIME to a sipX OsTime * @param ft - The Windows FILETIME to convert * @returns an OsTime representing the FILETIME */ /// Get information about a file. virtual OsStatus getFileInfo(OsFileInfoBase& rFileinfo) const; /**< * Returns all the relevant info on this file * @param[out] rFileinfo - The object that is filled with the * file information. */ /* ============================ INQUIRY =================================== */ UtlBoolean isReadonly() const; //: Returns TRUE if file is readonly /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsFileWnt(const OsFileWnt& rOsFileWnt); //:Copy constructor OsFileWnt& operator=(const OsFileWnt& rhs); //:Assignment operator /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _OsFileWnt_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/OsMutexWnt.h0000644000175000017500000000533612205613256025010 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsMutexWnt_h_ #define _OsMutexWnt_h_ // SYSTEM INCLUDES #define WIN32_LEAN_AND_MEAN #include // APPLICATION INCLUDES #include "os/OsMutex.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS typedef HANDLE WinMutex; // FORWARD DECLARATIONS //:Mutual exclusion semaphore (mutex) for Windows NT // The mutual-exclusion semaphore is a specialized version of the binary // semaphore, designed to address issues inherent in mutual exclusion, such // as recursive access to resources, priority inversion, and deletion safety // The fundamental behavior of the mutual-exclusion semaphore is identical to // except for the following restrictions: it can only be used for mutual // exclusion and it can only be released by the task that acquired it. class OsMutexWnt : public OsMutexBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsMutexWnt(const unsigned options); //:Constructor virtual ~OsMutexWnt(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsStatus acquire(const OsTime& rTimeout = OsTime::OS_INFINITY); //:Block the task until the semaphore is acquired or the timeout expires virtual OsStatus tryAcquire(void); //:Conditionally acquire the mutex (i.e., don't block) // Return OS_BUSY if the mutex is held by some other task virtual OsStatus release(void); //:Release the semaphore /* ============================ ACCESSORS ================================= */ virtual void OsMutexShow(void); //:Print mutex information to the console. /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: WinMutex mMutexImp; // Windows NT mutex OsMutexWnt(); //:Default constructor (not implemented for this class) OsMutexWnt(const OsMutexWnt& rOsMutexWnt); //:Copy constructor (not implemented for this class) OsMutexWnt& operator=(const OsMutexWnt& rhs); //:Assignment operator (not implemented for this class) }; /* ============================ INLINE METHODS ============================ */ #endif // _OsMutexWnt_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/OsPathWnt.h0000644000175000017500000000401112205613256024567 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsPathWnt_h_ #define _OsPathWnt_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsPathBase.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsPathBase; class UtlString; //:OS generic path class. Will massage any input string so separators are correct. //:Also provided functions to class OsPathWnt : public OsPathBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsPathWnt(); //:Default constructor OsPathWnt(const OsPathWnt& rOsPathWnt); //:Copy constructor virtual ~OsPathWnt(); //:Destructor OsPathWnt(const UtlString& rPath); //: Copy contructor OsPathWnt(const char* pPath); //: Construct OsPathWnt from char* OsPathWnt(const UtlString& rVolume, const UtlString& rDirName, const UtlString& rFileName, const UtlString& rExtension); //: Forms a OsPathWnt from discrete parts /* ============================ MANIPULATORS ============================== */ OsPathWnt& operator=(const OsPathWnt& rhs); //:Assignment operator /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _OsPathWnt_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/OsProcessIteratorWnt.h0000644000175000017500000000411112205613256027024 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsProcessIteratorWnt_h_ #define _OsProcessIteratorWnt_h_ // SYSTEM INCLUDES #define WIN32_LEAN_AND_MEAN #include // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsProcess.h" #include "os/OsProcessIterator.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsProcessBase; class OsProcessIteratorBase; //: Used to enumerate running processes class OsProcessIteratorWnt : OsProcessIteratorBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsProcessIteratorWnt(); //:Default constructor virtual ~OsProcessIteratorWnt(); //:Destructor /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ OsStatus findFirst(OsProcess &rProcess); //: Start enumeration of running processes //: Returns OS_SUCCESS if found //: Returns OS_FAILED if none found. OsStatus findNext(OsProcess &rProcess); //: Continues enumeration of running processes //: Returns OS_SUCCESS if found //: Returns OS_FAILED if none found. /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsProcess mProcess; HANDLE hProcessSnapshot; //:Last process found by this class }; /* ============================ INLINE METHODS ============================ */ #endif // _OsProcessIteratorWnt_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/OsProcessWnt.h0000644000175000017500000000754712205613256025332 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsProcessWnt_h_ #define _OsProcessWnt_h_ // SYSTEM INCLUDES #define WIN32_LEAN_AND_MEAN #include // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsProcess.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlString; //: This encapsulates a pid, and allows querying, killing and all the //: other cool things you want to do to a process. class OsProcessWnt : public OsProcessBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsProcessWnt(); //:Default constructor virtual ~OsProcessWnt(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsStatus launch(UtlString &rAppName, UtlString parameters[], OsPath &startDir, OsProcessPriorityClass prio = NormalPriorityClass, UtlBoolean bExeclusive = FALSE); //: Pass the appname and parameters to start the process //: Returns TRUE if process started ok. //: If bExclusive is TRUE and another process by the same name already //: is running the return is OS_FAILED virtual OsStatus kill(); //: Kills the process specified by pid virtual OsStatus setPriority(int prio); //: Changes the process priority. Must own the process for this to be legal. static OsStatus getByPID(PID pid, OsProcessWnt &rProcess); //: Given a PID, this method will fill in the process passed in so the user //: can then manipulate it virtual OsStatus setIORedirect(OsPath &rStdInputFilename, OsPath &rStdOutputFilename, OsPath &rStdErrorFilename); //: Sets the standard input, output and/or stderror /* ============================ ACCESSORS ================================= */ static PID getCurrentPID(); //: Returns the current process id. virtual OsStatus getPriority(int &rPrio); //: Returns the process priority. Must own the process for this to be legal. virtual OsStatus getPriorityClass(OsProcessPriorityClass &rPrioClass); //: Returns the Priority Class for this process. Priority is a function of the class. virtual OsStatus getMinPriority(int &rMinPrio); //: Returns the min priority base on which class is selected virtual OsStatus getMaxPriority(int &rMaxPrio); //: Returns the max priority base on which class is selected virtual OsStatus getInfo(OsProcessInfo &rProcessInfo); //: Returns full information on process, including priority. //: See OsProcessInfo for more information virtual OsStatus getUpTime(OsTime &rUpTime); //: How long has this process been runnign for? /* ============================ INQUIRY =================================== */ virtual UtlBoolean isRunning () const ; //: Returns TRUE if process is still active virtual int wait(int numSecs = -1); //:waits for a process to complete before returning //:or exits when WaitInSecs has completed /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: HANDLE mStdInputHandle; HANDLE mStdOutputHandle; HANDLE mStdErrorHandle; HANDLE mhProcess; //handle to process HANDLE mhThread; //handle to main thread }; /* ============================ INLINE METHODS ============================ */ #endif // _OsProcessWnt_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/OsSharedLibMgrWnt.h0000644000175000017500000000527212205613256026210 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsSharedLibMgrWnt_h_ #define _OsSharedLibMgrWnt_h_ // SYSTEM INCLUDES //#include <...> // APPLICATION INCLUDES #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Class short description which may consist of multiple lines (note the ':') // Class detailed description which may extend to multiple lines class OsSharedLibMgrWnt : public OsSharedLibMgrBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ friend class OsSharedLibMgrBase; public: /* ============================ CREATORS ================================== */ virtual ~OsSharedLibMgrWnt(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsStatus loadSharedLib(const char* libName); //: Loads the given shared library //!param: libName - name of library, may include absolute or relative path virtual OsStatus getSharedLibSymbol(const char* libName, const char* symbolName, void*& symbolAddress); //: Gets the address of a symbol in the shared lib //!param: (in) libName - name of library, may include absolute or relative path //!param: (in) symbolName - name of the variable or function exported in the shared lib //!param: (out) symbolAddress - the address of the function or variable virtual OsStatus unloadSharedLib(const char* libName); //: Unloads the given shared library // Before unloading library make sure that no one else use it! //!param: libName - name of library, may include absolute or relative path /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsSharedLibMgrWnt(); //:Default constructor disallowed, use getOsSharedLibMgr /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsSharedLibMgrWnt(const OsSharedLibMgrWnt& rOsSharedLibMgrWnt); //:Copy constructor OsSharedLibMgrWnt& operator=(const OsSharedLibMgrWnt& rhs); //:Assignment operator }; /* ============================ INLINE METHODS ============================ */ #endif // _OsSharedLibMgrWnt_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/OsTaskWnt.h0000644000175000017500000002451712205617431024611 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsTaskWnt_h_ #define _OsTaskWnt_h_ // SYSTEM INCLUDES #define WIN32_LEAN_AND_MEAN #include // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "os/OsDefs.h" #include "os/OsMutex.h" #include "os/OsRWMutex.h" #include "os/OsStatus.h" #include "os/OsTask.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsTime; class UtlString; //:Task abstraction for Windows NT // A task represents a thread of execution. All tasks run within the same // address space but have their own stack and program counter. Tasks may be // created and deleted dynamically. // // Users create tasks by: // 1) Deriving a new class based on OsTask or one of its descendants, // and overriding the run() method in the derived class. // 2) Calling the constructor for the derived class. // 3) Invoking the start() method for the derived class. This creates the // corresponding low-level OS task and associates it with the class. // // Note: Many of the methods in this class are only applicable once the // start() method for the object has been called and the corresponding // low-level task has been created. Accordingly, before a successful call // to start(), most of the methods in this class return the // OS_TASK_NOT_STARTED status. class OsTaskWnt : public OsTaskBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsTaskWnt(const UtlString& name="", void* pArg=NULL, const int priority=DEF_PRIO, const int options=DEF_OPTIONS, const int stackSize=DEF_STACKSIZE); //:Constructor // For Windows NT, the "options" parameter is ignored. virtual ~OsTaskWnt(); //:Destructor -- delete the task virtual OsStatus deleteForce(void); //:Delete the task even if the task is protected from deletion // After calling this method, the user will still need to delete the // corresponding OsTask object to reclaim its storage. /* ============================ MANIPULATORS ============================== */ virtual UtlBoolean restart(void); //:Restart the task // The task is first terminated, and then reinitialized with the same // name, priority, options, stack size, original entry point, and // parameters it had when it was terminated. // Return TRUE if the restart of the task is successful. virtual OsStatus resume(void); //:Resume the task // This routine resumes the task. The task suspension is cleared, and // the task operates in the remaining state. virtual UtlBoolean start(void); //:Spawn a new task and invoke its run() method. // Return TRUE if the spawning of the new task is successful. // Return FALSE if the task spawn fails or if the task has already // been started. virtual OsStatus suspend(void); //:Suspend the task // This routine suspends the task. Suspension is additive: thus, tasks // can be delayed and suspended, or pended and suspended. Suspended, // delayed tasks whose delays expire remain suspended. Likewise, // suspended, pended tasks that unblock remain suspended only. virtual OsStatus setErrno(int errno); //:Set the errno status for the task // This call has no effect under Windows NT and, if the task has been // started, will always returns OS_SUCCESS virtual OsStatus setOptions(int options); //:Set the execution options for the task // The only option that can be changed after a task has been created // is whether to allow breakpoint debugging. // This call has no effect under Windows NT virtual OsStatus setPriority(int priority); //:Set the priority of the task // Priorities range from 0, the highest priority, to 255, the lowest // priority. virtual OsStatus varAdd(int* pVar); //:Add a task variable to the task // This routine adds a specified variable pVar (4-byte memory // location) to its task's context. After calling this routine, the // variable is private to the task. The task can access and modify // the variable, but the modifications are not visible to other tasks, // and other tasks' modifications to that variable do not affect the // value seen by the task. This is accomplished by saving and restoring // the variable's value each time a task switch occurs to or from the // calling task. virtual OsStatus varDelete(int* pVar); //:Remove a task variable from the task // This routine removes a specified task variable, pVar, from its // task's context. The private value of that variable is lost. virtual OsStatus varSet(int* pVar, int value); //:Set the value of a private task variable // This routine sets the private value of the task variable for a // specified task. The specified task is usually not the calling task, // which can set its private value by directly modifying the variable. // This routine is provided primarily for debugging purposes. static OsStatus delay(const int milliSecs); //:Delay a task from executing for the specified number of milliseconds // This routine causes the calling task to relinquish the CPU for the // duration specified. This is commonly referred to as manual // rescheduling, but it is also useful when waiting for some external // condition that does not have an interrupt associated with it. static OsStatus safe(void); //:Make the calling task safe from deletion // This routine protects the calling task from deletion. Tasks that // attempt to delete a protected task will block until the task is // made unsafe, using unsafe(). When a task becomes unsafe, the // deleter will be unblocked and allowed to delete the task. // The safe() primitive utilizes a count to keep track of // nested calls for task protection. When nesting occurs, // the task becomes unsafe only after the outermost unsafe() // is executed. static OsStatus unsafe(void); //:Make the calling task unsafe from deletion // This routine removes the calling task's protection from deletion. // Tasks that attempt to delete a protected task will block until the // task is unsafe. When a task becomes unsafe, the deleter will be // unblocked and allowed to delete the task. // The unsafe() primitive utilizes a count to keep track of nested // calls for task protection. When nesting occurs, the task becomes // unsafe only after the outermost unsafe() is executed. static void yield(void); //:Yield the CPU if a task of equal or higher priority is ready to run. /* ============================ ACCESSORS ================================= */ static OsTaskWnt* getCurrentTask(void); //:Return a pointer to the OsTask object for the currently executing task // Return NULL if none exists. static OsStatus getCurrentTaskId(int &rid); //:Return an Id of the currently executing task static OsTaskWnt* getTaskByName(const UtlString& taskName); //:Return a pointer to the OsTask object corresponding to the named task // Return NULL if there is no task object with that name. static OsTaskWnt* getTaskById(const int taskId); //:Return a pointer to the OsTask object corresponding to taskId // Return NULL is there is no task object with that id. virtual OsStatus getErrno(int& rErrno); //:Get the errno status for the task // Under Windows NT, the rErrno value will always be 0. virtual int getOptions(void); //:Return the execution options for the task virtual OsStatus getPriority(int& rPriority); //:Return the priority of the task virtual OsStatus varGet(void); //:Get the value of a task variable // This routine returns the private value of a task variable for its // task. The task is usually not the calling task, which can get its // private value by directly accessing the variable. This routine is // provided primarily for debugging purposes. static void getIdString(UtlString&, DWORD); //:See the linux version... /* ============================ INQUIRY =================================== */ virtual OsStatus id(OsTaskId_t& rId); //:Get the task ID for this task virtual UtlBoolean isSuspended(void); //:Check if the task is suspended // Return TRUE is the task is suspended, otherwise FALSE. /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: virtual int run(void* pArg) = 0; //:The entry point for the task. // Derive new tasks as subclasses of OsTask, overriding this method. /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsRWMutex mDeleteGuard; // RWMutex guard to prevent unwanted task deletion int mSuspendCnt; // Counts the nesting level of taskSuspend() calls HANDLE mThreadH; // Windows NT thread handle int mThreadId; // Windows NT unique ID for thread // saved initialization information (used for task restarts) int mOptions; int mPriority; int mStackSize; UtlBoolean doWntCreateTask(void); //:Do the real work associated with creating a new WinNT task // The mDataGuard lock should be held upon entry into this method. void doWntTerminateTask(UtlBoolean doForce); //:Do the real work associated with terminating a WinNT task // The mDataGuard lock should be held upon entry into this method. static unsigned int __stdcall threadEntry(LPVOID arg); //:Function that serves as the starting address for a Windows thread OsTaskWnt(const OsTaskWnt& rOsTaskWnt); //:Copy constructor (not implemented for this class) OsTaskWnt& operator=(const OsTaskWnt& rhs); //:Assignment operator (not implemented for this class) }; /* ============================ INLINE METHODS ============================ */ #endif // _OsTaskWnt_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/OsUtilWnt.h0000644000175000017500000000532512205613256024621 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsUtilWnt_h_ #define _OsUtilWnt_h_ // SYSTEM INCLUDES #define WIN32_LEAN_AND_MEAN #include // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsTime.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Static methods that are useful when running on top of Window NT class OsUtilWnt { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ static OsStatus synchObjAcquire(const HANDLE synchObj, const OsTime& rTimeout = OsTime::OS_INFINITY); //:Block the task until the synch obj is acquired or the timeout expires static OsStatus synchObjTryAcquire(const HANDLE synchObj); //:Conditionally acquire the synch obj (i.e., don't block) // Return OS_BUSY if the synch object is held by some other task /* ============================ ACCESSORS ================================= */ static DWORD cvtOsTimeToWntTime(const OsTime& rTimer); //:Convert an OsTime to the corresponding number of millisecs for WinNT static int cvtOsPrioToWntPrio(const int osPrio); //:Convert an abstraction layer task priority to a WinNT thread priority static int cvtWntPrioToOsPrio(const int wntPrio); //:Convert a WinNT thread priority to an abstraction layer task priority /* ============================ INQUIRY =================================== */ static UtlBoolean isOsTimeValid(const OsTime& rTimer); //:Verify that the OsTime is >= 0 and representable in msecs /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsUtilWnt(); //:Default constructor (not implemented for this class) OsUtilWnt(const OsUtilWnt& rOsUtilWnt); //:Copy constructor (not implemented for this class) virtual ~OsUtilWnt(); //:Destructor (not implemented for this class) OsUtilWnt& operator=(const OsUtilWnt& rhs); //:Assignment operator (not implemented for this class) }; /* ============================ INLINE METHODS ============================ */ #endif // _OsUtilWnt_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/wnt/WIndowsAdapterInfo.h0000644000175000017500000000240112205613256026410 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _WINDOWSADAPTERINFO_H #define _WINDOWSADAPTERINFO_H #define MAX_ADAPTERS 20 //if you have more than 20 adapters, something is wrong with you. :) #ifndef MAX_ADAPTER_NAME_LENGTH #define MAX_ADAPTER_NAME_LENGTH 256 #endif typedef struct _AdapterInfo { char AdapterName[MAX_ADAPTER_NAME_LENGTH + 4]; //long adapter name char IpAddress[40]; //ip address of adapter BYTE MacAddress[MAX_ADAPTER_NAME_LENGTH]; //mac address of adapter } AdapterInfoRec, *pAdapterInfoRec; #ifdef WIN32 //FUNCTIONS //pass in amac address and get out the current ip address assigned to it extern int lookupIpAddressByMacAddress(char *mac_address, char *ipaddress); //initializes internal adapter structure extern int getAdaptersInfo(); extern int getWindowsDomainName(char *domain_name); #endif //WIN32 #endif //_WINDOWSADAPTERINFO_H sipxtapi-3.3.0~test17/sipXportLib/include/os/fstream0000644000175000017500000000075012205613256023311 0ustar00danieldaniel00000000000000// // // Copyright (C) 2004, 2005 Pingtel Corp. // // // $$ ////////////////////////////////////////////////////////////////////////////// #ifndef _fstream_h_ #define _fstream_h_ // If we are compiling for VxWorks, use the old form of fstream.h // We do this to stay compatible with the version of the tools++ // object modules that are distributed with VxWorks. #if defined(_VXWORKS) #include #else #include using namespace std; #endif #endif // _fstream_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/HostAdapterAddress.h0000644000175000017500000000312512205613256025621 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef HostAdapterAddress_h #define HostAdapterAddress_h // SYSTEM INCLUDES // APPLICATION INCLUDES #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * Simple class definition for an object that contains */ class HostAdapterAddress { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /** * Constructor accepting an optional default value. */ HostAdapterAddress(const char* szAdapter, const char* szAddress) : mAdapter(szAdapter), mAddress(szAddress) { } /** * Destructor */ virtual ~HostAdapterAddress() { } UtlString mAdapter; UtlString mAddress; /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; #endif sipxtapi-3.3.0~test17/sipXportLib/include/os/iostream0000644000175000017500000000075612205613256023501 0ustar00danieldaniel00000000000000// // // Copyright (C) 2004, 2005 Pingtel Corp. // // // $$ ////////////////////////////////////////////////////////////////////////////// #ifndef _iostream_h_ #define _iostream_h_ // If we are compiling for VxWorks, use the old form of iostream.h // We do this to stay compatible with the version of the tools++ // object modules that are distributed with VxWorks. #if defined(_VXWORKS) #include #else #include using namespace std; #endif #endif // _iostream_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/istream0000644000175000017500000000072312205613256023314 0ustar00danieldaniel00000000000000// // // Copyright (C) 2004, 2005 Pingtel Corp. // // // $$ ////////////////////////////////////////////////////////////////////////////// #ifndef _istream_h_ #define _istream_h_ // If we are compiling for VxWorks, use the old form of istream.h // We do this to stay compatible with the version of the tools++ // object modules that are distributed with VxWorks. #if defined(_VXWORKS) #include #else #include #endif #endif // _istream_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/IStunSocket.h0000644000175000017500000001614612205613256024317 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 Pingtel Corp. // // $$ ////////////////////////////////////////////////////////////////////////////// #ifndef _IStunSocket_h_ #define _IStunSocket_h_ #include "os/OsDateTime.h" #include "os/OsMsg.h" #include "utl/UtlString.h" // DEFINES #define NAT_MSG_TYPE (OsMsg::USER_START + 1) /**< Stun Msg type/Id */ // The follow defines are used to keep track of what has been recorded for // various time-based metrics. #define ONDS_MARK_NONE 0x00000000 #define ONDS_MARK_FIRST_READ 0x00000001 #define ONDS_MARK_LAST_READ 0x00000002 #define ONDS_MARK_FIRST_WRITE 0x00000004 #define ONDS_MARK_LAST_WRITE 0x00000008 #define MAX_RTP_BYTES 4096 typedef enum { UNKNOWN_PACKET, MEDIA_PACKET, STUN_PROBE_PACKET, STUN_DISCOVERY_PACKET, TURN_PACKET, CRLF_KEEPALIVE_PACKET, STUN_KEEPALIVE_PACKET, OTHER_PACKET } PacketType ; /** * Possible roles that a Media connection can have. */ typedef enum { RTP_TRANSPORT_UNKNOWN = 0x00000000, RTP_TRANSPORT_UDP = 0x00000001, RTP_TRANSPORT_TCP = 0x00000002, RTP_TCP_ROLE_ACTIVE = 0x00000004, RTP_TCP_ROLE_PASSIVE = 0x00000008, RTP_TCP_ROLE_ACTPASS = 0x00000010, RTP_TCP_ROLE_CONNECTION = 0x00000020, } RTP_TRANSPORT ; typedef int RtpTransportOptions; typedef int RtpTcpRoles; class OsSocket; class OsNotification; typedef enum { STUN = 0x02, DATA = 0x03 } TURN_FRAMING_TYPE; /** * Generic interface representing a media transport object. * Implemented by VoiceEngineDatagramSocket, VoiceEngineConnectionSocket, * and any other class which provides RTP transport for VoiceEngine. */ class IStunSocket { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ MANIPULATORS ============================== */ /** * virtual destructor. */ virtual ~IStunSocket() {}; virtual OsSocket* getSocket() = 0; /** * Standard write - should be used to invoke the base class's write method */ virtual int socketWrite(const char* buffer, int bufferLength, const char* ipAddress, int port, PacketType packetType=UNKNOWN_PACKET) = 0; virtual UtlBoolean getRelayIp(UtlString* ip, int* port) = 0; virtual UtlBoolean getMappedIp(UtlString* ip, int* port) = 0; virtual void enableTransparentReads(bool bEnable) = 0; /** * Enable STUN. Enabling STUN will reset the the keep alive timer and * will force a binding refresh. * * @param szStunServer * @param stunPort * @param iKeepAlive * @param stunOptions * @param bReadFromSocket */ virtual void enableStun(const char* szStunServer, int stunPort, int iKeepAlive, int stunOptions, bool bReadFromSocket) = 0; /** * Sets the STUN-resolved address and port for this socket. * * @param address String containing the stunned address. * @param iPort integer value of the stunned port. */ virtual void setStunAddress(const UtlString& address, const int iPort) = 0; /** * Set the TURN-dervied relay address for this socket. * * @param address TURN-derived hostname/IP address * @param iPort TURN-derived port address */ virtual void setTurnAddress(const UtlString& address, const int iPort) = 0; /** * Report that a stun attempt failed. */ virtual void markStunFailure() = 0; /** * Report that a stun attempt succeeded. */ virtual void markStunSuccess(bool bAddressChanged) = 0; /** * Report that a stun attempt failed. */ virtual void markTurnFailure() = 0; /** * Report that a stun attempt succeeded. */ virtual void markTurnSuccess() = 0; /** * Reset the destination address for this OsNatDatagramSocket. This * method is called by the OsStunAgentTask when a better address is * found via STUN/ICE. * * @param address The new destination address * @param iPort The new destination port * @param priority Priority of the destination address */ virtual void evaluateDestinationAddress(const UtlString& address, int iPort, int priority) = 0; /** * Enable STUN. Enabling STUN will reset the the keep alive timer and * will force a binding refresh. * * @param szTurnSever * @param turnPort * @param iKeepAlive * @param username * @param password * @param bReadFromSocket */ virtual void enableTurn(const char* szTurnSever, int turnPort, int iKeepAlive, const char* username, const char* password, bool bReadFromSocket) = 0; /** * Prepares a destination under TURN usage. */ virtual void readyDestination(const char* szAddress, int iPort) = 0; /** * TODO: DOCS */ virtual UtlBoolean applyDestinationAddress(const char* szAddress, int iPort) = 0; /** * TODO: DOCS */ virtual UtlBoolean getBestDestinationAddress(UtlString& address, int& iPort) = 0; /** * Add an alternate destination to this OsNatDatagramSocket. Alternate * destinations are tested by sending stun packets. If a stun response is * received and the priority is greater than what has already been selected * then that address is used. * * @param szAddress IP address of the alternate destination * @param iPort port number of the alternate destination * @param priority priority of the alternate where a higher number * indicates a higher priority. */ virtual void addAlternateDestination(const char* szAddress, int iPort, int priority) = 0; /** * Set a notification object to be signaled when the first the data * packet is received from the socket. Once this is signaled, the * notification object is discarded. */ virtual void setReadNotification(OsNotification* pNotification) = 0 ; /* ============================ ACCESSORS ================================= */ /** * Get the timestamp of the first read data packet (excluding any * STUN/TURN/NAT packets). */ virtual bool getFirstReadTime(OsDateTime& time) = 0 ; /** * Get the timestamp of the last read data packet (excluding any * STUN/TURN/NAT packets). */ virtual bool getLastReadTime(OsDateTime& time) = 0 ; /** * Get the timestamp of the first written data packet (excluding any * STUN/TURN/NAT packets). */ virtual bool getFirstWriteTime(OsDateTime& time) = 0 ; /** * Get the timestamp of the last written data packet (excluding any * STUN/TURN/NAT packets). */ virtual bool getLastWriteTime(OsDateTime& time) = 0 ; /** * Cleanup routine. */ virtual void destroy() = 0; }; #endif // #ifndef _IStunSocket_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/NatMsg.h0000644000175000017500000000366212205613256023274 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 Pingtel Corp. // // $$ ////////////////////////////////////////////////////////////////////////////// #ifndef _NatMsg_h_ #define _NatMsg_h_ #include "os/IStunSocket.h" #include "os/OsMsg.h" #include "utl/UtlString.h" //: Basic NatMsg -- relies on external bodies to allocate and free memory. class NatMsg : public OsMsg { public: enum { STUN_MESSAGE, TURN_MESSAGE, EXPIRATION_MESSAGE } ; /* ============================ CREATORS ================================== */ NatMsg(int type, char* szBuffer, int nLength, IStunSocket* pSocket, UtlString receivedIp, int iReceivedPort); //:Constructor NatMsg(int type, void* pContext); //:Constructor NatMsg(const NatMsg& rNatMsg); //:Copy constructor virtual OsMsg* createCopy(void) const; //:Create a copy of this msg object (which may be of a derived type) virtual ~NatMsg(); //:Destructor /* ============================ MANIPULATORS ============================== */ NatMsg& operator=(const NatMsg& rhs); //:Assignment operator /* ============================ ACCESSORS ================================= */ char* getBuffer() const ; int getLength() const ; IStunSocket* getSocket() const ; UtlString getReceivedIp() const ; int getReceivedPort() const ; int getType() const ; void* getContext() const ; /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: int miType ; char* mBuffer ; int mLength ; IStunSocket* mpSocket ; UtlString mReceivedIp ; int miReceivedPort ; void* mpContext ; /* //////////////////////////// PRIVATE /////////////////////////////////// */ }; #endif sipxtapi-3.3.0~test17/sipXportLib/include/os/OsAssert.h0000644000175000017500000000221712205613256023641 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsAssert_h_ #define _OsAssert_h_ /* SYSTEM INCLUDES */ /* APPLICATION INCLUDES */ #ifdef __cplusplus extern "C" { #endif /* DEFINES */ #define OS_ASSERT_REBOOT 47 #define OS_ASSERT_SUSPEND 17 #define OS_ASSERT_ALWAYS_SUSPEND 4717 /* MACROS */ /* EXTERNAL FUNCTIONS */ /* * OsAssert_SetFailureAction(boolean): * Set action on assert() failure: reboot system, or suspend calling task */ #ifdef _VXWORKS /* [ */ extern int OsAssert_SetFailureAction(int assertFailureAction); #else /* _VXWORKS ] [ */ #define OsAssert_SetFailureAction(assertFailureAction) #endif /* _VXWORKS ] */ /* * assertCount(): Return number of assertion failures reported. */ extern int assertCount(void); /* EXTERNAL VARIABLES */ /* CONSTANTS */ /* STRUCTS */ /* TYPEDEFS */ /* FORWARD DECLARATIONS */ #ifdef __cplusplus } #endif #endif /* _OsAssert_h_ */ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsAtomics.h0000644000175000017500000002206312205613256024000 0ustar00danieldaniel00000000000000// // Copyright (C) 2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Alexander Chemeris #ifndef _OsAtomics_H_ // [ #define _OsAtomics_H_ #ifdef HAVE_C_ATOMICS // [ # include typedef atomic_int OsAtomicInt; typedef atomic_uint OsAtomicUInt; typedef atomic_long OsAtomicLong; typedef atomic_ulong OsAtomicULong; typedef atomic_address OsAtomicVoidPtr; #define OsAtomicLight OsAtomic #elif defined(ANDROID) // HAVE_C_ATOMICS ][ ANDROID #include #else // ANDROID ][ #ifdef __arm__ #warning ARM version of OsAtomics need to be fixed to support ARM features. #endif # include # include # include # include typedef enum memory_order { memory_order_relaxed, memory_order_consume, memory_order_acquire, memory_order_release, memory_order_acq_rel, memory_order_seq_cst } memory_order; template class OsAtomic { public: bool is_lock_free() const {return false;} void store(T val, memory_order = memory_order_seq_cst) {OsLock lock(mMutex); mVal = val;} T load(memory_order = memory_order_seq_cst) const {OsLock lock(mMutex); return mVal;} operator T() const {return load();} // T exchange(T val, memory_order = memory_order_seq_cst); // bool compare_exchange(T &, T , memory_order, memory_order); // bool compare_exchange(T &, T , memory_order = memory_order_seq_cst); void fence(memory_order) const {}; T fetch_add(T val, memory_order = memory_order_seq_cst) {OsLock lock(mMutex); T temp = mVal; mVal += val; return temp;} T fetch_sub(T val, memory_order = memory_order_seq_cst) {OsLock lock(mMutex); T temp = mVal; mVal -= val; return temp;} T fetch_and(T val, memory_order = memory_order_seq_cst) {OsLock lock(mMutex); T temp = mVal; mVal &= val; return temp;} T fetch_or(T val, memory_order = memory_order_seq_cst) {OsLock lock(mMutex); T temp = mVal; mVal |= val; return temp;} T fetch_xor(T val, memory_order = memory_order_seq_cst) {OsLock lock(mMutex); T temp = mVal; mVal ^= val; return temp;} OsAtomic() : mMutex(0) {}; explicit OsAtomic(T val) : mVal(val), mMutex(0) {}; T operator=(T val) {store(val); return val;} T operator++(int) {return fetch_add(1);} T operator--(int) {return fetch_sub(1);} T operator++() {return operator+=(1);} T operator--() {return operator-=(1);} T operator+=(T val) {OsLock lock(mMutex); mVal += val; return mVal;} T operator-=(T val) {OsLock lock(mMutex); mVal -= val; return mVal;} T operator&=(T val) {OsLock lock(mMutex); mVal &= val; return mVal;} T operator|=(T val) {OsLock lock(mMutex); mVal |= val; return mVal;} T operator^=(T val) {OsLock lock(mMutex); mVal ^= val; return mVal;} private: T mVal; mutable OsMutex mMutex; // Prohibit use of copy constructor and operator= OsAtomic(const OsAtomic&); OsAtomic& operator=(const OsAtomic&); }; typedef OsAtomic OsAtomicInt; typedef OsAtomic OsAtomicUInt; typedef OsAtomic OsAtomicLong; typedef OsAtomic OsAtomicULong; class OsAtomicBool { public: bool is_lock_free() const {return false;} OsAtomicBool() : mMutex(0) {}; explicit OsAtomicBool(bool val) : mVal(val), mMutex(0) {}; void store(bool val, memory_order = memory_order_seq_cst) {OsLock lock(mMutex); mVal = val;} bool load(memory_order = memory_order_seq_cst) const {OsLock lock(mMutex); return mVal;} bool operator=(bool val) {store(val); return val;} operator bool() const {return load();} // bool exchange(bool, memory_order = memory_order_seq_cst); // bool compare_exchange(bool&, bool, memory_order, memory_order); // bool compare_exchange(bool&, bool, memory_order = memory_order_seq_cst); void fence(memory_order) const {} private: bool mVal; mutable OsMutex mMutex; // Prohibit use of copy constructor and operator= OsAtomicBool(const OsAtomicBool&); OsAtomicBool& operator=(const OsAtomicBool&); }; class OsAtomicVoidPtr { public: bool is_lock_free() const {return false;} void store(void* val, memory_order = memory_order_seq_cst) {OsLock lock(mMutex); mVal = val;} void* load(memory_order = memory_order_seq_cst) const {OsLock lock(mMutex); return mVal;} operator void*() const {return load();} // void* exchange(void* val, memory_order = memory_order_seq_cst); // bool compare_exchange(void* &, void* , memory_order, memory_order); // bool compare_exchange(void* &, void* , memory_order = memory_order_seq_cst); void fence(memory_order) const {}; void* fetch_add(ptrdiff_t val, memory_order = memory_order_seq_cst) {OsLock lock(mMutex); void* temp = mVal; mVal = (int8_t*)mVal + val; return temp;} void* fetch_sub(ptrdiff_t val, memory_order = memory_order_seq_cst) {OsLock lock(mMutex); void* temp = mVal; mVal = (int8_t*)mVal - val; return temp;} OsAtomicVoidPtr() : mMutex(0) {}; explicit OsAtomicVoidPtr(void* val) : mVal(val), mMutex(0) {}; void* operator=(void* val) {store(val); return val;} void* operator+=(ptrdiff_t val) {OsLock lock(mMutex); mVal = (int8_t*)mVal + val; return mVal;} void* operator-=(ptrdiff_t val) {OsLock lock(mMutex); mVal = (int8_t*)mVal - val; return mVal;} private: void* mVal; mutable OsMutex mMutex; // Prohibit use of copy constructor and operator= OsAtomicVoidPtr(const OsAtomicVoidPtr&); OsAtomicVoidPtr& operator=(const OsAtomicVoidPtr&); }; template class OsAtomicPtr : public OsAtomicVoidPtr { public: bool is_lock_free() const {return false;} void store(T* val, memory_order mo = memory_order_seq_cst) {OsAtomicVoidPtr::store((void*)val, mo);} T* load(memory_order mo = memory_order_seq_cst) const {return (T*)OsAtomicVoidPtr::load(mo);} operator T*() const {return (T*)OsAtomicVoidPtr::operator void*();} // T* exchange(T* val, memory_order mo = memory_order_seq_cst); // bool compare_exchange(T* &, T* , memory_order mo, memory_order mo); // bool compare_exchange(T* &, T* , memory_order mo = memory_order_seq_cst); void fence(memory_order mo) const {OsAtomicVoidPtr::fence(mo);} T* fetch_add(ptrdiff_t val, memory_order mo = memory_order_seq_cst) {return (T*)OsAtomicVoidPtr::fetch_add(val, mo);} T* fetch_sub(ptrdiff_t val, memory_order mo = memory_order_seq_cst) {return (T*)OsAtomicVoidPtr::fetch_sub(val, mo);} OsAtomicPtr() {}; explicit OsAtomicPtr(T* val) : OsAtomicVoidPtr((void*)val) {}; T* operator=(T* val) {return (T*)OsAtomicVoidPtr::operator=((void*)val);} T* operator+=(ptrdiff_t val) {return (T*)OsAtomicVoidPtr::operator+=(val);} T* operator-=(ptrdiff_t val) {return (T*)OsAtomicVoidPtr::operator-=(val);} private: // Prohibit use of copy constructor and operator= OsAtomicPtr(const OsAtomicPtr&); OsAtomicPtr& operator=(const OsAtomicPtr&); }; #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__amd64__) || defined (__arm__)// [ template class OsAtomicLight { public: bool is_lock_free() const {return true;} void store(T val, memory_order = memory_order_relaxed) {mVal = val;} T load(memory_order = memory_order_relaxed) const {return mVal;} operator T() const {return load();} void fence(memory_order) const {}; OsAtomicLight() {}; explicit OsAtomicLight(T val) : mVal(val) {}; T operator=(T val) {store(val); return val;} private: volatile T mVal; // Prohibit use of copy constructor and operator= OsAtomicLight(const OsAtomicLight&); OsAtomicLight& operator=(const OsAtomicLight&); }; template class OsAtomicLightPtr { public: bool is_lock_free() const {return true;} void store(T* val, memory_order mo = memory_order_relaxed) {mVal = val;} const T* load(memory_order mo = memory_order_relaxed) const {return mVal;} T* load(memory_order mo = memory_order_relaxed) {return mVal;} operator const T*() const {return load();} operator T*() {return load();} void fence(memory_order mo) const {} OsAtomicLightPtr() {}; explicit OsAtomicLightPtr(T* val) : mVal(val) {}; T* operator=(T* val) {store(val); return val;} private: T * volatile mVal; // Prohibit use of copy constructor and operator= OsAtomicLightPtr(const OsAtomicLightPtr&); OsAtomicLightPtr& operator=(const OsAtomicLightPtr&); }; #else // X86/X86_64/ARM ][ #define OsAtomicLight OsAtomic #define OsAtomicLightPtr OsAtomicPtr #endif // !X86/X86_64/ARM #endif // HAVE_C_ATOMICS ] typedef OsAtomicLight OsAtomicLightInt; typedef OsAtomicLight OsAtomicLightUInt; typedef OsAtomicLight OsAtomicLightLong; typedef OsAtomicLight OsAtomicLightULong; typedef OsAtomicLight OsAtomicLightBool; #endif // _OsAtomics_H_ ] sipxtapi-3.3.0~test17/sipXportLib/include/os/OsBSem.h0000644000175000017500000000662712205613256023237 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsBSem_h_ #define _OsBSem_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsSyncBase.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /// Binary semaphore class OsBSemBase : public OsSyncBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum InitialSemaphoreState { EMPTY = 0, ///< semaphore is initially unavailable FULL = 1 ///< semaphore is initially available }; enum QueueOptions { Q_FIFO = 0x0, ///< queue blocked tasks on a first-in, first-out basis Q_PRIORITY = 0x1 ///< queue blocked tasks based on their priority }; /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ /// Block the task until the semaphore is acquired or the timeout expires virtual OsStatus acquire(const OsTime& rTimeout = OsTime::OS_INFINITY) = 0; /// Conditionally acquire the semaphore (i.e., don't block) virtual OsStatus tryAcquire(void) = 0; /** * @return OS_BUSY if the semaphore is held by some other task. */ /// Release the semaphore virtual OsStatus release(void) = 0; /* ============================ ACCESSORS ================================= */ /// Print semaphore information to the console virtual void OsBSemShow(void) = 0; /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: int mOptions; ///< options specified at time of binary semaphore creation int mTaskId; ///< if OS_SYNC_DEBUG is enabled, ONLY ON WNT, we use this ///< variable to store the ID of the task currently holding the semaphore /// Default constructor OsBSemBase() { }; /// Destructor virtual ~OsBSemBase() { }; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /// Copy constructor (not implemented for this class) OsBSemBase(const OsBSemBase& rOsBSemBase); /// Assignment operator (not implemented for this class) OsBSemBase& operator=(const OsBSemBase& rhs); }; /* ============================ INLINE METHODS ============================ */ /// Depending on the native OS that we are running on, we include the class /// declaration for the appropriate lower level implementation and use a /// "typedef" statement to associate the OS-independent class name (OsBSem) /// with the OS-dependent realization of that type (e.g., OsBSemWnt). #if defined(_WIN32) # include "os/Wnt/OsBSemWnt.h" typedef class OsBSemWnt OsBSem; #elif defined(_VXWORKS) # include "os/Vxw/OsBSemVxw.h" typedef class OsBSemVxw OsBSem; #elif defined(__pingtel_on_posix__) # include "os/linux/OsBSemLinux.h" typedef class OsBSemLinux OsBSem; #else # error Unsupported target platform. #endif #endif // _OsBSem_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsCallback.h0000644000175000017500000000571612205613256024103 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsCallback_h_ #define _OsCallback_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS typedef void (*OsCallbackFunc) (const intptr_t userData, const intptr_t eventData); // FORWARD DECLARATIONS //:Callback function that is executed when the event is signaled. //:Event notification method where a callback function is executed in the //:Notifier's context when the corresponding event occurs. //

Background //

First, a little bit of terminology. The task that wishes to be notified // when an event occurs is the "Listener" task. The task that signals when // a given event occurs is the "Notifier" task. A Notifier informs the // Listener that a given event has occurred by sending an "Event // Notification".

// //

Expected Usage //

When the corresponding event occurs, the designated callback routine is // invoked in the Notifier's task context. class OsCallback : public OsNotification { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsCallback(const intptr_t userData, const OsCallbackFunc func); //:Constructor virtual ~OsCallback(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsStatus signal(const intptr_t eventData); //:Signal the occurrence of the event by executing the callback function // Always return OS_SUCCESS. /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsCallbackFunc mFunc; // routine that will be invoked in the notifier's // context to signal the event intptr_t mUserData; // data specified on behalf of the user and // not otherwise used by this class -- the user // data is specified as an argument to the class // constructor OsCallback(const OsCallback& rOsCallback); //:Copy constructor (not implemented for this class) OsCallback& operator=(const OsCallback& rhs); //:Assignment operator (not implemented for this class) }; /* ============================ INLINE METHODS ============================ */ #endif // _OsCallback_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsConfigDb.h0000644000175000017500000002464112205613256024060 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsConfigDb_h_ #define _OsConfigDb_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsRWMutex.h" #include "utl/UtlContainable.h" #include "utl/UtlSortedList.h" #include "utl/UtlString.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsConfigEncryption; class UtlSList; /** * Class for holding a name/value pair. */ class DbEntry : public UtlContainable { public: DbEntry(const UtlString &key); DbEntry(const UtlString &key, const UtlString &value); ~DbEntry(); virtual UtlContainableType getContainableType() const; static const UtlContainableType TYPE; virtual unsigned int hash() const; int compareTo(const UtlContainable *b) const; UtlString key; UtlString value; }; /** * Configuration database containing key/value pairs with ability to * read and write to disk. */ class OsConfigDb { friend class OsConfigDbTest; public: OsConfigDb(); virtual ~OsConfigDb(); virtual OsStatus loadFromFile(FILE* fp); /** * Load the configuration database from a file */ virtual OsStatus loadFromFile(const char *filename); /** * Load the configuation database from a string buffer(Buffer * CANNOT be encrypted) with the following format: * * s : s\n * s : * s\n... */ virtual OsStatus loadFromBuffer(const char *buf); /** * Store the config database to a file */ virtual OsStatus storeToFile(const char *filename); /** * Attempts to update existing file without loosing comments or parameter order */ virtual OsStatus updateFile(const char* filename) const; /** * Remove the key/value pair associated with rKey. * * return OS_SUCCESS if the key was found in the database, * return OS_NOT_FOUND otherwise */ OsStatus remove(const UtlString& rKey); /** * Remove all the key/value pairs starting with the designated prefix * * return OS_SUCCESS if one key or more keys were found in the database, * return OS_NOT_FOUND otherwise */ OsStatus removeByPrefix(const UtlString& rPrefix) ; /** * Insert the key/value pair into the config database If the * database already contains an entry for this key, then set the * value for the existing entry to rNewValue. */ void set(const UtlString& rKey, const UtlString& rNewValue); /** * Insert the key/value pair into the config database If the * database already contains an entry for this key, then set the * value for the existing entry to iNewValue. */ void set(const UtlString& rKey, const int iNewValue) ; /** * Sets rValue to the value in the database associated with rKey. * If rKey is found in the database, returns OS_SUCCESS. Otherwise, * returns OS_NOT_FOUND and sets rValue to the empty string. */ virtual OsStatus get(const UtlString& rKey, UtlString& rValue) const; /** * Sets rValue to the value in the database associated with rKey. * If rKey is found in the database, returns OS_SUCCESS. Otherwise, * returns OS_NOT_FOUND and sets rValue to -1. */ virtual OsStatus get(const UtlString& rKey, int& rValue) const; /** * Filename, URI, or what helps identify the contents of this config */ virtual const char *getIdentityLabel() const; /** * Filename, URI, or what helps identify the contents of this config */ virtual void setIdentityLabel(const char *idLabel); /** * Current encryption support. NULL when there's no encryption * support, !NULL then there's a possiblity that actual contents of * config will be encrypted or decrypted from/to io source. */ OsConfigEncryption *getEncryption() const; /** * Set the default encryption support for all OsConfig instances */ static void setStaticEncryption(OsConfigEncryption *encryption); /** * Get the encryption support for call instances */ static OsConfigEncryption *getStaticEncryption(); /** * force capitalization of all keys, most profiles want this off * even keys are typcialy stored as capitalized */ void setCapitalizeName(UtlBoolean capitalize); /** * Store all contents into a buffer, call calculateBufferSize to * get safe size. Call strlen to get actual size */ void storeToBuffer(char *buff) const; /** * Return gauronteed to be large enough, (unless values are * changed) when storing into a buffer */ int calculateBufferSize() const; /** * Return TRUE if the database is empty, otherwise FALSE */ virtual UtlBoolean isEmpty(void) const; /** * Return the number of entries in the config database */ virtual int numEntries(void) const; /** * Get a hash of name value pairs with the given key prefix */ virtual OsStatus getSubHash(const UtlString& rHashSubKey, /**< the prefix for keys to name value pairs * which are copied into the given rSubDb. The key in the * sub-OsConfigDb have the prefix removed. */ OsConfigDb& rSubDb) const; /** * Relative to rKey, return the key and value associated * with next (lexicographically ordered) key/value pair stored in * the database. If rKey is the empty string, key and value * associated with the first entry in the database will be * returned. * * @return OS_SUCCESS if there is a "next" entry; * @return OS_NOT_FOUND if rKey is not found in the database and is not the * empty string * @return OS_NO_MORE_DATA if there is no "next" entry. */ virtual OsStatus getNext(const UtlString& rKey, UtlString& rNextKey, UtlString& rNextValue) const; /** * Stores a list of strings to the configuration datadase using the * designated prefix as the base for the list items. The prefix is used * to build unique configuration keys. For example, if you use specify * a prefix of "MYLIST" and supply a list containing ("item 1", "item 2", * and "item 3"), you will end up with the following: * * MYLIST.COUNT : 3 * MYLIST.1 : item 1 * MYLIST.2 : item 2 * MYLIST.3 : item 3 * * Warning: All items with a key of "[rPrefix]." are removed as a side effect. * * @param rPrefix Configuration name prefix * @param rList List of UtlString values. */ virtual void addList(const UtlString& rPrefix, UtlSList& rList) ; /** * Loads a list of strings from the configuration datadase using the * designated prefix as the base for the list items. The number of * list items is returned. * * @param rPrefix Configuration name prefix * @param rList List of UtlString values. * * @see addList */ virtual int loadList(const UtlString& rPrefix, UtlSList& rList) const; /** * Helper method to obtain a port value from the configuration database. * Results are as follows: *

     *   PORT_DEFAULT : Let a port be selected automatically.
     *                  Represented as "DEFAULT".
     *   PORT_NONE :    Disabled (either specified as such, the key
     *                  was not found, or the value was blank)
     *                  Represented as "NONE".
     *   other :        The port number that was specified
     *                  Represented as a decimal integer.
     * 
* * @param szKey Key file to lookup. */ int getPort(const char* szKey) const; /** * Delete all entries from the configuration database */ void clear() ; /** * Remove newlines and carriage returns from string */ static void removeNewlineReturns(UtlString& stringData); protected: /** reader/writer lock for synchronization */ mutable OsRWMutex mRWMutex; /** sorted storage of key/values */ UtlSortedList mDb; /** ID, used to distiguish which files should be encrypted */ UtlString mIdentityLabel; /** * Force capitalization on all keys. Most profile do not want this * on even though most of their keys are already captilized */ UtlBoolean mCapitalizeName; OsStatus loadFromEncryptedFile(const char *filename); OsStatus loadFromUnencryptedFile(FILE* fp); OsStatus loadFromEncryptedBuffer(char *buf, int bufLen); OsStatus loadFromUnencryptedBuffer(const char *buf); OsStatus storeToEncryptedFile(const char *filename); OsStatus storeBufferToFile(const char *filename, const char *buff, unsigned long buffLen); void dump(); virtual OsStatus storeToFile(FILE* fp); /** * Parse "key : value" and returns TRUE if parameter found * Returns false if line is blank or a comment (begins with #). */ static UtlBoolean parseLine(const char* line, UtlBoolean capitalizeName, const char* fileLabelForError, UtlString& name, UtlString& value); /** * Method for inserting a key/value pair into the dictionary * The write lock for the database should be taken before calling this * method. If the database already contains an entry for this key, then * set the value for the existing entry to rNewValue. */ void insertEntry(const UtlString& rKey, const UtlString& rNewValue); /** * Copy constructor (not implemented for this class) */ OsConfigDb(const OsConfigDb& rOsConfigDb); /** * Assignment operator (not implemented for this class) */ OsConfigDb& operator=(const OsConfigDb& rhs); /** * Utility func to remove all chars = c from given string */ static void removeChars(UtlString *s, char c); }; /* ============================ INLINE METHODS ============================ */ #endif // _OsConfigDb_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsConfigEncryption.h0000644000175000017500000000425712205613256025666 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsConfigEncryption_h_ #define _OsConfigEncryption_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsEncryption.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsConfigDb; // for some reason, #include os/OsConfigDb was not working /*! OsConfigDb consults a this class to handle all the details of encrypting and decrypting files and buffers w/o knowing the details. Systems provide an implemenation of this and in the case of the phone, determines which profiles should be encrypted, what the key is and can configure the OsEncryption instance */ class OsConfigEncryption { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: //! Test a buffer if it's actually encrypted virtual UtlBoolean isEncrypted(OsConfigDb *cfg, const char *buffer, int buffLen) = 0; //! Is this profile typically encrypted, decision usually based from cfg->getIndentyLabel() virtual UtlBoolean isNormallyEncrypted(OsConfigDb *cfg) = 0; //! Handle the details of encrypting, look in OsEncryption instance for results virtual OsStatus encrypt(OsConfigDb *cfg, OsEncryption *encryption, char *buffer, int buffLen) = 0; //! Handle the details of decrypting, look in OsEncryption instance for results virtual OsStatus decrypt(OsConfigDb *cfg, OsEncryption *encryption, char *buffer, int buffLen) = 0; //! Is writing profile encrypted on/off at a system level. virtual UtlBoolean isWriteEncryptedEnabled() = 0; //! If not NULL, a binary prefix header on files to tell if files are encrypted or not // virtual const unsigned char *getFileHeader(int& headerLen) = 0; virtual ~OsConfigEncryption(){}; }; /* ============================ INLINE METHODS ============================ */ #endif // _OsConfigEncryption_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsConnectionSocket.h0000644000175000017500000001213512205613256025650 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsConnectionSocket_h_ #define _OsConnectionSocket_h_ // SYSTEM INCLUDES //#include <...> // APPLICATION INCLUDES #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlSList; //: Implements TCP version of OsSocket // This class provides the implementation of the TCP datagram // based socket class which may be instantiated. class OsConnectionSocket : public OsSocket { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsConnectionSocket(int remoteHostPort, const char* remoteHostName, UtlBoolean makeBlocking = TRUE, const char* localIp = NULL, const bool bConnect = true); OsConnectionSocket(int connectedSocketDescriptor); OsConnectionSocket(const char* localIp, int connectedSocketDescriptor); virtual ~OsConnectionSocket(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual int connect(); //: Sets up the initial connection with the server virtual UtlBoolean reconnect(); //: Sets up the connection again, assuming the connection failed virtual int read(char* buffer, int bufferLength); //:Blocking read from the socket // Read bytes into the buffer from the socket up to a maximum of // bufferLength bytes. This method will block until there is // something to read from the socket. //!param: buffer - Place to put bytes read from the socket. //!param: bufferLength - The maximum number of bytes buffer will hold. //!returns: The number of bytes actually read. virtual int read(char* buffer, int bufferLength, UtlString* ipAddress, int* port); //:Blocking read from the socket // Read bytes into the buffer from the socket up to a maximum of // bufferLength bytes. This method will block until there is // something to read from the socket. //!param: buffer - Place to put bytes read from the socket. //!param: bufferLength - The maximum number of bytes buffer will hold. //!param: ipAddress - The address of the socket that sent the bytes read. //!param: port - The port of the socket that sent the bytes read. //!returns: The number of bytes actually read. virtual int read(char* buffer, int bufferLength, long waitMilliseconds); //: Non-blocking or limited blocking read from socket // Same as blocking version except that this read will block // for no more than the specified length of time. //!param: waitMilliseconds - The maximum number of milliseconds to block. This may be set to zero in which case it does not block. /* ============================ ACCESSORS ================================= */ virtual OsSocket::IpProtocolSocketType getIpProtocol() const; //: Returns the protocol type of this socket /* ============================ INQUIRY =================================== */ /// Is this connection encrypted using TLS/SSL? virtual bool isEncrypted() const; /// Get any authenticated peer host names. virtual bool peerIdentity( UtlSList* altNames = NULL /**< UtlStrings for verfied subjectAltNames * are added to this * @note caller must free them. */ ,UtlString* commonName = NULL ///< the Subject name is returned here ) const; /**< * Usually, the names in the altNames will be easier to parse and use than commonName * Either or both of altNames or commonName may be NULL, in which case no names are returned; * the return value still indicates the trust relationship with the peer certificate. * @returns * - true if the connection is TLS/SSL and the peer has presented * a certificate signed by a trusted certificate authority * - false if not */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: bool initialize(const char* serverName, int serverPort, UtlBoolean blockingConnect); /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: struct sockaddr_in serverSockAddr; OsConnectionSocket(const OsConnectionSocket& rOsConnectionSocket); //:Disable copy constructor OsConnectionSocket(); //:Disable default constructor OsConnectionSocket& operator=(const OsConnectionSocket& rhs); //:Assignment operator }; /* ============================ INLINE METHODS ============================ */ #endif // _OsConnectionSocket_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsContact.h0000644000175000017500000001301212205613256023766 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 Pingtel Corp. // // // $$ //////////////////////////////////////////////////////////////////////// ////// #ifndef _OsContact_h_ #define _OsContact_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlContainable.h" #include "utl/UtlString.h" #include "os/OsSocket.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /* ============================ ENUMERATIONS ============================== */ /** * Enumeration of IP address types. */ enum IpAddressType { IP4, /** < Internet Protocol version 4 >*/ IP6 /** < Internet Protocol version 6 >*/ }; /** * OsContact is a containable object which represents * an inter-networking point of contact, * which could also be described as a "transport endpoint". * It contains an address, a port value, a protocol, and the * address type. */ class OsContact : public UtlContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ FRIENDS =================================== */ friend class OsContactTests; /* ============================ ENUMERATIONS ============================== */ /* ============================ CREATORS ================================== */ /** * Constructor. * * @param address String representation of the ip address. * For IPv4, it should be in "dotted quad" notation. * For IPv6, it should use the text representation of * addresses specified in RFC 3513. * * Note that IP addresses which are sematically * identical, but differ in string representation, will * be considered as not being equal. (e.g. - * a contact having an address "192.168.1.2" will not equal * a contact having an address "192.168.001.002". * * Note that the current design doesn't allow for IPV4 tunneled over * IPV6 to compare correctly with the original IPV4 address. * * Note that IP addresses will be compared as strings, * so, use of wildcard addresses ("0.0.0.0") will not match any * other address. * * @param port The port value for the contact. * @param protocol The prefered protocol for this contact. * @param type The type of ip address. */ OsContact(UtlString address, int port, OsSocket::IpProtocolSocketType protocol, IpAddressType type); /** * Copy constructor. */ OsContact(const OsContact& ref); /** * Destructor */ virtual ~OsContact(); /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /** * Accessor for the address string. */ const void getAddress(UtlString& address) const; /** * Accessor for the port value. */ const int getPort() const; /** * Accessor for the protocol enum value. */ const OsSocket::IpProtocolSocketType getProtocol() const; /** * Accessor for the address type enum value. */ const IpAddressType getAddressType() const; /** * Calculate a unique hash code for this object. If the equals * operator returns true for another object, then both of those * objects must return the same hashcode. */ virtual unsigned hash() const ; /** * Get the ContainableType for a UtlContainable derived class. */ virtual UtlContainableType getContainableType() const; /* ============================ INQUIRY =================================== */ /** * Compare the this object to another like-objects. Results for * designating a non-like object are undefined. * * @returns 0 if equal, < 0 if less then and >0 if greater. */ virtual int compareTo(UtlContainable const *) const ; /** * Test this object to another like-object for equality. This method * returns false if unlike-objects are specified. */ virtual UtlBoolean isEqual(UtlContainable const *) const ; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: static UtlContainableType TYPE ; /** < Class type used for runtime checking */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /** * Disallow assignment. */ OsContact& operator=(const OsContact&) ; /** * Helper function for comparison of two ints. * * @param first First integer in the comparison pair. * @param second Second integer in the comparison pair. * * @returns 0 if equal, < 0 if first is less then and >0 if greater. */ const int compareInt(const int first, const int second) const; UtlString mAddress; /** < String representation of the ip address. */ int mPort ; /** < The port value for the contact. */ OsSocket::IpProtocolSocketType mProtocol; /**< The prefered protocol for this contact. */ IpAddressType mType; /**< The type of ip address. */ } ; /* ============================ INLINE METHODS ============================ */ #endif // _OsContact_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsContactList.h0000644000175000017500000000430512205613256024627 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 Pingtel Corp. // // // $$ //////////////////////////////////////////////////////////////////////// ////// #ifndef _OsContactList_h_ #define _OsContactList_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlSList.h" #include "os/OsContact.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlContainable; /** * OsContactList is a simple extension of UtlSList that allows for the * setting and getting of a 'primary' contact. * * @see UtlSList * @see UtlContainer * @see UtlContainable */ class OsContactList : public UtlSList { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ FRIENDS =================================== */ friend class OsContactListTest; /* ============================ CREATORS ================================== */ /** * Default Constructor */ OsContactList(); /* ============================ MANIPULATORS ============================== */ /** * Method for designating a 'primary' contact, which may or * may not already be in the list. If it is not already in the list * it is added to the list. * * @param contact The contact to set as the 'primary'. */ void setPrimary(const OsContact& contact); /* ============================ INQUIRY =================================== */ /** * Method for gettting the 'primary' contact. If no primary contact has * be explicitly set with setPrimary, the first contact in the list is * returned. */ const OsContact* getPrimary(); /** * Get the ContainableType for the OsContactList as a contained object. */ virtual UtlContainableType getContainableType() const; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: friend class UtlSListIterator; static const UtlContainableType TYPE; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: } ; /* ============================ INLINE METHODS ============================ */ #endif // _OsContactList_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsCSem.h0000644000175000017500000001002312205613256023221 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsCSem_h_ #define _OsCSem_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsSyncBase.h" #include "os/OsBSem.h" // DEFINES //Uncomment next line to see semaphore errors when they occur //#define OS_CSEM_DEBUG //Uncomment next line (as well as above line) to see all acquires and releases. //#define OS_CSEM_DEBUG_SHOWALL // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /// Counting semaphore class OsCSemBase : public OsSyncBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum QueueOptions { Q_FIFO = 0x0, ///< queue blocked tasks on a first-in, first-out basis Q_PRIORITY = 0x1 ///< queue blocked tasks based on their priority }; /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ /// Block the task until the semaphore is acquired or the timeout expires virtual OsStatus acquire(const OsTime& rTimeout = OsTime::OS_INFINITY) = 0; /// Conditionally acquire the semaphore (i.e., don't block) virtual OsStatus tryAcquire(void) = 0; /** * @return OS_BUSY if the semaphore is held by some other task. */ /// Release the semaphore virtual OsStatus release(void) = 0; /* ============================ ACCESSORS ================================= */ #ifdef OS_CSEM_DEBUG /// Print statistics gathered virtual void show(void) ; /// Returns the current value of the semaphone virtual int getValue(void) ; #endif /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: #ifdef OS_CSEM_DEBUG OsBSem mGuard; ///< Guard to protect the statistics ///< used for debugging int mQueueOptions; int mInitialCount; int mMaxCount; int mCurCount; int mHighCount; int mLowCount; int mNumAcquires; int mNumReleases; #endif /// Default constructor OsCSemBase(const int queueOptions, const int maxCount, const int initCount) ; /// Destructor virtual ~OsCSemBase() { }; #ifdef OS_CSEM_DEBUG /// Update the statistics associated with acquiring a counting semaphore void updateAcquireStats(void); /// Update the statistics associated with releasing a counting semaphore void updateReleaseStats(void); #endif /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /// Copy constructor (not implemented for this class) OsCSemBase(const OsCSemBase& rOsCSemBase); /// Assignment operator (not implemented for this class) OsCSemBase& operator=(const OsCSemBase& rhs); }; /* ============================ INLINE METHODS ============================ */ /// Depending on the native OS that we are running on, we include the class /// declaration for the appropriate lower level implementation and use a /// "typedef" statement to associate the OS-independent class name (OsCSem) /// with the OS-dependent realization of that type (e.g., OsCSemWnt). #if defined(_WIN32) # include "os/Wnt/OsCSemWnt.h" typedef class OsCSemWnt OsCSem; #elif defined(_VXWORKS) # include "os/Vxw/OsCSemVxw.h" typedef class OsCSemVxw OsCSem; #elif defined(__pingtel_on_posix__) # include "os/linux/OsCSemLinux.h" typedef class OsCSemLinux OsCSem; #else # error Unsupported target platform. #endif #endif // _OsCSem_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsDatagramSocket.h0000644000175000017500000001252212205613256025271 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsDatagramSocket_h_ #define _OsDatagramSocket_h_ // SYSTEM INCLUDES //#include <...> // APPLICATION INCLUDES #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //: Implements UDP version of OsSocket // This class provides the implementation of the UDP datagram-based // socket class which may be instantiated. class OsDatagramSocket : public OsSocket { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsDatagramSocket(int remoteHostPort, const char* remoteHostName, int localHostPort = PORT_DEFAULT, const char* localHostName = NULL); //:Constructor virtual ~OsDatagramSocket(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual UtlBoolean reconnect(); //: Sets up the connection again, assuming the connection failed void doConnect(int remotePort, const char* remoteHostName, UtlBoolean simulateConnect = FALSE); // Setup a connection with a remote host on the specified remote port //! param: remoteHostName - remote host to send datagram(s) in subsequent calls to write (overloaded version without host and port) //! param: remotePort - port on the remote host to send the datgram(s) //! param: simulateConnect - if TRUE do not call connect but default the to location (as in sendto) to the given host and port. This is desirable to prevent the receiving of packets from other hosts from being filtered out by the IP stack. virtual int write(const char* buffer, int bufferLength); //: Blocking write to the socket // Write the characters in the given buffer to the socket. // This method will block until all of the bytes are written. //! param: buffer - the bytes to be written to the socket //! param: bufferLength - the number of bytes contained in buffer //! returns: the number of bytes actually written to the socket virtual int write(const char* buffer, int bufferLength, const char* ipAddress, int port); //: Blocking write to the socket // Write the characters in the given buffer to the socket. // This method will block until all of the bytes are written. //! param: buffer - the bytes to be written to the socket //! param: bufferLength - the number of bytes contained in buffer //! param: ipAddress - remote host to send datagram(s) to //! param: port - port on the remote host to send the datgram(s) //! returns: the number of bytes actually written to the socket virtual int read(char* buffer, int bufferLength); /* ============================ ACCESSORS ================================= */ virtual OsSocket::IpProtocolSocketType getIpProtocol() const; //: Returns the protocol type of this socket virtual void getRemoteHostIp(struct in_addr* remoteHostAddress, int* remotePort = NULL); //:Return remote host ip address // Returns the ip address for the host on which the socket on the // other end of this socket is bound. virtual UtlBoolean getMappedIp(UtlString* ip, int* port) ; //:Return the external IP address for this socket. // OsStunDatagramSocket will return the NATted address if available, /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsDatagramSocket(); //:Bare-bones constructor // Callers will need to call bind & doConnect on their own when this returns // (This allows for children to set socket options before the bind call) int bind(int localHostPortNum = PORT_DEFAULT, const char* localHost = NULL); /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsDatagramSocket(const OsDatagramSocket& rOsDatagramSocket); //:Disable copy constructor OsDatagramSocket& operator=(const OsDatagramSocket& rhs); //:Disable assignment operator time_t mLastWriteErrorTime; int mNumTotalWriteErrors; int mNumRecentWriteErrors; UtlBoolean mSimulatedConnect; UtlBoolean mToSockaddrValid; struct sockaddr_in* mpToSockaddr; int ctorCommonCode(); //:Common code for both constructors. virtual int writeTo(const char* buffer, int bufferLength); //: Blocking write to the socket, with simulated connection // Write the characters in the given buffer to the socket. // This method will block until all of the bytes are written. //! param: buffer - the bytes to be written to the socket //! param: bufferLength - the number of bytes contained in buffer //! returns: the number of bytes actually written to the socket virtual UtlBoolean getToSockaddr(void); }; /* ============================ INLINE METHODS ============================ */ #endif // _OsDatagramSocket_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsDateTime.h0000644000175000017500000002214012205613256024071 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsDateTime_h_ #define _OsDateTime_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS #if defined(_WIN32) && !defined(_TIMESPEC_T) #define _TIMESPEC_T struct timespec { time_t tv_sec; // seconds long tv_nsec; // nanoseconds }; #endif // TYPEDEFS // FORWARD DECLARATIONS class OsTime; class UtlString; //:DateTime management functions /* On Solaris, DST_NONE is defined to be 0! This causes a syntax error. Rather * than change it, we can just undefine it - if it ever is defined, even in * other operating systems, we don't want it to be. Since anyone who wants to * use OsDateTime::DST_NONE will include this file, they'll inherit the * undefinition. */ #ifdef DST_NONE #undef DST_NONE #endif class OsDateTimeBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum DstRule { DST_NONE, DST_NORTH_AMERICA, DST_WESTERN_EUROPE }; static const char* spMonthStrings[12]; //: Array containing the 3 character month names static const char* spDayStrings[7]; //: Array containing the 3 character day of the week names /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ static long tm2Epoch(const struct tm *t); //:Convert tm struct to epoch time //! returns: the number of seconds since the begining of 1970. static long convertHttpDateToEpoch(const char *date); //:Parse HTTP text format date and convert to epoch time // See RFC 822, 1123, 850, 1036 //! returns: the number of seconds since the begining of 1970. static void setTime(struct timespec gmt); //:Set the system time and retain the previous settings for //: time zone offset and daylight savings rules static void setTime(struct timespec gmt, int tzOffsetSecs, DstRule dstRule); //:Set the system time //!param: (in) gmt - time relative to the beginning of 1970 (GMT) //!param: (in) tzOffsetSecs - local time offset (seconds relative to GMT) //!param: (in) dstRule - daylight savings time rule static void setTimeZone(int tzOffsetSecs, DstRule dstRule); //:Set the time zone and daylight savings time information //!param: (in) tzOffsetSecs - local time offset (seconds relative to GMT) //!param: (in) dstRule - daylight savings time rule /* ============================ ACCESSORS ================================= */ virtual OsStatus cvtToTimeSinceBoot(OsTime& rTime) const = 0; //:Convert the OsDateTimeBase value to an OsTime value. //:The OsTime value is relative to when the system was booted. virtual OsStatus cvtToTimeSinceEpoch(OsTime& rTime) const; //:Convert the OsDateTimeBase value to an OsTime value. //:The OsTime value is relative to midnight (0 hour) 01/01/70. static void getDayOfWeek(int year, int month, int dayOfMonth, int& dayOfWeek); //:Get the day of the week given the date //!param: (in) year - 4 digit year //!param: (in) month - 0-11 //!param: (in) dayOfMonth - the day of the month 1-31 //!param: (out) dayOfWeek - the day of the week 0-6 void getDayOfWeek(int& dayOfWeek); //:Get the day of the week for this OsDateTime //!param: (out) dayOfWeek - the day of the week 0-6 inline unsigned int getMicrosecond() const; //:Microsecond, valid range: 0 - 999999 inline unsigned short getYear() const; //:4 digit year inline unsigned char getMonth() const; //:January = 0, February = 1, and so on inline unsigned char getDay() const; //:Day of month, valid range: 1-31 inline unsigned char getHour() const; //:Hour, valid range: 0 - 23 inline unsigned char getMinute() const; //:Minute, valid range 0 - 59 inline unsigned char getSecond() const; //:Second, valid range 0 - 59 virtual void getHttpTimeString(UtlString& dataString); //:Get the RFC 822/1123 format date string for this OsDateTime // E.g. Wed, 06 Mar 2002 05:51:44 GMT // Assumes this OsDateTime is GMT static void getLocalTimeString(UtlString& dateString); //:Return the current local time as an OsDateTime value in the // following format: // Mon, 8/26/2002 07:21:32 PM EST /// Set the dateString to the time as UTC time in a Postgres compatible format: /// 2002-08-26 19:21:32.000 void getSqlTimeStringZ(UtlString& dateString); /// Set the dateString to the time as UTC time in the following format: /// 2002-08-26T19:21:32.000Z void getIsoTimeStringZ(UtlString& dateString); /// Set the dateString to the time as UTC time in the following format: /// 2002-08-26T19:21:32.000000Z void getIsoTimeStringZus(UtlString& dateString); static void getCurTime(OsDateTimeBase& rDateTime); //:Return the current time as an OsDateTime value static void getCurTime(OsTime& rTime); //:Return the current time as an OsTime value static void getCurTimeSinceBoot(OsTime& rTime); //:Return the current time as an OsTime value // The OsTime value is relative to when the system was booted. static unsigned long getSecsSinceEpoch(void); //:Current time as the number of seconds since midnight (0 hour) 01/01/70 /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: static DstRule sDstRule; // the daylight savings time rule in effect static int sDstYear; // the year (relative to 1900) that was // used to determine the start and end // dates for daylight savings time static int sTzOffsetSecs; // time zone offset expressed as seconds // east of the zero meridian. For example // US Eastern time is -18000 OsDateTimeBase(); //:Default constructor OsDateTimeBase(const unsigned short year, /**< XXXX year */ const unsigned char month, /**< 0-based month; 0=JAN, 1=FEB */ const unsigned char day, /**< 1-based day (1..31) */ const unsigned char hour, /**< Hour is 24-hour format (0..23) */ const unsigned char minute, /**< Minute (0..59) */ const unsigned char second, /**< Second (0..59) */ const unsigned int microsecond); /**< Microseconds (0 - 999999) */ //:Constructor OsDateTimeBase(const OsDateTimeBase& rOsDateTime); //:Copy constructor virtual ~OsDateTimeBase(); //:Destructor OsDateTimeBase& operator=(const OsDateTimeBase& rhs); //:Assignment operator unsigned int mMicrosecond; //:Microsecond, valid range: 0 - 999999 unsigned short mYear; //:4 digit year unsigned char mMonth; //:January = 0, February = 1, and so on unsigned char mDay; //:Day of month, valid range: 1-31 unsigned char mHour; //:Hour, valid range: 0 - 23 unsigned char mMinute; //:Minute, valid range 0 - 59 unsigned char mSecond; //:Second, valid range 0 - 59 /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: static int checkmask(const char *data, const char *mask); //: parsing utility used to parse text dates and times }; /* ============================ INLINE METHODS ============================ */ unsigned int OsDateTimeBase::getMicrosecond() const { return mMicrosecond; } unsigned short OsDateTimeBase::getYear() const { return mYear; } unsigned char OsDateTimeBase::getMonth() const { return mMonth; } unsigned char OsDateTimeBase::getDay() const { return mDay; } unsigned char OsDateTimeBase::getHour() const { return mHour; } unsigned char OsDateTimeBase::getMinute() const { return mMinute; } unsigned char OsDateTimeBase::getSecond() const { return mSecond; } // Depending on the native OS that we are running on, we include the class // declaration for the appropriate lower level implementation and use a // "typedef" statement to associate the OS-independent class name (OsDateTime) // with the OS-dependent realization of that type (e.g., OsDateTimeWnt). #if defined(_WIN32) # include "os/Wnt/OsDateTimeWnt.h" typedef class OsDateTimeWnt OsDateTime; #elif defined(_VXWORKS) # include "os/Vxw/OsDateTimeVxw.h" typedef class OsDateTimeVxw OsDateTime; #elif defined(__pingtel_on_posix__) # include "os/linux/OsDateTimeLinux.h" typedef class OsDateTimeLinux OsDateTime; #else # error Unsupported target platform. #endif #endif // _OsDateTime_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsDefs.h0000644000175000017500000001303212205613256023256 0ustar00danieldaniel00000000000000/* // // // Copyright (C) 2005-2009 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2009 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// */ /* NOTE THIS FILE MUST BE INCLUDABLE IN C CODE as well as C++ */ /* USE C Style comments */ #ifndef _OsDefs_h_ #define _OsDefs_h_ /* SYSTEM INCLUDES */ /* APPLICATION INCLUDES */ #include #ifdef _VXWORKS # include "os/Vxw/OsVxwDefs.h" #endif /* _VXWORKS */ #ifdef __pingtel_on_posix__ # include "os/linux/OsLinuxDefs.h" #endif /* __pingtel_on_posix__ */ /* MACROS */ #if defined(_VXWORKS) /* wdn - OK == 0 defined in vxWorks.h but has issues ??? */ # define IS_INET_RETURN_OK( x ) (x == 0) #else # define IS_INET_RETURN_OK( x ) (x > 0) #endif /* * S_IREAD and S_IWRITE are not always defined, e.g. they're not * defined in bionic (Android's libc). */ #ifdef DEFINE_S_IREAD_IWRITE # define S_IREAD (S_IRUSR | S_IRGRP | S_IROTH) # define S_IWRITE (S_IWUSR) #endif // O_BINARY is needed for WIN32, but is not defined under VxWorks and Linux #ifdef __pingtel_on_posix__ # define O_BINARY 0 #endif /* * If we're compiling for windows using a visual studio prior to VS2008 * http:*www.casabasecurity.com/content/visual-studio-2008-crt-bug * Basically, prior versions of Visual Studio did not define snprintf * or vsnprintf, because they were not ANSI compliant. * Even now, with VS2008, they aren't compliant, however visual studio * has gone about and defined vsnprintf. * http:*connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=101293 */ #if defined(WIN32) && defined(_MSC_VER) # define snprintf _snprintf #if (_MSC_VER < 1500) # define vsnprintf _vsnprintf #endif #define popen _popen #define pclose _pclose /* * WIN32 doesn't have wait(), so the return value for children * is simply the return value specified by the child, without * any additional information on whether the child terminated * on its own or via a signal. These macros are also used * to interpret the return value of system(). */ #define WEXITSTATUS(w) (w) #define WIFEXITED(w) (true) #define WIFSIGNALED(w) (false) #define WTERMSIG(w) (0) #endif #if defined(va_copy) #elif defined(__va_copy) # define va_copy(dst, src) __va_copy((dst), (src)) #else //# define va_copy(dst, src) (memcpy(&(dst), &(src), sizeof (va_list))) # define va_copy(dst, src) ((dst) = (src)) #endif /* * Handle the case-insensitive string comparison functions, by making * the Posix names strcasecmp and strncasecmp available on all platforms. * (On newer Windows environments, str(n)casecmp are built-in, along * with the older str(n)icmp, but on older ones, they are not.) */ #ifdef WIN32 /* if wince, or win and >= msvc8(vs2005) */ # if defined(WINCE) || (defined(_MSC_VER) && (_MSC_VER >= 1400)) # ifndef strcasecmp # define strcasecmp _stricmp # endif # ifndef strncasecmp # define strncasecmp _strnicmp # endif # else # ifndef strcasecmp # define strcasecmp stricmp # endif # ifndef strncasecmp # define strncasecmp strnicmp # endif # endif #endif /* Define min and max if they're not already defined. */ #ifndef sipx_max # define sipx_max(x,y) (((x)>(y))?(x):(y)) #endif #ifndef sipx_min # define sipx_min(x,y) (((x)<(y))?(x):(y)) #endif #ifdef __cplusplus extern "C" { #endif #if defined (_VXWORKS) /* Only needed for VxWorks --GAT */ int strcasecmp(const char *, const char *); char * strdup (const char *); /* These function names are for code compatibility with Windows. --GAT */ # ifndef strcmpi # define strcmpi strcasecmp # endif # ifndef stricmp # define stricmp strcasecmp # endif # ifndef _stricmp # define _stricmp strcasecmp # endif #endif /* _VXWORKS */ extern unsigned int pspGetLocalMemLocalAddr(void); extern unsigned int pspGetLocalMemSize(void); #define SysLowerMemoryLimit (pspGetLocalMemLocalAddr()) #define SysUpperMemoryLimit (pspGetLocalMemLocalAddr() + pspGetLocalMemSize() - 4) extern int hSipLogId; void enableConsoleOutput(int bEnable) ; void osPrintf(const char* format , ...) #ifdef __GNUC__ /* with the -Wformat switch, this enables format string checking */ __attribute__ ((format (printf, 1, 2))) #endif ; /* A special value for "port number" which means that no port is specified. */ #define PORT_NONE (-1) /* * A special value for "port number" which means that some default * port number should be used. The default may be defined by the * situation, or the OS may choose a port number. * For use when PORT_NONE is used to mean "open no port", and in * socket-opening calls. */ #define PORT_DEFAULT (-2) /* * Macro to test a port number for validity as a real port (and not * PORT_NONE or PORT_DEFAULT). Note that 0 is a valid port number for * the protocol, but the Berkeley sockets interface makes it * impossible to specify it. In addition, RTP treats port 0 as a * special value. Thus we forbid port 0. */ #define portIsValid(p) ((p) >= 1 && (p) <= 65535) #ifdef __cplusplus } #endif #include "stdlib.h" #include "string.h" #include "stdio.h" #include "time.h" #if defined(__sun) && defined(__SVR4) # include # include # include # ifdef __cplusplus extern "C" # endif extern int getdomainname(char *, int); #endif #endif /* _OsDefs_h_ */ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsDirBase.h0000644000175000017500000000575212205613256023720 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsDirBase_h_ #define _OsDirBase_h_ // SYSTEM INCLUDES #include "os/OsStatus.h" #include "os/OsDefs.h" #include "os/OsFS.h" // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsFileInfoBase; class OsPathBase; //:Abstraction class to hande directory manipulations class OsDirBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsDirBase(const char* pathname); OsDirBase(const OsPathBase& rOsPath); OsDirBase(const OsDirBase& rOsDir); //:Copy constructor virtual ~OsDirBase(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsStatus create() const; //: Create the path specified by this object // Returns OS_SUCCESS if successful, or OS_INVALID virtual OsStatus remove(UtlBoolean bRecursive, UtlBoolean bForce) const; //: Removes the directory name specified by this object //: Set bForce to TRUE to remove read-only directory //: Set bRecursive to TRUE remove sub-directories // Returns: // OS_SUCCESS if successful // OS_FILE_ACCESS_DENIED if directory is in use or contains files // OS_FILE_PATH_NOT_FOUND if specifed directory is not found virtual OsStatus rename(const char* name); //: Renames the current directory to the name specified // Returns: // OS_SUCCESS if successful // OS_INVALID if failed /* ============================ ACCESSORS ================================= */ virtual OsStatus getFileInfo(OsFileInfoBase& rFileInfo) const = 0; //: Returns the file information for this objects path (see //: OsFileInfo for more detail) // Returns: // OS_SUCCESS if successful // OS_INVALID if failed virtual void getPath(OsPathBase& rOsPath) const; //: Returns a reference to the full path stored in this object /* ============================ INQUIRY =================================== */ virtual UtlBoolean exists(); //: Returns TRUE if the directory specified by this object exists /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsDirBase& operator=(const OsDirBase& rhs); //:Assignment operator OsPathBase mDirName; //:Directory name /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _OsDirBase_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsEncryption.h0000644000175000017500000000676512205613256024546 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsEncryption_h_ #define _OsEncryption_h_ // SYSTEM INCLUDES #ifdef HAVE_SSL #define OSENCRYPTION #endif #if defined (OSENCRYPTION) #include #include #endif // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsTime.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define OE_MAX_KEY_LEN 64 #define OE_MAX_RESULTS_HEADER_LEN 32 // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //! Wrapper and helper around system encryption routines. /*! Hide encryption details like: what alg. is chosen initialization details of alg. messy details allocating buffers padded to minumal key length Create one instance per encryption/decryption operation. As such, this class makes no provisions to be multi-threaded FUTURE: enum encryption alg posibilities and add approp accessor methods. today there is only one, PBE/DES via OpenSSL */ class OsEncryption { public: //! Create one for each encryption/decryption operation OsEncryption(void); virtual ~OsEncryption(void); //! Data to feed to encryption, not touched and NOT copied, so keep it around void setDataPointer(unsigned char *pIn, int inLen); //! How large is the untouched data buffer int getDataLen(void); //! Pointer to untouched data buffer unsigned char *getDataPointer(void); //! If you want to prepend this to the results header for file identification purposes void setResultsHeader(const unsigned char *header, int headerLen); //! After [en/de]crypting, here's your results unsigned char *getResults(void); //! After [en/de]crypting get your results here int getResultsLen(void); //! set secret password void setKey(const unsigned char *key, int keyLen); //! operate after setting approp. input. . NOTE: This will return OS_FAILED on vxworks. */ OsStatus decrypt(void); //! operate after setting approp. input. NOTE: This will return OS_FAILED on vxworks. */ OsStatus encrypt(void); //! free all, called in descructor OsStatus release(void); //! DEBUG turn on/off static UtlBoolean sIgnoreEncryption; protected: //! OpenSSL state differentation direction for API calls enum Direction { DECRYPT = 0, ENCRYPT = 1 }; //! allocate OpenSSL stuff OsStatus init(Direction direction); //! common handling of OpenSSL's errors UtlBoolean openSslError(void); //! common [en/de]crypt method OsStatus crypto(Direction direction); private: #if defined (OSENCRYPTION) X509_ALGOR *mAlgorithm; EVP_CIPHER_CTX mContext; #endif unsigned char *mSalt; // defeats brute force decryption via appling dictionary int mSaltLen; unsigned char mKey[OE_MAX_KEY_LEN]; // storage of password int mKeyLen; unsigned char *mData; // pointer to storage of data int mDataLen; unsigned char *mResults; // allocated storage of results int mResultsLen; unsigned char mHeader[OE_MAX_RESULTS_HEADER_LEN]; // set/expect extra data in results buffer int mHeaderLen; // TEST: See unittests/EncryptionTest }; #endif // _OsEncryption_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsEvent.h0000644000175000017500000001365612205613256023472 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsEvent_h_ #define _OsEvent_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsBSem.h" #include "os/OsNotification.h" #include "os/OsTime.h" #include "os/OsMutex.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * @brief Events are used to synchronize a task with an ISR or between two tasks. * * Events consist of event data (an integer) that is set when the event is * signaled and a state variable that indicates whether the event has been * signaled. When first initialized, an OsEvent is ready to be signaled. * However, once signaled, the OsEvent must be explicitly reset before it * may be signaled again. An OsEvent is intended for use in synchronizing * one notifier (task or ISR) with one listener task. If an OsEvent object * is intended for use with more than one notifier or listener, then an * external mutex must be used to serialize access and avoid race * conditions. * *

Background

* First, a little bit of terminology. The task that wishes to be notified * when an event occurs is the "Listener" task. The task that signals when * a given event occurs is the "Notifier" task. A Notifier informs the * Listener that a given event has occurred by sending an "Event * Notification". * *

Expected Usage

* The Listener passes an event object to the Notifier. When the * corresponding event occurs, the Notifier uses the event object * to signal the occurrence of the event. The Listener may receive * event notifications by: polling, blocking until the event is * signaled, or blocking until either the event is signaled or a * timeout expires. When the Listener receives the event * notification, it can then invoke the appropriate event handler. * This handler will run in the Listener's task context. * * @note Using a busy loop to poll for event status is considered * anti-social behavior. However, when using the event object * approach, a task can perform a blocking wait for only one event * at a time. A solution that allows a task to receive signals * for multiple events is a message queue (see OsQueuedEvent for more * information). */ class OsEvent : public OsNotification { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /// Constructor OsEvent(const intptr_t userData=0); /// Destructor virtual ~OsEvent(); /* ============================ MANIPULATORS ============================== */ /// Set the event data and signal the occurrence of the event virtual OsStatus signal(const intptr_t eventData); /**< * Return OS_ALREADY_SIGNALED if the event has already been signaled * (and has not yet been cleared), otherwise return OS_SUCCESS. */ /// Reset the event so that it may be signaled again virtual OsStatus reset(void); /**< * Return OS_NOT_SIGNALED if the event has not been signaled (or has * already been cleared), otherwise return OS_SUCCESS. */ /// Wait for the event to be signaled virtual OsStatus wait(const OsTime& rTimeout=OsTime::OS_INFINITY); /**< * Return OS_BUSY if the timeout expired, otherwise return OS_SUCCESS. */ /// Sets the user data specified. There are situations (such as the OsProtedtedEvent) virtual OsStatus setUserData(intptr_t userData); /**< * when the user data can not be specified when this object was constructed * so that this method is necessary to set the user data. * Always returns OS_SUCCESS. */ /* ============================ ACCESSORS ================================= */ /// Return the event data that was signaled by the notifier task. virtual OsStatus getEventData(intptr_t& rEventData); /**< * Return OS_NOT_SIGNALED if the event has not been signaled (or has * already been cleared), otherwise return OS_SUCCESS. */ /// Return the user data specified when this object was constructed. virtual OsStatus getUserData(intptr_t& rUserData) const; /**< * Always returns OS_SUCCESS. */ /* ============================ INQUIRY =================================== */ /// Return TRUE if the event has been signaled, otherwise FALSE virtual UtlBoolean isSignaled(void); /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: intptr_t mEventData; ///< Data set when the event was signaled. UtlBoolean mIsSignaled; ///< Indicates whether the event has been signaled. OsBSem mSignalSem; ///< Semaphore used to queue up tasks waiting for ///< the event to be signaled. OsMutex mMutex; ///< Mutex to synchronize access to member variables, ///< especially to mIsSignaled, which may cause ///< deadlock when changed without synchronization. intptr_t mUserData; ///< Data specified on behalf of the user and ///< not otherwise used by this class -- the user ///< data is specified as an argument to the class ///< constructor. /// Copy constructor (not implemented for this class) OsEvent(const OsEvent& rOsEvent); /// Assignment operator (not implemented for this class) OsEvent& operator=(const OsEvent& rhs); }; /* ============================ INLINE METHODS ============================ */ #endif // _OsEvent_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsEventMsg.h0000644000175000017500000000560112205613256024130 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsEventMsg_h_ #define _OsEventMsg_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsMsg.h" #include "os/OsStatus.h" #include "os/OsTime.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsQueuedEvent; //:Message used to send event notifications class OsEventMsg : public OsMsg { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum MsgSubType { UNSPECIFIED, // Not yet initialized NOTIFY // Event notification }; //!enumcode: UNSPECIFIED - not yet initialized //!enumcode: NOTIFY - event notification. /* ============================ CREATORS ================================== */ OsEventMsg(const unsigned char subType, const OsQueuedEvent& rEvent, const intptr_t eventData, const OsTime& rTimestamp); //:Constructor OsEventMsg(const OsEventMsg& rOsEventMsg); //:Copy constructor virtual OsMsg* createCopy(void) const; //:Create a copy of this msg object (which may be of a derived type) virtual ~OsEventMsg(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsEventMsg& operator=(const OsEventMsg& rhs); //:Assignment operator /* ============================ ACCESSORS ================================= */ virtual int getMsgSize() const; //:Return the size of the message in bytes // This is a virtual method so that it will return the accurate size for // the message object even if that object has been upcast to the type of // an ancestor class. virtual OsStatus getEventData(intptr_t& rEventData) const; //:Return the event data that was signaled by the notifier task // Always returns OS_SUCCESS. virtual OsStatus getTimestamp(OsTime& rTimestamp) const; //:Return the timestamp associated with this event // Always returns OS_SUCCESS. virtual OsStatus getUserData(intptr_t& rUserData) const; //:Return the user data specified when the OsQueuedEvent was constructed // Always returns OS_SUCCESS. /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: intptr_t mEventData; intptr_t mUserData; OsTime mTimestamp; }; /* ============================ INLINE METHODS ============================ */ #endif // _OsEventMsg_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsExcept.h0000644000175000017500000000666312205613256023641 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsExcept_h_ #define _OsExcept_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "OsDefs.h" #include "utl/UtlString.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Base class for exceptions thrown from the OS abstraction layer // The abstraction layer exception handling mechanism is based on the // OsExcept class. This class stores information about the type, cause, // and location of the exception. class OsExcept { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum MajorCode { MAJOR_NONE, // Unclassified exception MAJOR_RUNTIME, // Runtime exception MAJOR_USER // User-defined exception }; //!enumcode: MAJOR_NONE - Unclassified exception //!enumcode: MAJOR_RUNTIME - Runtime exception //!enumcode: MAJOR_USER - User-defined exception enum MinorCode { MINOR_NONE, // Unclassified exception MINOR_RUNTIME, // Runtime exception MINOR_USER // User-defined exception }; //!enumcode: MINOR_NONE - Unclassified exception //!enumcode: MINOR_RUNTIME - Runtime exception //!enumcode: MINOR_USER - User-defined exception /* ============================ CREATORS ================================== */ OsExcept(const int majorCode=MAJOR_NONE, const int minorCode=MINOR_NONE, const UtlString& rText="", const UtlString& rContext=""); //:Constructor OsExcept(const OsExcept& rOsExcept); //:Copy constructor virtual ~OsExcept(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsExcept& operator=(const OsExcept& rhs); //:Assignment operator virtual void setMajorCode(const int majorCode); //:Set major exception code virtual void setMinorCode(const int minorCode); //:Set minor exception code virtual void setContext(const UtlString& rContext); //:Set exception context virtual void setText(const UtlString& rText); //:Set exception text /* ============================ ACCESSORS ================================= */ virtual int getMajorCode(void) const; //:Get major exception code virtual int getMinorCode(void) const; //:Get minor exception code virtual const UtlString& getContext(void) const; //:Get exception context virtual const UtlString& getText(void) const; //:Get exception text /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: int mMajorCode; // major exception code int mMinorCode; // minor exception code UtlString* mpText; // exception text UtlString* mpContext; // exception context void init(void); //:Initialize the member variables (called by the constructors) }; /* ============================ INLINE METHODS ============================ */ #endif // _OsExcept_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsFileBase.h0000644000175000017500000001721712205613256024060 0ustar00danieldaniel00000000000000// // Copyright (C) 2005, 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsFile_h_ #define _OsFile_h_ // SYSTEM INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsPathBase.h" #include "os/OsLock.h" #include "os/OsBSem.h" #include "os/OsMutex.h" #include "os/OsConfigDb.h" #include // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsFileInfoBase; class OsPathBase; //:OS class for creating,reading, writing, manipulating files. class OsFileBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum Mode { READ_ONLY = 1, WRITE_ONLY = 2, READ_WRITE = 4, CREATE = 8, TRUNCATE = 16, APPEND = 32, FSLOCK = 64, FSLOCK_WAIT = 128 }; //!enumcode: FSLOCK - Opens the file exclusively (advisory locking). //!enumcode: FSLOCK_WAIT - Waits to open the file locked rather than fail. //: Options for the origin in setting the file position. enum FilePositionOrigin { START = 0, CURRENT = 1, END = 2 }; //!enumcode: Start - Set position relative to start of file. //!enumcode: Current - Set position relative to current file position. //!enumcode: End - Set position relative to end of file. /* ============================ CREATORS ================================== */ OsFileBase(const OsPathBase& filename); //:Default constructor virtual ~OsFileBase(); //:Destructor /* ============================ MANIPULATORS ============================== */ //! Opens and reads the contents of the named file into the given UtlString static long openAndRead(const char* filename, UtlString& fileContentsRead); //! Opens and write the given UtlString to the named file static long openAndWrite(const char* filename, const UtlString& fileContentsToWrite); //! Opens and write the given data to the named file static long openAndWrite(const char* filename, const char* fileContentsToWrite, unsigned int contentLength); virtual OsStatus open(const int mode = READ_WRITE); //: Opens the specified file using the specified mode //: Returns: //: OS_SUCCESS if successful //: OS_FILE_ACCESS_DENIED if file is readonly or currently in use //: OS_FILE_NOT_FOUND if the file specified was not found. //: For file locking, use FSLOCK or FSLOCK_WAIT in mode. Note that you //: must open the file read-write to lock it, and that file locking is //: advisory: other callers must also use FSLOCK or FSLOCK_WAIT. virtual OsStatus fileunlock(); //: Cross-process unlocks this file. //: Notes: This method should only be called by OsFileBase::close()! virtual OsStatus filelock(const bool wait); //: Cross-process locks this file, optionally waiting for the lock. //: Returns: //: OS_SUCCESS if successful //: OS_FAILED if unsuccessful //: Notes: This method should only be called by OsFileBase::open()! virtual OsStatus flush(); //: Flushes any pending output virtual OsStatus write(const void* pBuf, unsigned long bufLen, unsigned long& rBytesWritten); //: Write X bytes to file //: Returns: //: OS_SUCCESS if successful //: OS_FILE_DISKFULL if (you guessed it) disk full. :) //: OS_localFileLocks //: FILE_INVALID_HANDLE if something has gone wrong an handle is invalid. virtual OsStatus setLength(unsigned long newLength); //: Sets the length of the file specified by the object to the new size //: Sets the length of the file specified by the object to the new size //: Shrinking or Growing the file as needed. virtual OsStatus setPosition(long pos, FilePositionOrigin origin = START); //: Set the current active position in the file for the next read or write //: operation. The pos variable is a signed number which is //: added to the specified origin. For origin == OsFile::Start //: only positive values for pos are meaningful. For //: origin == OsFile::End only negative values for //: pos are meaningful virtual OsStatus remove(UtlBoolean bForce = FALSE); //: Removes the file specified by this object //: Set bForce to TRUE to remove read-only files //: Returns: //: OS_SUCCESS if successful //: OS_INVALID if failed virtual OsStatus rename(const OsPathBase& rNewFilename); //: Rename this file to the new file name //: Returns: //: OS_SUCCESS if successful //: OS_INVALID if failed virtual OsStatus copy(const OsPathBase& rNewFilename); //: Copy this file to the new specified location //: Returns: //: OS_SUCCESS if successful //: OS_FILE_WRITE_FAILED if it fails to create the file. virtual OsStatus setReadOnly(UtlBoolean isReadOnly); //: Sets the file to the new state //: Returns: //: OS_SUCCESS if successful //: OS_INVALID if failed virtual OsStatus touch(); //: Updates the date and time on the file. Creates if needed. /* ============================ ACCESSORS ================================= */ virtual OsStatus getPosition(unsigned long &pos); //: Get the current active position in the file for the next read or write operation. virtual void getFileName(OsPathBase& rOsPath) const; //: Returns the fully qualified filename for this File object virtual OsStatus read(void *pBuf, unsigned long bufLen, unsigned long &rBytesRead); //: Read X bytes from file virtual OsStatus readLine(UtlString &str); //: Read bytes up to \n or eof, whichever comes first //: Return virtual UtlBoolean close(); //: Closes the file. OsStatus getLength(unsigned long &length); //: Returns the length of the file specified by the object FILE* getFileDescriptor() { return mOsFileHandle; }; OsConfigDb* getFileLocks() { return mpFileLocks; }; /* ============================ INQUIRY =================================== */ UtlBoolean isReadonly() const; //: Returns TRUE if file is readonly UtlBoolean exists() ; //: Returns TRUE if file object filename exists virtual OsStatus getFileInfo(OsFileInfoBase& rFileinfo) const = 0; //: Returns all the relevant info on this file UtlBoolean isEOF(); //: Returns TRUE if stream is past end of file /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsMutex fileMutex; //: Block other methods like close // while we are busy reading,writing and close. OsFileBase(const OsFileBase& rOsFile); //:Copy constructor OsFileBase& operator=(const OsFileBase& rhs); //:Assignment operator FILE *mOsFileHandle; //: Handle to file OsPathBase mFilename; //:Fully qualified name where file is (or will be) located int mMode; //: The open file's mode /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: static OsConfigDb *mpFileLocks; }; /* ============================ INLINE METHODS ============================ */ #endif // _OsFile_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsFileInfoBase.h0000644000175000017500000000510412205613256024664 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsFileInfoBase_h_ #define _OsFileInfoBase_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsTime.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsPathBase; //:Class short description which may consist of multiple lines (note the ':') // Class detailed description which may extend to multiple lines class OsFileInfoBase { friend class OsDirBase; friend class OsFileBase; friend class OsFileLinux; friend class OsDirLinux; friend class OsFileVxw; friend class OsFileSystem; friend class OsDirWnt; friend class OsFileWnt; friend class OsFileSystemWnt; /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsFileInfoBase(); //:Default constructor OsFileInfoBase(const OsFileInfoBase& rOsFileInfoBase); //:Copy constructor virtual ~OsFileInfoBase(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsFileInfoBase& operator=(const OsFileInfoBase& rhs); //:Assignment operator /* ============================ ACCESSORS ================================= */ OsStatus getCreateTime(OsTime& rTime) const; //: Returns the creation time in seconds since epoch OsStatus getModifiedTime(OsTime& rTime) const; //: Returns the modified time in seconds since epoch OsStatus getSize(unsigned long& rSize) const; //: Returns the entry size /* ============================ INQUIRY =================================== */ UtlBoolean isReadOnly() const; //: return TRUE if entry is readonly UtlBoolean isDir() const; //: return TRUE if entry is a directory /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsTime mCreateTime; OsTime mModifiedTime; UtlBoolean mbIsReadOnly; UtlBoolean mbIsDirectory; unsigned long mSize; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _OsFileInfoBase_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsFileIteratorBase.h0000644000175000017500000000734612205613256025574 0ustar00danieldaniel00000000000000// // Copyright (C) 2005 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsFileIteratorBase_h_ #define _OsFileIteratorBase_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsFileInfoBase; class OsFileBase; //:Abstraction class to iterate through files and/or directories class OsFileIteratorBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum OsFileType { ANY_FILE, DIRECTORIES, FILES }; #ifdef _WIN32 enum { INVALID_HANDLE = -1 }; #else enum { INVALID_HANDLE = 0 }; #endif //: type specified for FindFirst //!enumcode: ANY_FILE - Directories and Files //!enumcode: DIRECTORY - Search for directories only //!enumcode: FILE - Search for files only /* ============================ CREATORS ================================== */ OsFileIteratorBase(); OsFileIteratorBase(const OsPathBase& rPathName); virtual ~OsFileIteratorBase(); //:Destructor /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ virtual OsStatus findFirst(OsPathBase& rEntry, const char* filterExp = ".*", OsFileType fileType = ANY_FILE); //: Searches a directory specified by rEntry for all entries matching //: the (unanchored) regexp filterExp and also of type fileType. //: Returns the full path name of the found entries. //: filterExp is unanchored; it need only match a substring of the //: file name. To force it to match the entire file name, use "^...$". //: On Unix-like systems the "." and ".." entries may be returned. virtual OsStatus findNext(OsPathBase& rEntry); //: Finds the next entry matching the search criteria. //: Use FindFirst before calling this function. /* ============================ INQUIRY =================================== */ int getFileCount() {return mFileCount;} //: Returns total files enumerated thus far. /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsPathBase mUserSpecifiedPath; //: What the user passed in as path to search OsPathBase mFullSearchSpec; //: What is searched against the filesystem RegEx* mFilterExp; //: The regular expression that the user searched for long mSearchHandle; // release memory that allocated for mFilterExp // // Morerover, OsFileIteratorBase's Subclass needs override this // function for releasing mSearchHandle. virtual void Release(); /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: virtual OsStatus getNextEntryName(UtlString &rName, OsFileType &rFileType); //: Platform dependant call for getting entry virtual OsStatus getFirstEntryName(UtlString &rName, OsFileType &rFileType); //: Platform dependant call for getting entry OsFileType mMatchAttrib; //: Attributes for file matching long mFileCount; //: How many file did this class find }; /* ============================ INLINE METHODS ============================ */ #endif // _OsFileIteratorBase_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsFileSystem.h0000644000175000017500000000656112205613256024472 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsFileSystem_h_ #define _OsFileSystem_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDateTime.h" #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsFS.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Helper class that constructs OsDir and OsFile objects //:for you. This may be expanded to include enumerating versions //:of these functions. class OsFileSystem { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ OsFileSystem& operator=(const OsFileSystem& rhs); //:Assignment operator static OsStatus copy(const OsPath& rSource, const OsPath& rOsPath); //: Returns TRUE if file moved ok static OsStatus remove(const OsPath& rOsPath, UtlBoolean bRecursive = FALSE, UtlBoolean bForce = FALSE); //: Removes the directory or file specified by path //: Specify bForce = TRUE to remove if read-only static OsStatus rename(const OsPath& rSourceFile, const OsPath& rDestFile); //: Renames the directory or file specified by path static OsStatus change(const OsPath& rOsPath); //: Change the current working directory to the specified location static OsStatus createDir(const OsPath& rOsPath, const UtlBoolean createParent = FALSE); //: Creates the specified directory //: Fails if a file by the same name already exists in the directory static OsStatus setReadOnly(const OsPath& rFile, UtlBoolean isReadOnly); //: Sets the read-only flag onthe specified file. //: Set to TRUE to make the file READONLY /* ============================ ACCESSORS ================================= */ static OsStatus getFileInfo(OsPath& filespec, OsFileInfo& rfileInfo); //: Retrieve system info for specified directory of file /* ============================ INQUIRY =================================== */ static UtlBoolean exists(const OsPath& rFilename); //: Returns true if file exists static OsStatus getWorkingDirectory(OsPath& rOsPath); //: Returns the current working directory /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsFileSystem(const OsFileSystem& rOsFileSystem); //:Copy constructor OsFileSystem(); //:Default constructor virtual ~OsFileSystem(); //:Destructor /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: static OsStatus removeTree(const OsPath& rOsPath, UtlBoolean bForce = FALSE); //: Removes a directory, files and all sub-dirs //: Specify bForce = TRUE to remove files and directories //: even if read-only static OsStatus createDirRecursive(const OsPath& rOsPath); //: Recursively creates a directory and its parents if non-existant }; /* ============================ INLINE METHODS ============================ */ #endif // _OsFileSystem_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsFS.h0000644000175000017500000000414312205613256022710 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsFS_h_ #define _OsFS_h_ #include "os/OsFileBase.h" #include "os/OsFileIteratorBase.h" #include "os/OsDirBase.h" #include "os/OsPathBase.h" #include "os/OsFileInfoBase.h" // Depending on the native OS that we are running on, we include the class // declaration for the appropriate lower level implementation and use a // "typedef" statement to associate the OS-independent class name (OsTask) // with the OS-dependent realization of that type (e.g., OsTaskWnt). #if defined(_WIN32) # include "os/Wnt/OsFileWnt.h" # include "os/Wnt/OsDirWnt.h" # include "os/Wnt/OsPathWnt.h" # include "os/Wnt/OsFileInfoWnt.h" # include "os/Wnt/OsFileIteratorWnt.h" # include "os/Wnt/OsFileSystemWnt.h" typedef class OsFileWnt OsFile; typedef class OsDirWnt OsDir; typedef class OsPathWnt OsPath; typedef class OsFileInfoWnt OsFileInfo; typedef class OsFileIteratorWnt OsFileIterator; #elif defined(_VXWORKS) # include "os/Vxw/OsFileVxw.h" # include "os/Vxw/OsDirVxw.h" # include "os/Vxw/OsPathVxw.h" # include "os/Vxw/OsFileInfoVxw.h" # include "os/Vxw/OsFileIteratorVxw.h" typedef class OsPathVxw OsPath; typedef class OsDirVxw OsDir; typedef class OsFileVxw OsFile; typedef class OsFileInfoVxw OsFileInfo; typedef class OsFileIteratorVxw OsFileIterator; #elif defined(__pingtel_on_posix__) # include "os/linux/OsFileLinux.h" # include "os/linux/OsDirLinux.h" # include "os/linux/OsPathLinux.h" # include "os/linux/OsFileInfoLinux.h" # include "os/linux/OsFileIteratorLinux.h" typedef class OsPathLinux OsPath; typedef class OsDirLinux OsDir; typedef class OsFileLinux OsFile; typedef class OsFileInfoLinux OsFileInfo; typedef class OsFileIteratorLinux OsFileIterator; #else # error Unsupported target platform. #endif #include "os/OsFileSystem.h" #endif /* ifdef _OsFS_h_ */ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsIntPtrMsg.h0000644000175000017500000000415012205613256024265 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef OsIntPtrMsg_h__ #define OsIntPtrMsg_h__ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "utl/UtlContainable.h" #include "os/OsMsg.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Base class for message queue buffers class OsIntPtrMsg : public OsMsg { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const UtlContainableType TYPE ; /** < Class type used for runtime checking */ /* ============================ CREATORS ================================== */ OsIntPtrMsg(const unsigned char msgType, const unsigned char msgSubType, intptr_t pData1 = 0, intptr_t pData2 = 0); //:Constructor OsIntPtrMsg(const OsIntPtrMsg& rOsMsg); //:Copy constructor virtual OsMsg* createCopy(void) const; //:Create a copy of this msg object (which may be of a derived type) /* ============================ MANIPULATORS ============================== */ OsIntPtrMsg& operator=(const OsIntPtrMsg& rhs); //:Assignment operator /* ============================ ACCESSORS ================================= */ intptr_t getData1() const { return mpData1; } intptr_t getData2() const { return mpData2; } void setData1(intptr_t val) { mpData1 = val; } void setData2(intptr_t val) { mpData2 = val; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: intptr_t mpData1; intptr_t mpData2; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // OsIntPtrMsg_h__ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsIntTypes.h0000644000175000017500000000371312205613256024161 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // Author: Alexander Chemeris #ifndef _OsIntTypes_h_ #define _OsIntTypes_h_ /** @file * @brief Include this file if you want use C99 integer types with specified * width and corresponding set of macros. * * This file is just a dispatcher, including one or other implementation * of C99 and . It is created to simplify porting * to different platforms and compilers, some of them have no C99 integer * types implemented. */ // Define these macros to include support for minimum/maximum constants // and constant macros, if they have not already been defined on the compiler // command line by the build system. #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #ifndef __STDC_CONSTANT_MACROS #define __STDC_CONSTANT_MACROS #endif #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #ifdef _MSC_VER // Microsoft Visual Studio C/C++ compiler # include #elif __GNUC__ // GNU C/C++ compiler # include # include #else # error Unknown compiler. Check does your compiler support C99 "inttypes.h" and edit this file. #endif /* Test to see whether this file got included soon enough - if the __STDC macros * weren't defined on the compiler command line, then we have to include this * file before anything else includes inttypes.h or stdint.h for the __STDC * macros to have any effect. Use INT16_MAX as a simple check for success. */ #ifndef INT16_MAX #warning #include os/OsIntTypes.h before stdint.h/inttypes.h #define _STDINT_H help_find_first_include_of_stdint.h #define _STDINT_H_ help_find_first_include_of_stdint.h #endif #endif // _OsIntTypes_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsLock.h0000644000175000017500000000551212205613256023271 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsLock_h_ #define _OsLock_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "OsSyncBase.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * @brief Lock class for mutual exclusion in a critical section. * * This class uses OsSyncBase objects for synchronization. * The constructor for the class automatically blocks until the designated * semaphore is acquired. Similarly, the destructor automatically releases * the lock. The easiest way to use this object as a guard for a critical * section is to create the object as a variable on the stack just before * the critical section. When the variable goes out of scope, the lock will * be automatically released. An example of this form of use is shown below. * * *    someMethod()
*    {
*       OsLock lock(myBSemaphore);
*
*       < critical section >
*    } *
*/ class OsLock { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /// Constructor OsLock(OsSyncBase& rSemaphore) : mrSemaphore(rSemaphore) { rSemaphore.acquire(); }; /// Destructor virtual ~OsLock() { mrSemaphore.release(); }; /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsSyncBase& mrSemaphore; /// Default constructor (not implemented for this class) OsLock(); /// Copy constructor (not implemented for this class) OsLock(const OsLock& rOsLock); /// Assignment operator (not implemented for this class) OsLock& operator=(const OsLock& rhs); }; /* ============================ INLINE METHODS ============================ */ #endif // _OsLock_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsLockingList.h0000644000175000017500000000523012205613256024620 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsLockingList_h_ #define _OsLockingList_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include "utl/UtlDList.h" #include "utl/UtlDListIterator.h" #include "utl/UtlVoidPtr.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //: // class OsLockingList { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsLockingList(); //:Default constructor virtual ~OsLockingList(); //:Destructor /* ============================ MANIPULATORS ============================== */ int getIteratorHandle(); //: Get a handle to lock the list and allow safe iteration void resetIterator(int iteratorHandle); //: Reset the iterator back to the beginning void* next(int iteratorHandle); //: Get without removing the next element void* remove(int iteratorHandle); //: Get and remove the pointer at the current element void releaseIteratorHandle(int iteratorHandle); //: Release the iterator lock so that other methods may be used void push(void* element); //: Add an element to the end // This method blocks while the iterator is outstanding or other // methods are in use. A NULL element is not allowed. void* pop(); //: Get and remove the last element // This method blocks while the iterator is outstanding or other // methods are in use. int getCount(); //: Get the number of elements in the list /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsMutex listMutex; int iteratorLockCount; UtlDList list; UtlDListIterator* listIterator; UtlVoidPtr* currentElement; void assertIterator(int iteratorHandle); OsLockingList& operator=(const OsLockingList& rhs); //:Assignment operator OsLockingList(const OsLockingList& rOsLockingList); //:Copy constructor }; /* ============================ INLINE METHODS ============================ */ #endif // _OsLockingList_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsMsg.h0000644000175000017500000001345412205613256023133 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsMsg_h_ #define _OsMsg_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "utl/UtlContainable.h" #include "os/OsAtomics.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Base class for message queue buffers class OsMsg : public UtlContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum MsgTypes { UNSPECIFIED = 0, OS_SHUTDOWN, // Task shutdown request message OS_TIMER, // Timer request messages OS_EVENT, // Event notification messages PS_MSG, // Phone set messages PHONE_APP, // Phone application messages MP_TASK_MSG, // Media processing task messages MP_FLOWGRAPH_MSG, // Media processing flowgraph messages MP_RESOURCE_MSG, // Media resource messages MP_RES_NOTF_MSG, // Media resource notification messages MP_BUFFER_MSG, // Media processing buffer queue messages MI_NOTF_MSG, // Media Interface notification messages SIP_PROXY_STATE, // SIP proxy call state message TAO_MSG, // Tao messages TAO_EVENT, // Tao listener event messages TAO_LISTENER_EVENT_MSG,// Tao listener event message (call backs) PINGER_MSG, // Pinger messages REFRESH_MSG, LINE_MGR_MSG, OS_SYSLOG, // OS SysLog events STREAMING_MSG, // Streaming related messages USER_START = 128 }; //!enumcode: OS_SHUTDOWN - Task shutdown request message //!enumcode: OS_TIMER - Timer request messages //!enumcode: OS_EVENT - Event notification messages //!enumcode: PS_MSG - Phone set messages //!enumcode: PHONE_APP - Phone application class of messages //!enumcode: MP_TASK_MSG - Media processing task class of messages //!enumcode: MP_FLOWGRAPH_MSG - Media processing flowgraph class of messages //!enumcode: MP_RESOURCE_MSG - Media processing resource class of messages for new (2007-03) resource framework //!enumcode: MP_BUFFER_MSG - Media processing buffer queue messages //!enumcode: SIP_PROXY_STATE - SIP proxy call state message //!enumcode: OS_SYSLOG - OS SysLog Messages //!enumcode: USER_START - User defined message type categories start at USER_START static const UtlContainableType TYPE ; /** < Class type used for runtime checking */ /* ============================ CREATORS ================================== */ OsMsg(const unsigned char msgType, const unsigned char msgSubType); //:Constructor OsMsg(const OsMsg& rOsMsg); //:Copy constructor virtual OsMsg* createCopy(void) const; //:Create a copy of this msg object (which may be of a derived type) virtual void releaseMsg(void); //:Done with message, delete it or mark it unused virtual ~OsMsg(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsMsg& operator=(const OsMsg& rhs); //:Assignment operator virtual void setMsgSubType(unsigned char subType); //:Set the message subtype virtual void setSentFromISR(UtlBoolean sentFromISR); //:Set the SentFromISR (interrupt service routine) flag virtual void setReusable(UtlBoolean isReusable); //:Set the Is Reusable (from permanent pool) flag virtual void setInUse(UtlBoolean isInUse); //:Set the Is In Use flag /* ============================ ACCESSORS ================================= */ virtual unsigned char getMsgType(void) const; //:Return the message type virtual unsigned char getMsgSubType(void) const; //:Return the message subtype virtual int getMsgSize(void) const; //:Return the size of the message in bytes // This is a virtual method so that it will return the accurate size for // the message object even if that object has been upcast to the type of // an ancestor class. virtual UtlBoolean getSentFromISR(void) const; //:Return TRUE if msg was sent from an interrupt svc routine, else FALSE virtual UtlBoolean isMsgReusable(void) const; //:Return TRUE if msg is from a permanent pool, else FALSE virtual UtlBoolean isMsgInUse(void) const; //:Return TRUE if msg is currently in use, else FALSE //! Implements the interface for a UtlContainable virtual unsigned hash() const; virtual UtlContainableType getContainableType() const; virtual int compareTo(UtlContainable const *) const; /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: unsigned char mMsgType; unsigned char mMsgSubType; UtlBoolean mSentFromISR; UtlBoolean mReusable; OsAtomicLightBool mInUse; ///< Access to mInUse should be synchronized, ///< because it can be accessed from different ///< threads - e.g. one thread can call setInUse() ///< freeing message, while other will call ///< isMsgInUse() seeking for free OsMsg. }; /* ============================ INLINE METHODS ============================ */ #endif // _OsMsg_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsMsgPool.h0000644000175000017500000001400212205613256023753 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsMsgPool_h_ #define _OsMsgPool_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsMsg.h" #include "os/OsMutex.h" /***************************************************************************** * OS Message Pool * Container for a set of reusable OsMsg objects (actually, message objects * derived from the OsMsg base class). All the OsMsg objects in any * particular pool must be of the same derived type. * * The client of the OsMsgPool is the thread or interrupt service routine * that retrieves available messages from the pool, fills in the payload, * and sends it into an OsMsgQ. A pool with a single client thread is * unshared, while a pool that may be used from more than one thread is * shared. * * Note that an interrupt service routine must use a single client pool of * its very own since interrupt routines cannot Take or Give mutexes. It * must also be completely populated when it is created, as an ISR is not * permitted to allocate memory, as would be necessary to expand the pool. * * Note, also, that the receiver of messages that may be from such a pool * must not delete the messages explicitly, but rather should always invoke * the new OsMsg::releaseMsg(void) method. This method clears the in-use * flag on reusable messages, or deletes one-use messages. It is a safe * and general rule that all OsMsg objects should only be disposed of by * way of releaseMsg() and should never be explicitly deleted. In aid of * this rule the destructor, OsMsg::~OsMsg(), now checks that only objects * without the is-reusable flag set are deleted. * * To create the pool, the caller must supply a "model" message, one of the * type to be contained in the pool. The OsMsgPool will clone that message * by calling its createCopy() method to allocate the messages contained in * the pool. On return from the OsMsgPool constructor, the model message * should be deleted by the caller. * * The pool will initially be populated with the number of messages specified * by the initialCount constructor argument. The pool may grow beyond that * initial size, if so indicated by the other constructor arguments. To * indicate that the pool may be expanded, the caller specifies three more * values: * * softLimit - a count, larger than initialCount, that will generate a * warning if the automatic expansion increases the pool beyond this * count. * * hardLimit - a count, larger than initialCount, that is the absolute * maximum to which the pool can grow. It is a fatal error if this * count is reached and another element is needed to satisfy a request. * This is the size of the array of OsMsg* pointers allocated in the * constructor. * * increment - the number of message to create each time there is no * message available to satisfy a request. */ // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlString; //:Manager of a collection of OsMsg objects class OsMsgPool { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: // Shared among multiple clients, or used by only a single client enum OsMsgPoolSharing { MULTIPLE_CLIENTS, SINGLE_CLIENT }; /* ============================ CREATORS ================================== */ OsMsgPool(const char* name, // for identification const OsMsg& model, // message to clone to populate pool int initialCount, // number of messages to create initially int softLimit=0, // number of message without complaining int hardLimit=0, // absolute maximum number of messages int increment=1, // number of messages to allocate when expanding OsMsgPoolSharing sharing=MULTIPLE_CLIENTS); //:Default constructor. model is a message of the single type that //:will be contained in the pool, and its createCopy virtual method //:will be used to populate the pool. The caller disposes of model virtual ~OsMsgPool(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsMsg* findFreeMsg(void); //:Find and return an available element of the pool, creating more if //:necessary and permitted. Return NULL if failure. /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ int getNoInUse(void); //:Return the number of items in use. int getSoftLimit(void); //:Return the current soft limit. int getHardLimit(void); //:Return the current hard limit. /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: int mInitialCount; // initial number of items int mCurrentCount; // current number of items int mSoftLimit; // soft limit, warn when expanding above this int mHardLimit; // hard limit AND length of mpElts int mIncrement; // number to create when expanding int mNext; // index to next element to examine OsMutex* mpMutex; // NULL if single client OsMsg* mpModel; // model element to clone OsMsg** mpElts; // array of pointers to contained objects UtlString* mpName; // for ID in error messages OsMsgPool(const OsMsgPool& rOsMsgPool); //:Copy constructor (not implemented for this class) OsMsgPool& operator=(const OsMsgPool& rhs); //:Assignment operator (not implemented for this class) }; #endif // _OsMsgPool_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsMsgQ.h0000644000175000017500000001626712205613256023261 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsMsgQ_h_ #define _OsMsgQ_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsTime.h" #include "utl/UtlString.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // FORWARD DECLARATIONS class OsMsg; // TYPEDEFS typedef UtlBoolean (*OsMsgQSendHookPtr) (const OsMsg& rMsg); typedef void (*OsMsgQFlushHookPtr) (const OsMsg& rMsg); //:Message queue for inter-task communication class OsMsgQBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const int DEF_MAX_MSGS; ///< Default maximum number of messages static const int DEF_MAX_MSG_LEN; ///< Default maximum msg length (in bytes) static const UtlString MSGQ_PREFIX; ///< Prefix for OsMsgQ names stored in ///< the name database enum Options { Q_FIFO = 0x0, ///< queue blocked tasks on a first-in, first-out basis Q_PRIORITY = 0x1 ///< queue blocked tasks based on their priority }; /* ============================ CREATORS ================================== */ /// Constructor OsMsgQBase(const UtlString& name); /**< * If name is specified but is already in use, throw an exception. */ /// Destructor virtual ~OsMsgQBase(); /// Return a pointer to the named queue, or NULL if not found. static OsMsgQBase* getMsgQByName(const UtlString& name); /* ============================ MANIPULATORS ============================== */ /// Insert a copy of the message at the tail of the queue virtual OsStatus send(const OsMsg& rMsg, const OsTime& rTimeout=OsTime::OS_INFINITY) = 0; /**< * Wait until there is either room on the queue or the timeout expires. * * This method creates a copy of the \p pMsg, before inserting it * to the queue. */ /// Insert an original of the message at the tail of the queue virtual OsStatus sendNoCopy(OsMsg *pMsg, const OsTime& rTimeout=OsTime::OS_INFINITY) = 0; /**< * Wait until there is either room on the queue or the timeout expires. * * This method does not create a copy of the \p pMsg, inserting it * to the queue as is. */ /// Insert a copy of the message at the head of the queue virtual OsStatus sendUrgent(const OsMsg& rMsg, const OsTime& rTimeout=OsTime::OS_INFINITY) = 0; /**< * Wait until there is either room on the queue or the timeout expires. */ /// Insert a copy of the message at the tail of the queue with ISR flag. virtual OsStatus sendFromISR(OsMsg& rMsg) = 0; /**< * Sending from an ISR has a couple of implications. Since we can't * allocate memory within an ISR, we don't create a copy of the message * before sending it and the sender and receiver need to agree on a * protocol (outside this class) for when the message can be freed. * The sentFromISR flag in the OsMsg object will be TRUE for messages * sent using this method. */ /// Remove a message from the head of the queue virtual OsStatus receive(OsMsg*& rpMsg, const OsTime& rTimeout=OsTime::OS_INFINITY) = 0; /**< * Wait until either a message arrives or the timeout expires. * Other than for messages sent from an ISR, the receiver is responsible * for freeing the received message. */ /// Delete all messages currently in the queue virtual void flush(); /// Set the function that is invoked whenever a msg is sent to the queue virtual void setSendHook(OsMsgQSendHookPtr func); /**< * The function takes the message to be sent as an argument and returns a * boolean value indicating whether the SendHook method has handled the * message. If TRUE, the message is not inserted into the queue (since it * has already been handled. If FALSE, the (possibly modified) message is * inserted into the queue. */ /// Set the function that is invoked whenever a msg is flushed from the queue. virtual void setFlushHook(OsMsgQFlushHookPtr func); /**< * Messages get flushed when the OsMsgQ is deleted while there are messages * still queued. * * The function takes an OsMsg reference as an argument. */ /* ============================ ACCESSORS ================================= */ /// Return the number of messages in the queue virtual int numMsgs() = 0; /// Returns the maximum number of messages that can be queued int maxMsgs() const; /// Return a pointer to the current send hook function virtual OsMsgQSendHookPtr getSendHook() const; /* ============================ INQUIRY =================================== */ /// Return TRUE if the message queue is empty, FALSE otherwise virtual UtlBoolean isEmpty(); /// Get the name associated with the queue. const UtlString& getName() const { return mName; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /// Method that is invoked whenever a message is sent to the queue OsMsgQSendHookPtr mSendHookFunc; /// Method that is invoked whenever a message is flushed from the queue OsMsgQFlushHookPtr mFlushHookFunc; /* ---------------------------- DEBUG SCAFFOLDING ------------------------- */ protected: int mMaxMsgs; ///< maximum number of messages the queue can hold #if MSGQ_IS_VALID_CHECK virtual void testMessageQ() = 0; unsigned int mNumInsertEntry; unsigned int mNumInsertExitOk; unsigned int mNumInsertExitFail; unsigned int mNumRemoveEntry; unsigned int mNumRemoveExitOk; unsigned int mNumRemoveExitFail; unsigned int mLastSuccessTest; #endif /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: UtlString mName; ///< global name associated with the msg queue /// Copy constructor (not implemented for this class) OsMsgQBase(const OsMsgQBase& rOsMsgQBase); /// Assignment operator (not implemented for this class) OsMsgQBase& operator=(const OsMsgQBase& rhs); }; /* ============================ INLINE METHODS ============================ */ // Depending on the native OS that we are running on, we include the class // declaration for the appropriate lower level implementation and use a // "typedef" statement to associate the OS-independent class name (OsMsgQ) // with the OS-dependent realization of that type (e.g., OsMsgQWnt). #if defined(_WIN32) # include "os/shared/OsMsgQShared.h" typedef class OsMsgQShared OsMsgQ; #elif defined(_VXWORKS) # include "os/Vxw/OsMsgQVxw.h" typedef class OsMsgQVxw OsMsgQ; #elif defined(__pingtel_on_posix__) # include "os/shared/OsMsgQShared.h" typedef class OsMsgQShared OsMsgQ; #else # error Unsupported target platform. #endif #endif // _OsMsgQ_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsMsgDispatcher.h0000644000175000017500000001204112205613256025131 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Keith Kyzivat #ifndef _OsMsgDispatcher_h_ #define _OsMsgDispatcher_h_ // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsMsg.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * @brief Dispatcher for Resource Notification Messages. * * The Message Dispatcher is used to hold and notify users of * messages. If users are not interested in particular types of messages, * they can subclass this Message dispatcher and provide filtering to enable * only certain types of messages to be sent up through it's framework. */ class OsMsgDispatcher { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ ///@name Creators //@{ /// Default constructor OsMsgDispatcher(); /**< * This constructor creates a queue, which will be destroyed in destructor. */ /// Constructor for using external message queue for dispatching. OsMsgDispatcher(OsMsgQ* msgQ); /**< * This constructor does not own the passed queue, so won't be deleted * in destructor. It's user responsibility to manage the queue. */ /// Destructor virtual ~OsMsgDispatcher(); //@} /* ============================ MANIPULATORS ============================== */ ///@name Manipulators //@{ /// Post a resource notification message. virtual OsStatus post(const OsMsg& msg); /**< * This posts a message to the dispatcher queue. * @NOTE If the queue is full, a flag will be set that messages * were lost, and the new messages will be dropped on the floor * until such time as the queue empties until there is room available. * It is the application's duty to service and receive messages from * the queue. * * @param[in] msg - the message to post. * @retval OS_SUCCESS - if it was able to add to the queue, * @retval OS_LIMIT_REACHED otherwise. */ /// Receive a message from the dispatcher queue. virtual OsStatus receive(OsMsg*& rpMsg, const OsTime& rTimeout=OsTime::OS_INFINITY); /**< * Remove a message from the head of the queue * Wait until either a message arrives or the timeout expires. * Other than for messages sent from an ISR, the receiver is responsible * for freeing the received message. * * @param[in] rpMsg - pointer to msg will be stored here. * @param[in] rTimeout - how long to wait for a notification.. * @retval OS_SUCCESS if the message was received and rpMsg filled in. * @retval OS_WAIT_TIMEOUT if no message is in the queue before the timeout value. */ //@} /* ============================ ACCESSORS ================================= */ ///@name Accessors //@{ /// Return the number of messages in the queue inline virtual int numMsgs(void); /// Returns the maximum number of messages that can be queued inline int maxMsgs() const; /* ============================ INQUIRY =================================== */ ///@name Inquiry //@{ /// Return TRUE if the message queue is empty, FALSE otherwise inline virtual UtlBoolean isEmpty(void); inline UtlBoolean isMsgsLost() const; //@} /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsMsgQ* mMsgQueue; ///< The message queue that this dispatcher is using. UtlBoolean mQueueOwned; ///< Indicates whether or not mMsgQueue is owned by the dispatcher UtlBoolean mMsgsLost; ///< Whether any messages have been dropped on the ///< floor due to the queue being full. /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /// Set that there were notifications lost. inline void setMsgsLost(); /// Copy constructor (not implemented for this class) OsMsgDispatcher(const OsMsgDispatcher& rMsgDispatcher); /// Assignment operator (not implemented for this class) OsMsgDispatcher& operator=(const OsMsgDispatcher& rhs); }; /* ============================ INLINE METHODS ============================ */ int OsMsgDispatcher::numMsgs( void ) { return mMsgQueue->numMsgs(); } int OsMsgDispatcher::maxMsgs() const { return mMsgQueue->maxMsgs(); } UtlBoolean OsMsgDispatcher::isEmpty( void ) { return mMsgQueue->isEmpty(); } UtlBoolean OsMsgDispatcher::isMsgsLost() const { return mMsgsLost; } void OsMsgDispatcher::setMsgsLost() { mMsgsLost = TRUE; } #endif // _OsMsgDispatcher_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsMulticastSocket.h0000644000175000017500000000474512205613256025526 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsMulticastSocket_h_ #define _OsMulticastSocket_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //: Implements multicast version of OsDatagramSocket // This class provides the implementation of the multicast UDP datagram class OsMulticastSocket : public OsDatagramSocket { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsMulticastSocket(int multicastPort = PORT_DEFAULT, const char* multicastHostName = NULL, int localHostPort = PORT_DEFAULT, const char* localHostName = NULL); virtual ~OsMulticastSocket(); //:Destructor /* ============================ MANIPULATORS ============================== */ /// Joins a multicast group. Returns 0 on success. int joinGroup(const char* multicastHostName); //int leaveGroup(const char* multicastHostName); /// Sets the hop count (a.k.a. TimeToLive) for outgoing multicast packets. int setHopCount(unsigned char hopCount); /// Enables/disables local loopback of outgoing multicast packets. int setLoopback(bool enabled); /* ============================ ACCESSORS ================================= */ virtual OsSocket::IpProtocolSocketType getIpProtocol() const; //: Returns the protocol type of this socket /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsMulticastSocket(const OsMulticastSocket& rOsMulticastSocket); //:Disable copy constructor OsMulticastSocket& operator=(const OsMulticastSocket& rhs); //:Assignment operator }; /* ============================ INLINE METHODS ============================ */ #endif // _OsMulticastSocket_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsMutex.h0000644000175000017500000001004612205613256023501 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsMutex_h_ #define _OsMutex_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsSyncBase.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * @brief Mutual exclusion semaphore (mutex) * * The mutual-exclusion semaphore is a specialized version of the binary * semaphore, designed to address issues inherent in mutual exclusion, such * as recursive access to resources, priority inversion, and deletion safety. * * The fundamental behavior of the mutual-exclusion semaphore is identical to * that of a binary semaphore except for^ * * * It can only be used for mutual exclusion and it can only be released by the * task that acquired it. * * * If a thread already holds the mutex, it may acquire it again without * first releasing it. The thread must release the mutex as many times as it * has acquired it before the mutex is free to be acquired by another thread. */ class OsMutexBase : public OsSyncBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum MutexOptions { Q_FIFO = 0x0, ///< queue blocked tasks on a first-in, first-out ///< basis Q_PRIORITY = 0x1, ///< queue blocked tasks based on their priority DELETE_SAFE = 0x4, ///< protect a task that owns the mutex from ///< unexpected deletion INVERSION_SAFE = 0x8 ///< protect the system from priority inversion: NOTE ///< VxWorks requires Q_PRIORITY with this. }; /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ /// Block the task until the mutex is acquired or the timeout expires virtual OsStatus acquire(const OsTime& rTimeout = OsTime::OS_INFINITY) = 0; /// Conditionally acquire the mutex (i.e., don't block) virtual OsStatus tryAcquire(void) = 0; /** * @return OS_BUSY if the mutex is held by some other task */ /// Release the mutex virtual OsStatus release(void) = 0; /* ============================ ACCESSORS ================================= */ /// Print mutex information to the console. virtual void OsMutexShow(void) = 0; /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /// Default constructor OsMutexBase() { }; /// Destructor virtual ~OsMutexBase() { }; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /// Copy constructor (not implemented for this class) OsMutexBase(const OsMutexBase& rOsMutexBase); /// Assignment operator (not implemented for this class) OsMutexBase& operator=(const OsMutexBase& rhs); }; /* ============================ INLINE METHODS ============================ */ /// Depending on the native OS that we are running on, we include the class /// declaration for the appropriate lower level implementation and use a /// "typedef" statement to associate the OS-independent class name (OsMutex) /// with the OS-dependent realization of that type (e.g., OsMutexWnt). #if defined(_WIN32) # include "os/Wnt/OsMutexWnt.h" typedef class OsMutexWnt OsMutex; #elif defined(_VXWORKS) # include "os/Vxw/OsMutexVxw.h" typedef class OsMutexVxw OsMutex; #elif defined(__pingtel_on_posix__) # include "os/linux/OsMutexLinux.h" typedef class OsMutexLinux OsMutex; #else # error Unsupported target platform. #endif #endif // _OsMutex_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsNameDb.h0000644000175000017500000000755712205613256023542 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsNameDb_h_ #define _OsNameDb_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsBSem.h" #include "os/OsRWMutex.h" #include "os/OsStatus.h" #include "utl/UtlHashMap.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlString; //:Name service maintaining mappings between string names and integer values // The OsNameDb is a singleton object that maintains a dictionary of // mappings between string names and the associated integer values. // Duplicate names are not allowed. class OsNameDb { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ static OsNameDb* getNameDb(); //:Return a pointer to the singleton object, creating it if necessary /* ============================ MANIPULATORS ============================== */ OsStatus insert(const UtlString& rKey, const intptr_t value); //:Add the key-value pair to the name database // Return OS_SUCCESS if successful, OS_NAME_IN_USE if the key is // already in the database. OsStatus remove(const UtlString& rKey, intptr_t* pValue = NULL); //:Remove the indicated key-value pair from the name database // If pValue is non-NULL, the value for the key-value pair is returned // via pValue.
// Return OS_SUCCESS if the lookup is successful, return // OS_NOT_FOUND if there is no match for the specified key. /* ============================ ACCESSORS ================================= */ OsStatus lookup(const UtlString& rKey, intptr_t* pValue = NULL); //:Retrieve the value associated with the specified key // If pValue is non-NULL, the value is returned via pValue.
// Return OS_SUCCESS if the lookup is successful, return // OS_NOT_FOUND if there is no match for the specified key. int numEntries(); //: Return the number of key-value pairs in the name database /* ============================ INQUIRY =================================== */ UtlBoolean isEmpty(); //:Return TRUE if the name database is empty /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: friend class OsNameDBInit; OsNameDb(); //:Default constructor (only callable from within this class) // This class implements the singleton pattern and therefore the // class constructor will not be called from outside the class. // We identify this as a protected (rather than a private) method so // that gcc doesn't complain that the class only defines a private // constructor and has no friends. virtual ~OsNameDb(); //:Destructor /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: static OsNameDb* spInstance; // pointer to the single instance of the // OsNameDb class UtlHashMap mDict; // hash table used to store the name/value // mappings OsRWMutex mRWLock; // R/W mutex used to coordinate access to // the name database by multiple tasks OsNameDb(const OsNameDb& rOsNameDb); //:Copy constructor (not supported for this class) OsNameDb& operator=(const OsNameDb& rhs); //:Assignment operator (not supported for this class) }; /* ============================ INLINE METHODS ============================ */ #endif // _OsNameDb_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsNameDbInit.h0000644000175000017500000000403312205613256024350 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 Jaroslav Libak // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef OsNameDbInit_h__ #define OsNameDbInit_h__ // SYSTEM INCLUDES // APPLICATION INCLUDES // DEFINES // Be sure to include all dependencies in the right order! #include "utl/UtlInit.h" // OsNameDb uses Utl // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // FORWARD DECLARATIONS // STRUCTS // TYPEDEFS /** * @brief OsNameDB initializer class. Solves the problem with ordering of * constructors & destructors. * * The h file needs to be included in: * - all cpp files whose static members are initialized in OsNameDBInit * constructor, in order to make sure they are initialized properly whenever * they are linked into program. * - it also has to be included as the first include in cpp files, that * initialize static members whose constructor or destructor tries to use any * static members we initialize here. */ class OsNameDBInit { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ ///@name Creators //@{ /// Constructor OsNameDBInit(void); /// Destructor ~OsNameDBInit(void); //@} /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: static unsigned int msCount; ///< Class instance counter. }; /* * This fixes constructor/destructor ordering by declaring a static instance * of this Init class in every cpp file where this .h file is included. * Thus constructor of this class will be run first, and destructor as the last. */ static OsNameDBInit gOsNameDBInit; #endif // OsNameDbInit_h__ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsNatAgentTask.h0000644000175000017500000003063212205613256024726 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsNatAgentTask_h_ /* [ */ #define _OsNatAgentTask_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/IStunSocket.h" #include "os/OsNatKeepaliveListener.h" #include "os/OsServerTask.h" #include "os/OsRpcMsg.h" #include "os/OsEventMsg.h" #include "utl/UtlHashMap.h" #include "os/TurnMessage.h" #include "os/StunMessage.h" #include "os/NatMsg.h" // DEFINES #define SYNC_MSG_TYPE (OsMsg::USER_START + 2) /**< Synchronized Msg type/id */ #define NAT_INITIAL_ABORT_COUNT 4 /** Abort after N times (first attempt) */ #define NAT_PROBE_ABORT_COUNT 3 /** Abort STUN probes after N attempts */ #define NAT_RESEND_ABORT_COUNT 75 /** Fail after N times (refreshes) */ #define NAT_RESPONSE_TIMEOUT_MS 300 /** How long to wait for each attempt */ #define NAT_FIND_BINDING_POOL_MS 50 /** poll delay for contact searchs */ #define NAT_BINDING_EXPIRATION_SECS 60 /** expiration for bindings if new renewed */ // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS typedef enum { STUN_DISCOVERY, STUN_PROBE, TURN_ALLOCATION, CRLF_KEEPALIVE, STUN_KEEPALIVE } NAT_AGENT_BINDING_TYPE ; typedef enum { SUCCESS, SENDING, SENDING_ERROR, RESENDING, RESENDING_ERROR, FAILED } NAT_AGENT_STATUS ; #define MAX_OLD_TRANSACTIONS 3 typedef struct { NAT_AGENT_BINDING_TYPE type ; NAT_AGENT_STATUS status ; UtlString serverAddress ; int serverPort ; int options ; STUN_TRANSACTION_ID transactionId ; int nOldTransactions ; STUN_TRANSACTION_ID oldTransactionsIds[MAX_OLD_TRANSACTIONS] ; IStunSocket* pSocket ; OsTimer* pTimer ; int keepAliveSecs ; int abortCount ; int refreshErrors ; UtlString address ; int port ; UtlString username ; // TURN_ALLOCATION only UtlString password ; // TURN_ALLOCATION only int priority ; // STUN_PROBE only OsNatKeepaliveListener* pKeepaliveListener ; } NAT_AGENT_CONTEXT ; typedef struct { OsSocket* pSocket ; UtlString remoteAddress ; int remotePort ; UtlString contactAddress ; int contactPort ; OsTime expiration ; } NAT_AGENT_EXTERNAL_CONTEXT ; // FORWARD DECLARATIONS /** * The OsNatAgentTask is responsible for servicing all stun requests and * and responses on behalf of the IStunSocket. This handles the * stun requests/responses however relies on someone else to pump sockets. * * Use cases: * * 1) Send a STUN request via a supplied IStunSocket * 2) Process responses from a IStunSocket * 3) Process server requests from a IStunSocket */ class OsNatAgentTask : public OsServerTask { /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ private: /** * Private constructor, use getInstance() */ OsNatAgentTask(); /** * Private destuctor, use freeInstance() ; */ virtual ~OsNatAgentTask(); public: /** * Obtain a singleton instance */ static OsNatAgentTask* getInstance() ; /** * Release/Free the singleton instance obtained by calling getInstance. * This method is included for clean shutdown of the system. */ static void releaseInstance() ; /* ============================ MANIPULATORS ============================== */ /** * Standard OsServerTask message handler -- used to process timer * messages for stun refreshes, reads, etc. */ virtual UtlBoolean handleMessage(OsMsg& rMsg) ; UtlBoolean sendStunProbe(IStunSocket* pSocket, const UtlString& remoteAddress, int remotePort, int priority) ; UtlBoolean enableStun(IStunSocket* pSocket, const UtlString& stunServer, int stunPort, const int stunOptions, int keepAlive) ; UtlBoolean disableStun(IStunSocket* pSocket) ; UtlBoolean enableTurn(IStunSocket* pSocket, const UtlString& turnServer, int iTurnPort, int keepAliveSecs, const UtlString& username, const UtlString& password) ; UtlBoolean primeTurnReception(IStunSocket* pSocket, const char* szAddress, int iPort ) ; UtlBoolean setTurnDestination(IStunSocket* pSocket, const char* szAddress, int iPort ) ; void disableTurn(IStunSocket* pSocket) ; UtlBoolean addCrLfKeepAlive(IStunSocket* pSocket, const UtlString& remoteIp, int remotePort, int keepAliveSecs, OsNatKeepaliveListener* pListener) ; UtlBoolean removeCrLfKeepAlive(IStunSocket* pSocket, const UtlString& serverIp, int serverPort) ; UtlBoolean addStunKeepAlive(IStunSocket* pSocket, const UtlString& remoteIp, int remotePort, int keepAliveSecs, OsNatKeepaliveListener* pListener) ; UtlBoolean removeStunKeepAlive(IStunSocket* pSocket, const UtlString& serverIp, int serverPort) ; UtlBoolean removeKeepAlives(IStunSocket* pSocket) ; UtlBoolean removeStunProbes(IStunSocket* pSocket) ; /** * Synchronize with the OsNatAgentTask by posting a message to this event * queue and waiting for that message to be processed. Do not call this * method from the OsNatAgentTask's thread context (will block forever). */ void synchronize() ; /** * Determines if probes of a higher priority are still outstanding */ UtlBoolean areProbesOutstanding(IStunSocket* pSocket, int priority) ; /** * Does a binding of the designated type/server exist */ UtlBoolean doesBindingExist(IStunSocket* pSocket, NAT_AGENT_BINDING_TYPE type, const UtlString& serverIp, int serverPort) ; /** * Accessor for the timer object. */ OsTimer* getTimer() ; /* ============================ ACCESSORS ================================= */ /** * Look at all of the stun data structures and see if you can find a * known back-route to the specified destination. */ UtlBoolean findContactAddress( const UtlString& destHost, int destPort, UtlString* pContactHost, int* pContactPort, int iTimeoutMs = 0) ; /** * Add an external binding (used for findContactAddress) */ void addExternalBinding(OsSocket* pSocket, UtlString remoteAddress, int remotePort, UtlString contactAddress, int contactPort) ; void clearExternalBinding(OsSocket* pSocket, UtlString remoteAddress, int remotePort, bool bOnlyIfEmpty = false) ; /** * Locate an external binding for the specified destination host/port. * This API while block while wait for a result. */ UtlBoolean findExternalBinding(const UtlString& destHost, int destPort, UtlString* pContactHost, int* pContactPort, int iTimeoutMs = 0, UtlBoolean* pTimedOut = NULL) ; /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: virtual UtlBoolean handleTimerEvent(NAT_AGENT_CONTEXT* pContext) ; virtual void handleStunTimeout(NAT_AGENT_CONTEXT* pContext) ; virtual void handleTurnTimeout(NAT_AGENT_CONTEXT* pContext) ; virtual UtlBoolean handleCrLfKeepAlive(NAT_AGENT_CONTEXT* pContext) ; virtual UtlBoolean handleStunKeepAlive(NAT_AGENT_CONTEXT* pContext) ; /** * Handle an inbound Stun message. The messages are handled to this * thread by the IStunSocket whenever someone calls one of the * read methods. */ virtual UtlBoolean handleStunMessage(NatMsg& rMsg) ; /** * Handle an inbound Turn message. The messages are handled to this * thread by the IStunSocket whenever someone calls one of the * read methods. */ virtual UtlBoolean handleTurnMessage(NatMsg& rMsg) ; /** * Handle a synchronization request. Synchronization consists of sending * a message and waiting for that messsage to be processed. */ virtual UtlBoolean handleSynchronize(OsRpcMsg& rMsg) ; virtual UtlBoolean sendMessage(StunMessage* pMsg, IStunSocket* pSocket, const UtlString& toAddress, unsigned short toPort, PacketType packetType = UNKNOWN_PACKET) ; NAT_AGENT_CONTEXT* getBinding(IStunSocket* pSocket, NAT_AGENT_BINDING_TYPE type) ; NAT_AGENT_CONTEXT* getBinding(NAT_AGENT_CONTEXT* pContext) ; NAT_AGENT_CONTEXT* getBinding(STUN_TRANSACTION_ID* pId) ; void destroyBinding(NAT_AGENT_CONTEXT* pBinding) ; void releaseTimer(OsTimer* pTimer) ; UtlBoolean sendStunRequest(NAT_AGENT_CONTEXT* pBinding) ; UtlBoolean sendTurnRequest(NAT_AGENT_CONTEXT* pBinding) ; void markStunFailure(NAT_AGENT_CONTEXT* pBinding) ; void markStunSuccess(NAT_AGENT_CONTEXT* pBinding, const UtlString& mappedAddress, int mappedPort) ; void markTurnFailure(NAT_AGENT_CONTEXT* pBinding) ; void markTurnSuccess(NAT_AGENT_CONTEXT* pBinding, const UtlString& relayAddress, int relayPort) ; OsNatKeepaliveEvent populateKeepaliveEvent(NAT_AGENT_CONTEXT* pContext) ; void dumpContext(UtlString* pResults, NAT_AGENT_CONTEXT* pBinding) ; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: static OsNatAgentTask* spInstance ; /**< Singleton instance */ static OsMutex sLock ; /**< Lock for singleton accessors */ UtlSList mTimerPool; /**< List of free timers available for use */ UtlHashMap mContextMap ; OsMutex mMapsLock ; /**< Lock for Notify and Connectiviy maps */ UtlSList mExternalBindingsList ; OsRWMutex mExternalBindingMutex ; /** Disabled copy constructor (not supported) */ OsNatAgentTask(const OsNatAgentTask& rOsNatAgentTask); /** Disabled equal operators (not supported) */ OsNatAgentTask& operator=(const OsNatAgentTask& rhs); }; /* ============================ INLINE METHODS ============================ */ #endif /* _OsNatAgentTask_h_ ] */ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsNatConnectionSocket.h0000644000175000017500000003403712205613256026320 0ustar00danieldaniel00000000000000// $Id$ // // Copyright (C) 2005 Pingtel Corp. // // $$ ////////////////////////////////////////////////////////////////////////////// #ifndef _OsNatConnectionSocket_h_ #define _OsNatConnectionSocket_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsConnectionSocket.h" #include "os/OsNatDatagramSocket.h" #include "os/OsMsgQ.h" #include "os/OsTimer.h" #include "os/OsQueuedEvent.h" #include "os/OsRWMutex.h" #include "os/OsNatSocketBaseImpl.h" #include "utl/UtlHashMap.h" // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class NatMsg ; class OsEvent ; class OsNatAgentTask; class OsNatKeepaliveListener; /** * OsNatConnectionSocket extends an OsDatagramSocket by adding an integrated * STUN and TURN client. If STUN or TURN is enabled, request will be send * to the designated server every refresh period. The external addresses * obtained by these mechanisms are retrieved by invoking getMappedIp and * getRelayIp. * * For this mechanism to work, someone must pump inbound socket data by * calling one of the ::read() methods. Otherwise, the packets will not be * received/processed. Internally, the implemenation peeks at the read * data and passes the message to the OsNatAgentTask for processing. */ class OsNatConnectionSocket : public OsConnectionSocket, public OsNatSocketBaseImpl { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: friend class OsNatAgentTask ; /* ============================ CREATORS ================================== */ OsNatConnectionSocket(int connectedSocketDescriptor, const RtpTcpRoles role); OsNatConnectionSocket(const char* szLocalIp, int connectedSocketDescriptor, const RtpTcpRoles role); // Constructor OsNatConnectionSocket(int serverPort, const char* serverName, UtlBoolean blockingConnect, const char* localIp, const bool bConnect, const RtpTcpRoles role); /** * Standard Destructor */ virtual ~OsNatConnectionSocket(); /* ============================ MANIPULATORS ============================== */ virtual OsSocket* getSocket(); virtual void setRole(const RtpTcpRoles role); virtual const RtpTcpRoles getRole() const; /** * Standard read, see OsDatagramSocket for details. */ virtual int read(char* buffer, int bufferLength) ; /** * Standard read, see OsDatagramSocket for details. */ virtual int read(char* buffer, int bufferLength, UtlString* ipAddress, int* port); /** * Standard read, see OsDatagramSocket for details. */ virtual int read(char* buffer, int bufferLength, struct in_addr* ipAddress, int* port); /** * Standard read, see OsDatagramSocket for details. */ virtual int read(char* buffer, int bufferLength, long waitMilliseconds); /** * Standard write, see OsDatagramSocket for details. */ virtual int write(const char* buffer, int bufferLength); /** * Standard write, see OsDatagramSocket for details. */ virtual int socketWrite(const char* buffer, int bufferLength, const char* ipAddress, int port, PacketType packetType=UNKNOWN_PACKET); /** * Standard write, see OsDatagramSocket for details. */ virtual int write(const char* buffer, int bufferLength, const char* ipAddress, int port); /** * Standard write, see OsDatagramSocket for details. */ virtual int write(const char* buffer, int bufferLength, long waitMilliseconds); /** * Enable STUN. Enabling STUN will reset the the keep alive timer and * will force a binding refresh. * * @param szStunServer * @param stunPort * @param iKeepAlive * @param stunOptions * @param bReadFromSocket */ virtual void enableStun(const char* szStunServer, int stunPort, int iKeepAlive, int stunOptions, bool bReadFromSocket) ; /** * Disable STUN. Disabling STUN will stop all keep alives and cause * getMappedIp to fail. */ virtual void disableStun() ; /** * Enable STUN. Enabling STUN will reset the the keep alive timer and * will force a binding refresh. * * @param szTurnSever * @param turnPort * @param iKeepAlive * @param username * @param password * @param bReadFromSocket */ virtual void enableTurn(const char* szTurnSever, int turnPort, int iKeepAlive, const char* username, const char* password, bool bReadFromSocket) ; /** * Disable TURN. Disabling TURN will stop all keep alives and cause * getRelayIp to fail. */ virtual void disableTurn() ; /** * When a stun packet is received this socket can either call read again * to obtain the next packet or return with zero bytes read. By default * the socket will transparently call Read again and will block until a * non-stun packet is read. Calling this method will effect the next * read -- in other words it will not unblock an active read. * * @param bEnable True to enable transparent stun reads and block until * a non-stun packet is received (default) or False to return * with zero bytes read if a stun packet is received. */ virtual void enableTransparentReads(bool bEnable) ; /** * Add an alternate destination to this OsNatConnectionSocket. Alternate * destinations are tested by sending stun packets. If a stun response is * received and the priority is greater than what has already been selected * then that address is used. * * @param szAddress IP address of the alternate destination * @param iPort port number of the alternate destination * @param priority priority of the alternate where a higher number * indicates a higher priority. */ virtual void addAlternateDestination(const char* szAddress, int iPort, int priority) ; /** * Prepares a destination under TURN usage. */ virtual void readyDestination(const char* szAddress, int iPort) ; /** * Sets as notification event that is signaled upon the next successful * stun response or on failure (did not receive a stun response within * (STUN_ABORT_THRESHOLD * STUN_TIMEOUT_RESPONSE_MS). If a notification * event was previous set either by calling this method or via the * constructor, it will be overridden. If the initial STUN success/failure * state has already been determined, this method is undefined. * * @param pNotification Notification event signaled on success or failure. */ virtual void setNotifier(OsNotification* pNotification) ; virtual UtlBoolean addCrLfKeepAlive(const char* szRemoteIp, const int remotePort, const int keepAliveSecs, OsNatKeepaliveListener* pListener) ; virtual UtlBoolean removeCrLfKeepAlive(const char* szRemoteIp, const int remotePort) ; virtual UtlBoolean addStunKeepAlive(const char* szRemoteIp, const int remotePort, const int keepAliveSecs, OsNatKeepaliveListener* pListener) ; virtual UtlBoolean removeStunKeepAlive(const char* szRemoteIp, const int remotePort) ; /* ============================ ACCESSORS ================================= */ /** * Return the external mapped IP address for this socket. This method will * return false if stun is disabled, it was unable to retrieve a stun * binding, or both the ip and port parameters are null. * * @param ip Buffer to place STUN-discovered IP address * @param port Buffer to place STUN-discovered port number */ virtual UtlBoolean getMappedIp(UtlString* ip, int* port) ; /** * Return the external relay IP address for this socket. This method will * return false if stun is disabled, it was unable to retrieve a turn * allocation, or both the ip and port parameters are null. * * @param ip Buffer to place TURN-discovered IP address * @param port Buffer to place TURN-discovered port number */ virtual UtlBoolean getRelayIp(UtlString* ip, int* port) ; /** * TODO: DOCS */ virtual UtlBoolean getBestDestinationAddress(UtlString& address, int& iPort) ; /** * TODO: DOCS */ virtual UtlBoolean applyDestinationAddress(const char* szAddress, int iPort) ; /** * Applies framing to buffers sent over streaming connections * to a TURN server. * Framing prepends with a header like so: * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Type | Reserved = 0 | Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * * @param type Type of framed buffer - STUN or DATA * @param buffer Buffer to be framed. * @param bufferLength Length of the buffer to be framed. * @param framedBufferLen Output parameter for the length of the * framed buffer. * * @returns Pointer to a newly allocated buffer. Must be freed by caller. */ const char* frameBuffer(TURN_FRAMING_TYPE type, const char* buffer, const int bufferLength, int& framedBufferLen); virtual void destroy(); virtual int clientConnect(const char* szServer, const int port); virtual bool isClientConnected(const char* szServer, const int port); virtual OsNatConnectionSocket* getClientConnection(const char* szServer, const int port); /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /** * active, passive, or actpass */ RtpTcpRoles mRole; mutable OsRWMutex mRoleMutex; mutable OsMutex mStreamHandlerMutex; /** * Set the STUN-derived address for this socket. * * @param address STUN-derived hostname/IP address * @param iPort STUN-derived port address */ void setStunAddress(const UtlString& address, const int iPort) ; /** * Set the TURN-dervied relay address for this socket. * * @param address TURN-derived hostname/IP address * @param iPort TURN-derived port address */ void setTurnAddress(const UtlString& address, const int iPort) ; /** * Report that a stun attempt failed. */ void markStunFailure() ; /** * Report that a stun attempt succeeded. */ void markStunSuccess(bool bAddressChanged) ; /** * Report that a stun attempt failed. */ void markTurnFailure() ; /** * Report that a stun attempt succeeded. */ void markTurnSuccess() ; /** * Reset the destination address for this OsNatConnectionSocket. This * method is called by the OsStunAgentTask when a better address is * found via STUN/ICE. * * @param address The new destination address * @param iPort The new destination port * @param priority Priority of the destination address */ void evaluateDestinationAddress(const UtlString& address, int iPort, int priority) ; virtual void handleFramedStream( char* pData, const int size, const char* receivedIp, const int port); virtual bool handleUnframedBuffer(const TURN_FRAMING_TYPE type, const char* buff, const int buffSize, const char* receivedIp, const int port); bool mbTransparentReads ; /**< Block until a non-stun/turn packet is read */ /** * This is the connection socket's analogous UDP socket. * Used for STUN and other requests that require UDP. */ OsNatDatagramSocket* mpDatagramSocket; void addClientConnection(const char* ipAddress, const int port, OsNatConnectionSocket* pClient); UtlHashMap mClientConnectionSockets; // map of client connection sockets // key = destination IP address // value = OsNatConnectionSocket pointer /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: STUN_STATE mStunState ; /**< STUN status/state */ TURN_STATE mTurnState ; /**< TURN status/state */ /* Global Attributes */ OsNatAgentTask* mpNatAgent; /**< Pointer to Nat agent task (handles refreshes) */ OsNotification* mpNotification ; /** Notify on initial stun success or failure */ bool mbNotified ; /** Have we notified the requestor? */ /* ICE Settings */ int miDestPriority ; /**< Priority of destination address / port. */ UtlString mDestAddress; /**< Destination address */ int miDestPort ; /**< Destination port */ char mszFragment[(MAX_RTP_BYTES + 4)]; int mFragmentSize; }; #endif // _OsNatConnectionSocket_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsNatDatagramSocket.h0000644000175000017500000003440612205613256025741 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsNatDatagramSocket_h_ #define _OsNatDatagramSocket_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsNatSocketBaseImpl.h" #include "os/OsDatagramSocket.h" #include "os/OsMsgQ.h" #include "os/OsTimer.h" #include "os/OsQueuedEvent.h" // DEFINES #define NAT_MSG_TYPE (OsMsg::USER_START + 1) /**< Stun Msg type/Id */ // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class NatMsg ; class OsEvent ; class OsNatAgentTask; class OsNatKeepaliveListener; class OsNotification; /** * NAT_STATUS is used internally to mark the end-state of a NAT attempt. NAT * attempts range from a discovery lookup (what is my external IP address) to * a TURN allocation (relaying). */ typedef enum { NAT_STATUS_UNKNOWN, /** Unknown NAT status -- either idle or pending */ NAT_STATUS_SUCCESS, /** NAT binding/allocation was successful */ NAT_STATUS_FAILURE /** NAT binding/allocation was unsuccessful (no response or negative response) */ } NAT_STATUS ; typedef enum { NO_BINDING, STUN_BINDING, TURN_BINDING, STUN_TURN_BINDING } NAT_BINDING; /** * STUN_STATE holds state information for a STUN discovery binding/attempt */ typedef struct { bool bEnabled ; /** Is STUN enabled? */ NAT_STATUS status ; /** What is the stun status? */ UtlString mappedAddress ; /** Mapped STUN address */ int mappedPort ; /** Mapped STUN port */ } STUN_STATE ; /** * TURN_STATE holds state information for a TURN allocation */ typedef struct { bool bEnabled ; /** Is TURN enabled? */ NAT_STATUS status ; /** What is the turn status */ UtlString relayAddress ; /** TURN relay address */ int relayPort ; /** TURN relay port */ } TURN_STATE ; /** * OsNatDatagramSocket extends an OsDatagramSocket by adding an integrated * STUN and TURN client. If STUN or TURN is enabled, request will be send * to the designated server every refresh period. The external addresses * obtained by these mechanisms are retrieved by invoking getMappedIp and * getRelayIp. * * For this mechanism to work, someone must pump inbound socket data by * calling one of the ::read() methods. Otherwise, the packets will not be * received/processed. Internally, the implementation peeks at the read * data and passes the message to the OsNatAgentTask for processing. */ class OsNatDatagramSocket : public OsDatagramSocket, public OsNatSocketBaseImpl { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: friend class OsNatAgentTask ; /* ============================ CREATORS ================================== */ /** * Constructor accepting the remote host port, name, localhost port, * name, and stun attributes. * * @param remoteHostPort Port of the remote host for connection-like use of * OsDatagramSocket. Alternatively, you can also use the ::WriteTo * method and include the host/port at sent time. * @param remoteHostName Hostname of remote host for a connection-like use * of OsDatagramSocket. * @param localHostPort Local port number for the socket, * PORT_DEFAULT to autoselect * @param localHostName Local host name for the socket (e.g. which interface * to bind on. * @param pNotification Optional notification event that is signaled upon * the initial successful stun response or on failure. */ OsNatDatagramSocket(int remoteHostPort, const char* remoteHostName, int localHostPort = PORT_DEFAULT, const char* localHostName = NULL, OsNotification* pNotification = NULL) ; /** * Standard Destructor */ virtual ~OsNatDatagramSocket(); /* ============================ MANIPULATORS ============================== */ virtual OsSocket* getSocket(); /** * Standard read, see OsDatagramSocket for details. */ virtual int read(char* buffer, int bufferLength) ; /** * Standard read, see OsDatagramSocket for details. */ virtual int read(char* buffer, int bufferLength, UtlString* ipAddress, int* port); /** * Standard read, see OsDatagramSocket for details. */ virtual int read(char* buffer, int bufferLength, struct in_addr* ipAddress, int* port); /** * Standard read, see OsDatagramSocket for details. */ virtual int read(char* buffer, int bufferLength, long waitMilliseconds); /** * Standard write, see OsDatagramSocket for details. */ virtual int write(const char* buffer, int bufferLength); /** * Standard write - used to invoke the base class write, * without timestamping. */ virtual int socketWrite(const char* buffer, int bufferLength, const char* ipAddress, int port, PacketType packetType=UNKNOWN_PACKET); /** * Standard write, see OsDatagramSocket for details. */ virtual int write(const char* buffer, int bufferLength, const char* ipAddress, int port); /** * Standard write, see OsDatagramSocket for details. */ virtual int write(const char* buffer, int bufferLength, long waitMilliseconds); /** * Enable STUN. Enabling STUN will reset the the keep alive timer and * will force a binding refresh. * * @param szStunServer * @param stunPort * @param iKeepAlive * @param stunOptions * @param bReadFromSocket */ virtual void enableStun(const char* szStunServer, int stunPort, int iKeepAlive, int stunOptions, bool bReadFromSocket) ; /** * Disable STUN. Disabling STUN will stop all keep alives and cause * getMappedIp to fail. */ virtual void disableStun() ; /** * Enable STUN. Enabling STUN will reset the the keep alive timer and * will force a binding refresh. * * @param szTurnSever * @param turnPort * @param iKeepAlive * @param username * @param password * @param bReadFromSocket */ virtual void enableTurn(const char* szTurnSever, int turnPort, int iKeepAlive, const char* username, const char* password, bool bReadFromSocket) ; /** * Disable TURN. Disabling TURN will stop all keep alives and cause * getRelayIp to fail. */ virtual void disableTurn() ; /** * Waits for result of STUN/TURN binding on this socket. Must be * called after STUN/TURN is enabled and reading is not done from * socket. * * @param binding Binding type to wait for. * @param bWaitUntilReady Whether we should block until bindings are * ready * @return True if this function needs to be called again, because * some of bindings are not yet available. False if all requested * bindings are ready. */ virtual bool waitForBinding(NAT_BINDING binding, bool bWaitUntilReady); /** * When a stun packet is received this socket can either call read again * to obtain the next packet or return with zero bytes read. By default * the socket will transparently call Read again and will block until a * non-stun packet is read. Calling this method will effect the next * read -- in other words it will not unblock an active read. * * @param bEnable True to enable transparent stun reads and block until * a non-stun packet is received (default) or False to return * with zero bytes read if a stun packet is received. */ virtual void enableTransparentReads(bool bEnable) ; /** * Add an alternate destination to this OsNatDatagramSocket. Alternate * destinations are tested by sending stun packets. If a stun response is * received and the priority is greater than what has already been selected * then that address is used. * * @param szAddress IP address of the alternate destination * @param iPort port number of the alternate destination * @param priority priority of the alternate where a higher number * indicates a higher priority. */ virtual void addAlternateDestination(const char* szAddress, int iPort, int priority) ; /** * Set a notification object to be signaled when the first the data * packet is received from the socket. Once this is signaled, the * notification object is discarded. */ virtual void setReadNotification(OsNotification* pNotification) ; /** * Prepares a destination under TURN usage. */ virtual void readyDestination(const char* szAddress, int iPort) ; /** * Sets as notification event that is signaled upon the next successful * stun response or on failure (did not receive a stun response within * (STUN_ABORT_THRESHOLD * STUN_TIMEOUT_RESPONSE_MS). If a notification * event was previous set either by calling this method or via the * constructor, it will be overridden. If the initial STUN success/failure * state has already been determined, this method is undefined. * * @param pNotification Notification event signaled on success or failure. */ virtual void setNotifier(OsNotification* pNotification) ; virtual UtlBoolean addCrLfKeepAlive(const char* szRemoteIp, const int remotePort, const int keepAliveSecs, OsNatKeepaliveListener* pListener) ; virtual UtlBoolean removeCrLfKeepAlive(const char* szRemoteIp, const int remotePort) ; virtual UtlBoolean addStunKeepAlive(const char* szRemoteIp, const int remotePort, const int keepAliveSecs, OsNatKeepaliveListener* pListener) ; virtual UtlBoolean removeStunKeepAlive(const char* szRemoteIp, const int remotePort) ; /* ============================ ACCESSORS ================================= */ /** * Return the external mapped IP address for this socket. This method will * return false if stun is disabled, it was unable to retrieve a stun * binding, or both the ip and port parameters are null. * * @param ip Buffer to place STUN-discovered IP address * @param port Buffer to place STUN-discovered port number */ virtual UtlBoolean getMappedIp(UtlString* ip, int* port) ; /** * Return the external relay IP address for this socket. This method will * return false if stun is disabled, it was unable to retrieve a turn * allocation, or both the ip and port parameters are null. * * @param ip Buffer to place TURN-discovered IP address * @param port Buffer to place TURN-discovered port number */ virtual UtlBoolean getRelayIp(UtlString* ip, int* port) ; /** * TODO: DOCS */ virtual UtlBoolean getBestDestinationAddress(UtlString& address, int& iPort) ; /** * TODO: DOCS */ virtual UtlBoolean applyDestinationAddress(const char* szAddress, int iPort) ; virtual void destroy(); /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /** * Set the STUN-derived address for this socket. * * @param address STUN-derived hostname/IP address * @param iPort STUN-derived port address */ void setStunAddress(const UtlString& address, const int iPort) ; /** * Set the TURN-dervied relay address for this socket. * * @param address TURN-derived hostname/IP address * @param iPort TURN-derived port address */ void setTurnAddress(const UtlString& address, const int iPort) ; /** * Report that a stun attempt failed. */ void markStunFailure() ; /** * Report that a stun attempt succeeded. */ void markStunSuccess(bool bAddressChanged) ; /** * Report that a stun attempt failed. */ void markTurnFailure() ; /** * Report that a stun attempt succeeded. */ void markTurnSuccess() ; /** * Reset the destination address for this OsNatDatagramSocket. This * method is called by the OsStunAgentTask when a better address is * found via STUN/ICE. * * @param address The new destination address * @param iPort The new destination port * @param priority Priority of the destination address */ void evaluateDestinationAddress(const UtlString& address, int iPort, int priority) ; /* ICE Settings */ int miDestPriority ; /**< Priority of destination address / port. */ UtlString mDestAddress; /**< Destination address */ int miDestPort ; /**< Destination port */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: STUN_STATE mStunState ; /**< STUN status/state */ TURN_STATE mTurnState ; /**< TURN status/state */ /* Global Attributes */ OsNatAgentTask* mpNatAgent; /**< Pointer to Nat agent task (handles refreshes) */ bool mbTransparentReads ; /**< Block until a non-stun/turn packet is read */ OsNotification* mpNotification ; /** Notify on initial stun success or failure */ bool mbNotified ; /** Have we notified the requestor? */ }; /* ============================ INLINE METHODS ============================ */ /* ///////////////////////// HELPER CLASSES /////////////////////////////// */ #endif // _OsNatDatagramSocket_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsNatKeepaliveListener.h0000644000175000017500000000715112205613256026460 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // $Id$ // // Copyright (C) 2006 Pingtel Corp. // // $$ ////////////////////////////////////////////////////////////////////////////// #ifndef _OsNatKeepaliveListener_h_ /* [ */ #define _OsNatKeepaliveListener_h_ // SYSTEM INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlString.h" // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS typedef enum { OS_NAT_KEEPALIVE_CRLF, OS_NAT_KEEPALIVE_STUN, OS_NAT_KEEPALIVE_SIP_PING, OS_NAT_KEEPALIVE_SIP_OPTIONS, OS_NAT_KEEPALIVE_INVALID = -1 } OS_NAT_KEEPALIVE_TYPE ; // FORWARD DECLARATIONS /** * Simple event object/container for the OsNatKeepaliveListener. */ class OsNatKeepaliveEvent { public: // Default Constructor OsNatKeepaliveEvent() { type = OS_NAT_KEEPALIVE_INVALID ; remotePort = PORT_NONE ; keepAliveSecs = 0 ; mappedPort = 0 ; } ; // Default Destructor virtual ~OsNatKeepaliveEvent() { } ; // Copy Constructor OsNatKeepaliveEvent(const OsNatKeepaliveEvent& r) { type = r.type ; remoteAddress = r.remoteAddress ; remotePort = r.remotePort ; keepAliveSecs = r.keepAliveSecs ; mappedAddress = r.mappedAddress ; mappedPort = r.mappedPort ; } ; // Equals operator OsNatKeepaliveEvent& operator=(const OsNatKeepaliveEvent& r) { if (this == &r) // handle the assignment to self case return *this; type = r.type ; remoteAddress = r.remoteAddress ; remotePort = r.remotePort ; keepAliveSecs = r.keepAliveSecs ; mappedAddress = r.mappedAddress ; mappedPort = r.mappedPort ; return *this ; } ; // Attribute OS_NAT_KEEPALIVE_TYPE type ; UtlString remoteAddress ; int remotePort ; int keepAliveSecs ; UtlString mappedAddress ; int mappedPort ; } ; /** * Simple listener interface for keepalive events */ class OsNatKeepaliveListener { /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ public: OsNatKeepaliveListener() {} ; virtual ~OsNatKeepaliveListener() {} ; /* ============================ MANIPULATORS ============================== */ /** * A keepalive has been started */ virtual void OnKeepaliveStart(const OsNatKeepaliveEvent& event) = 0 ; /** * A keepalive has been disabled */ virtual void OnKeepaliveStop(const OsNatKeepaliveEvent& event) = 0 ; /** * A keepalive response has been received (not applicable to CrLf * keepalives) */ virtual void OnKeepaliveFeedback(const OsNatKeepaliveEvent& event) = 0 ; /** * A keepalive failure occured (e.g. unable to send -- failures are not * send if responses are not received) */ virtual void OnKeepaliveFailure(const OsNatKeepaliveEvent& event) = 0 ; /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif /* _OsNatKeepaliveListener_h_ ] */ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsNatSocketBaseImpl.h0000644000175000017500000000706412205613256025715 0ustar00danieldaniel00000000000000// $Id$ // // Copyright (C) 2005 Pingtel Corp. // // $$ ////////////////////////////////////////////////////////////////////////////// #ifndef _OsNatSocketBaseImpl_h_ #define _OsNatSocketBaseImpl_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsMutex.h" #include "os/IStunSocket.h" #include "os/OsNotification.h" // The follow defines are used to keep track of what has been recorded for // various time-based metrics. #define ONDS_MARK_NONE 0x00000000 #define ONDS_MARK_FIRST_READ 0x00000001 #define ONDS_MARK_LAST_READ 0x00000002 #define ONDS_MARK_FIRST_WRITE 0x00000004 #define ONDS_MARK_LAST_WRITE 0x00000008 class OsNatSocketBaseImpl : public IStunSocket { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: OsNatSocketBaseImpl() ; virtual ~OsNatSocketBaseImpl() ; /** * Set a notification object to be signaled when the first the data * packet is received from the socket. Once this is signaled, the * notification object is discarded. */ virtual void setReadNotification(OsNotification* pNotification) ; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: void markReadTime() ; void markWriteTime() ; /** * Get the timestamp of the first read data packet (excluding any * STUN/TURN/NAT packets). */ virtual bool getFirstReadTime(OsDateTime& time) ; /** * Get the timestamp of the last read data packet (excluding any * STUN/TURN/NAT packets). */ virtual bool getLastReadTime(OsDateTime& time) ; /** * Get the timestamp of the first written data packet (excluding any * STUN/TURN/NAT packets). */ virtual bool getFirstWriteTime(OsDateTime& time) ; /** * Get the timestamp of the last written data packet (excluding any * STUN/TURN/NAT packets). */ virtual bool getLastWriteTime(OsDateTime& time) ; /** * Handle/process an inbound STUN message. */ virtual void handleStunMessage(char* pBuf, int length, UtlString& fromAddress, int fromPort) ; /** * Handle/process an inbound TURN message. */ virtual void handleTurnMessage(char* pBuf, int length, UtlString& fromAddress, int fromPort) ; /** * Pull a data indication out of the buffer */ virtual int handleTurnDataIndication(char* buffer, int bufferLength, UtlString* pRecvFromIp, int* pRecvFromPort) ; /** * Handle/process an inbound STUN or TURN message. */ virtual bool handleSturnData(char* buffer, int& bufferLength, UtlString& receivedIp, int& receivedPort) ; virtual OsSocket* getSocket() =0; protected: unsigned int miRecordTimes ; // Bitmask populated w/ ONDS_MARK_* OsDateTime mFirstRead ; OsDateTime mLastRead ; OsDateTime mFirstWrite ; OsDateTime mLastWrite ; OsMutex mReadNotificationLock ; OsNotification* mpReadNotification ; }; /* ============================ INLINE METHODS ============================ */ /* ///////////////////////// HELPER CLASSES /////////////////////////////// */ #endif // _OsNatSocketBaseImpl_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsNotification.h0000644000175000017500000000424712205613256025033 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsNotification_h_ #define _OsNotification_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Abstract base class for event notifications class OsNotification { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ //:Default constructor OsNotification() : mSignalTimeout(OsTime::OS_INFINITY) { }; virtual ~OsNotification() { }; //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsStatus signal(const intptr_t eventData) = 0; //:Signal the occurrence of the event /// Set timeout to use when signalling if supported by derived class virtual void setTimeout(const OsTime& signalTimeout) { mSignalTimeout = signalTimeout; }; /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsTime mSignalTimeout; ///< Used by derived classes that support a timeout on signal /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsNotification(const OsNotification& rOsNotification); //:Copy constructor (not implemented for this class) OsNotification& operator=(const OsNotification& rhs); //:Assignment operator (not implemented for this class) }; /* ============================ INLINE METHODS ============================ */ #endif // _OsNotification_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsPathBase.h0000644000175000017500000000730312205613256024070 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsPathBase_h_ #define _OsPathBase_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsFS.h" #include "utl/UtlDefs.h" #include "utl/UtlString.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:OS generic path class. Will massage any input string so separators are correct. //:Also provided functions to class OsPathBase : public UtlString { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static UtlString separator; //: platform specific separator (eg. '/' or '\') /* ============================ CREATORS ================================== */ OsPathBase(); //:Default constructor OsPathBase(const OsPathBase& rOsPath); //:Copy constructor virtual ~OsPathBase(); //:Destructor OsPathBase(const UtlString& rPath); //: Copy contructor OsPathBase(const char* pPath); //: Construct OsPath from char* OsPathBase(const UtlString& rVolume, const UtlString& rDirName, const UtlString& rFileName, const UtlString& rExtension); //: Forms a OsPath from discrete parts /* ============================ MANIPULATORS ============================== */ OsPathBase& operator=(const OsPathBase& rhs); //:Assignment operator OsPathBase& operator+=(const OsPathBase& rhs); //:+= operator static void setSeparator(UtlString &rSeparator); //: Set path separator for this platform void Split(); //: breaks path into its parts /* ============================ ACCESSORS ================================= */ UtlString getVolume() const; //: Returns just the volume of this object (eg. for DOS c:,d: etc...) UtlString getDirName() const; //: Returns just the path of this object (without volume or filename) UtlString getFilename() const; //: Retrieves just the filename part of this object UtlString getExt() const; //: Returns just the extension part of this object OsStatus getNativePath(OsPathBase &rFullPath) const; //: Returns TRUE if the full path for the specified platform was //: found to be valid. Returns the full path in rFullPath. static UtlString getSeparator(); //: Returns the path separator for this platform /* ============================ INQUIRY =================================== */ UtlBoolean isValid(); //:Return TRUE if pathname represented by object is valid for the platform. /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: UtlString mDirName; //: Directory name. Ends with backslash UtlString mVolume; //: Volume (eg. c: d: /sda1) UtlString mFilename; //: Returns the filename (without extension). // If the OsPath object contains just a path, then filename and ext will blank. UtlString mExtension; //: Returns the extension of the file. // If the OsPath object contains just a path, then filename and ext will blank. /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: void massage(); //: Based on the platform in use, this function manipulates the string // so it reprsents a valid platform path }; /* ============================ INLINE METHODS ============================ */ #endif // _OsPathBase_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsProcess.h0000644000175000017500000002006612205613256024020 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsProcess_h_ #define _OsProcess_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsTime.h" #include "os/OsConfigDb.h" #include "os/OsFS.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS typedef int PID; typedef struct OS_PROCESS_STRUCT { PID processID; //: Process Id of process specified by object PID parentProcessID; //: Parent Process Id of process specified by object UtlString name; //: Name of process. Does not include full path, just executable name. UtlString commandline; //: Command line used to start the process int prioClass; //: Current priority of process } *pOsProcessInfo, OsProcessInfo; // FORWARD DECLARATIONS //: This encapsulates a pid, and allows querying, killing and all the //: other cool things you want to do to a process. class OsProcessBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: friend class OsProcessIteratorWnt; friend class OsProcessIteratorVxw; friend class OsProcessIteratorLinux; friend class OsProcessMgr; enum OsProcessPriorityClass { IdlePriorityClass = 0, NormalPriorityClass = 1, HighPriorityClass = 2, RealtimePriorityClass = 3 }; //!enumcode: IdlePriorityClass - Lowest priority //!enumcode: NormalPriorityClass - Default priority //!enumcode: HighPriorityClass - High //!enumcode: RealtimePriorityClass - Very High /* ============================ CREATORS ================================== */ OsProcessBase(); //:Default constructor /* ============================ MANIPULATORS ============================== */ virtual OsStatus launch(UtlString &rAppName, UtlString rParameters[],OsPath &startDir, OsProcessPriorityClass prio = NormalPriorityClass, UtlBoolean bExeclusive = FALSE) = 0; //: Pass the appname and parameters to start the process. //: the Appname could just be the exe name, in which case it is search using your PATH. //: startDir is the default directory the app will start from. //: Returns OS_SUCCESS if process started ok. //: prio specifies the priority class. You may also get the range and manipulate //: the values yourself though setPriority //: If bExclusive is TRUE and another process by the same name already //: is running the return is OS_FAILED virtual OsStatus kill() = 0; //: Kills the process specified by pid virtual OsStatus setPriority(int prio) = 0; //: Changes the process priority. Must own the process for this to be legal. //: Returns TRUE if the priority was set correctly. //: Returns FALSE if the priority could not be set. //: Must be in the range specified by the getMin and Max Priorities. virtual OsStatus setEnv(UtlString &rKey, UtlString &rValue); //: The presets an environment variable. This does NOT set the OS env variable. //: It will set the OS variable just before launch. Then clears it after the launch. //: The process object will continue to contain the env setting, the current OS, however does not. virtual OsStatus unsetEnv(UtlString &rKey); //: The removes the variable from the process object only. It does not modify OS variables. virtual OsStatus setIORedirect(OsPath &rStdInputFilename, OsPath &rStdOutputFilename, OsPath &rStdErrorFilename) = 0; //: Sets the standard input, output and/or stderror /* ============================ ACCESSORS ================================= */ static OsStatus getByPID(PID pid, OsProcessBase &rProcess); //: Given a PID, this method will fill in the process passed in so the user //: can then manipulate it static PID getCurrentPID(); //: returns the current process ID. // This Id is unique within the entire host, in that any two simultaneous // executions that do not share their memory space will have different // values from getCurrentPID(). virtual PID getPID(); //: Returns the process id contained by this object virtual PID getParentPID(); //: Returns the parent PID for this process. virtual OsStatus getProcessName(UtlString& rProcessName); //: Returns the current process name (full path). //: Returns OS_SUCCESS if name retrieved ok. //: Returns OS_FAILED if process not assigned yet, virtual OsStatus getPriority(int &rPrio) = 0; //: Returns the process priority. (1-255) //: Adjusted based on Priority Class virtual OsStatus getMinPriority(int &rMinPrio) = 0; //:returns the value repesenting the minimum priority virtual OsStatus getMaxPriority(int &rMaxPrio) = 0; //:returns the value repesenting the maximum priority virtual OsStatus getPriorityClass(OsProcessPriorityClass &rPrioClass) = 0; //: Returns the Current PriorityClass specified at launch OsStatus getEnv(UtlString &rKey, UtlString &rValue); //: Returns the os environment variable virtual OsStatus getInfo(OsProcessInfo& rProcessInfo) = 0; //: Returns full information on process, including priority. //: See OsProcessInfo for more information virtual OsStatus getUpTime(OsTime &rUpTime) = 0; //: How long has this process been running for? /* ============================ INQUIRY =================================== */ virtual UtlBoolean isRunning () const = 0; //: Returns TRUE if process is still active virtual int wait(int WaitInSecs = -1); //: waits for a process to complete before returning //: or exits when WaitInSecs has completed /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: int mPID; //: Process this object represents int mParentPID; //: Parent PID of this process UtlString mProcessName; //:Used to store the processname this object represents //:This should also be the FULL path name //:This is what was passed on startup OsProcessPriorityClass mPrioClass; //: Priority Class specified on process startup UtlBoolean mExeclusive; //: Startup flag which specified whether multiple instances of process //: can exist. UtlString mParameters; //: Parameters specified at startup UtlString mStdErrorFilename; //: Stores the std error output stream specified by the user. UtlString mStdInputFilename; //: Stores the std input stream specified by the user. UtlString mStdOutputFilename; //: Stores the std output stream specified by the user. OsConfigDb mEnvList; //: Place to store the env variables before launching the process virtual OsStatus ApplyEnv(); //: Called by object before launch to set any environment variables set by user. virtual ~OsProcessBase(); //:Destructor /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ // Depending on the native OS that we are running on, we include the class // declaration for the appropriate lower level implementation and use a // "typedef" statement to associate the OS-independent class name (OsProcess) // with the OS-dependent realization of that type (e.g., OsMutexWnt). #if defined(_WIN32) # include "os/Wnt/OsProcessWnt.h" typedef class OsProcessWnt OsProcess; #elif defined(_VXWORKS) # include "os/Vxw/OsProcessVxw.h" typedef class OsProcessVxw OsProcess; #elif defined(__pingtel_on_posix__) # include "os/linux/OsProcessLinux.h" typedef class OsProcessLinux OsProcess; #else # error Unsupported target platform. #endif //now add this header. #include "os/OsProcessIterator.h" #include "os/OsProcessMgr.h" #endif // _OsProcess_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsProcessIterator.h0000644000175000017500000000564112205613256025534 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsProcessIteratorBase_h_ #define _OsProcessIteratorBase_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsProcess.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //: Used to enumerate running processes class OsProcessIteratorBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsProcessIteratorBase(); //:Default constructor OsProcessIteratorBase(const char* filterExp); //:Return processes filtered by name /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ virtual OsStatus findFirst(OsProcess &rProcess) = 0; //: Start enumeration of running processes //: Returns OS_SUCCESS if found //: Returns OS_FAILED if none found. virtual OsStatus findNext(OsProcess &rProcess) = 0; //: Continues enumeration of running processes //: Returns OS_SUCCESS if found //: Returns OS_FAILED if none found. /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: virtual ~OsProcessIteratorBase(); //:Destructor /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsProcess mProcess; //:Last process found by this class UtlString mProcessNameFilter; //: Used to match enumerated files for filtering OsProcess::OsProcessPriorityClass prioFilterClass; //: Used to match enumerated files for filtering }; /* ============================ INLINE METHODS ============================ */ // Depending on the native OS that we are running on, we include the class // declaration for the appropriate lower level implementation and use a // "typedef" statement to associate the OS-independent class name (OsProcess) // with the OS-dependent realization of that type (e.g., OsMutexWnt). #if defined(_WIN32) # include "os/Wnt/OsProcessIteratorWnt.h" typedef class OsProcessIteratorWnt OsProcessIterator; #elif defined(_VXWORKS) # include "os/Vxw/OsProcessIteratorVxw.h" typedef class OsProcessIteratorVxw OsProcessIterator; #elif defined(__pingtel_on_posix__) # include "os/linux/OsProcessIteratorLinux.h" typedef class OsProcessIteratorLinux OsProcessIterator; #else # error Unsupported target platform. #endif #endif // _OsProcessIteratorBase_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsProcessMgr.h0000644000175000017500000001376612205613256024477 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsProcessMgr_h_ #define _OsProcessMgr_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsFS.h" #include "os/OsProcess.h" #include "os/OsProcessIterator.h" #include "os/OsMutex.h" //to turn on debug string uncomment the next line //#define DEBUG_OUTPUT // DEFINES #define PROCESS_ALIAS_FILE "processAlias.dat" #define PROCESS_ALIAS_LOCK_FILE "locked.lck" // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const int PROCESS_STARTED = 1; const int PROCESS_STOPPED = 2; const int PROCESS_FAILED = 3; const int PROCESS_NEVERRUN = 4; const int PROCESS_STOPPING = 5; const int PROCESS_STARTING = 6; // User requested states const int USER_PROCESS_NONE = 0; const int USER_PROCESS_START = 1; const int USER_PROCESS_STOP = 2; const int USER_PROCESS_RESTART = 3; // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //: This encapsulates a pid, and allows querying, killing and all the //: other cool things you want to do to a process. class OsProcessMgr { friend class MonitoredProcess; /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsProcessMgr(const char* workingDirectory); //:Default constructor virtual ~OsProcessMgr(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsStatus startProcess(UtlString &rAlias, UtlString &rExeName, UtlString rParameters[], UtlString &startupDir, OsProcessBase::OsProcessPriorityClass prio = OsProcessBase::NormalPriorityClass, UtlBoolean bExeclusive = FALSE); //: Start process OsStatus setIORedirect(OsPath &rStdInputFilename, OsPath &rStdOutputFilename, OsPath &rStdErrorFilename); //: Sets the standard input, output and/or stderror //: Applies to all processes created from this point on //: Set them to "" to provide the defaul action. OsStatus stopProcess(UtlString &rAlias); //: Stop process OsStatus stopProcess(PID pid); //: Stop process by id void setProcessListFilename(UtlString &rFilename); //: Overrides the init file of processAlias.dat //: Working directory will be prepended. void setAliasStopped(UtlString &rAlias); OsStatus setUserRequestState(UtlString &rAlias, int userRequestedState); //: Sets a state which watchdog or another program can use to determine //: if a user wishes to change the state of a process. //: ProcessMgr directly does not change the state of the process. //: This function is used to allow users to set a new state (as the third param) //: in processAlias.dat. It is up to an external program to read this //: state via getUserRequestState and change the process state. /* ============================ ACCESSORS ================================= */ int getUserRequestState(UtlString &rAlias); //: Gets the state which a user set when they wish to change the state of a process. //: ProcessMgr directly does not change the state of the process. //: This function is used to allow users to set a new state (as the third param) //: in processAlias.dat. It is up to an external program to read this //: state and change the process state. OsStatus getProcessByAlias(UtlString &rAlias, OsProcess &rProcess); //: Retrieve process object given ID. OsStatus getAliasByPID(PID pid ,UtlString &rAlias); //: Retrieves the alias if you know the pid //: Returns OS_SUCCESS if found, or OS_FAILED if....failed. static OsProcessMgr *getInstance(const char* workingDirectory); //: returns the one and only process manager /* ============================ INQUIRY =================================== */ UtlBoolean isStarted(UtlString &rAlias); int getAliasState(UtlString &rAlias); //: Return the state of the alias void lockAliasFile(); void unlockAliasFile(); /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsStatus setAliasState(UtlString &rAlias,int state); /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: void getAliasFirstValue(UtlString &rinValue); //: helper func to pull the first part of the two part value void getAliasSecondValue(UtlString &rinValue); //: helper func to pull the second part of the two part value static OsProcessMgr * spManager; //: pointer to the one and only process manager OsPath mProcessFilename; //: Name of file which store the alias and PID OsPath mProcessLockFilename; //: Simple Lock file for cross process locking OsPath mWorkPath; //:Where files will be stored //: Defaults to ProcessMgr OsPath mStdInputFilename; //: Where will input come from? OsPath mStdOutputFilename; //: Where will output go to? OsPath mStdErrorFilename; //: Where will errors be sent? OsConfigDb *pProcessList; // Internal list of alias and PID's OsStatus addEntry(UtlString &rAlias, int pid); //: Add an entry to our process file //: Returns OS_SUCCESS if added ok //: or OS_FAILED on failure OsStatus removeEntry(UtlString &rAlias); //: Remove the entry from the file //: Returns OS_SUCCESS if removed //: or OS_FAILED on failure OsStatus loadProcessFile(); //: Returns OS_SUCCESS if saved ok. //: or OS_FAILED on failure OsStatus storeProcessFile(); //: Returns OS_SUCCESS if saved ok. //: or OS_FAILED on failure int mAliasLockFileCount; /** lock for synchronization */ OsMutex mMutex; }; /* ============================ INLINE METHODS ============================ */ #endif // _OsProcessMgr_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsProtectEvent.h0000644000175000017500000000513612205613256025025 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsProtectedEvent_h_ #define _OsProtectedEvent_h_ #include "os/OsEvent.h" #include "os/OsBSem.h" #include "os/OsTime.h" #include "utl/UtlString.h" //#define TAO_DEBUG class OsProtectedEvent : public OsEvent { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsProtectedEvent(const intptr_t userData=0); virtual ~OsProtectedEvent(); /* ============================ MANIPULATORS ============================== */ virtual OsStatus signal(const intptr_t eventData); //:Set the event data and signal the occurrence of the event // Return OS_ALREADY_SIGNALED if the event has already been signaled // (and has not yet been cleared), otherwise return OS_SUCCESS. virtual OsStatus reset(void); //:Reset the event so that it may be signaled again // Return OS_NOT_SIGNALED if the event has not been signaled (or has // already been cleared), otherwise return OS_SUCCESS. virtual OsStatus wait(int msgId, const OsTime& rTimeout=OsTime::OS_INFINITY); //:Wait for the event to be signaled // Return OS_BUSY if the timeout expired, otherwise return OS_SUCCESS. void setStringData(UtlString& rStringData); void setIntData(intptr_t rIntData); void setIntData2(intptr_t rIntData); void setInUse(UtlBoolean inUse); /* ============================ ACCESSORS ================================= */ OsStatus getStringData(UtlString& data); //:Return the user data specified when this object was constructed. // Always returns OS_SUCCESS. OsStatus getIntData(intptr_t& data); OsStatus getIntData2(intptr_t& data); //:Return the user data specified when this object was constructed. // Always returns OS_SUCCESS. /* ============================ INQUIRY =================================== */ virtual UtlBoolean isInUse(); //:Return TRUE if the event has been signaled, otherwise FALSE /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsBSem mRefSem; ///< semaphore used to protect mRef UtlString mStringData; intptr_t mIntData; intptr_t mIntData2; int mRef; ///< reference count }; #endif // _OsProtectedEvent_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsProtectEventMgr.h0000644000175000017500000000732412205613256025474 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsProtectEventMgr_h_ #define _OsProtectEventMgr_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsBSem.h" #include "os/OsProtectEvent.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsProtectEventMgr { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ static OsProtectEventMgr* getEventMgr(); //:Return a pointer to the OsProtectEventMgr, creating it if necessary virtual ~OsProtectEventMgr(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsProtectedEvent* alloc(int userData = 0); //:Allocate a new OsProtectEvent // Return OS_SUCCESS if allocation is successful OsStatus release(OsProtectedEvent* pEvent); //:Release the OsProtectEvent // Return OS_SUCCESS if the OsProtectEvent is released. /* ============================ ACCESSORS ================================= */ int allocCnt(); //:Return the number of events that are allocated. int availCnt(); //:Return the number of events that are available. /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: friend class OsProtectEventMgrInit; #if defined(_pingtel_on_posix_) OsProtectEventMgr(int userData = 0, int initialCount = 1000, int softLimit = 2500, int hardLimit = 25000, int increment = 500); #else OsProtectEventMgr(int userData = 0, int initialCount = 200, int softLimit = 500, int hardLimit = 5000, int increment = 50); #endif //:Constructor /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: // Static data members used to enforce Singleton behavior static OsProtectEventMgr* spInstance; // pointer to the single instance of // the OsProtectEventMgr class OsBSem mListSem; // semaphore used to protect the list table int mAllocs; // number of allocations int mFrees; // number of freed events int mInitialCount; // initial number of items int mCurrentCount; // current number of items int mSoftLimit; // soft limit, warn when expanding above this int mHardLimit; // hard limit AND length of mpElts int mIncrement; // number to create when expanding int mNext; // index to next element to examine OsProtectedEvent** mpEvents; // array of pointers to contained objects OsProtectEventMgr(const OsProtectEventMgr& rOsProtectEventMgr); //:Copy constructor (not implemented for this class) OsProtectEventMgr& operator=(const OsProtectEventMgr& rhs); //:Assignment operator (not implemented for this class) OsStatus addtoList(unsigned int key, unsigned int pEvent); OsStatus remove(unsigned int key); }; /* ============================ INLINE METHODS ============================ */ #endif // _OsProtectEventMgr_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsProtectEventMgrInit.h0000644000175000017500000000401312205613256026310 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 Jaroslav Libak // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef OsProtectEventMgrInit_h__ #define OsProtectEventMgrInit_h__ // SYSTEM INCLUDES // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // FORWARD DECLARATIONS // STRUCTS // TYPEDEFS /** * @brief OsProtectEventMgr initializer class. Solves the problem with ordering * of constructors & destructors. * * The h file needs to be included in: * - all cpp files whose static members are initialized in OsProtectEventMgrInit * constructor, in order to make sure they are initialized properly whenever * they are linked into program. * - it also has to be included as the first include in cpp files, that * initialize static members whose constructor or destructor tries to use any * static members we initialize here. */ class OsProtectEventMgrInit { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ ///@name Creators //@{ /// Constructor OsProtectEventMgrInit(void); /// Destructor ~OsProtectEventMgrInit(void); //@} /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: static unsigned int msCount; ///< Class instance counter. }; /** * This fixes constructor/destructor ordering by declaring a static instance * of this Init class in every cpp file where this .h file is included. * Thus constructor of this class will be run first, and destructor as the last. */ static OsProtectEventMgrInit gOsProtectEventMgrInit; #endif // OsProtectEventMgrInit_h__ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsPtrMsg.h0000644000175000017500000000365712205613256023625 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsPtrMsg_h_ #define _OsPtrMsg_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "utl/UtlContainable.h" #include "os/OsMsg.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Base class for message queue buffers class OsPtrMsg : public OsMsg { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const UtlContainableType TYPE ; /** < Class type used for runtime checking */ /* ============================ CREATORS ================================== */ OsPtrMsg(const unsigned char msgType, const unsigned char msgSubType, void* pData, void* pData2 = NULL); //:Constructor OsPtrMsg(const OsPtrMsg& rOsMsg); //:Copy constructor virtual OsMsg* createCopy(void) const; //:Create a copy of this msg object (which may be of a derived type) /* ============================ MANIPULATORS ============================== */ OsPtrMsg& operator=(const OsPtrMsg& rhs); //:Assignment operator /* ============================ ACCESSORS ================================= */ void* getPtr(); void* getPtr2(); /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: void* mpData; void* mpData2; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _OsPtrMsg_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsQueuedEvent.h0000644000175000017500000001003412205613256024626 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsQueuedEvent_h_ #define _OsQueuedEvent_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsBSem.h" #include "os/OsMsgQ.h" #include "os/OsNotification.h" #include "os/OsTime.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * @brief Queued events are used to send event notifications using a message queue. * * When the corresponding event occurs, the Notifier sends a message the * designated message queue. The Listener must wait on the queue to receive * the event messages. * *

Background

* First, a little bit of terminology. The task that wishes to be notified * when an event occurs is the "Listener" task. The task that signals when * a given event occurs is the "Notifier" task. A Notifier informs the * Listener that a given event has occurred by sending an "Event * Notification". * *

Expected Usage

* The Listener passes an OsQueuedEvent object to the Notifier which * includes a message queue identifier for that message queue that will be * used for event notifications. When the corresponding event occurs, * the Notifier sends a message the designated message queue. The * Listener waits on the queue to receive the event notification. * This mechanism allows a task to receive notifications for multiple * events. The same message queue that is used to receive event * notifications may also be used to receive other types of messages. */ class OsQueuedEvent : public OsNotification { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /// Constructor OsQueuedEvent(OsMsgQ& rMsgQ, const intptr_t userData); /// Destructor virtual ~OsQueuedEvent(); /* ============================ MANIPULATORS ============================== */ /// Set the event data and send an event message to the designated queue. virtual OsStatus signal(const intptr_t eventData); /**< * @return The result of the message send operation. */ /// Set the user data value for this object. virtual OsStatus setUserData(intptr_t userData); /**< * @returns Always OS_SUCCESS. */ /* ============================ ACCESSORS ================================= */ /// Return the user data specified when this object was constructed. virtual OsStatus getUserData(intptr_t& rUserData) const; /**< * @returns Always OS_SUCCESS. */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: intptr_t mUserData; ///< Data specified on behalf of the user and ///< not otherwise used by this class -- the user ///< data is specified as an argument to the class ///< constructor. OsMsgQ* mpMsgQ; ///< Message queue where event notifications will ///< be sent. /// Send an event message to the designated message queue. OsStatus doSendEventMsg(const int msgType, const intptr_t eventData) const; /** * @return The result of the message send operation. */ /// Copy constructor (not implemented for this class). OsQueuedEvent(const OsQueuedEvent& rOsQueuedEvent); /// Assignment operator (not implemented for this class). OsQueuedEvent& operator=(const OsQueuedEvent& rhs); }; /* ============================ INLINE METHODS ============================ */ #endif // _OsQueuedEvent_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsReadLock.h0000644000175000017500000000562512205613256024072 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsReadLock_h_ #define _OsReadLock_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "OsRWMutex.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Lock class allowing multiple simultaneous readers within a critical section // This class uses OsRWMutex objects for synchronization. // The constructor for the class automatically blocks until the OsRWMutex // is acquired for reading. Similarly, the destructor automatically releases // the lock. The easiest way to use this object as a guard is to create the // object as a variable on the stack just before the section that needs to // support multiple simultaneous readers. When the OsReadLock object goes out // of scope, the reader lock will be automatically released. // An example of this form of use is shown below. //

// //    someMethod()
//    {
//       OsReadLock lock(myRWMutex);
//
//       < section allowing multiple // simultaneous readers >
//    }
class OsReadLock { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsReadLock(OsRWMutex& rRWMutex) : mrRWMutex(rRWMutex) { rRWMutex.acquireRead(); }; //:Constructor virtual ~OsReadLock() { mrRWMutex.releaseRead(); }; //:Destructor /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsRWMutex& mrRWMutex; OsReadLock(); //:Default constructor (not implemented for this class) OsReadLock(const OsReadLock& rOsReadLock); //:Copy constructor (not implemented for this class) OsReadLock& operator=(const OsReadLock& rhs); //:Assignment operator (not implemented for this class) }; /* ============================ INLINE METHODS ============================ */ #endif // _OsReadLock_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsRpcMsg.h0000644000175000017500000000555212205613256023600 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsRpcMsg_h_ #define _OsRpcMsg_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsMsg.h" #include "os/OsMsgQ.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsEvent; //:Message object used for synchronous (RPC-style) inter-task communication // RPC inter-task communication works as follows: //

The client task sends an RPC message to the server task. The RPC message // includes a pointer to an OsEvent object. After sending the message, the // client either polls or blocks while waiting for the completion event to // be signaled.

When the server finishes the requested operation, it uses // the OsEvent to specify an integer result and to signal that the operation // has completed. class OsRpcMsg : public OsMsg { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum OsRpcMsgType { REQUEST // message from client to server }; //!enumcode: Request - Message from client to server /* ============================ CREATORS ================================== */ OsRpcMsg(const unsigned char msgType, const unsigned char msgSubType, const OsEvent& rEvent); //:Constructor OsRpcMsg(const OsRpcMsg& rOsRpcMsg); //:Copy constructor virtual OsMsg* createCopy(void) const; //:Create a copy of this msg object (which may be of a derived type) virtual ~OsRpcMsg(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsRpcMsg& operator=(const OsRpcMsg& rhs); //:Assignment operator /* ============================ ACCESSORS ================================= */ virtual int getMsgSize(void) const; //:Return the size of the message in bytes // This is a virtual method so that it will return the accurate size for // the message object even if that object has been upcast to the type of // an ancestor class. virtual OsEvent* getEvent(void) const; //:Return the pointer to the OsEvent object used to signal completion /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsEvent* mpEvent; // pointer to the OsEvent used to signal completion }; /* ============================ INLINE METHODS ============================ */ #endif // _OsRpcMsg_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsRWMutex.h0000644000175000017500000000323412205613256023753 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsRWMutex_h_ #define _OsRWMutex_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "utl/UtlDefs.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Mutual exclusion semaphore handling multiple readers and writers // Two kinds of concurrent tasks, called "readers" and "writers", share a // single resource. The readers can use the resource simultaneously, but each // writer must have exclusive access to it. When a writer is ready to use the // resource, it should be enabled to do so as soon as possible. /// Depending on the native OS that we are running on, we include the class /// declaration for the appropriate lower level implementation and use a /// "typedef" statement to associate the OS-independent class name (OsRWMutex) /// with the OS-dependent realization of that type (e.g., OsRWMutexWnt). #if defined(_WIN32) # include "os/shared/OsRWMutexShared.h" typedef class OsRWMutexShared OsRWMutex; #elif defined(_VXWORKS) || defined(ANDROID) # include "os/shared/OsRWMutexShared.h" typedef class OsRWMutexShared OsRWMutex; #elif defined(__pingtel_on_posix__) # include "os/linux/OsRWMutexLinux.h" typedef class OsRWMutexLinux OsRWMutex; #else # error Unsupported target platform. #endif #endif // _OsRWMutex_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsServerSocket.h0000644000175000017500000000727712205613256025032 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsServerSocket_h_ #define _OsServerSocket_h_ // SYSTEM INCLUDES //#include <...> // APPLICATION INCLUDES #include #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //: Implements TCP server for accepting TCP connections // This class provides the implementation of the UDP datagram-based // socket class which may be instantiated. class OsServerSocket { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsServerSocket(int connectionQueueSize, int serverPort=PORT_DEFAULT, const char* szBindAddr = NULL, const bool bPerformBind = true); //:Constructor to set up TCP socket server // Sets the socket connection queue and starts listening on the // port for requests to connect. // //!param: connectionQueueSize - The maximum number of outstanding // connection requests which are allowed before subsequent requests // are turned away. //!param: serverPort - The port on which the server will listen to // accept connection requests. PORT_DEFAULT means let OS pick port. OsServerSocket& operator=(const OsServerSocket& rhs); //:Assignment operator virtual ~OsServerSocket(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsConnectionSocket* accept(); //:Blocking accept of next connection // Blocks and waits for the next TCP connection request. //!returns: Returns a socket connected to the client requesting the //!returns: connection. If an error occurs returns NULL. virtual void close(); //: Close down the server /* ============================ ACCESSORS ================================= */ virtual int getSocketDescriptor() const; //:Return the socket descriptor // Warning: Use of this method risks the creation of platform-dependent // code. virtual int getLocalHostPort() const; //:Return the local port number // Returns the port to which this socket is bound on this host. virtual void getBindIp(UtlString& ip) const ; //:Gets the bind ip (could be 0.0.0.0) /* ============================ INQUIRY =================================== */ virtual UtlBoolean isOk() const; //: Server socket is in ready to accept incoming conection requests. int isConnectionReady(); //: Poll to see if connections are waiting //!returns: 1 if one or call to accept() will not block
//!returns: 0 if no connections are ready (i.e. accept() will block). /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: virtual OsConnectionSocket* createConnectionSocket(UtlString localIp, int descriptor); OsAtomicLightInt socketDescriptor; int localHostPort; UtlString mLocalIp; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsServerSocket(const OsServerSocket& rOsServerSocket); //:Disable copy constructor OsServerSocket(); //:Disable default constructor }; /* ============================ INLINE METHODS ============================ */ #endif // _OsServerSocket_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsServerTask.h0000644000175000017500000001023612205613256024471 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsServerTask_h_ #define _OsServerTask_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsTask.h" #include "os/OsTime.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsMsg; //:Abstract base class for tasks that process incoming msgs from an OsMsgQ class OsServerTask : public OsTask { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const int DEF_MAX_MSGS; /* ============================ CREATORS ================================== */ /// @brief Main constructor for OsServerTask OsServerTask(const UtlString& name="", void* pArg=NULL, const int maxRequestQMsgs=DEF_MAX_MSGS, const int priority=DEF_PRIO, const int options=DEF_OPTIONS, const int stackSize=DEF_STACKSIZE); /**< * @param[in] name - the name of this OsServerTask * @param[in] pArg - argument that is passed to the new thread as a parameter of the thread run method. * @param[in] maxRequestQMsgs - defines the size of the request message queue. * @param[in] priority - the thread priority to use. high = 0, low = 255 * @param[in] options - Thread execution options to set, such as whether * to allow breakpoint debugging. * @param[in] stackSize - The stack size to use for this task. */ virtual ~OsServerTask(); //:Destructor // As part of destroying the task, flush all messages from the incoming // OsMsgQ. /* ============================ MANIPULATORS ============================== */ virtual UtlBoolean handleMessage(OsMsg& rMsg) = 0; //:Handles an incoming message // If the message is not one that the object is prepared to process, // the handleMessage() method in the derived class should return FALSE // which will cause the OsMessageTask::handleMessage() method to be // invoked on the message. virtual OsStatus postMessage(const OsMsg& rMsg, const OsTime& rTimeout=OsTime::OS_INFINITY, UtlBoolean sentFromISR=FALSE); //:Posts a message to this task // Return the result of the message send operation. virtual void requestShutdown(void); //:Call OsTask::requestShutdown() and then post an OS_SHUTDOWN message //:to the incoming message queue to unblock the task /* ============================ ACCESSORS ================================= */ OsMsgQ* getMessageQueue(); //:Get the pointer to the incoming message queue /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsMsgQ mIncomingQ; // Queue for incoming messages. virtual OsStatus receiveMessage(OsMsg*& rpMsg); //:Waits for a message to arrive on the task's incoming message queue virtual OsStatus receiveMessage(OsMsg*& rpMsg, const OsTime& rTimeout); //:Waits for a message to arrive on the task's incoming message queue, // with timeout. virtual int run(void* pArg); //:The entry point for the task // This method executes a message processing loop until either // requestShutdown(), deleteForce(), or the destructor for this object // is called. /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsServerTask(const OsServerTask& rOsServerTask); //:Copy constructor (not implemented for this class) OsServerTask& operator=(const OsServerTask& rhs); //:Assignment operator (not implemented for this task) }; /* ============================ INLINE METHODS ============================ */ #endif // _OsServerTask_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsSharedLibMgr.h0000644000175000017500000000712612205613256024707 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsSharedLibMgrBase_h_ #define _OsSharedLibMgrBase_h_ // SYSTEM INCLUDES //#include <...> // APPLICATION INCLUDES #include #include #include "utl/UtlHashBag.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //: Singleton manager class to load shared libraries and access symbols in the libs // Class detailed description which may extend to multiple lines class OsSharedLibMgrBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static OsSharedLibMgrBase* getOsSharedLibMgr(); /* ============================ CREATORS ================================== */ virtual ~OsSharedLibMgrBase(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsStatus loadSharedLib(const char* libName) = 0; //: Loads the given shared library //!param: libName - name of library, may include absolute or relative path virtual OsStatus getSharedLibSymbol(const char* libName, const char* symbolName, void*& symbolAddress) = 0; //: Gets the address of a symbol in the shared lib //!param: (in) libName - name of library, may include absolute or relative path //!param: (in) symbolName - name of the variable or function exported in the shared lib //!param: (out) symbolAddress - the address of the function or variable virtual OsStatus unloadSharedLib(const char* libName) = 0; //: Unloads the given shared library // Before unloading library make sure that no one else use it! //!param: libName - name of library, may include absolute or relative path /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsSharedLibMgrBase(); //:Default constructor disallowed, use getOsSharedLibMgr // Static data members used to enforce Singleton behavior static OsSharedLibMgrBase* spInstance; // pointer to the single instance of // the OsProtectEventMgr class static OsBSem sLock; // semaphore used to ensure that there // is only one instance of this class UtlHashBag mLibraryHandles; // List of all the shared libraries and the os specific handle for each /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsSharedLibMgrBase(const OsSharedLibMgrBase& rOsSharedLibMgrBase); //:Copy constructor OsSharedLibMgrBase& operator=(const OsSharedLibMgrBase& rhs); //:Assignment operator }; /* ============================ INLINE METHODS ============================ */ #if defined(_WIN32) # include "os/wnt/OsSharedLibMgrWnt.h" typedef class OsSharedLibMgrWnt OsSharedLibMgr; #elif defined(_VXWORKS) # include "os/Vxw/OsSharedLibMgrVxw.h" typedef class OsSharedLibMgrVxw OsSharedLibMgr; #elif defined(__pingtel_on_posix__) # include "os/linux/OsSharedLibMgrLinux.h" typedef class OsSharedLibMgrLinux OsSharedLibMgr; #else # error Unsupported target platform. #endif #endif // _OsSharedLibMgrBase_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsSocket.h0000644000175000017500000003104712205613256023633 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsSocket_h_ #define _OsSocket_h_ // SYSTEM INCLUDES #if defined(__pingtel_on_posix__) // To get "struct sockaddr_in". #include #include #endif #include // APPLICATION INCLUDES #include "os/OsDefs.h" #include "utl/UtlContainableAtomic.h" #include "utl/UtlString.h" #include "os/OsBSem.h" #include "os/OsAtomics.h" // DEFINES #define MAX_IP_ADDRESSES 32 #define MAX_ADAPTER_NAME_LENGTH 256 //: constant indentifier indicating the maximum number of IP addresses on this host. #define OS_INVALID_SOCKET_DESCRIPTOR (-1) #if defined(_WIN32) # include # include "os/wnt/WindowsAdapterInfo.h" # define OsSocketGetERRNO() (WSAGetLastError()) # define OS_INVALID_INET_ADDRESS INADDR_NONE // 0xffffffff #elif defined(_VXWORKS) # include # define OsSocketGetERRNO() (errno) # define OS_INVALID_INET_ADDRESS 0xffffffff #elif defined(__pingtel_on_posix__) # include "os/linux/AdapterInfo.h" # define OsSocketGetERRNO() (errno) # define OS_INVALID_INET_ADDRESS 0xffffffff #else # error Unsupported target platform. #endif // MACROS // EXTERNAL FUNCTIONS //used to access BindAddress from "C" code extern "C" unsigned long osSocketGetDefaultBindAddress(); // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // ENUMS // FORWARD DECLARATIONS //: Abstract Socket class // This class encapsulates the Berkley socket in an object oriented, // platform independent way. The intention is also to be independent of // the protocol over IP as much as is possible. This should enable // generic message transport with minimal knowledge of the underlying // protocol. class OsSocket : public UtlContainableAtomic { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static UtlBoolean socketInitialized; /// Determine whether or not the values in a containable are comparable. virtual UtlContainableType getContainableType() const; /**< * This returns a unique type for UtlString */ typedef enum { UNKNOWN = -1, TCP = 0, UDP = 1, MULTICAST = 2, SSL_SOCKET = 3, CUSTOM = 4 } IpProtocolSocketType ; //: Protocol Types /* ============================ CREATORS ================================== */ OsSocket(); //:Default constructor virtual ~OsSocket(); //:Destructor /* ============================ MANIPULATORS ============================== */ static UtlBoolean socketInit(); static unsigned long initDefaultAdapterID(UtlString &adapter_id); virtual int write(const char* buffer, int bufferLength, const char* ipAddress, int port) { // default implementation ignores ipAddress and port return write(buffer, bufferLength); } virtual int write(const char* buffer, int bufferLength); //:Blocking write to the socket // Write the characters in the given buffer to the socket. // This method will block until all of the bytes are written. //!param: buffer - The bytes to be written to the socket. //!param: bufferLength - The number of bytes contained in buffer. //!returns: The number of bytes actually written to the socket. //!returns:
Note: This does not necessarily mean that the bytes were //!returns: actually received on the other end. virtual int write(const char* buffer, int bufferLength, long waitMilliseconds); //:Non-blocking or limited blocking write to socket // Same as blocking version except that this write will block // for no more than the specified length of time. //!param: waitMilliseconds - The maximum number of milliseconds to block. This may be set to zero, in which case it does not block. virtual int read(char* buffer, int bufferLength); //:Blocking read from the socket // Read bytes into the buffer from the socket up to a maximum of // bufferLength bytes. This method will block until there is // something to read from the socket. //!param: buffer - Place to put bytes read from the socket. //!param: bufferLength - The maximum number of bytes buffer will hold. //!returns: The number of bytes actually read. virtual int read(char* buffer, int bufferLength, UtlString* ipAddress, int* port); //:Blocking read from the socket // Read bytes into the buffer from the socket up to a maximum of // bufferLength bytes. This method will block until there is // something to read from the socket. //!param: buffer - Place to put bytes read from the socket. //!param: bufferLength - The maximum number of bytes buffer will hold. //!param: ipAddress - The address of the socket that sent the bytes read. //!param: port - The port of the socket that sent the bytes read. //!returns: The number of bytes actually read. virtual int read(char* buffer, int bufferLength, struct in_addr* ipAddress, int* port); //:Blocking read from the socket // Read bytes into the buffer from the socket up to a maximum of // bufferLength bytes. This method will block until there is // something to read from the socket. //!param: buffer - Place to put bytes read from the socket. //!param: bufferLength - The maximum number of bytes buffer will hold. //!param: ipAddress - The address of the socket that sent the bytes read. //!param: port - The port of the socket that sent the bytes read. //!returns: The number of bytes actually read. virtual int read(char* buffer, int bufferLength, long waitMilliseconds); //: Non-blocking or limited blocking read from socket // Same as blocking version except that this read will block // for no more than the specified length of time. //!param: waitMilliseconds - The maximum number of milliseconds to block. This may be set to zero in which case it does not block. virtual void close(); //: Closes the socket virtual void makeNonblocking(); virtual void makeBlocking(); //: Make the connect and all subsequent operations blocking // By default the sockets are blocking. static void setDefaultBindAddress(const unsigned long bind_address); //set the default ipaddress the phone should bind to /* ============================ ACCESSORS ================================= */ virtual OsSocket::IpProtocolSocketType getIpProtocol() const = 0; //:Return the protocol type of this socket /// return the string representation of the SocketProtocolType static const char* ipProtocolString(OsSocket::IpProtocolSocketType); virtual UtlBoolean reconnect() = 0; //:Set up the connection again, assuming the connection failed virtual int getSocketDescriptor() const; //:Return the socket descriptor // Warning: Use of this method risks the creation of platform-dependent // code. static void getDomainName(UtlString &domain_name); //gets static member m_DomainName static unsigned long getDefaultBindAddress(); // get default ip address in network byte order static void getHostName(UtlString* hostName); //:Get this host's name // Gets the host name independent of a socket. static void getHostIp(UtlString* hostAddress); //:Get this host's IP address // virtual void getLocalHostName(UtlString* localHostName) const; //:Return this host's name // Returns a string containing the name of the host on which this socket // resides. This may be the local name, a fully qualified domain name or // anything in between. This name may vary on the same host if it is // multi-homed, depending upon which NIC the Socket is associated with. virtual void getLocalHostIp(UtlString* localHostAddress) const; //:Return this host's ip address // Returns the ip address for this host on which this socket is communicating // On multi-homed machines, this is the address to the NIC over which the // socket communicates. The format is of the form: xx.x.xxx.x virtual const UtlString& getLocalIp() const; //:Return this socket's Local Ip Address virtual void setLocalIp(const UtlString& localIp) { mLocalIp = localIp; } virtual int getLocalHostPort() const; //:Return the local port number // Returns the port to which this socket is bound on this host. virtual void getRemoteHostName(UtlString* remoteHostName) const; //:Return remote host name // Returns a string containing the name of the host on which the socket // on the other end of this socket is bound. This may be the local // name, a fully qualified domain name or anything in between. virtual void getRemoteHostIp(struct in_addr* remoteHostAddress, int* remotePort = NULL); //:Return remote host ip address // Returns the ip address for the host on which the socket on the // other end of this socket is bound. virtual void getRemoteHostIp(UtlString* remoteHostAddress, int* remotePort = NULL); //:Return remote host ip address // Returns the ip address for the host on which the socket on the // other end of this socket is bound. The format is of the form: // xx.x.xxx.x virtual int getRemoteHostPort() const; //:Return the remote port number // Returns the port to which the socket on the other end of this socket // is bound. /* ============================ INQUIRY =================================== */ virtual UtlBoolean isOk() const; //:Returns TRUE if this socket's descriptor is not the invalid descriptor virtual UtlBoolean isConnected() const; //:Returns TRUE if this socket is connected virtual UtlBoolean isReadyToReadEx(long waitMilliseconds, UtlBoolean &rSocketError) const; //:Poll if there are bytes to read // Returns TRUE if socket is read to read. // Returns FALSE if wait expires or socket error. // rSocketError returns TRUE is socket error occurred. virtual UtlBoolean isReadyToRead(long waitMilliseconds = 0) const; //:Poll if there are bytes to read // Returns TRUE if socket is ready to read. // Returns FALSE if wait expires or socket error. virtual UtlBoolean isReadyToWrite(long waitMilliseconds = 0) const; //:Poll if socket is able to write without blocking static UtlBoolean isIp4Address(const char* address); //:Is the address a dotted IP4 address // (i.e., nnn.nnn.nnn.nnn where 0 <= nnn <= 255) static UtlBoolean isMcastAddr(const char* ipAddress); //:Is the given dotted IP4 address a multicast address static UtlBoolean isLocalHost(const char* hostAddress); //:Is the given host name this host static UtlBoolean isSameHost(const char* host1, const char* host2); //:Are these two host names/addresses equivalent static UtlBoolean getHostIpByName(const char* hostName, UtlString* hostAddress); //:Look up IP address for host name static void inet_ntoa_pt(struct in_addr input_address, UtlString& output_address); //:Convert in_addr input_address to dot ip address to avoid memory leak static UtlBoolean isFramed(IpProtocolSocketType type); //:Returns TRUE if the given IpProtocolSocketType is a framed message protocol // (that is, every read returns exactly one message), and so the Content-Length // header may be omitted. /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: static const UtlContainableType TYPE; ///< Class type used for runtime checking static OsBSem mInitializeSem; OsAtomicLightInt socketDescriptor; int localHostPort; int remoteHostPort; UtlString mLocalIp; UtlString localHostName; UtlString remoteHostName; UtlString mRemoteIpAddress; UtlBoolean mIsConnected; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: static unsigned long m_DefaultBindAddress; //default ip address the phone should bind to. May be IPADDR_ANY static UtlString m_DomainName; //domain name for host machine OsSocket& operator=(const OsSocket& rhs); //:Disable assignment operator OsSocket(const OsSocket& rOsSocket); //:Disable copy constructor static UtlBoolean hasDefaultDnsDomain(); //:Returns TRUE if this host has a default DNS domain }; /* ============================ INLINE METHODS ============================ */ #endif // _OsSocket_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsSocketCrypto.h0000644000175000017500000003123312205613256025031 0ustar00danieldaniel00000000000000// // Copyright (C) 2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2008 Mutualink, Inc. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // Author: Sergey Kostanbaev #ifdef HAVE_SSL #ifndef _OsSocketCrypto_h_ #define _OsSocketCrypto_h_ // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsSocket.h" #include "utl/UtlCryptoData.h" #include "utl/UtlCryptoKey.h" #include "os/OsMulticastSocket.h" #include "os/OsDatagramSocket.h" #include "os/OsNatDatagramSocket.h" // DEFINES #define MAX_CRYPTOBUFFER 3000 // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * @brief Encrypted socket base. * * This socket is very limited in its operation: * 1) it blindly assume that flowing data is RTP stream(s) * 2) it encode/decode only RTP payload (headers are not changed) * 3) it only encode/decode packets with selected payload type * * Read the code for more details. */ class OsSocketCryptoProxy { /* //////////////////////////////// PUBLIC //////////////////////////////// */ public: /* =============================== CREATORS =============================== */ ///@name Creators //@{ /// Constructor OsSocketCryptoProxy(OsSocket* pureSocket, int (OsSocket::*read1)(char*, int), int (OsSocket::*read2)(char*, int, UtlString*, int*), int (OsSocket::*read3)(char*, int, struct in_addr*, int*), int (OsSocket::*read4)(char*, int, long), int (OsSocket::*write1)(const char*, int), int (OsSocket::*write2)(const char*, int, const char*, int), int (OsSocket::*write3)(const char*, int, long), const char* pEncBinData, int encBinLength, const char* pDecBinData, int decBinLength); /// Destructor virtual ~OsSocketCryptoProxy(); //@} /* ============================= MANIPULATORS ============================= */ ///@name Manipulators //@{ /// @copydoc OsSocket::write(const char*, int) int write(const char* buffer, int bufferLength); /// @copydoc OsSocket::write(const char*, int, const char*, int) int write(const char* buffer, int bufferLength, const char* ipAddress, int port); /// @copydoc OsSocket::write(const char*, int, long) int write(const char* buffer, int bufferLength, long waitMilliseconds); /// @copydoc OsSocket::read(char*, int) int read(char* buffer, int bufferLength); /// @copydoc OsSocket::read(char*, int, UtlString*, int*) int read(char* buffer, int bufferLength, UtlString* fromAddress, int* fromPort); /// @copydoc OsSocket::read(char*, int, struct in_addr*, int*) int read(char* buffer, int bufferLength, struct in_addr* ipAddress, int* port); /// @copydoc OsSocket::read(char*, int, long) int read(char* buffer, int bufferLength, long waitMilliseconds); //@} /* ============================== ACCESSORS =============================== */ ///@name Accessors //@{ //@} /* =============================== INQUIRY ================================ */ ///@name Inquiry //@{ //@} /* ////////////////////////////// PROTECTED /////////////////////////////// */ protected: /* /////////////////////////////// PRIVATE //////////////////////////////// */ private: /// Set encryption and decryption keys UtlBoolean setSymKeys(const char* pEncBinData, int encBinLength, const char* pDecBinData, int decBinLength); UtlBoolean mDoPadding; uint8_t mCryptoBuffer[MAX_CRYPTOBUFFER]; uint8_t mDecodeBuffer[MAX_CRYPTOBUFFER]; UtlCryptoKey* mpRtpEncryptKey; ///< Encryption key UtlCryptoKey* mpRtpDecryptKey; ///< Decryption key OsSocket* mPureSocket; ///< Basic socket object /// Decode from internal buffer UtlBoolean decode(char* buffer, int bufferLength, int originalLength, int& decodedLen); /// Encode to internal buffer UtlBoolean encode(const char* buffer, int bufferLength, int& encodedLen); /// Read call being overridden in crypto class int (OsSocket::*mRead1)(char* buffer, int bufferLength); /// Read call being overridden in crypto class int (OsSocket::*mRead2)(char* buffer, int bufferLength, UtlString* fromAddress, int* fromPort); /// Read call being overridden in crypto class int (OsSocket::*mRead3)(char* buffer, int bufferLength, struct in_addr* ipAddress, int* port); /// Read call being overridden in crypto class int (OsSocket::*mRead4)(char* buffer, int bufferLength, long waitMilliseconds); /// Write call being overridden in crypto class int (OsSocket::*mWrite1)(const char* buffer, int bufferLength); /// Write call being overridden in crypto class int (OsSocket::*mWrite2)(const char* buffer, int bufferLength, const char* ipAddress, int port); /// Write call being overridden in crypto class int (OsSocket::*mWrite3)(const char* buffer, int bufferLength, long waitMilliseconds); }; /* ============================ INLINE METHODS ============================ */ ////////////////////////////////////////////////////////////////////////// class OsMulticastSocketCrypto : public OsMulticastSocket { public: OsMulticastSocketCrypto(int multicastPortNum, const char* multicastHost, int localHostPortNum, const char* localHost, const char* pEncBinData, int encBinLength, const char* pDecBinData, int decBinLength) : OsMulticastSocket(multicastPortNum, multicastHost, localHostPortNum, localHost) , mCryptoProxy(this, (int (OsSocket::*)(char*, int))&OsMulticastSocketCrypto::readProxy1, (int (OsSocket::*)(char*, int, UtlString*, int*))&OsMulticastSocketCrypto::readProxy2, (int (OsSocket::*)(char*, int, struct in_addr*, int*))&OsMulticastSocketCrypto::readProxy3, (int (OsSocket::*)(char*, int, long))&OsMulticastSocketCrypto::readProxy4, (int (OsSocket::*)(const char*, int))&OsMulticastSocketCrypto::writeProxy1, (int (OsSocket::*)(const char*, int, const char*, int))&OsMulticastSocketCrypto::writeProxy2, NULL, pEncBinData, encBinLength, pDecBinData, decBinLength) { }; int write(const char* buffer, int bufferLength) { return mCryptoProxy.write(buffer, bufferLength); } int write(const char* buffer, int bufferLength, const char* ipAddress, int port) { return mCryptoProxy.write(buffer, bufferLength, ipAddress, port); } int read(char* buffer, int bufferLength) { return mCryptoProxy.read(buffer, bufferLength); } int read(char* buffer, int bufferLength, UtlString* fromAddress, int* fromPort) { return mCryptoProxy.read(buffer, bufferLength, fromAddress, fromPort); } int read(char* buffer, int bufferLength, struct in_addr* ipAddress, int* port) { return mCryptoProxy.read(buffer, bufferLength, ipAddress, port); } int read(char* buffer, int bufferLength, long waitMilliseconds) { return mCryptoProxy.read(buffer, bufferLength, waitMilliseconds); } protected: int writeProxy1(const char* buffer, int bufferLength) { return OsMulticastSocket::write(buffer, bufferLength); } int writeProxy2(const char* buffer, int bufferLength, const char* ipAddress, int port) { return OsMulticastSocket::write(buffer, bufferLength, ipAddress, port); } int readProxy1(char* buffer, int bufferLength) { return OsMulticastSocket::read(buffer, bufferLength); } int readProxy2(char* buffer, int bufferLength, UtlString* fromAddress, int* fromPort) { return OsSocket::read(buffer, bufferLength, fromAddress, fromPort); } int readProxy3(char* buffer, int bufferLength, struct in_addr* ipAddress, int* port) { return OsSocket::read(buffer, bufferLength, ipAddress, port); } int readProxy4(char* buffer, int bufferLength, long waitMilliseconds) { return OsSocket::read(buffer, bufferLength, waitMilliseconds); } private: OsSocketCryptoProxy mCryptoProxy; }; ////////////////////////////////////////////////////////////////////////// class OsNatDatagramSocketCrypto : public OsNatDatagramSocket { public: OsNatDatagramSocketCrypto(int remoteHostPortNum, const char* remoteHost, int localHostPortNum, const char* localHost, OsNotification *pNotification, const char* pEncBinData, int encBinLength, const char* pDecBinData, int decBinLength) : OsNatDatagramSocket(remoteHostPortNum, remoteHost, localHostPortNum, localHost, pNotification) , mCryptoProxy(this, (int (OsSocket::*)(char*, int))&OsNatDatagramSocketCrypto::readProxy1, (int (OsSocket::*)(char*, int, UtlString*, int*))&OsNatDatagramSocketCrypto::readProxy2, (int (OsSocket::*)(char*, int, struct in_addr*, int*))&OsNatDatagramSocketCrypto::readProxy3, (int (OsSocket::*)(char*, int, long))&OsNatDatagramSocketCrypto::readProxy4, (int (OsSocket::*)(const char*, int))&OsNatDatagramSocketCrypto::writeProxy1, (int (OsSocket::*)(const char*, int, const char*, int))&OsNatDatagramSocketCrypto::writeProxy2, (int (OsSocket::*)(const char*, int, long))&OsNatDatagramSocketCrypto::writeProxy3, pEncBinData, encBinLength, pDecBinData, decBinLength) { }; int write(const char* buffer, int bufferLength) { return mCryptoProxy.write(buffer, bufferLength); } int write(const char* buffer, int bufferLength, const char* ipAddress, int port) { return mCryptoProxy.write(buffer, bufferLength, ipAddress, port); } int write(const char* buffer, int bufferLength, long waitMilliseconds) { return mCryptoProxy.write(buffer, bufferLength, waitMilliseconds); } int read(char* buffer, int bufferLength) { return mCryptoProxy.read(buffer, bufferLength); } int read(char* buffer, int bufferLength, UtlString* fromAddress, int* fromPort) { return mCryptoProxy.read(buffer, bufferLength, fromAddress, fromPort); } int read(char* buffer, int bufferLength, struct in_addr* ipAddress, int* port) { return mCryptoProxy.read(buffer, bufferLength, ipAddress, port); } int read(char* buffer, int bufferLength, long waitMilliseconds) { return mCryptoProxy.read(buffer, bufferLength, waitMilliseconds); } protected: int writeProxy1(const char* buffer, int bufferLength) { return OsNatDatagramSocket::write(buffer, bufferLength); } int writeProxy2(const char* buffer, int bufferLength, const char* ipAddress, int port) { return OsNatDatagramSocket::write(buffer, bufferLength, ipAddress, port); } int writeProxy3(const char* buffer, int bufferLength, long waitMilliseconds) { return OsNatDatagramSocket::write(buffer, bufferLength, waitMilliseconds); } int readProxy1(char* buffer, int bufferLength) { return OsNatDatagramSocket::read(buffer, bufferLength); } int readProxy2(char* buffer, int bufferLength, UtlString* fromAddress, int* fromPort) { return OsNatDatagramSocket::read(buffer, bufferLength, fromAddress, fromPort); } int readProxy3(char* buffer, int bufferLength, struct in_addr* ipAddress, int* port) { return OsNatDatagramSocket::read(buffer, bufferLength, ipAddress, port); } int readProxy4(char* buffer, int bufferLength, long waitMilliseconds) { return OsNatDatagramSocket::read(buffer, bufferLength, waitMilliseconds); } private: OsSocketCryptoProxy mCryptoProxy; }; #endif // _OsSocketCrypto_h_ #endif sipxtapi-3.3.0~test17/sipXportLib/include/os/OsSSL.h0000644000175000017500000001265112205613256023044 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsSSL_h_ #define _OsSSL_h__ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsBSem.h" #include "os/OsSysLog.h" #include "openssl/ssl.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlString; class UtlSList; /// Wrapper for the OpenSSL SSL_CTX context structure. /// This class is responsible for all global policy initialization and /// enforcement. class OsSSL { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /// Construct an SSL Context from which connections are created. OsSSL(const char* authorityPath = NULL, /**< Path to a directory containing trusted * certificates files; * If NULL, compiled-in default is used */ const char* publicCertificatePath = NULL, /**< Path to certificate file; * If NULL, compiled-in default is used */ const char* privateKeyPath = NULL /**< Path to private key file; * If NULL, compiled-in default is used. * @note: If publicCertificatePath is NULL, this * must also be NULL. */ ); ~OsSSL(); /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /// Get an SSL server connection handle SSL* getServerConnection(); /// Get an SSL client connection handle SSL* getClientConnection(); /// Release an SSL session handle void releaseConnection(SSL*& connection); /// Get the validated names for the connection peer. static bool peerIdentity( SSL* connection ///< SSL context from connection to be described ,UtlSList* altNames /**< UtlStrings for verfied subjectAltNames * are added to this - caller must free them. */ ,UtlString* commonName ///< the Subject name is returned here ); /**< * Usually, the names in the altNames will be easier to parse and use than commonName * Either or both of altNames or commonName may be NULL, in which case no names are returned; * the return value still indicates the trust relationship with the peer certificate. * @returns * - true if the connection peer is validated by a trusted authority * - false if not, in which case no names are returned. */ /// Log SSL connection information static void logConnectParams(const OsSysLogFacility facility, ///< callers facility const OsSysLogPriority priority, ///< log priority const char* callerMsg, ///< Identifies circumstances of connection SSL* connection ///< SSL connection to be described ); /// Log an error resulting from an SSL call, with the SSL error text expanded static void logError(const OsSysLogFacility facility, ///< callers facility const OsSysLogPriority priority, ///< how bad was it? const char* callerMsg, ///< Identifies caller and what failed int errCode ///< error returned from ssl routine ); /// Debug: print out list of ciphers enabled void dumpCipherList(); /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: static bool sInitialized; SSL_CTX* mCTX; /// Certificate chain validation hook called by openssl static int verifyCallback(int valid, ///< validity so far from openssl X509_STORE_CTX* store ///< certificate information db ); /**< * @returns validity as determined by local policy * @note See 'man SSL_CTX_set_verify' */ /// Disable copy constructor OsSSL(const OsSSL& rOsSSL); /// Disable assignment operator OsSSL& operator=(const OsSSL& rhs); }; /// A singleton wrapper for OsSSL class OsSharedSSL { public: static OsSSL* get(); private: static OsBSem* spSslLock; static OsSSL* spSharedSSL; /// singleton constructor OsSharedSSL(); ~OsSharedSSL(); /// Disable copy constructor OsSharedSSL(const OsSharedSSL& r); /// Disable assignment operator OsSharedSSL& operator=(const OsSharedSSL& rhs); }; /* ============================ INLINE METHODS ============================ */ #endif // _OsSSL_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsSSLConnectionSocket.h0000644000175000017500000001456112205613256026237 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsSSLConnectionSocket_h_ #define _OsSSLConnectionSocket_h_ #ifdef HAVE_SSL // SYSTEM INCLUDES //#include <...> // APPLICATION INCLUDES #include #include #include #include #include #include #include #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /// Implements TLS version of OsSocket class OsSSLConnectionSocket : public OsConnectionSocket { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsSSLConnectionSocket(int remoteHostPort, const char* remoteHostName, long timeoutInSecs = 0 ); OsSSLConnectionSocket(int connectedSocketDescriptor, long timeoutInSecs = 0); OsSSLConnectionSocket(SSL *s, int connectedSocketDescriptor); virtual ~OsSSLConnectionSocket(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual UtlBoolean reconnect(); //: Sets up the connection again, assuming the connection failed virtual int write(const char* buffer, int bufferLength); //:Blocking write to the socket // Write the characters in the given buffer to the socket. // This method will block until all of the bytes are written. //!param: buffer - The bytes to be written to the socket. //!param: bufferLength - The number of bytes contained in buffer. //!returns: The number of bytes actually written to the socket. //!returns:
Note: This does not necessarily mean that the bytes were //!returns: actually received on the other end. virtual int write(const char* buffer, int bufferLength, long waitMilliseconds); //:Non-blocking or limited blocking write to socket // Same as blocking version except that this write will block // for no more than the specified length of time. //!param: waitMilliseconds - The maximum number of milliseconds to block. This may be set to zero, in which case it does not block. virtual int read(char* buffer, int bufferLength); //:Blocking read from the socket // Read bytes into the buffer from the socket up to a maximum of // bufferLength bytes. This method will block until there is // something to read from the socket. //!param: buffer - Place to put bytes read from the socket. //!param: bufferLength - The maximum number of bytes buffer will hold. //!returns: The number of bytes actually read. virtual int read(char* buffer, int bufferLength, UtlString* ipAddress, int* port); //:Blocking read from the socket // Read bytes into the buffer from the socket up to a maximum of // bufferLength bytes. This method will block until there is // something to read from the socket. //!param: buffer - Place to put bytes read from the socket. //!param: bufferLength - The maximum number of bytes buffer will hold. //!param: ipAddress - The address of the socket that sent the bytes read. //!param: port - The port of the socket that sent the bytes read. //!returns: The number of bytes actually read. virtual int read(char* buffer, int bufferLength, long waitMilliseconds); //: Non-blocking or limited blocking read from socket // Same as blocking version except that this read will block // for no more than the specified length of time. //!param: waitMilliseconds - The maximum number of milliseconds to block. This may be set to zero in which case it does not block. /* ============================ ACCESSORS ================================= */ virtual void close(); //: Closes the SSL socket /* ============================ INQUIRY =================================== */ virtual OsSocket::IpProtocolSocketType getIpProtocol() const; //: Returns the protocol type of this socket /// Is this connection encrypted using TLS/SSL? virtual bool isEncrypted() const; /// Get any authenticated peer host names. virtual bool peerIdentity( UtlSList* altNames /**< UtlStrings for verfied subjectAltNames * are added to this - caller must free them. */ ,UtlString* commonName ///< the Subject name is returned here ) const; /**< * Usually, the names in the altNames will be easier to parse and use than commonName * Either or both of altNames or commonName may be NULL, in which case no names are returned; * the return value still indicates the trust relationship with the peer certificate. * @returns * - true if the connection is TLS/SSL and the peer has presented * a certificate signed by a trusted certificate authority * - false if not */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: SSL* mSSL; // cached copies of peer information - parsing the cert is expensive mutable enum { NOT_IDENTIFIED, TRUSTED, UNTRUSTED } mPeerIdentity; mutable UtlSList mAltNames; mutable UtlString mCommonName; UtlBoolean mbExternalSSLSocket; //:Should this object clean up SSL when shutdown. //:It shouldn't if SSL is managed by a parent class void SSLInitSocket(int socket, long timeoutInSecs); OsSSLConnectionSocket(const OsSSLConnectionSocket& rOsSSLConnectionSocket); //:Disable copy constructor OsSSLConnectionSocket(); //:Disable default constructor OsSSLConnectionSocket& operator=(const OsSSLConnectionSocket& rhs); //:Disable Assignment operator }; /* ============================ INLINE METHODS ============================ */ #endif // HAVE_SSL #endif // _OsSSLConnectionSocket_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsSSLServerSocket.h0000644000175000017500000000723512205613256025406 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsSSLServerSocket_h_ #define _OsSSLServerSocket_h_ #ifdef HAVE_SSL // SYSTEM INCLUDES //#include <...> // APPLICATION INCLUDES #include #include #include #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /// Implements Server for accepting TLS/SSL connections class OsSSLServerSocket : public OsServerSocket { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /// Constructor to set up TCP socket server OsSSLServerSocket(int connectionQueueSize, /**< The maximum number of outstanding connection * requests which are allowed before subsequent * requests are turned away.*/ int serverPort=PORT_DEFAULT /**< The port on which the server will listen to * accept connection requests. * PORT_DEFAULT means let OS pick port. */ ); /** * Sets the socket connection queue and starts listening on the * port for requests to connect. */ /// Assignment operator OsSSLServerSocket& operator=(const OsSSLServerSocket& rhs); virtual ~OsSSLServerSocket(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsConnectionSocket* accept(); //:Blocking accept of next connection // Blocks and waits for the next TCP connection request. //!returns: Returns a socket connected to the client requesting the //!returns: connection. If an error occurs returns NULL. void close(); //: Close down the server /* ============================ ACCESSORS ================================= */ virtual int getLocalHostPort() const; //:Return the local port number // Returns the port to which this socket is bound on this host. /* ============================ INQUIRY =================================== */ virtual OsSocket::IpProtocolSocketType getIpProtocol() const; //: Returns the protocol type of this socket virtual UtlBoolean isOk() const; //: Server socket is in ready to accept incoming conection requests. int isConnectionReady(); //: Poll to see if connections are waiting //!returns: 1 if one or call to accept() will not block
//!returns: 0 if no connections are ready (i.e. accept() will block). /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: static int pemPasswdCallbackFunc(char *buf, int size, int rwflag, void *userdata); //:Callback used to set the private key password for decrypting the key //:buf is the buffer to fill with a password //:size is the maximum size of the buffer OsSSLServerSocket(const OsSSLServerSocket& rOsSSLServerSocket); //:Disable copy constructor OsSSLServerSocket(); //:Disable default constructor }; /* ============================ INLINE METHODS ============================ */ #endif // HAVE_SSL #endif // _OsSSLServerSocket_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsStatus.h0000644000175000017500000001714212205613256023666 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsStatus_h_ #define _OsStatus_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Status codes returned by OS abstraction layer methods enum OsStatus { OS_INVALID=0, // invalid status (not yet set) OS_SUCCESS, // success OS_FAILED, // general purpose failure message // Name database OS_NAME_IN_USE, // requested object name is already in use OS_NO_MORE_DATA, // no more data exists // Resource management OS_DELETED, // object has been deleted OS_NOT_FOUND, // object not found OS_NOT_OWNER, // not the owner of the resource OS_LIMIT_REACHED, // resource limit reached // Synchronization OS_BUSY, // requested object is locked OS_NOT_ISR_CALLABLE, // operation not available from an ISR // Timers OS_NO_TIMER_SUPPORT, // timers not supported OS_WAIT_TIMEOUT, // wait operation timed out OS_WAIT_ABANDONED, // synchronization object was abandoned // Message queues OS_INVALID_LENGTH, // message is too long for this message queue // Event Management OS_ALREADY_SIGNALED, // attempt to signal an already signaled event OS_NOT_SIGNALED, // attempt to clear a not-yet-signaled event // Scheduling OS_INVALID_PRIORITY, // you requested an invalid priority level OS_NO_TASK_READY, // no task ready (when attempting to yield // the remainder of a time slice) // Task Management OS_TASK_NOT_STARTED, // task has not yet been started (or has been // shut down) OS_PORT_IN_USE, // task failed while trying to bind to port // Network status OS_DESTINATION_UNREACHABLE,// no route to destination OS_DESTINATION_NOT_RESPONDING, // destination not responding OS_DHCP_UNAVAILABLE, // DHCP lease renewal failed or timed out OS_DNS_UNAVAILABLE, // no DNS server available OS_NETWORK_UNAVAILABLE, // Network unusable, e.g. LINK is inactive // Memory Management OS_NO_MEMORY, // memory allocation error // Directed Graph Management OS_LOOP_DETECTED, // loop detected in flow graph // Version Check OS_VERSIONCHECK_NO_PLATFORMTYPE, // platform type not provided while calling findLatestVersion OS_VERSIONCHECK_NO_LATESTURL, // latest url not provided while calling findLatestVersion OS_VERSIONCHECK_NO_SCRIPTURL, // script url not found in the catalog file OS_VERSIONCHECK_NO_CATALOGURL, // catalog_url not found in the latest file OS_VERSIONCHECK_NO_LATESTVERSION, // version not found in the latest file OS_VERSIONCHECK_FAILURE_CONNECT_TO_SERVER, // failed to connect to the web server for the latest or catalog url OS_VERSIONCHECK_FAILURE_GET_LATESTFILE, // failed to get the specified latest file OS_VERSIONCHECK_FAILURE_GET_CATALOGFILE, // failed to get the specified catalog file OS_VERSIONCHECK_FAILURE_GET_UPGRADESCRIPTS, // failed to get the specified upgrade scripts file OS_VERSIONCHECK_FAILURE_OUT_OF_MEMORY, // failed to get the required memory // cmd results OS_COMMAND_NOT_FOUND, // if the specified cmd is not supported OS_COMMAND_AMBIGUOUS, // if the specified cmd is ambiguous, i.e., more than one cmd can be assigned to it OS_COMMAND_BAD_SYNTAX, // if the arguments do not match specified the cmd OS_HTTP_MOVED_PERMANENTLY_CODE = 301, // Moved Permanently OS_HTTP_MOVED_TEMPORARILY_CODE = 302, // Moved Temporatily OS_HTTP_UNAUTHORIZED_CODE = 401, // Unauthorized OS_HTTP_FILE_NOT_FOUND_CODE = 404, // File Not Found OS_HTTP_PROXY_UNAUTHORIZED_CODE = 407, // Proxy Authentication Required OS_HTTP_UNSUPPORTED_METHOD_CODE = 501, // Not Implemented //File System Error Messages OS_FILE_DIRECTORY_ALREADY_EXISTS, OS_FILE_SAMENAME, OS_FILE_ACCESS_DENIED, OS_FILE_DISKFULL, OS_FILE_INVALID_HANDLE, OS_FILE_READONLY, OS_FILE_DIR_NOT_EMPTY, OS_FILE_PATH_NOT_FOUND, OS_FILE_NOT_FOUND, OS_FILE_WRITE_FAILED, OS_FILE_READ_FAILED, OS_FILE_EOF, OS_FILE_SEEK_ERROR, // Tls initialization OS_TLS_INIT_DATABASE_FAILURE, OS_TLS_INIT_BAD_PASSWORD, OS_TLS_INIT_TCP_IMPORT_FAILURE, OS_TLS_INIT_NSS_FAILURE, // Other OS_INTERRUPTED, // operation was interrupted from completion OS_INVALID_ARGUMENT, // invalid argument to subroutine OS_INVALID_STATE, // invalid state, unable to perform operation OS_NOT_SUPPORTED, // Not supported at this time OS_NOT_YET_IMPLEMENTED, // coming soon ... OS_UNSPECIFIED, // unspecified error OS_UNAUTHORIZED, // "unauthorized" error OS_PLATFORM_NOT_SUPPORTED // OS Platform not supported or missing libraries }; //!enumcode: OS_INVALID=0 - invalid status (not yet set) //!enumcode: OS_SUCCESS - success //!enumcode: OS_NAME_IN_USE - requested object name is already in use //!enumcode: OS_NO_MORE_DATA - no more data exists //!enumcode: OS_DELETED - object has been deleted //!enumcode: OS_NOT_FOUND - object not found //!enumcode: OS_NOT_OWNER - not the owner of the resource //!enumcode: OS_LIMIT_REACHED - resource limit reached //!enumcode: OS_BUSY - requested object is locked //!enumcode: OS_NOT_ISR_CALLABLE - operation not available from an ISR //!enumcode: OS_NO_TIMER_SUPPORT - timers not supported //!enumcode: OS_WAIT_TIMEOUT - wait operation timed out //!enumcode: OS_WAIT_ABANDONED - synchronization object was abandoned //!enumcode: OS_INVALID_LENGTH - message is too long for this message queue //!enumcode: OS_ALREADY_SIGNALED - attempt to signal an already signaled event //!enumcode: OS_NOT_SIGNALED - attempt to clear a not-yet-signaled event //!enumcode: OS_INVALID_PRIORITY - you requested an invalid priority level //!enumcode: OS_NO_TASK_READY - no task ready (when attempting to yield the remainder of a time slice) //!enumcode: OS_TASK_NOT_STARTED - task has not yet been started (or has been shut down) //!enumcode: OS_NO_MEMORY - memory allocation error //!enumcode: OS_LOOP_DETECTED - loop detected in flow graph //!enumcode: OS_DESTINATION_UNREACHABLE - TBS //!enumcode: OS_DESTINATION_NOTRESPONDING - TBS //!enumcode: OS_DHCP_UNAVAILABLE - DHCP lease renewal timed out or failed //!enumcode: OS_DNS_UNAVAILABLE - No DNS server available //!enumcode: OS_NETWORK_UNAVAILABLE - Network unusable (e.g. no LINK) //!enumcode: OS_INVALID_ARGUMENT - invalid argument to subroutine //!enumcode: OS_INVALID_STATE - invalid state, unable to perform operation //!enumcode: OS_NOT_SUPPORTED - Not supported at this time //!enumcode: OS_NOT_YET_IMPLEMENTED - coming soon... //!enumcode: OS_UNSPECIFIED - unspecified error /* ============================ INLINE METHODS ============================ */ #endif // _OsStatus_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsSyncBase.h0000644000175000017500000001017312205613256024107 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsSyncBase_h_ #define _OsSyncBase_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsStatus.h" #include "os/OsTime.h" // DEFINES // If OS_SYNC_DEBUG, enable debugging information for binary semaphores and // mutexes. // #define OS_SYNC_DEBUG #ifdef OS_SYNC_DEBUG # include "os/OsDateTime.h" #endif // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * @brief Base class for the synchronization mechanisms in the OS abstraction layer */ class OsSyncBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /// Destructor virtual ~OsSyncBase() { }; /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ /// Assignment operator OsSyncBase& operator=(const OsSyncBase& rhs); /// Block until the sync object is acquired or the timeout expires virtual OsStatus acquire(const OsTime& rTimeout = OsTime::OS_INFINITY) = 0; /// Conditionally acquire the semaphore (i.e., don't block) virtual OsStatus tryAcquire(void) = 0; /** * @return OS_BUSY if the sync object is held by some other task. */ /// Release the sync object virtual OsStatus release(void) = 0; /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: #ifdef OS_SYNC_DEBUG /// Operations on an OsSyncBase object typedef enum { crumbUnused, ///< array slot not yet used crumbCreated, ///< OsSyncBase constructed crumbAcquired, ///< OsSyncBase acquired crumbReleased, ///< OsSyncBase released crumbDeleted ///< OsSyncBase deleted } OsSyncOperation; #endif # ifdef OS_SYNC_DEBUG /// Track usage of any OsSyncBase object class OsSyncCrumbs { # define NUMBER_OF_CRUMBS 6 public: /// Constructor to initialize crumb trail OsSyncCrumbs() : mCrumb(0) { mTrail[mCrumb].operation = crumbCreated; mTrail[mCrumb].taskId = 0; // default; parent constructor should call dropCrumb for ( unsigned int crumb=1; crumb < NUMBER_OF_CRUMBS; crumb++ ) { mTrail[crumb].operation = crumbUnused; mTrail[crumb].taskId = 0; } } /// record the task id and operation in the mTrail circular buffer void dropCrumb(int id, OsSyncOperation op) { mCrumb = (mCrumb + 1) % NUMBER_OF_CRUMBS; mTrail[mCrumb].operation = op; mTrail[mCrumb].taskId = id; OsDateTime::getCurTime(mTrail[mCrumb].time); } ~OsSyncCrumbs() { // better if the destructor in the object calls, but make sure there is something. dropCrumb(0, crumbDeleted); } private: unsigned int mCrumb; ///< circular index into mTrail: most recently used entry struct { OsSyncOperation operation; ///< operation on the syncronizer unsigned int taskId; ///< the ID of the task that touched the syncronizer OsTime time; ///< when the operation happened } mTrail[NUMBER_OF_CRUMBS]; } mSyncCrumbs; # endif /// Default constructor OsSyncBase() { }; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /// Copy constructor OsSyncBase(const OsSyncBase& rOsSyncBase); }; /* ============================ INLINE METHODS ============================ */ #endif // _OsSyncBase_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsSysLog.h0000644000175000017500000005440412321301427023616 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsSysLog_h_ #define _OsSysLog_h_ // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include #include #include #include #include #include #include // DEFINES #define SYSLOG_NUM_PRIORITIES 8 // Number of OsSysLogPriority entries // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // ENUMS // TYPEDEFS typedef enum tagOsSysLogPriority { PRI_DEBUG, // debug-level message PRI_INFO, // informational message PRI_NOTICE, // normal, but significant, condition PRI_WARNING, // warning conditions PRI_ERR, // error conditions PRI_CRIT, // critical conditions PRI_ALERT, // action must be taken immediately PRI_EMERG // system is unusable // NOTE: If adding/removing priorities, please adjust static name // initializer in OsSysLog.cpp and the SYSLOG_NUM_PRIORITIES define above. // NOTE: The levels are listed in priority order, so they can be // compared with "<", etc. } OsSysLogPriority; //:The priority of log messages ordered from lowest priority to //:highest. // //!enumcode: LOG_DEBUG - Debug-level message. Debug level messages should // be understandable by third party reviewers, however, are // not informative/significant enought to be be an INFO. These // messages tend to be high volume and disruptive to those who did // not author the message. // Example: Session reinvite received from party XXXX //!enumcode: LOG_INFO - Informational message. Informational messages // clearly inform the reviewer of routine and non-special event // within the system. Generally, these events tend to only affect // the closed system and not external systems/parties. The volume // of INFO messages is also smaller than DEBUG messages. // Example: Using codec XXXX for call YYYY //!enumcode: LOG_NOTICE - Normal, but significant, condition. Notices are // expected events, however, are significant enough to warrant // a closer review from administrator. These events may also // involve an external system. // Example: Replicating data to server XXXX // Example: New User 'XXXX' added to database YYYY //!enumcode: LOG_WARNING - Warning conditions. Warnings tend to be minor // expected errors that are easily recoverable. A warning does // not result in any loss of functionality or data. // Example: Received older form of XXXX //!enumcode: LOG_ERR - Error conditions. Error should be used whenever an // expected error is observed and some minor amount of // functionality is lost. // Example: Unknown/Invalid command received. //!enumcode: LOG_CRIT - Critical conditions. Critial errors are errors // where some major amount of functionality/data is lost, however, // the system as a whole will continue to function. // Example: Unable to commit record XXX to disk, index is invalid. //!enumcode: LOG_ALERT - Action must be taken immediately. ALERTs are // errors or events which require immediate action before the // situation grows worse. There is most likely functionality // and/or data loss, however, the entire system may also fail. // Example: Unable to create a new file; file system full. //!enumcode: LOG_EMERG - System is unusable. The worst possible error // where the system will ultimately fail. // Example: Memory corrupted; closing down. // Signature for a callback function that takes three parameters: priority, // source Id of the generating module, and the message itself. typedef void (*OsSysLogCallback)(const char* szPriority, const char* szSource, const char* szMsg); // FORWARD DECLARATIONS class OsSysLogTask; class OsTimer; //:The OsSysLog provides a system wide logger and alternative to printf or //:osPrintf for error/informational/debugging purposes. // // OsSysLog is designed to work on both the xpressa phone where fixed size // circular buffer is needed along with server-type environments where a // simple log is required. // // Daemon Setup // ============ // // Setting up a rolling log: // // To setup a rolling log, you need call the static initialize method // followed by a call to setOutputFile. For example: // // OsSysLog::initialize(1024, "myXpressa3422") ; // // This tells OsSysLog to create log of up to 1024 entries and to use the // string "myXpressa3422" to uniquely identify this process. // // OsSysLog::setOutputFile(90, "/flash0/syslog.txt") ; // // This tell OsSysLog to save the logged data to disk every 90 seconds into // the file "/flash0/syslog.txt". // // Setting up a server-style unbounded log // // Like setting up a rolling log, to setup a unbounded log, you will need to // call the static initialize method followed by a call to setOutputFile. For // example: // // OsSysLog::initialize(0, "ServerXYZ") ; // // This instructs OsSysLog not to create an in-memory buffer and names the // process "ServerXYZ". It is important that you specify "0" as the in-memory // buffer size; otherwise, your log may limited in size. // // OsSysLog::setOutputFile(0, "/usr/var/myserverlog") ; // // This last statement instructs the server to write data immediately to the // log located at "/usr/var/myserverlog". // // Usage // ===== // // Ideally, you should use the syslog method build ontop of OsTask. This will // make sure that that task id, and task name are included as part of the // log entry. // // syslog(FAC_HTTP, PRI_ERR, "The url '%s' is invalid", szUrl) ; // // Alternatively, you can also call static methods on OsSysLog. I would // recommend using a OsTask if possible, however, if you are unable to // reference an OsTask: // // OsSysLog::add(FAC_HTTP, PRI_ERR, "The url '%s' is invalid", szUrl) ; // // or // // OsSysLog::add("MyTaskName", taskId, FAC_HTTP, PRI_ERR, // "The url '%s' is invalid", szUrl) ; // // // The "FAC_HTTP" defines the facility or functional related to the log // message. This helps users and reviewer filter and categorize different // log messages. Please see OsSysLogFacilities.h for a list of available // facilities. Please also feel free to add additional facilities. // // The "PRI_ERR" defines the priority of the log message. Please see the // description above for the different priority levels. // class OsSysLog { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const char* sPriorityNames[] ; //:List of Priority Names orders in the same order as OsSysLogPriority. static const int sPriorityNamesNum; //:Number of elements in sPriorityNames array; static const char* sFacilityNames[] ; //:List of Facility Names orders in the same order as OsSysLogFacility. static const int sFacilityNamesNum; //:Number of elements in sFacilityNames array; enum OsSysLogOptions { OPT_NONE = 0x00000000, // No Options OPT_SHARED_LOGFILE = 0x00000001 // Assume a shared log file // NOTE: Options are designed to be used as bitmasks (and ORed together). // Make sure new additions are defined as power of twos (0x01, // 0x02, 0x04, 0x08, 0x10, 0x10, 0x20, 0x40, ...) } ; //:Defines the set of possible options passed to the initialize method. // //!enumcode: OPT_NONE - No Extra Options // //!enumcode: OPT_SHARED_LOGFILE - Places the OsSysLog in a mode where // multiple loggers (processes) to write to the same log file. // This option should only be set if required to avoid // performance hits. /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ static OsStatus initialize(const int maxInMemoryLogEntries, const char* processId, const int options = OPT_NONE); //:Initialize the sys log facility and the in-memory circular buffer //:size. // This must be called prior to invoking any of the set, add, or enable // manipulators defined in this class. // //!param maxInMemoryLogEntries - Defines the maximum number of in-memory // log entries stored at any one point. This setting may also // impact file based output logging. If the minFlushPeriod is // greater than 0, the output file will never grow larger than // this value. // //!param processId - This parameter represents an arbitrary identifier // that uniquely differentiates this process from other processes. // Examples could range from a phones mac address or server's name. // //!param options - This parameter defines instance specific options. See // the OsSysLogOptions enum defined above for valid settings. static OsStatus shutdown() ; //:Shutdown the OsSysLog task static OsStatus setOutputFile(const int minFlushPeriod, const char* logfile); //:Set an output file to collect logging results. // //!param minFlushPeriod - Defines the minimum amount of that that must // pass before a log entries are flushed to the log file in // seconds. Specifying a value of less than or equal to zero will // force immediate writes. A positive value will limit only allow // log writes periodically and will limit the log file size to the // maxInMemoryLogEntries defined in the call to // OsSysLog::initialize(maxInMemoryLogEntries). //!param logfile - The full qualified path the the target log file. static OsStatus setCallbackFunction(OsSysLogCallback pCallback); //:Set a callback function to collect logging results. // //!param pCallback - Pointer to a callback function that takes three // strings as parameters: Logging priority, source // of log entry, and the entry itself static OsStatus addOutputSocket(const char* remoteHost); //:Add an output socket to the list of output targets. // Log events are fired to output sockets on a low-priority thread and // are not subject to minFlushPeriods such as file output targets. static OsStatus enableConsoleOutput(const UtlBoolean enable); //:Enables or Disable console output for logging events. // Log events are displayed on a low-priority thread and are not subject // to minFlushPeriods as file output targets are. // //!param enable - Specify TRUE to enable console logging or FALSE to // disable it. The default is disabled. static OsStatus setLoggingPriority(const OsSysLogPriority priority); //:Sets the priority logging level. // All log events of lesser priority are disgarded immediately. These // events are not delievered to sockets, file logs, or the console. // // Resetting the global logging priority will clear any facility // priorities. //!param priority - Defines the minimum priority level of log events that // should be logged. static OsStatus setLoggingPriorityForFacility(const OsSysLogFacility facility, const OsSysLogPriority priority); //:Set the priority logging level for a specific facility. // A facilities's logging level overrides the global logging level. This // allow developers to dynamically increase verbosity for a specific // facility. // // Resetting the global logging priority will clear any facility // priorities. // //!param facility - Defines the facility whose logging events should be // either promoted or demoted. //!param priority - Defines the minimum priority level of log events that // should be logged. static OsStatus add(const char* taskName, const int taskId, const OsSysLogFacility facility, const OsSysLogPriority priority, const char* format, ... ) #ifdef __GNUC__ // with the -Wformat switch, this enables format string checking __attribute__ ((format (printf, 5, 6))) #endif ; //:Adds an event to the sys log. If the sys log has not been //:initialized, the message is printed to the console. // //!param: taskName - The name of the task if available. //!param: taskId - The TaskID of the task if available. //!param: facility - Defines the facility responsible for adding the // event. See the OsSysLogFacility for more information. //!param: priority - Defines the priority of the event. See // OsSysLogPriority for more information. static OsStatus add(const OsSysLogFacility facility, const OsSysLogPriority priority, const char* format, ...) #ifdef __GNUC__ // with the -Wformat switch, this enables format string checking __attribute__ ((format (printf, 3, 4))) #endif ; //:Adds an event to the sys log. If the sys log has not been //:initialized, the message is printed to the console. // //!param: facility - Defines the facility responsible for adding the // event. See the OsSysLogFacility for more information. //!param: priority - Defines the priority of the event. See // OsSysLogPriority for more information. static OsStatus vadd(const OsSysLogFacility facility, const OsSysLogPriority priority, const char* format, va_list ap) #ifdef __GNUC__ // with the -Wformat switch, this enables format string checking __attribute__ ((format (printf, 3, 0))) #endif ; //:Adds an event to the sys log. If the sys log has not been //:initialized, the message is printed to the console. // //!param: facility - Defines the facility responsible for adding the // event. See the OsSysLogFacility for more information. //!param: priority - Defines the priority of the event. See // OsSysLogPriority for more information. static OsStatus vadd(const char* taskName, const OsTaskId_t taskId, const OsSysLogFacility facility, const OsSysLogPriority priority, const char* format, va_list ap) #ifdef __GNUC__ // with the -Wformat switch, this enables format string checking __attribute__ ((format (printf, 5, 0))) #endif ; //:Adds an event to the sys log. If the sys log has not been //:initialized, the message is printed to the console. // //!param: taskName - The name of the task if available. //!param: taskId - The TaskID of the task if available. //!param: facility - Defines the facility responsible for adding the // event. See the OsSysLogFacility for more information. //!param: priority - Defines the priority of the event. See // OsSysLogPriority for more information. static OsStatus clearInMemoryLog() ; //:Purges all entries from the in memory log. // If configured to using a flush period (setOutputFile), then entries // entries will also be flushed from the file on next flush. static OsStatus flush(const OsTime& rTimeout = OsTime::OS_INFINITY) ; //:Flushes the in-memory circular buffer log to disk or an unbounded //:log file. static void initSysLog(const OsSysLogFacility facility, const char* processID, const char* logname, const char* loglevel); // Initialize the OsSysLog priority /* ============================ ACCESSORS ================================= */ static OsStatus getMaxInMemoryLogEntries(int& maxEntries) ; //:Obtains the maximum number of in-memory log entries. // This value is specified as part of initialize() process and cannot // be changed at runtime. //!param maxEntries - The maximum number of in-memory log entries static OsStatus tailMemoryLog(const int numEntries) ; //:Displays the last numEntries log entries available within the //:in-memory log buffer. // //!param: numEntries - The number of log entries display starting from // the end (or tail) of the log. Specify a value of <= 0 to // display the entire in-memory log contents. static OsStatus headMemoryLog(const int numEntries) ; //:Displays the first numEntries log entries available within the //:in-memory log buffer. // //!param: numEntries - The number of log entries display starting from // the beginning (or head) of the log. Specify a value of <= 0 // to display the entire in-memory log contents. static OsStatus getLogEntries( const int maxEntries, char* entries[], int& actualEntries) ; //:Gets the last log entries ordered with the most recent //:entry first. //!param: maxEntries - The maximum number of entries to fetch. //!param: entries - Array of char* large enough to accommodate // maxEntries entries. It is the caller responsibility to free // all of the char* pointers. //!param: actualEntries - The actual number of entries returned. This // will always be less than or equal to maxEntries. static OsStatus parseLogString(const char *szSource, UtlString& date, UtlString& eventCount, UtlString& facility, UtlString& priority, UtlString& hostname, UtlString& taskname, UtlString& taskId, UtlString& processId, UtlString& content) ; //:Parses a log string into its parts. static OsStatus getPriorityName(OsSysLogPriority priorityId, UtlString& name); //: Get the string name for the given priority level static OsStatus getPriorityForName(const UtlString& name, OsSysLogPriority& priorityId); //: Get the priority level for the given string (case sensitive) /* ============================ INQUIRY =================================== */ static OsSysLogPriority getLoggingPriority() ; //:Return the logging level priority. // All log events added with a lower priority are discarded. static OsSysLogPriority getLoggingPriorityForFacility(const OsSysLogFacility facility) ; //:Return the logging level for a specific facility. // A facilities's logging level overrides the global logging level. This // allow developers to dynamically increase verbosity for a specific // facility. static UtlBoolean willLog(OsSysLogFacility facility, OsSysLogPriority priority) ; //:Determine if a message of a given facility/priority will be logged or //:digarded. static int getNumFacilities(); //:Return the number of available facilities. static OsTimer* getTimer(); static UtlBoolean isTaskPtrNull() { return(spOsSysLogTask.load() == NULL); }; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: static OsAtomicLightPtr spOsSysLogTask; static OsAtomicULong sEventCount; static OsSysLogPriority spPriorities[FAC_MAX_FACILITY] ; static OsSysLogPriority sLoggingPriority; static UtlString sProcessId; static UtlString sHostname; static UtlBoolean bPrioritiesInitialized; OsSysLog(const OsSysLog& rOsSysLog); //:Copy constructor OsSysLog& operator=(const OsSysLog& rhs); //:Assignment operator OsSysLog(); //:Default constructor virtual ~OsSysLog(); //:Destructor static UtlString escape(const UtlString& source) ; //:Escapes Quotes and CrLfs within a string static UtlString unescape(const UtlString& source) ; //:Unescapes previously escaped Quotes and CrLfs static void getTaskInfo(UtlString& taskName, OsTaskId_t& taskId); //:Get current task name and id /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /** Protect against simple apps that do not call setLoggingPriority */ static void initializePriorities() ; }; class OsStackTraceLogger { public: OsStackTraceLogger(const OsSysLogFacility facility, const OsSysLogPriority priority, const char* methodName); OsStackTraceLogger(const OsSysLogFacility facility, const OsSysLogPriority priority, const char* methodName, const OsStackTraceLogger& oneBackInStack); ~OsStackTraceLogger(); private: // disallow copy OsStackTraceLogger(const OsStackTraceLogger& ref) : mFacility(FAC_LOG), mPriority(PRI_ERR) { // should never get here } // disallow assignment OsStackTraceLogger& operator=(const OsStackTraceLogger& ref) { // should never get here return *this; // avoid compiler warning } UtlString mMethodName; const OsSysLogFacility mFacility; const OsSysLogPriority mPriority; int mTid; }; /* ============================ INLINE METHODS ============================ */ #endif // _OsSysLog_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsSysLogFacilities.h0000644000175000017500000001275212205613256025622 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsSysLogFacilities_h_ #define _OsSysLogFacilities_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // ENUMS // // *** READ THIS *** // // NOTE: If adding a facility, please: // 1) Insert it before the FAC_MAX_FACILITY. // 2) Update OsSysLogFacilties.cpp to include the // string name. // 3) Update the !enum comments below. // // *** READ THIS *** // // enum tagOsSysLogFacility { FAC_PERF=0, // performance related FAC_KERNEL, // kernel/os related FAC_AUTH, // authentication/security related FAC_NET, // networking related FAC_RTP, // RTP/RTCP related FAC_PHONESET, // phoneset related FAC_HTTP, // http sever related FAC_SIP, // sip related FAC_CP, // call processing related FAC_MP, // media processing related FAC_TAO, // TAO related FAC_JNI, // JNI Layer related FAC_JAVA, // Java related FAC_LOG, // OsSysLog related FAC_WATCHDOG, // WatchDog related FAC_SIP_OUTGOING, // Outgoing SIP messages FAC_SIP_INCOMING, // Incoming SIP messages FAC_SIP_INCOMING_PARSED,// Incoming SIP messages after being parsed FAC_MEDIASERVER_CGI, // Mediaserver CGIs FAC_MEDIASERVER_VXI, // Mediaserver VXI engine FAC_ACD, // ACD related FAC_PARK, // Park Server related FAC_APACHE_AUTH, // Apache Authentication Module FAC_UPGRADE, // Update/Upgrade related FAC_LINE_MGR, // SIP line manager related FAC_REFRESH_MGR, // SIP refresh manager related FAC_PROCESSCGI, // Process Management CGI (process.cgi) FAC_STREAMING, // Stream Media related message FAC_REPLICATION_CGI, // replication cgi( replicates databases across components ) FAC_DB, // Database related (sipdb) FAC_PROCESSMGR, // OsProcessMgr FAC_PROCESS, // process related FAC_SIPXTAPI, // sipXtapi related FAC_AUDIO, // audio related FAC_CONFERENCE, // Conference bridge FAC_ODBC, // ODBC related FAC_CDR, // CDR generating related FAC_RLS, // Resource list server FAC_VOICEENGINE, // GIPS VoiceEngine-specific logging FAC_VIDEOENGINE, // GIPS VideoEngine-specific logging FAC_APP, // Generic application facility FAC_SIP_CUSTOM, // Custom transport messages FAC_SDP, // SDP parsing FAC_MAX_FACILITY // Last Facility (used to for length) // // *** READ THIS *** // // NOTE: If adding a facility, please: // 1) Insert it before the FAC_MAX_FACILITY. // 2) Update OsSysLogFacilties.cpp to include the // string name. // 3) Update the !enum comments below. // // *** READ THIS *** // // } ; //: Defines the various facilities available for platforms. // // //!enumcode: FAC_PERF - performance related //!enumcode: FAC_KERNEL - kernel/os related //!enumcode: FAC_AUTH - authentication/security related //!enumcode: FAC_NET - networking related //!enumcode: FAC_RTP - RTP/RTCP related //!enumcode: FAC_PHONESET - phoneset related //!enumcode: FAC_HTTP - http sever related //!enumcode: FAC_SIP - sip related //!enumcode: FAC_CP - call processing related //!enumcode: FAC_TAO - TAO related //!enumcode: FAC_JNI - JNI Layer related //!enumcode: FAC_JAVA - Java related //!enumcode: FAC_LOG - OsSysLog related //!enumcode: FAC_SIP_OUTGOING - Outgoing SIP messages //!enumcode: FAC_SIP_INCOMING - Incoming SIP messages //!enumcode: FAC_SIP_INCOMING_PARSED - Incoming SIP messages after being parsed //!enumcode: FAC_MEDIASERVER_CGI - Mediaserver CGIs //!enumcode: FAC_MEDIASERVER_VXI - Mediaserver VXI engine //!enumcode: FAC_ACD - ACD related //!enumcode: FAC_PARK - Park Server related //!enumcode: FAC_APACHE_AUTH - Apache Authentication Module //!enumcode: FAC_UPGRADE - Update/Upgrade related //!enumcode: FAC_PROCESSCGI - Process Management CGI (process.cgi) //!enumcode: FAC_DB - Database related (sipdb) //!enumcode: FAC_REPLICATION_CGI - replication cgi( replicates databases across components ) //!enumcode: FAC_PROCESSMGR - os processmanager related //!enumcode: FAC_PROCESS - process related //!enumcode: FAC_SIPXTAPI - sipXtapi related //!enumcode: FAC_AUDIO - audio related //!enumcode: FAC_CONFERENCE - Conference bridge //!enumcode: FAC_ODBC - ODBC related //!enumcode: FAC_CDR - CDR generating related //!enumcode: FAC_RLS - Resource list server //!enumcode: FAC_VOICEENGINE - GIPS VoiceEngine related //!enumcode: FAC_VIDEOENGINE - GIPS VideoEngine related //!enumcode: FAC_APP - Generic application messages //!enumcode: FAC_SIP_CUSTOM - custom transport message (in/out) //!enumcode: FAC_SDP - SDP parsing and handling // TYPEDEFS typedef enum tagOsSysLogFacility OsSysLogFacility ; // FORWARD DECLARATIONS #endif /* _OsSysLogFacilities_h_ ] */ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsSysLogMsg.h0000644000175000017500000000554412205613256024275 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsSysLogMsg_h_ #define _OsSysLogMsg_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsSysLog.h" #include "os/OsMsg.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Base class for message queue buffers class OsSysLogMsg : public OsMsg { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum SubMsgTypes { LOG = 0, // Log Message ENABLE_CONSOLE, // Enable console output DISABLE_CONSOLE, // Disable console output HEAD, // Head the log TAIL, // Tail the log SET_FILE, // Set the target output file ADD_SOCKET, // Add a target output socket SET_FLUSH_PERIOD, // Set the flush period FLUSH_LOG, // Flush the log (write to disk) SET_CALLBACK // Set the callback function } ; //: Defines the various SysLog Msg Subtypes // // //!enumcode: LOG - Log Message //!enumcode: ENABLE_CONSOLE - Enable console output //!enumcode: DISABLE_CONSOLE - Disable console output //!enumcode: HEAD - Head the log //!enumcode: TAIL - Tail the log //!enumcode: SET_FILE - Set the target output file //!enumcode: ADD_SOCKET - Add a target output socket //!enumcode: SET_FLUSH_PERIOD - Set the flush period //!enumcode: FLUSH_LOG - Flush the log (write to disk) /* ============================ CREATORS ================================== */ OsSysLogMsg(const unsigned char msgSubType, const void* pData = NULL) ; //:Constructor OsSysLogMsg(const OsSysLogMsg& rOsSysLogMsg); //:Copy constructor virtual OsMsg* createCopy(void) const; //:Create a copy of this msg object (which may be of a derived type) virtual ~OsSysLogMsg(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsSysLogMsg& operator=(const OsSysLogMsg& rhs); //:Assignment operator /* ============================ ACCESSORS ================================= */ const void* getData() const ; //:Get data associated with this message /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: const void* mpData; }; /* ============================ INLINE METHODS ============================ */ #endif /* _OsSysLogMsg_h_ */ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsSysLogTask.h0000644000175000017500000001267712205613256024456 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsSysLogTask_h_ #define _OsSysLogTask_h_ // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsSocket.h" #include "os/OsSysLog.h" #include "os/OsSysLogFacilities.h" #include "os/OsServerTask.h" #include "os/OsRWMutex.h" // DEFINES #define MAX_SOCKET_TARGETS 4 // Max number of output sockets #define MAX_REOPEN_LOG_DELAY_SEC 15 // Close/Reopen log after 15 // seconds. This is actually // performed on the next message, // so it will likely be larger- // perhaps much. // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // ENUMS // TYPEDEFS // FORWARD DECLARATIONS class OsTimer; class OsSocket; class OsEvent; // The OsSysLogTask handles all of the syslog processing class OsSysLogTask : public OsServerTask { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsSysLogTask(const int maxInMemoryLogEntries = 0, const int options = OsSysLog::OPT_NONE); //:Default constructor virtual ~OsSysLogTask(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual UtlBoolean handleMessage(OsMsg& eventMessage); //:Handles all incoming requests OsStatus clear(); //:Clear all of the log entries OsStatus flush(const OsTime& rTimeout = OsTime::OS_INFINITY); //:Stores all of the in-memory log entries to storage OsTimer* getTimer() { return mpTimer; } /* ============================ ACCESSORS ================================= */ OsStatus getMaxEntries(int& maxEntries); //:Obtains the maximum number of in-memory log entries. //!param maxEntries - The maximum number of in-memory log entries OsStatus getLogEntries( const int maxEntries, char* entries[], int& actualEntries) ; //:Gets the last log entries ordered with the most recent //:entry first. //!param: maxEntries - The maximum number of entries to fetch. //!param: entries - Array of char* large enough to accommodate // maxEntries entries. It is the caller responsibility to free // all of the char* pointers. //!param: actualEntries - The actual number of entries returned. This // will always be less than or equal to maxEntries. /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: UtlBoolean mConsoleEnabled; // Is console output enabled? char** mpRingBuffer; // In memory ring buffer int mLogCount; // Number of entries in ring buffer int mRingBufferLength; // Length of ring buffer int mRingBufferNext; // Next available ring buffer FILE* mpUnboundedLog; // Unbounded Log file (if used) UtlString mUnboundedLogFile; // File/Path of Unbounded log file UtlString mBoundedLogFile; // Name/Path of bounded log file int mFlushPeriod; // How often the log file should be flushed UtlBoolean mLogChanged; // Has the log changed/need flushing? OsTimer* mpTimer; // Timer responsible for flushing log OsSocket* mpSockets[MAX_SOCKET_TARGETS] ; // Output sockets OsSysLogCallback mpCallback; // Callback function OsRWMutex mRWMutex; // Guards log data OsTime mpLastReopen ; // Time of last reopen (unbounded only) int mOptions ; // Instance-specific options OsStatus processAdd(char* pEntry); //:Handlers adding a new log entry OsStatus processAddTail(char* pEntry); //:Handlers adding a log entry to the "tail" of the list OsStatus processConsoleEnable(const UtlBoolean enable); //:Handles enabling/disabling console output OsStatus processHeadCommand(const int iEntries); //:Handles displaying log contents starting from "head" of log OsStatus processTailCommand(const int iEntries); //:Handles displaying log contents starting from "tail" of log OsStatus processSetFile(const char* szFile); //:Process setting the target output file OsStatus processAddSocket(const char* remoteHost); //:Process adding a target output socket OsStatus processSetFlushPeriod(const int iPeriod); //:Process setting the flush period OsStatus processFlushLog(OsEvent* pEvent); //:Process flushing the actual log. OsStatus processSetCallback(OsSysLogCallback pCallback); //:Process setting a callback function /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsSysLogTask(const OsSysLogTask& rOsSysLogTask); //:Copy constructor OsSysLogTask& operator=(const OsSysLogTask& rhs); //:Assignment operator }; /* ============================ INLINE METHODS ============================ */ #endif /* _OsSysLogTask_h_ */ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsTask.h0000644000175000017500000003525012205617431023304 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsTask_h_ #define _OsTask_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include // DEFINES #define OSTASK_STACK_SIZE_1M 1024*1024 // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsTime; //:Task abstraction // A task represents a thread of execution. All tasks run within the same // address space but have their own stack and program counter. Tasks may be // created and deleted dynamically. // //

Users create tasks by: //

  1. Deriving a new class based on OsTask or one of its descendants, // and overriding the run() method in the derived class.
  2. //
  3. Calling the constructor for the derived class.
  4. //
  5. Invoking the start() method for the derived class. This creates // the corresponding low-level OS task and associates it with the class.
  6. //
//

Note: Many of the methods in this class are only applicable once the // start() method for the object has been called and the corresponding // low-level task has been created. Accordingly, before a successful call // to start(), most of the methods in this class return the // OS_TASK_NOT_STARTED status. // //

Note: carefully read documentation for ackShutdown() and waitUntilShutDown() // methods, or you may get deadlocks. class OsTaskBase { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const int DEF_OPTIONS; // default task execution options static const int DEF_PRIO; // default task priority static const int DEF_STACKSIZE; // default task stack size static const UtlString TASK_PREFIX; // prefix for OsTask names stored in // the name database static const UtlString TASKID_PREFIX; // prefix for taskID stored in the // name database. static OsAtomicInt taskCount; enum TaskState { UNINITIALIZED, // no low-level task, no name DB entries STARTED, // low-level task and name DB entries exist SHUTTING_DOWN, // requested low-level task shutdown SHUT_DOWN // no low-level task, name DB entries still exist }; //!enumcode: UNINITIALIZED - no low-level task, no name DB entries //!enumcode: STARTED - low-level task and name DB entries exist //!enumcode: SHUTTING_DOWN - requested low-level task shutdown //!enumcode: SHUT_DOWN - no low-level task, name DB entries still exist /* ============================ CREATORS ================================== */ virtual OsStatus deleteForce(void) = 0; //:Delete the task even if the task is protected from deletion // After calling this method, the user will still need to delete the // corresponding OsTask object to reclaim its storage. /* ============================ MANIPULATORS ============================== */ virtual void requestShutdown(void); //:Request a task shutdown // The run() method of the derived class is expected to call the // isShuttingDown() method to detect when a task shutdown has been // requested. After a task has been shut down, it may be restarted // by calling the start() method. virtual UtlBoolean restart(void) = 0; //:Restart the task // The task is first terminated, and then reinitialized with the same // name, priority, options, stack size, original entry point, and // parameters it had when it was terminated. // Return TRUE if the restart of the task is successful. virtual OsStatus resume(void) = 0; //:Resume the task // This routine resumes the task. The task suspension is cleared, and // the task operates in the remaining state. virtual UtlBoolean start(void) = 0; //:Spawn a new task and invoke its run() method. // Return TRUE if the spawning of the new task is successful. // Return FALSE if the task spawn fails or if the task has already // been started. virtual OsStatus suspend(void) = 0; //:Suspend the task // This routine suspends the task. Suspension is additive: thus, tasks // can be delayed and suspended, or pended and suspended. Suspended, // delayed tasks whose delays expire remain suspended. Likewise, // suspended, pended tasks that unblock remain suspended only. virtual OsStatus setErrno(int errno) = 0; //:Set the errno status for the task virtual OsStatus setOptions(int options) = 0; //:Set the execution options for the task // The only option that can be changed after a task has been created // is whether to allow breakpoint debugging. virtual OsStatus setPriority(int priority) = 0; //:Set the priority of the task // Priorities range from 0, the highest priority, to 255, the lowest // priority. virtual void setUserData(int data); //:Set the userData for the task. // The class does not use this information itself, but merely stores // it on behalf of the caller. virtual OsStatus varAdd(int* pVar) = 0; //:Add a task variable to the task // This routine adds a specified variable pVar (4-byte memory // location) to its task's context. After calling this routine, the // variable is private to the task. The task can access and modify // the variable, but the modifications are not visible to other tasks, // and other tasks' modifications to that variable do not affect the // value seen by the task. This is accomplished by saving and restoring // the variable's value each time a task switch occurs to or from the // calling task. virtual OsStatus varDelete(int* pVar) = 0; //:Remove a task variable from the task // This routine removes a specified task variable, pVar, from its // task's context. The private value of that variable is lost. virtual OsStatus varSet(int* pVar, int value) = 0; //:Set the value of a private task variable // This routine sets the private value of the task variable for a // specified task. The specified task is usually not the calling task, // which can set its private value by directly modifying the variable. // This routine is provided primarily for debugging purposes. virtual OsStatus syslog(const OsSysLogFacility facility, const OsSysLogPriority priority, const char* format, ...) #ifdef __GNUC__ // with the -Wformat switch, this enables format string checking __attribute__ ((format(printf, 4, 5))) #endif ; //:Adds a syslog entry to the system logger. // //!param: facility - Defines the facility responsible for adding the // event. See the OsSysLogFacility for more information. //!param: priority - Defines the priority of the event. See // OsSysLogPriority for more information. static OsStatus delay(const int milliSecs); //:Delay a task from executing for the specified number of milliseconds // This routine causes the calling task to relinquish the CPU for the // duration specified. This is commonly referred to as manual // rescheduling, but it is also useful when waiting for some external // condition that does not have an interrupt associated with it. static OsStatus safe(void); //:Make the calling task safe from deletion // This routine protects the calling task from deletion. Tasks that // attempt to delete a protected task will block until the task is // made unsafe, using unsafe(). When a task becomes unsafe, the // deleter will be unblocked and allowed to delete the task. // The safe() primitive utilizes a count to keep track of // nested calls for task protection. When nesting occurs, // the task becomes unsafe only after the outermost unsafe() // is executed. static OsStatus unsafe(void); //:Make the calling task unsafe from deletion // This routine removes the calling task's protection from deletion. // Tasks that attempt to delete a protected task will block until the // task is unsafe. When a task becomes unsafe, the deleter will be // unblocked and allowed to delete the task. // The unsafe() primitive utilizes a count to keep track of nested // calls for task protection. When nesting occurs, the task becomes // unsafe only after the outermost unsafe() is executed. static void yield(void); //:Yield the CPU if a task of equal or higher priority is ready to run /* ============================ ACCESSORS ================================= */ static OsTaskBase* getCurrentTask(void); //:Return a pointer to the OsTask object for the currently executing task // Return NULL if none exists. static OsStatus getCurrentTaskId(int &rid); //:Return an Id of the currently executing task // This Id is unique within the current process, but not necessarily // over the entire host. // Any two simultaneous executions that share their memory space // will have different values from getCurrentTaskId(). static OsTaskBase* getTaskByName(const UtlString& taskName); //:Return a pointer to the OsTask object corresponding to the named task // Return NULL if there is no task object with that name. static OsTaskBase* getTaskById(const int taskId); //:Return a pointer to the OsTask object corresponding to taskId // Return NULL is there is no task object with that id. virtual void* getArg(void); //:Get the void* value passed as an argument to the task virtual OsStatus getErrno(int& rErrno) = 0; //:Get the errno status for the task virtual const UtlString& getName(void); //:Get the name associated with the task virtual int getOptions(void) = 0; //:Return the execution options for the task virtual OsStatus getPriority(int& rPriority) = 0; //:Return the priority of the task virtual int getUserData(void); //:Return the userData for the task. virtual OsStatus varGet(void) = 0; //:Get the value of a task variable // This routine returns the private value of a task variable for its // task. The task is usually not the calling task, which can get its // private value by directly accessing the variable. This routine is // provided primarily for debugging purposes. /* ============================ INQUIRY =================================== */ virtual OsStatus id(OsTaskId_t &rId) = 0; //:Get the task ID for this task virtual UtlBoolean isReady(void); //:Check if the task is running // Return TRUE is the task is started and not suspended, otherwise FALSE. virtual UtlBoolean isShutDown(void); //:Return TRUE if a task shutdown has been requested and acknowledged virtual UtlBoolean isShuttingDown(void); //:Return TRUE if a task shutdown has been requested but not acknowledged virtual UtlBoolean isStarted(void); //:Return TRUE if the task has been started (and has not been shut down) virtual UtlBoolean isSuspended(void) = 0; //:Check if the task is suspended // Return TRUE is the task is suspended, otherwise FALSE. virtual UtlBoolean isUnInitialized(void); //:Return TRUE if a task is un-initialized /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsMutex mDataGuard; // Mutex guard to protect the OsTask internal data UtlString mName; // global name associated with the task volatile TaskState mState; // Task object state OsTaskBase(const UtlString& name, void* pArg, const int priority, const int options, const int stackSize); //:Constructor virtual ~OsTaskBase(); //:Destructor virtual int run(void* pArg) = 0; //:The entry point for the task // Derive new tasks as subclasses of OsTask, overriding this method. virtual UtlBoolean waitUntilShutDown(int milliSecToWait = 20000); //: Wait until the task is shut down and the run method has exited. // Most subclasses of OsTask should call this method in // the destructor before deleting any members which are // accessed by the run method. virtual void ackShutdown(void); //:Acknowledge a shutdown request // This method should only be called by OS specific derived, concrete thread // classes in the threadEntry() static method that invoked the run method. // The point of this method is to signal that no member variables are accessed // by the run() method and that the run method has exited such that it is now // safe to delete this class. For this reason this method must be called // AFTER run exits (not within). Related to this handshake/signaling is // the waitUntilShutDown() method. The waitUntilShutDown() MUST be called by // the destructors of all classes derived from OsTask. waitUntilShutDown() // should be the first thing invoked in the destructor before any members // are destructed. /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: void* mpArg; // argument passed to the task int mUserData; // data stored on behalf of the user. This data // is read/written via getUserData()/setUserData() OsTaskBase(const OsTaskBase& rOsTask); //:Copy constructor (not implemented for this class) OsTaskBase& operator=(const OsTaskBase& rhs); //:Assignment operator (not implemented for this class) }; /* ============================ INLINE METHODS ============================ */ // Depending on the native OS that we are running on, we include the class // declaration for the appropriate lower level implementation and use a // "typedef" statement to associate the OS-independent class name (OsTask) // with the OS-dependent realization of that type (e.g., OsTaskWnt). #if defined(_WIN32) # include "os/Wnt/OsTaskWnt.h" typedef class OsTaskWnt OsTask; #elif defined(_VXWORKS) # include "os/Vxw/OsTaskVxw.h" typedef class OsTaskVxw OsTask; #elif defined(__pingtel_on_posix__) # include "os/linux/OsTaskLinux.h" typedef class OsTaskLinux OsTask; #else # error Unsupported target platform. #endif #endif // _OsTask_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsTaskId.h0000644000175000017500000000134412205617431023556 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsTaskId_h_ #define _OsTaskId_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // ENUMS // TYPEDEFS #if defined(WIN32) typedef int OsTaskId_t; // Not sure this is proper for this platform at least on 64bit ... #elif defined(_VXWORKS) typedef intptr_t OsTaskId_t; // Not sure this is proper for this platform... #elif defined(__pingtel_on_posix__) typedef pthread_t OsTaskId_t; #else # error Unsupported target platform. #endif #endif // _OsTaskId_h_sipxtapi-3.3.0~test17/sipXportLib/include/os/OsTime.h0000644000175000017500000000755712205613256023312 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsTime_h_ #define _OsTime_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "utl/UtlDefs.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Time or time interval // If necessary, this class will adjust the seconds and microseconds values // that it reports such that 0 <= microseconds < USECS_PER_SEC. class OsTime { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /// Time quantity enum for special time values typedef enum { OS_INFINITY = -1, NO_WAIT_TIME = 0 } TimeQuantity; static const long MSECS_PER_SEC; static const long USECS_PER_MSEC; static const long USECS_PER_SEC; /* ============================ CREATORS ================================== */ OsTime(); //:Default constructor (creates a zero duration interval) OsTime(const long msecs); //:Constructor specifying time/duration in terms of milliseconds OsTime(TimeQuantity quantity); //:Constructor specifying time/duration in terms of TimeQuantity enum OsTime(const long seconds, const long usecs); //:Constructor specifying time/duration in terms of seconds and microseconds OsTime(const OsTime& rOsTime); //:Copy constructor virtual ~OsTime(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsTime& operator=(TimeQuantity rhs); //:Assignment operator OsTime& operator=(const OsTime& rhs); //:Assignment operator OsTime operator+(const OsTime& rhs); //:Addition operator OsTime operator-(const OsTime& rhs); //:Subtraction operator OsTime operator+=(const OsTime& rhs); //:Increment operator OsTime operator-=(const OsTime& rhs); //:Decrement operator bool operator==(const OsTime& rhs) const; //:Test for equality operator bool operator!=(const OsTime& rhs) const; //:Test for inequality operator bool operator>(const OsTime& rhs) const; //:Test for greater than bool operator>=(const OsTime& rhs) const; //:Test for greater than or equal bool operator<(const OsTime& rhs) const; //:Test for less than bool operator<=(const OsTime& rhs) const; //:Test for less than or equal /* ============================ ACCESSORS ================================= */ virtual long seconds(void) const { return mSeconds; } //:Return the seconds portion of the time interval virtual long usecs(void) const { return mUsecs; } //:Return the microseconds portion of the time interval virtual long cvtToMsecs(void) const; //:Convert the time interval to milliseconds virtual double getDouble() const; //: Return number of seconds (and microseconds) as a double /* ============================ INQUIRY =================================== */ virtual UtlBoolean isInfinite(void) const; //:Return TRUE if the time interval is infinite virtual UtlBoolean isNoWait(void) const; //:Return TRUE if the time interval is zero (no wait) /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: long mSeconds; long mUsecs; void init(void); //:Initialize the instance variables for a newly constructed object }; /* ============================ INLINE METHODS ============================ */ #endif // _OsTime_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsTimeLog.h0000644000175000017500000000553112205613256023742 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsTimeLog_h_ #define _OsTimeLog_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsTime.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlString; //:Class short description which may consist of multiple lines (note the ':') // Class detailed description which may extend to multiple lines class OsTimeLog { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsTimeLog(int maxEventCount = 100); //:Default constructor OsTimeLog(const OsTimeLog& rOsTimeLog); //:Copy constructor virtual ~OsTimeLog(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsTimeLog& operator=(const OsTimeLog& rhs); //:Assignment operator void addEvent(const char* eventName); //: Adds an event to the log for the current time void addEvent(const char* eventName, OsTime* eventTime); //: Adds an event to the log for the given time // Note: eventTime must be allocated off the heap and is // freed by the OsTimeLog destructor. void dumpLog() const; //: Dumps the log out using osPrintf /* ============================ ACCESSORS ================================= */ void getLogString(UtlString& logString) const; //: Get log with column headers and rows of named events with lapse and incremental time // i.e.: // Name Time Incremental Time // CREATED 0.000000 N/A // SENDING 0.160000 0.160000 // SENDING 0.771000 0.771000 // SENDING 1.823000 1.823000 // SENDING 3.866000 2.866000 // SENDING 7.931000 4.931000 // SENDING 11.987000 4.987000 UtlBoolean getEventTime(const char* eventName, OsTime& time) const; //: Get the named event time UtlBoolean getEventTime(int eventIndex, OsTime& time) const; //: get the event time indicated by the index // Note: the first event index = 0 /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: UtlString** mpaEventNames; OsTime** mpaEventTimes; int mMaxEventCount; int mNumEvents; }; /* ============================ INLINE METHODS ============================ */ #endif // _OsTimeLog_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsTimer.h0000644000175000017500000002621212205613256023461 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsTimer_h_ #define _OsTimer_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include #include // DEFINES /// Macro to check that 'x' is an OsTimer* by testing its /// getContainableType value. This is to catch misuses of the OsTimer /// methods. #define CHECK_VALIDITY(x) \ assert((x)->getContainableType() == OsTimer::TYPE) // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * This class implements one-shot and periodic timers. * * Once a timer is created, it must be started. After the specified time, * the timer expires or "fires", at which point (depending on how the * timer was created) an OsNotification object is used to signal an * event, or a message is posted to a specified queue. * * A timer may be stopped at any time (except when the timer is being * destroyed). The destructor calls stop() before freeing the timer. * * If the stop() is synchronous, it may block, but it ensures that any * event routine call will have finished before stop() returns. If * the stop() is asynchronous, it will not block, but an event routine * execution that has been previously committed may execute after stop() * returns. (For one-shot timers, this can be detected by examining the * return value of stop().) * * Once a timer is stopped with stop() or by firing (if it is a one-shot * timer), it can be started again. The time interval of a timer can be * changed every time it is started, but its notification information is * fixed when it is created. * * All methods can be used concurrently, except that no other method may be * called concurrently with the destructor (which cannot be made to work, * as the destructor deletes the timer's memory). Note that a timer may * fire while it is being deleted; the destructor handles this situation * correctly, the timer is guaranteed to exist until after the event * routine returns. * * An event routine should be non-blocking, because it is called on * the timer task thread. Within an event routine, all non-blocking * methods may be executed on the timer. When the event routine of a * one-shot timer is entered, the timer is in the stopped state. When * the event routine of a periodic timer is entered, the timer is * still in the running state. * * (If mbManagedNotifier is set, the timer may not be destroyed (using * deleteAsync, which is non-blocking), as that destroys the * OsNotifier object whose method is the event notifier that is * currently running. But there is no current interface for creating * that situation.) * * Most methods are non-blocking, except to seize the timer's mutex * and to post messages to the timer task's message queue. The * exceptions are the destructor and synchronous stops, which must * block until they get a response from the timer task. * * If VALGRIND_TIMER_ERROR is defined, additional code is created to * detect and backtrace errors in timer usage. This code causes run-time * errors that Valgrind can detect to produce backtraces of where the * invalid method invocations were made. * * If NDEBUG is defined, some checking code that is used only to trigger * asserts is omitted. * * @nosubgrouping */ class OsTimer : public UtlContainable { friend class OsTimerTask; friend class OsTimerTest; /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /// The states a timer can be in. enum OsTimerState { STOPPED, ///< Timer has not been started, or has fired ///< or been stopped. STARTED ///< Timer is running and will fire. }; static const UtlContainableType TYPE; /**< Class type used for runtime checking */ /* ============================ CREATORS ================================== */ /** @name Constructors * * Constructors specify how fired timers will signal the application. * The event specification does not change over the lifetime of the * timer. The timer period information is specified by the start * method, and can be different for different starts. * * @{ */ /** Construct a timer that signals by calling * @code * rNotifier.signal((int) this) * @endcode */ OsTimer(OsNotification& rNotifier ///< OsNotification object to report event ); /** Construct a timer that signals by calling * @code * pQueue->doSendEventMsg(OsEventMsg::NOTIFY, (int) this) * @endcode */ OsTimer(OsMsgQ* pQueue, ///< Queue to send OsEventMsg::NOTIFY message intptr_t userData ///< userData value to store in OsQueuedEvent ); /// @} /// Destructor virtual ~OsTimer(); /// Non-blocking asynchronous delete operation virtual void deleteAsync(); /**< * Stops the timer, then sends a message to the timer task, which will * eventually delete it. Provides a non-blocking way to delete an * OsTimer. */ /* ============================ MANIPULATORS ============================== */ /** @name Start methods * * These methods start the timer. They may be called when the timer is * in any state, but if the timer is already started, they have no * effect. They return a value that reflects that state: OS_SUCCESS if * the start operation was successful and OS_FAILED if it failed * (because the timer was already started). * * @{ */ /// Start the timer to fire once at the indicated date/time virtual OsStatus oneshotAt(const OsDateTime& when); /// Start the timer to fire once at the current time + offset virtual OsStatus oneshotAfter(const OsTime& offset); /// Start the timer to fire periodically starting at the indicated date/time virtual OsStatus periodicAt(const OsDateTime& when, const OsTime &period); /// Start the timer to fire periodically starting at current time + offset virtual OsStatus periodicEvery(const OsTime &offset, const OsTime &period); /// @} /// Stop the timer if it has been started virtual OsStatus stop(UtlBoolean synchronous = TRUE); /**< * stop() can be called when the timer is in any state, and returns a * value that reflects that state: * * @returns OS_SUCCESS if the timer was started and OS_FAILED if the * timer was not started, was already stopped, or is a one-shot * timer and has fired. * * Thus, if it is a one-shot timer, and there are one or more calls to * stop(), if the event has been signaled, all calls will return * OS_FAILED. But if the event has not been signaled, exactly one call * will return OS_SUCCESS. This allows the caller of stop() to know * whether to clean up or not. * * If synchronous is TRUE, the call will block if necessary to * ensure that any event routine execution for this timer will * finish before stop() returns. If synchronous is FALSE, the call * will not block, but a previously committed event routine * execution may happen after stop() returns. */ /* ============================ ACCESSORS ================================= */ /// Return the OsNotification object for this timer virtual OsNotification* getNotifier(void) const; /**< * If the timer was constructed with OsTimer(OsMsgQ*, const int), * it returns the address of an internally allocated OsNotification. */ /// Calculate a unique hash code for this object. virtual unsigned hash() const; /**< * If the equals operator returns true for another object, then both of * those objects must return the same hashcode. */ /// Get the ContainableType for a UtlContainable derived class. virtual UtlContainableType getContainableType() const; /// Returns TRUE if timer was fired UtlBoolean getWasFired(); /**< * This flag is set to FALSE when timer is first started, and also * if stop operation succeeds. It is set to TRUE when timer is fired. * Note that stop fails on a stopped timer. */ /* ============================ INQUIRY =================================== */ /// Compare the this object to another like-objects. virtual int compareTo(UtlContainable const *) const; /**< * Results for comparing with a non-like object are undefined. * * @returns 0 if equal, < 0 if less-than and > 0 if greater-than. */ /// Return the state value for this OsTimer object virtual OsTimerState getState(); /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsBSem mBSem; ///< Semaphore to lock access to members. unsigned int mApplicationState; UtlBoolean mWasFired; ///< TRUE if timer is stopped because it was fired ///< state as seen by application methods. unsigned int mTaskState; ///< State as seen by the timer task. UtlBoolean mDeleting; ///< TRUE if timer is being deleted. OsNotification* mpNotifier; ///< Used to signal timer expiration event. UtlBoolean mbManagedNotifier; ///< TRUE if OsTimer destructor should ///< delete *mpNotifier. OsTime mExpiresAt; ///< Expire time of timer. UtlBoolean mPeriodic; ///< TRUE if timer fires repetitively. OsTime mPeriod; ///< Repetition time. // Copies of time values for use by timer task. OsTime mQueuedExpiresAt; ///< Expire time of timer (copy). UtlBoolean mQueuedPeriodic; ///< TRUE if timer fires repetitively (copy). OsTime mQueuedPeriod; ///< Repetition time (copy). int mOutstandingMessages; ///< Number of messages for this timer ///< in the timer task's queue. OsTimer* mTimerQueueLink; ///< To chain together timers. /// Start a timer. OsStatus startTimer(OsTime start, UtlBoolean periodic, OsTime period); /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /// Copy constructor (not implemented for this class) OsTimer(const OsTimer& rOsTimer); /// Assignment operator (not implemented for this class) OsTimer& operator=(const OsTimer& rhs); /* ============================ INLINE METHODS ============================ */ protected: /// Test whether a status indicates the timer has been started. inline static UtlBoolean isStarted(int status) { return (status & 1) == 1; } /// Test whether a status indicates the timer has been stopped. inline static UtlBoolean isStopped(int status) { return (status & 1) == 0; } }; #endif // _OsTimer_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsTimerMsg.h0000644000175000017500000000573712205613256024141 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2007 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// #ifndef _OsTimerMsg_h_ #define _OsTimerMsg_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsRpcMsg.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsTimer; //:Messages used to request timer services class OsTimerMsg : public OsRpcMsg { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum MsgSubType { OS_TIMER_UPDATE, ///< update the status of the timer OS_TIMER_UPDATE_SYNC, /**< update the status of the timer and signal * an event object */ OS_TIMER_UPDATE_DELETE, /**< update the status of the timer and * delete it */ OS_TIMER_SHUTDOWN ///< shut down the timer task */ }; /* ============================ CREATORS ================================== */ OsTimerMsg(const unsigned char subType, OsTimer* pTimer, OsEvent* pEvent); //:Constructor OsTimerMsg(const OsTimerMsg& rOsTimerMsg); //:Copy constructor virtual OsMsg* createCopy(void) const; //:Create a copy of this msg object (which may be of a derived type) virtual ~OsTimerMsg(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsTimerMsg& operator=(const OsTimerMsg& rhs); //:Assignment operator /* ============================ ACCESSORS ================================= */ virtual int getMsgSize(void) const; //:Return the size of the message in bytes // This is a virtual method so that it will return the accurate size for // the message object even if that object has been upcast to the type of // an ancestor class. /// Return the (pointer to the OsTimer object) in this message. inline OsTimer* getTimerP(void) const { return mpTimer; } /// Return the (pointer to the OsEvent object) in this message. inline OsEvent* getEventP(void) const { return OsRpcMsg::getEvent(); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsTimer* mpTimer; void init(void); //:Initialization common to all constructors }; /* ============================ INLINE METHODS ============================ */ #endif // _OsTimerMsg_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsTimerTask.h0000644000175000017500000000761112205613256024306 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsTimerTask_h_ #define _OsTimerTask_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsBSem.h" #include "os/OsMsgQ.h" #include "os/OsServerTask.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class OsTimer; class OsTimerMsg; //:Timer service request manager (runs as a separate task) // This task is responsible for managing timer service requests. Timer // requests are received via a message queue. class OsTimerTask : public OsServerTask { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ static OsTimerTask* getTimerTask(void); //:Return a pointer to the timer task, creating it if necessary static void destroyTimerTask(void); //: Destroy the singleton instance of the sys timer // Should only be called when timers are not being started or stopped. // All current timers are stopped. virtual ~OsTimerTask(); //:Destructor // Should not be called directly. Use destroyTimerTask(). /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /// Constructor (called only indirectly via getTimerTask()) OsTimerTask(); /**< We identify this as a protected (rather than a private) method so * that gcc doesn't complain that the class only defines a private * constructor and has no friends. */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: static const int TIMER_MAX_REQUEST_MSGS; // Maximum number of request messages /// The entry point for the task virtual int run(void* pArg); /**< We replace OsServerTask::run() so that it will simultaneously wait * for an incoming message or for the next timer to fire. */ /// Handle a timer service request. virtual UtlBoolean handleMessage(OsMsg& rMsg); ///< Return TRUE if the request was handled, otherwise FALSE. /** Fire a timer because it has expired. * Calls the if notification routine, if the timer hasn't been stopped * already. * If the timer is periodic and hasn't been stopped, reinserts it into * the queue. * Advances the timer's state if it is one-shot or has been stopped. */ virtual void fireTimer(OsTimer* timer); /// Pointer to the single instance of the OsTimerTask class. static volatile OsTimerTask* spInstance; ///< Declare as volatile because it is set and tested concurrently. /// Semaphore used to protect manipulations of spInstance. static OsBSem *sLock; /// The queue of timer requests, ordered by increasing firing time. OsTimer* mTimerQueue; /// Timeout to use when signalling OsTime mSignalTimeout; /// Insert a timer into the timer queue. void insertTimer(OsTimer* timer); /// Remove a timer from the timer queue. void removeTimer(OsTimer* timer); /// Copy constructor (not implemented for this class) OsTimerTask(const OsTimerTask& rOsTimerTask); /// Assignment operator (not implemented for this class) OsTimerTask& operator=(const OsTimerTask& rhs); }; /* ============================ INLINE METHODS ============================ */ #endif // _OsTimerTask_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsTLSServerSocket.h0000644000175000017500000001064612205613256025407 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsTLSServerSocket_h_ #define _OsTLSServerSocket_h_ #ifdef SIP_TLS #ifdef SIP_TLS_NSS // SYSTEM INCLUDES //#include <...> // APPLICATION INCLUDES #include #include #include #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS enum TlsInitCodes { TLS_INIT_SUCCESS, TLS_INIT_DATABASE_FAILURE, TLS_INIT_BAD_PASSWORD, TLS_INIT_TCP_IMPORT_FAILURE, TLS_INIT_NSS_FAILURE }; class OsTLSServerSocket : public OsServerSocket { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /// Constructor to set up TCP socket server OsTLSServerSocket(int connectionQueueSize, /**< The maximum number of outstanding connection * requests which are allowed before subsequent * requests are turned away.*/ int serverPort=PORT_DEFAULT, /**< The port on which the server will listen to * accept connection requests. * PORT_DEFAULT means let OS pick port. */ UtlString certNickname = "", UtlString certPassword = "", UtlString dbLocation = "", const UtlString bindAddress = "" ); /** * Sets the socket connection queue and starts listening on the * port for requests to connect. */ /// Assignment operator OsTLSServerSocket& operator=(const OsTLSServerSocket& rhs); virtual ~OsTLSServerSocket(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual OsConnectionSocket* accept(); //:Blocking accept of next connection // Blocks and waits for the next TCP connection request. //!returns: Returns a socket connected to the client requesting the //!returns: connection. If an error occurs returns NULL. virtual void close(); //: Close down the server /* ============================ ACCESSORS ================================= */ virtual int getLocalHostPort() const; //:Return the local port number // Returns the port to which this socket is bound on this host. /* ============================ INQUIRY =================================== */ virtual OsSocket::IpProtocolSocketType getIpProtocol() const; //: Returns the protocol type of this socket virtual UtlBoolean isOk() const; //: Server socket is in ready to accept incoming conection requests. int isConnectionReady(); //: Poll to see if connections are waiting //!returns: 1 if one or call to accept() will not block
//!returns: 0 if no connections are ready (i.e. accept() will block). TlsInitCodes getTlsInitCode() { return mTlsInitCode; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: static int pemPasswdCallbackFunc(char *buf, int size, int rwflag, void *userdata); //:Callback used to set the private key password for decrypting the key //:buf is the buffer to fill with a password //:size is the maximum size of the buffer OsTLSServerSocket(const OsTLSServerSocket& rOsTLSServerSocket); //:Disable copy constructor OsTLSServerSocket(); //:Disable default constructor UtlString mCertNickname; UtlString mCertPassword; UtlString mDbLocation; PRFileDesc* mpMozillaSSLSocket; SECKEYPrivateKey * mpPrivKey; CERTCertificate * mpCert; TlsInitCodes mTlsInitCode; }; /* ============================ INLINE METHODS ============================ */ #endif // SIP_TLS #endif // SIP_TLS_NSS #endif // _OsTLSServerSocket_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsTLSConnectionSocket.h0000644000175000017500000001434712205613256026242 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsTLSConnectionSocket_h_ #define _OsTLSConnectionSocket_h_ #ifdef SIP_TLS #ifdef SIP_TLS_NSS // SYSTEM INCLUDES #include #include #include #include #include // APPLICATION INCLUDES #include #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /// Implements TLS version of OsSocket class OsTLSConnectionSocket : public OsConnectionSocket { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsTLSConnectionSocket(int remoteHostPort, const char* remoteHostName, const UtlString certNickname, const UtlString password, const UtlString dbLocation, long timeoutInSecs, const char* localIp ); OsTLSConnectionSocket(int socketDescriptor, const UtlString certNickname, const UtlString password, const UtlString dbLocation, long timeoutInSecs = 0); virtual ~OsTLSConnectionSocket(); //:Destructor /* ============================ MANIPULATORS ============================== */ virtual UtlBoolean reconnect(); //: Sets up the connection again, assuming the connection failed virtual int write(const char* buffer, int bufferLength); //:Blocking write to the socket // Write the characters in the given buffer to the socket. // This method will block until all of the bytes are written. //!param: buffer - The bytes to be written to the socket. //!param: bufferLength - The number of bytes contained in buffer. //!returns: The number of bytes actually written to the socket. //!returns:
Note: This does not necessarily mean that the bytes were //!returns: actually received on the other end. virtual int write(const char* buffer, int bufferLength, long waitMilliseconds); //:Non-blocking or limited blocking write to socket // Same as blocking version except that this write will block // for no more than the specified length of time. //!param: waitMilliseconds - The maximum number of milliseconds to block. This may be set to zero, in which case it does not block. virtual int read(char* buffer, int bufferLength); //:Blocking read from the socket // Read bytes into the buffer from the socket up to a maximum of // bufferLength bytes. This method will block until there is // something to read from the socket. //!param: buffer - Place to put bytes read from the socket. //!param: bufferLength - The maximum number of bytes buffer will hold. //!returns: The number of bytes actually read. virtual int read(char* buffer, int bufferLength, UtlString* ipAddress, int* port); //:Blocking read from the socket // Read bytes into the buffer from the socket up to a maximum of // bufferLength bytes. This method will block until there is // something to read from the socket. //!param: buffer - Place to put bytes read from the socket. //!param: bufferLength - The maximum number of bytes buffer will hold. //!param: ipAddress - The address of the socket that sent the bytes read. //!param: port - The port of the socket that sent the bytes read. //!returns: The number of bytes actually read. virtual int read(char* buffer, int bufferLength, long waitMilliseconds); //: Non-blocking or limited blocking read from socket // Same as blocking version except that this read will block // for no more than the specified length of time. //!param: waitMilliseconds - The maximum number of milliseconds to block. This may be set to zero in which case it does not block. virtual UtlBoolean isReadyToReadEx(long waitMilliseconds, UtlBoolean &rSocketError) const; //:Poll if there are bytes to read // Returns TRUE if socket is read to read. // Returns FALSE if wait expires or socket error. // rSocketError returns TRUE is socket error occurred. virtual UtlBoolean isReadyToRead(long waitMilliseconds = 0) const; //:Poll if there are bytes to read // Returns TRUE if socket is read to read. // Returns FALSE if wait expires or socket error. virtual UtlBoolean isReadyToWrite(long timeoutMilliSec) const; void setHandshakeComplete() { mbHandshakeComplete = true; } bool waitForHandshake(long milliseconds) const; /* ============================ ACCESSORS ================================= */ virtual void close(); //: Closes the TLS socket /* ============================ INQUIRY =================================== */ virtual OsSocket::IpProtocolSocketType getIpProtocol() const; //: Returns the protocol type of this socket /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: virtual void NSSInitSocket(int socket, long timeoutInSecs, const char* szPassword) = 0; UtlBoolean mbExternalTLSSocket; OsTLSConnectionSocket(const OsTLSConnectionSocket& rOsTLSConnectionSocket); //:Disable copy constructor OsTLSConnectionSocket(); //:Disable default constructor OsTLSConnectionSocket& operator=(const OsTLSConnectionSocket& rhs); //:Assignment operator PRFileDesc* mpPRfd; UtlString mCertNickname; UtlString mCertPassword; UtlString mDbLocation; SECKEYPrivateKey * mpPrivKey; CERTCertificate * mpCert; mutable OsMutex mSocketGuard; bool mbHandshakeComplete; /* //////////////////////////// PRIVATE /////////////////////////////////// */ }; /* ============================ INLINE METHODS ============================ */ #endif // SIP_TLS #endif // SIP_TLS_NSS #endif // _OsTLSConnectionSocket_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsTLSClientConnectionSocket.h0000644000175000017500000000507612205613256027400 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsTLSClientConnectionSocket_h_ #define _OsTLSClientConnectionSocket_h_ #ifdef SIP_TLS #ifdef SIP_TLS_NSS // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "os/OsTLSConnectionSocket.h" #include "os/OsTLS.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /// Implements TLS version of OsSocket class OsTLSClientConnectionSocket : public OsTLSConnectionSocket { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsTLSClientConnectionSocket(int serverPort, const char* serverName, const UtlString certNickname, const UtlString password, const UtlString dbLocation, long timeoutInSecs, const char* localIp, ITlsSink* pSink); virtual ~OsTLSClientConnectionSocket(); //:Destructor /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: void NSSInitSocket(int socket, long timeoutInSecs, const char* szPassword); /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsTLSClientConnectionSocket(const OsTLSClientConnectionSocket& rOsTLSClientConnectionSocket); //:Disable copy constructor OsTLSClientConnectionSocket(); //:Disable default constructor OsTLSClientConnectionSocket& operator=(const OsTLSClientConnectionSocket& rhs); //:Assignment operator ITlsSink* mpTlsSink; }; /* ============================ INLINE METHODS ============================ */ #endif // SIP_TLS #endif // SIP_TLS_NSS #endif // _OsTLSClientConnectionSocket_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsTokenizer.h0000644000175000017500000000255612205613256024360 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// /* This code was taken from a program I wrote some time ago. It parses a string * for whitespace and quotes much like a shell would. Characters enclosed in * quotes are counted as a single token. Extra whitespace at the beginning and * end of the string is removed. The tokenizing function returns a token * structure, which can be used to access the tokens in the original string * (which will have been modified). Once the tokens have been used by the * caller, the token structure must be destroyed to free the token pointers. */ #ifndef __OsTokenizer_h #define __OsTokenizer_h typedef struct PT_TOKEN { char * string; int offset[8]; int offsets; struct PT_TOKEN * next; } pt_token_t; /* parse a string and return a (pointer to a) token structure */ /* sets the token count in *args */ pt_token_t * parse_tokenize(char * string, int * args); /* return a pointer to the given token */ const char * parse_token(pt_token_t * t, int which); /* destroy the token structure */ void parse_kill(pt_token_t * t); #endif /* __OsTokenizer_h */ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsTLS.h0000644000175000017500000001261212205613256023042 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsTLS_h_ #define _OsTLS_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsBSem.h" #include "os/OsSysLog.h" #include "utl/UtlString.h" #include "utl/UtlHashMap.h" #include #include #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define MAX_CERT_DIR_LENGTH 256 // STRUCTS // ENUMERATIONS typedef enum SECURITY_CAUSE { E_SECURITY_CAUSE_UNKNOWN = 0, /**< An UNKNOWN cause code is generated when the state for the security operation is no longer known. This is generally an error condition; see the info structure for details. */ E_SECURITY_CAUSE_NORMAL, /**< Event was fired as part of the normal encryption / decryption process. */ E_SECURITY_CAUSE_ENCRYPT_SUCCESS, /**< An S/MIME encryption succeeded. */ E_SECURITY_CAUSE_ENCRYPT_FAILURE_LIB_INIT, /**< An S/MIME encryption failed because the security library could not start. */ E_SECURITY_CAUSE_ENCRYPT_FAILURE_BAD_PUBLIC_KEY, /**< An S/MIME encryption failed because of a bad certificate / public key. */ E_SECURITY_CAUSE_ENCRYPT_FAILURE_INVALID_PARAMETER,/**< An S/MIME encryption failed because of an invalid parameter. */ E_SECURITY_CAUSE_DECRYPT_SUCCESS, /**< An S/MIME decryption succeeded. */ E_SECURITY_CAUSE_DECRYPT_FAILURE_DB_INIT, /**< An S/MIME decryption failed due to a failure to initialize the certificate database. */ E_SECURITY_CAUSE_DECRYPT_FAILURE_BAD_DB_PASSWORD, /**< An S/MIME decryption failed due to an invalid certificate database password. */ E_SECURITY_CAUSE_DECRYPT_FAILURE_INVALID_PARAMETER,/**< An S/MIME decryption failed due to an invalid parameter. */ E_SECURITY_CAUSE_DECRYPT_BAD_SIGNATURE, /**< An S/MIME decryption operation aborted due to a bad signature. */ E_SECURITY_CAUSE_DECRYPT_MISSING_SIGNATURE, /**< An S/MIME decryption operation aborted due to a missing signature. */ E_SECURITY_CAUSE_DECRYPT_SIGNATURE_REJECTED, /**< An S/MIME decryption operation aborted because the signature was rejected. */ E_SECURITY_CAUSE_TLS_SERVER_CERTIFICATE, E_SECURITY_CAUSE_TLS_BAD_PASSWORD, E_SECURITY_CAUSE_TLS_LIBRARY_FAILURE, E_SECURITY_CAUSE_REMOTE_HOST_UNREACHABLE, E_SECURITY_CAUSE_TLS_CONNECTION_FAILURE, E_SECURITY_CAUSE_TLS_HANDSHAKE_FAILURE, E_SECURITY_CAUSE_SIGNATURE_NOTIFY, /**< The SIGNATURE_NOTIFY event is fired when the user-agent receives a SIP message with signed SMIME as its content. The signer's certificate will be located in the info structure associated with this event. The application can choose to accept the signature, by returning 'true' in response to this message or can choose to reject the signature by returning 'false' in response to this message. */ E_SECURITY_CAUSE_TLS_CERTIFICATE_REJECTED /** < The application has rejected the server's TLS certificate. */ } SECURITY_CAUSE; // TYPEDEFS // FORWARD DECLARATIONS class ITlsSink { public: virtual bool onServerCertificate(void* pCert, char* serverHostName) = 0; virtual bool onTlsEvent(int cause) = 0; }; #ifdef SIP_TLS_NSS // Singleton class for invoking NSS functions. class OsTLS { /* //////////////////////////// PUBLIC //////////////////////////////////// */ private: OsTLS(); public: virtual ~OsTLS(); static OsStatus Initialize(const char* szCertDir); static SECStatus GetClientAuthData(void *arg, PRFileDesc *socket, struct CERTDistNamesStr *caNames, struct CERTCertificateStr **pRetCert, struct SECKEYPrivateKeyStr **pRetKey); static SECStatus AuthCertificate(void *arg, PRFileDesc *socket, PRBool checksig, PRBool isServer) ; static SECStatus BadCertHandler(void *arg, PRFileDesc *socket); static SECStatus HandshakeCallback(PRFileDesc *socket, void *arg); static char* PasswordCallback(PK11SlotInfo *slot, PRBool retry, void *arg); static void setTlsSink(PRFileDesc* key, ITlsSink* pSink); static ITlsSink* getTlsSink(PRFileDesc* key); static void removeTlsSink(PRFileDesc* key); private: static UtlHashMap* mpSinkMap; }; /* ============================ INLINE METHODS ============================ */ #endif #endif // _OsTLS_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/ostream0000644000175000017500000000075012205613256023322 0ustar00danieldaniel00000000000000// // // Copyright (C) 2004, 2005 Pingtel Corp. // // // $$ ////////////////////////////////////////////////////////////////////////////// #ifndef _ostream_h_ #define _ostream_h_ // If we are compiling for VxWorks, use the old form of ostream.h // We do this to stay compatible with the version of the tools++ // object modules that are distributed with VxWorks. #if defined(_VXWORKS) #include #else #include using namespace std; #endif #endif // _ostream_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsUtil.h0000644000175000017500000001543312205613256023321 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsUtil_h_ #define _OsUtil_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include "os/OsStatus.h" #include "os/OsTime.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Miscellaneous useful static methods class OsUtil { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum OsPlatformType { PLATFORM_UNKNOWN=-1, PLATFORM_BRUTUS=0, PLATFORM_TCAS1=1, PLATFORM_TCAS2=2, PLATFORM_TCAS3=3, PLATFORM_TCAS4=4, PLATFORM_TCAS5=5, PLATFORM_TCAS6=6, PLATFORM_TCAS7=7, PLATFORM_TCAS8=8, PLATFORM_MACOSX=97, PLATFORM_SOLARIS=98, PLATFORM_LINUX=99, PLATFORM_WIN32=100, PLATFORM_ANDROID=101 }; enum OsProductType { PRODUCT_UNKNOWN=-1, PRODUCT_XPRESSA=0, PRODUCT_INSTANT_XPRESSA=2 }; static const UtlString NULL_OS_STRING; //! Search a buffer for first occurance of another buffer. binary or ascii static char *memscan(const char *lookIn, int lookInLen, const char *lookFor, int lookForLen); /* ============================ Name Database ============================= */ static OsStatus insertKeyValue(const UtlString& rPrefix, const UtlString& rName, const intptr_t value, UtlBoolean exceptOnErr=TRUE); //:Insert a key-value pair into the name database // The key is constructed by concatenating rPrefix and rName. // If exceptOnErr is TRUE, then upon encountering an error, this method // will throw an exception. This is sometimes useful for indicating an // error from within an object constructor. static OsStatus deleteKeyValue(const UtlString& rPrefix, const UtlString& rName, intptr_t* pValue=NULL); //:Remove the indicated key-value pair from the name database // The key is constructed by concatenating rPrefix and rName. // If pValue is non-NULL, the value for the key-value pair is returned // via pValue. // Return OS_SUCCESS if the lookup is successful, return // OS_NOT_FOUND if there is no match for the specified key. static OsStatus lookupKeyValue(const UtlString& rPrefix, const UtlString& rName, intptr_t* pValue=NULL); //:Retrieve the value associated with the specified key // The key is constructed by concatenating rPrefix and rName. // If pValue is non-NULL, the value is returned via pValue. // Return OS_SUCCESS if the lookup is successful, return // OS_NOT_FOUND if there is no match for the specified key. static OsStatus convertUtlStringToInt(const UtlString& rStr, int& rInt); //:Convert the value in rStr to an integer. // Uses strtol() with base==0 to perform the conversion. // Return OS_SUCCESS if the conversion was successful and set rInt to // the converted value in rInt. If the conversion failed, return // OS_FAILED and set rInt to -1. static OsStatus checkIpAddress(const char* addr) ; // :Check the designated ip address for validity: // 1) 4 octets separated by '.' // 2) Each octet is between 0 and 255 // 3) Address is not 0.0.0.0 or 255.255.255.255 // Return OS_SUCCESS if the addr is valid, otherwise return OS_INVALID static OsStatus checkNetmask(const char* netmask) ; // :Check the designated netmask for validity: // 1) Between 255.0.0.0 and 255.255.255.254 // Return OS_SUCCESS if the addr is valid, otherwise return OS_INVALID static UtlBoolean isSameNetwork(const char* destIpAddr, const char* myIpAddr, const char* myNetMask) ; // :Return TRUE if the destIpAddress is on the same logical network as // myIpAddr given netmask myNetMask. Returns FALSE otherwise. //returns OS_SUCCESS if the host repsonds within timeout OsStatus checkDnsAvailability(char *dnsServer, OsTime timeout); //returns OS_SUCCESS if the host repsonds within timeout OsStatus checkResponsiveDest(char *destHost, OsTime timeout); /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ static void getCurDate(UtlString& dateStr, const struct tm* pCurTime, int maxLen); //:Return the current date // An example showing the date format is: "Wed Oct 7 1998". static void getCurTime(UtlString& timeStr, const struct tm* pCurTime, int maxLen); //:Return the current time // An example showing the time format is: "8:03 PM". static int getPlatformType(void); //:Return the type of platform we are running on (e.g., PLATFORM_TCAS2) static int getProductType(void); //:Return the type of platform we are running on (e.g., PRODUCT_XPRESSA) /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: OsUtil(); //:Default constructor (not implemented for this class) // We identify this as a protected method so that gcc doesn't complain // that the class only defines a private constructor and has no friends. virtual ~OsUtil(); //:Destructor (not implemented for this class) // We identify this as a protected method so that gcc doesn't complain // that the class only defines a private destructor and has no friends. static UtlBoolean convertIpAddressToOctets(const char* ipAddr, unsigned char octets[]) ; // :Convert a nnn.nnn.nnn.nnn ip address into an array of 4 unsigned chars. // Returns FALSE on error otherwise TRUE /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsUtil(const OsUtil& rOsUtil); //:Copy constructor (not implemented for this class) OsUtil& operator=(const OsUtil& rhs); //:Assignment operator (not implemented for this class) }; /* ============================ INLINE METHODS ============================ */ #endif // _OsUtil_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/OsWriteLock.h0000644000175000017500000000564212205613256024310 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _OsWriteLock_h_ #define _OsWriteLock_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "OsRWMutex.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:Lock class allowing exclusive access for a writer within a critical section // This class uses OsRWMutex objects for synchronization. The constructor // for the class automatically blocks until the OsRWMutex is acquired // for writing. Similarly, the destructor automatically releases the lock. //

// The easiest way to use this object as a guard is to create the // object as a variable on the stack just before the section that needs to // lock the resource for writing. When the OsWriteLock object goes out of // scope, the writer lock will be automatically released. // An example of this form of use is shown below. //

// //    someMethod()
//    {
//       OsWriteLock lock(myRWMutex);
//
//       < section that needs to be // locked for writing >
//    }
class OsWriteLock { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ OsWriteLock(OsRWMutex& rRWMutex) : mrRWMutex(rRWMutex) { rRWMutex.acquireWrite(); }; //:Constructor virtual ~OsWriteLock() { mrRWMutex.releaseWrite(); }; //:Destructor /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsRWMutex& mrRWMutex; OsWriteLock(); //:Default constructor (not implemented for this class) OsWriteLock(const OsWriteLock& rOsWriteLock); //:Copy constructor (not implemented for this class) OsWriteLock& operator=(const OsWriteLock& rhs); //:Assignment operator (not implemented for this class) }; /* ============================ INLINE METHODS ============================ */ #endif // _OsWriteLock_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/StunMessage.h0000644000175000017500000003650312205613256024341 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 Robert J. Andreasen, Jr. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _StunMessage_h_ #define _StunMessage_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsIntTypes.h" #include "utl/UtlRandom.h" // DEFINES #define STUN_MAX_STRING_LENGTH 128 #define STUN_MAX_UNKNOWN_ATTRIBUTES 16 #define STUN_MAX_MESSAGE_INTEGRITY_LENGTH 20 #define STUN_MIN_CHAR_PAD 4 #define STUN_MAGIC_COOKIE 0x2112A442 /** * STUN Message IDs */ #define MSG_STUN_BIND_REQUEST 0x0001 #define MSG_STUN_BIND_RESPONSE 0x0101 #define MSG_STUN_BIND_ERROR_RESPONSE 0x0111 #define MSG_STUN_SHARED_SECRET_REQUEST 0x0002 #define MSG_STUN_SHARED_SECRET_RESPONSE 0x0102 #define MSG_STUN_SHARED_SECRET_ERROR_RESPONSE 0x0112 /** * STUN attribute IDs */ #define ATTR_STUN_MAPPED_ADDRESS 0x0001 #define ATTR_STUN_RESPONSE_ADDRESS 0x0002 // deprecated #define ATTR_STUN_CHANGE_REQUEST 0x0003 // deprecated #define ATTR_STUN_SOURCE_ADDRESS 0x0004 // deprecated #define ATTR_STUN_CHANGED_ADDRESS 0x0005 // deprecated #define ATTR_STUN_USERNAME 0x0006 #define ATTR_STUN_PASSWORD 0x0007 // deprecated #define ATTR_STUN_MESSAGE_INTEGRITY 0x0008 #define ATTR_STUN_ERROR_CODE 0x0009 #define ATTR_STUN_UNKNOWN_ATTRIBUTE 0x000A #define ATTR_STUN_REFLECTED_FROM 0x000B // deprecated #define ATTR_STUN_ALTERNATE_SERVER2 0x000E // deprecated #define ATTR_STUN_REALM 0x0014 #define ATTR_STUN_NONCE 0x0015 #define ATTR_STUN_XOR_MAPPED_ADDRESS 0x0020 #define ATTR_STUN_XOR_ONLY 0x0021 // deprecated #define ATTR_STUN_FINGERPRINT 0x0023 #define ATTR_STUN_XOR_MAPPED_ADDRESS2 0x8020 // deprecated #define ATTR_STUN_SERVER 0x8022 #define ATTR_STUN_SERVER2 0x0022 // deprecated #define ATTR_STUN_ALTERNATE_SERVER 0x8023 #define ATTR_STUN_BINDING_LIFETIME 0x8024 #define ATTR_CHANGE_FLAG_PORT 0x0002 // deprecated #define ATTR_CHANGE_FLAG_IP 0x0004 // deprecated #define ATTR_ADDRESS_FAMILY_IPV4 0x01 #define ATTR_ADDRESS_FAMILY_IPV6 0x02 // Error Defines #define STUN_ERROR_TRY_ALTERNATE_CODE 300 #define STUN_ERROR_TRY_ALTERNATE_TEXT "Try Alternative" #define STUN_ERROR_BAD_REQUEST_CODE 400 #define STUN_ERROR_BAD_REQUEST_TEXT "Bad request" #define STUN_ERROR_UNAUTHORIZED_CODE 401 #define STUN_ERROR_UNAUTHORIZED_TEXT "Unauthorized" #define STUN_ERROR_UNKNOWN_ATTRIBUTE_CODE 420 #define STUN_ERROR_UNKNOWN_ATTRIBUTE_TEXT "Unknown attribute" #define STUN_ERROR_STALE_CREDENTIAL_CODE 430 #define STUN_ERROR_STALE_CREDENTIAL_TEXT "Stale credential" #define STUN_ERROR_BAD_INTEGRITY_CODE 431 #define STUN_ERROR_BAD_INTEGRITY_TEXT "Bad integrity" #define STUN_ERROR_MISSING_USERNAME_CODE 432 #define STUN_ERROR_MISSING_USERNAME_TEXT "Missing username" #define STUN_ERROR_USE_TLS_CODE 433 #define STUN_ERROR_USE_TLS_TEXT "Use TLS" #define STUN_ERROR_MISSING_REALM_CODE 434 #define STUN_ERROR_MISSING_REALM_TEXT "Missing Realm" #define STUN_ERROR_MISSING_NONCE_CODE 435 #define STUN_ERROR_MISSING_NONCE_TEXT "Missing Nonce" #define STUN_ERROR_UNKNOWN_USERNAME_CODE 436 #define STUN_ERROR_UNKNOWN_USERNAME_TEXT "Unknown username" #define STUN_ERROR_STALE_NONCE_CODE 438 #define STUN_ERROR_STALE_NONCE_TEXT "Stale Nonce" #define STUN_ERROR_SERVER_CODE 500 #define STUN_ERROR_SERVER_TEXT "Server error" #define STUN_ERROR_GLOBAL_CODE 600 #define STUN_ERROR_GLOBAL_TEXT "Global error" // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS typedef struct { uint32_t id ; } STUN_MAGIC_ID ; typedef struct { uint8_t id[12]; } STUN_TRANSACTION_ID; typedef struct { uint16_t type ; uint16_t length ; STUN_MAGIC_ID magicId ; STUN_TRANSACTION_ID transactionId ; } STUN_MESSAGE_HEADER ; typedef struct { uint16_t type; uint16_t length; } STUN_ATTRIBUTE_HEADER ; typedef struct { uint8_t unused ; uint8_t family ; /* unused today */ uint16_t port; uint32_t address ; } STUN_ATTRIBUTE_ADDRESS; typedef struct { uint16_t unused ; uint8_t unused2:4 ; uint8_t errorClass:4 ; // between 1 and 6 uint8_t errorNumber ; // between 0 and 99 char szReasonPhrase[STUN_MAX_STRING_LENGTH+1] ; } STUN_ATTRIBUTE_ERROR ; typedef struct { //size_t nTypes ; uint32_t nTypes ; uint16_t type[STUN_MAX_UNKNOWN_ATTRIBUTES] ; } STUN_ATTRIBUTE_UNKNOWN ; // FORWARD DECLARATIONS /** * A StunMessage includes all of the parse and encoding for a STUN message * as defined by draft-ietf-behave-rfc3489bis-04.txt: * * All data is stored internally in host byte order * * Error * Error * Attribute Request Response Response Indication * _______________________________________________________ * MAPPED-ADDRESS - C - - * USERNAME O - - O * PASSWORD - C - - * MESSAGE-INTEGRITY O O O O * ERROR-CODE - - M - * ALTERNATE-SERVER - - C - * REALM C - C - * NONCE C - C - * UNKNOWN-ATTRIBUTES - - C - * XOR-MAPPED-ADDRESS - C - - * SERVER - O O O * REFRESH-INTERVAL - O - - * FINGERPRINT M M M M * * * Shared Shared Shared * Secret Secret Secret * Attribute Request Response Error * Response * ____________________________________________________________________ * USERNAME O M - * PASSWORD - M - * MESSAGE-INTEGRITY O O O * ERROR-CODE - - M * ALTERNATE-SERVER - - C * UNKNOWN-ATTRIBUTES - - C * SERVER - O O * REALM C - C * NONCE C - C */ class StunMessage { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /** * Default constructor, if a msg is passed, the magic/transaction id * is copied -- otherwise a new magic/transaction id is generated. */ StunMessage(StunMessage* pRequest = NULL, bool bLegacyMode = true) ; /** * Destructor */ virtual ~StunMessage() ; /* ============================ MANIPULATORS ============================== */ virtual void reset() ; virtual bool parse(const char* pBuf, size_t nBufLength) ; virtual bool encode(char* pBuf, size_t nBufLength, size_t& nActualLength) ; virtual bool encodeBody(char* pBuf, size_t nBufLength, size_t& nBytesUsed) ; void setMagicId(STUN_MAGIC_ID& rMagicId) ; void setTransactionId(STUN_TRANSACTION_ID& rTransactionId) ; void allocTransactionId() ; void setType(uint16_t type) ; void setMappedAddress(const char* szIp, const uint16_t port) ; void setResponseAddress(const char* szIp, const uint16_t port) ; void setChangePort(const bool bChange) ; void setChangeIp(const bool bChange) ; void setSourceAddress(const char* szIp, const uint16_t port) ; void setChangedAddress(const char* szIp, const uint16_t port) ; void setUsername(const char* szUsername) ; void setPassword(const char* szPassword) ; void setRealm(const char* szRealm) ; void setNonce(const char* szNonce) ; void setError(const uint16_t code, const char* szReason) ; void addUnknownAttribute(uint16_t attributeId) ; void setReflectedFrom(const char* szIp, const uint16_t port) ; void setServer(const char* szServer) ; void setRequestXorOnly() ; void setSendXorOnly() ; void setIncludeMessageIntegrity(bool bInclude) ; void setIncludeFingerPrint(bool bInclude) ; void setAltServer(const char* szIp, uint16_t port) ; /* ============================ ACCESSORS ================================= */ void getMagicId(STUN_MAGIC_ID* pMagicId) ; void getTransactionId(STUN_TRANSACTION_ID* pTransactionId) ; uint16_t getType() ; bool getMappedAddress(char* szIp, uint16_t& rPort) ; bool getResponseAddress(char* szIp, uint16_t& rPort) ; bool getChangePort() ; bool getChangeIp() ; bool getSourceAddress(char* szIp, uint16_t& rPort) ; bool getChangedAddress(char* szIp, uint16_t& rPort) ; bool getUsername(char* szUsername) ; bool getPassword(char* szPassword) ; bool getRealm(char *szRealm) ; bool getNonce(char* szNonce) ; bool getMessageIntegrity(char* cMessageIntegrity) ; bool getError(uint16_t& rCode, char* szReason) ; bool getUnknownAttributes(uint16_t* pList, size_t nMaxItems, size_t& nActualItems) ; bool getReflectedFrom(char* szIp, uint16_t& rPort) ; bool getServer(char* szServer) ; bool getUnknownParsedAttributes(uint16_t* pList, size_t nMaxItems, size_t& nActualItems) ; bool getRequestXorOnly() ; bool getAltServer(char* szIp, uint16_t& rPort) ; bool getFingerPrint(bool& bValid) ; /* ============================ INQUIRY =================================== */ virtual bool validateMessageType(uint16_t type) ; static bool isStunMessage(const char* pBuf, uint16_t nBufLength) ; static bool isFingerPrintValid(const char* pBuf, uint16_t nBufLength, bool bMissingOk) ; virtual bool isRequestOrNonErrorResponse() ; virtual bool isMessageIntegrityValid(const char* cPassword, size_t nPassword) ; virtual bool isFingerPrintValid() ; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: bool encodeByte(char c, char*& pBuf, size_t& nBytesLeft) ; bool encodeShort(uint16_t value, char*& pBuf, size_t& nBytesLeft) ; bool encodeLong(uint32_t value, char*& pBuf, size_t& nBytesLeft) ; bool encodeRaw(const char* cRaw, size_t length, char*& pBuf, size_t& nBytesLeft) ; bool encodeHeader(STUN_MESSAGE_HEADER* pHeader, char*& pBuf, size_t& nBytesLeft) ; bool encodeAttributeHeader(int16_t type, int16_t length, char*& pBuf, size_t& nBytesLeft) ; bool encodeAttributeAddress(uint16_t type, STUN_ATTRIBUTE_ADDRESS* pAddress, char*& pBuf, size_t& nBytesLeft) ; bool encodeXorAttributeAddress(uint16_t type, STUN_ATTRIBUTE_ADDRESS* pAddress, char*& pBuf, size_t& nBytesLeft) ; bool encodeString(uint16_t type, const char* szString, char*& pBuf, size_t& nBytesLeft) ; bool encodeAttributeError(STUN_ATTRIBUTE_ERROR* pError, char*& pBuf, size_t& nBytesLeft) ; bool encodeAttributesUnknown(STUN_ATTRIBUTE_UNKNOWN* pAttributes, char*& pBuf, size_t& nBytesLeft) ; virtual bool parseAttribute(STUN_ATTRIBUTE_HEADER* pHeader, char* pBuf) ; bool parseAddressAttribute(char *pBuf, size_t nLength, STUN_ATTRIBUTE_ADDRESS* pAddress) ; bool parseXorAddressAttribute(char *pBuf, size_t nLength, STUN_ATTRIBUTE_ADDRESS* pAddress) ; bool parseShortAttribute(char *pBuf, size_t nLength, uint16_t* pShort) ; bool parseLongAttribute(char *pBuf, size_t nLength, uint32_t* pLong) ; bool parseStringAttribute(char* pBuf, size_t nLength, char* pString) ; bool parseRawAttribute(char* pBuf, size_t nLength, char* pDest, size_t nDest) ; bool parseErrorAttribute(char *pBuf, size_t nLength, STUN_ATTRIBUTE_ERROR* pError) ; bool parseUnknownAttribute(char* pBuf, size_t nLength, STUN_ATTRIBUTE_UNKNOWN* pAttributes) ; /** * zero pads to 64 boundry and results will be 20 bytes long for hmac/sha1 */ static void calculateHmacSha1(const char* pDataIn, size_t nDataIn, const char* pKey, size_t nKey, char results[20]) ; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: STUN_MESSAGE_HEADER mMsgHeader ; bool mbMsgHeaderValid ; STUN_ATTRIBUTE_ADDRESS mMappedAddress ; bool mbMappedAddressValid ; STUN_ATTRIBUTE_ADDRESS mResponseAddress ; bool mbResponseAddressValid ; STUN_ATTRIBUTE_ADDRESS mChangedAddress ; bool mbChangedAddressValid ; uint32_t mChangeRequest ; bool mbChangeRequestValid ; STUN_ATTRIBUTE_ADDRESS mSourceAddress ; bool mbSourceAddressValid ; char mUsername[STUN_MAX_STRING_LENGTH+1] ; bool mbUsernameValid ; char mPassword[STUN_MAX_STRING_LENGTH+1] ; bool mbPasswordValid ; char mRealm[STUN_MAX_STRING_LENGTH+1] ; bool mbRealmValid ; char mNonce[STUN_MAX_STRING_LENGTH+1] ; bool mbNonceValid ; char mMessageIntegrity[STUN_MAX_MESSAGE_INTEGRITY_LENGTH] ; bool mbMessageIntegrityValid ; STUN_ATTRIBUTE_ERROR mError ; bool mbErrorValid; STUN_ATTRIBUTE_UNKNOWN mUnknownAttributes ; bool mbUnknownAttributesValid ; STUN_ATTRIBUTE_ADDRESS mReflectedFrom ; bool mbReflectedFromValid ; char mServer[STUN_MAX_STRING_LENGTH+1]; bool mbServerValid ; bool mbSendXorOnly ; bool mbRequestXorOnly ; UtlRandom mbRandomGenerator ; bool mbIncludeMessageIntegrity ; STUN_ATTRIBUTE_ADDRESS mAltServer ; bool mbAltServerValid ; bool mbIncludeFingerPrint ; char mbFingerPrintValid ; uint32_t mFingerPrint ; char* mpRawData ; size_t mnRawData ; bool mbLegacyMode ; STUN_ATTRIBUTE_UNKNOWN mUnknownParsedAttributes ; /** Disabled copy constructor */ StunMessage(const StunMessage& rStunMessage); /** Disabled equals operator */ StunMessage& operator=(const StunMessage& rhs); }; /* ============================ INLINE METHODS ============================ */ #endif // _StunMessage_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/StunUtils.h0000644000175000017500000000557212205613256024057 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _StunUtils_h_ #define _StunUtils_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDatagramSocket.h" #include "os/StunMessage.h" #include "os/TurnMessage.h" // DEFINES #define DEFAULT_STUN_PORT 3478 // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS typedef enum { STUN_NAT_ERROR_BAD_SERVER, STUN_NAT_BLOCKED, STUN_NAT_SYMMETRIC_FIREWALL, STUN_NAT_OPEN, STUN_NAT_FULL_CONE, STUN_NAT_RESTRICTED_CONE, STUN_NAT_PORT_RESTRICTED_CONE, STUN_NAT_SYMMETRIC } STUN_NAT_TYPE ; // FORWARD DECLARATIONS /** * Various Stun Utility helpers */ class StunUtils { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ static STUN_NAT_TYPE determineStunNatType(const char* szServer, const int port) ; static bool sendStunNatTest(OsDatagramSocket* pSocket, const char* szServerIp, const int port, bool bChangePort, bool bChangeIP, char* szMappedIp, uint16_t* piMappedPort, char* szChangedIp, uint16_t* piChangedPort) ; static bool allocateTurnAddress(OsDatagramSocket* pSocket, const char* szServerIp, const int port, char* szRelayIp, uint16_t* piRelayPort, uint32_t* plLifetime) ; static const char* natTypeToString(STUN_NAT_TYPE type) ; static void debugDump(char* pPacket, size_t nPacket, UtlString& output) ; /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /** Private Default constructor -- use statics */ StunUtils(); /** Disabled Copy constructor */ StunUtils(const StunUtils& rStunUtils); /** Disables equals operator */ StunUtils& operator=(const StunUtils& rhs); /** Private Destructor -- use statics */ virtual ~StunUtils(); }; /* ============================ INLINE METHODS ============================ */ #endif // _StunUtils_h_ sipxtapi-3.3.0~test17/sipXportLib/include/os/TurnMessage.h0000644000175000017500000001651212205613256024336 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2006 Robert J. Andreasen, Jr. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _TurnMessage_h_ #define _TurnMessage_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsIntTypes.h" #include "os/StunMessage.h" // DEFINES /** * TURN Message IDs */ #define MSG_TURN_ALLOCATE_REQUEST 0x0003 #define MSG_TURN_ALLOCATE_RESPONSE 0x0103 #define MSG_TURN_ALLOCATE_ERROR_RESPONSE 0x0113 #define MSG_TURN_SEND_REQUEST 0x0004 #define MSG_TURN_SEND_RESPONSE 0x0104 // deprecated #define MSG_TURN_SEND_ERROR_RESPONSE 0x0114 // deprecated #define MSG_TURN_DATA_INDICATION 0x0115 #define MSG_TURN_ACTIVE_DESTINATION_REQUEST 0x0006 #define MSG_TURN_ACTIVE_DESTINATION_RESPONSE 0x0106 #define MSG_TURN_ACTIVE_DESTINATION_ERROR_RESPONSE 0x0116 #define MSG_TURN_CONNECTION_STATUS_INDICATION 0x0117 #define MSG_TURN_CLOSE_BINDING_REQUEST 0x0009 #define MSG_TURN_CLOSE_BINDING_RESPONSE 0x0109 #define MSG_TURN_CLOSE_BINDING_ERROR_RESPONSE 0x0119 /** * TURN attribute IDs */ #define ATTR_TURN_LIFETIME 0x000D #define ATTR_TURN_MAGIC_COOKIE 0x000F // deprecated #define ATTR_TURN_BANDWIDTH 0x0010 #define ATTR_TURN_DESTINATION_ADDRESS 0x0011 // deprecated #define ATTR_TURN_REMOTE_ADDRESS 0x0012 // rename from ATTR_TURN_SOURCE_ADDRESS #define ATTR_TURN_DATA 0x0013 #define ATTR_TURN_RELAY_ADDRESS 0x0016 #define ATTR_TURN_REQUESTED_PORT 0x0018 #define ATTR_TURN_REQUESTED_TRANSPORT 0x0019 //#define ATTR_TURN_TIMER_VAL 0x0021 #define ATTR_TURN_REQUESTED_IP 0x0022 #define ATTR_MAGIC_COOKIE 0x72c64bc6 // Error Defines #define TURN_ERROR_NO_BINDING_CODE 437 #define TURN_ERROR_NO_BINDING_TEXT "no binding" #define TURN_ERROR_TRANSITIONING_CODE 439 #define TURN_ERROR_TRANSITIONING_TEXT "transitioning" #define TURN_ERROR_WRONG_USERNAME_CODE 441 #define TURN_ERROR_WRONG_USERNAME_TEXT "wrong username" #define TURN_ERROR_TRANSPORT_PROTOCOL_CODE 442 #define TURN_ERROR_TRANSPORT_PROTOCOL_TEXT "bad transport" #define TURN_ERROR_INVALID_IP_CODE 443 #define TURN_ERROR_INVALID_IP_TEXT "invalid ip" #define TURN_ERROR_INVALID_PORT_CODE 444 #define TURN_ERROR_INVALID_PORT_TEXT "invalid port" #define TURN_ERROR_TCP_ONLY_CODE 445 #define TURN_ERROR_TCP_ONLY_TEXT "tcp only" #define TURN_ERROR_CONNECTION_FAILED_CODE 446 #define TURN_ERROR_CONNECTION_FAILED_TEXT "connection failed" #define TURN_ERROR_CONNECTION_TIMEOUT_CODE 447 #define TURN_ERROR_CONNECTION_TIMEOUT_TEXT "connection timeout" // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS typedef enum TURN_TRANSPORT_TYPE { TURN_TRANSPORT_UDP, TURN_TRANSPORT_TCP } TURN_TRANSPORT_TYPE ; // FORWARD DECLARATIONS /** */ class TurnMessage : public StunMessage { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /** * Default constructor */ TurnMessage(TurnMessage* pRequest = NULL, bool bLegacyMode = true) ; /** * Destructor */ virtual ~TurnMessage(); /* ============================ MANIPULATORS ============================== */ virtual void reset() ; virtual bool encodeBody(char* pBuf, size_t nBufLength, size_t& nBytesUsed) ; void setLifetime(uint32_t secs) ; void setBandwidth(uint32_t rKBPS) ; /** deprecated */ void setDestinationAddress(const char* szIp, uint16_t port) ; void setTurnRemoteAddress(const char* szIp, uint16_t port) ; void setData(const char* pData, uint16_t nLength) ; void setRelayAddress(const char* szIp, uint16_t port) ; void setRequestedTransport(TURN_TRANSPORT_TYPE transportType) ; void setRequestedIp(const char* szIp, uint16_t port) ; /* ============================ ACCESSORS ================================= */ bool getLifetime(uint32_t& rSecs) ; bool getBandwidth(uint32_t& rKBPS) ; /** deprecated */ bool getDestinationAddress(char* szIp, uint16_t& rPort) ; bool getTurnRemoteAddress(char* szIp, uint16_t& rPort) ; bool getData(char*& rpData, uint16_t& nLength) ; bool getRelayAddress(char* szIp, uint16_t& rPort) ; bool getRequestedTransport(TURN_TRANSPORT_TYPE& rTransportType) ; bool getRequestedIp(char* szIp, uint16_t& rPort) ; /* ============================ INQUIRY =================================== */ virtual bool validateMessageType(uint16_t type) ; static bool isTurnMessage(const char* pBuf, uint16_t nBufLength, bool* pbDataIndication = NULL) ; virtual bool isRequestOrNonErrorResponse() ; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: virtual bool parseAttribute(STUN_ATTRIBUTE_HEADER* pHeader, char* pBuf) ; bool encodeAttributeLong(uint16_t type, uint32_t value, char*& pBuf, size_t& nBytesLeft) ; bool encodeAttributeRaw(uint16_t type, const char* cBuf, size_t length, char*& pBuf, size_t& nBytesLeft) ; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: uint32_t mLifetime ; // ATTR_TURN_LIFETIME bool mbLifetimeValid ; uint32_t mBandwidth ; // ATTR_TURN_BANDWIDTH bool mbBandwidthValid ; STUN_ATTRIBUTE_ADDRESS mDestinationAddress ; // ATTR_TURN_DESTINATION_ADDRESS bool mbDestinationAddressValid ; STUN_ATTRIBUTE_ADDRESS mTurnRemoteAddress ; // ATTR_TURN_REMOTE_ADDRESS bool mbTurnRemoteAddressValid ; char* mszTurnData ; // ATTR_TURN_DATA size_t mnTurnData ; bool mbTurnDataValid ; STUN_ATTRIBUTE_ADDRESS mRelayAddress ; // ATTR_TURN_RELAY_ADDRESS bool mbRelayAddressValid ; uint32_t mTransport ; // ATTR_TURN_REQUESTED_TRANSPORT bool mbTransportValid ; STUN_ATTRIBUTE_ADDRESS mRequestedIp ; // ATTR_TURN_REQUESTED_IP bool mbRequestedIpValid ; /** Disabled Copy constructor */ TurnMessage(const TurnMessage& rTurnMessage); /** Disabled Assignment operator */ TurnMessage& operator=(const TurnMessage& rhs); }; /* ============================ INLINE METHODS ============================ */ #endif // _TurnMessage_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/0000755000175000017500000000000012321445025022102 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlLongLongInt.h0000644000175000017500000000661412205613256025145 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// #ifndef _UtlLongLongInt_h_ #define _UtlLongLongInt_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "utl/UtlDefs.h" #include "utl/UtlContainable.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * UtlContainable wrapper for a 64-bit long int. */ class UtlLongLongInt : public UtlContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const UtlContainableType TYPE ; ///< Class type used for runtime checking /* ============================ CREATORS ================================== */ /// Constructor accepting an optional default value. UtlLongLongInt(int64_t initialValue = 0) ; /// Destructor virtual ~UtlLongLongInt(); /* ============================ OPERATORS ============================== */ /// Prefix increment operator UtlLongLongInt& operator++(); /// Postfix increment operator UtlLongLongInt operator++(int); /// Prefix decrement operator UtlLongLongInt& operator--(); /// Postfix decrement operator UtlLongLongInt operator--(int); /// Conversion to long long int operator int64_t() { return mValue; } /* ============================ MANIPULATORS ============================== */ /// Set a new long long int value for this object. int64_t setValue(int64_t iValue); /**< * @returns the old value */ /// Convert a ASCII string to long long int static int64_t stringToLongLong(const char* longLongString); /* ============================ ACCESSORS ================================= */ /// Get the long long int wrapped by this object. int64_t getValue() const ; /// Calculate a unique hash code for this object. virtual unsigned hash() const ; /**< * If the equals operator returns true for another object, then both * of those objects must return the same hash code. */ /// Get the ContainableType for a UtlContainable derived class. virtual UtlContainableType getContainableType() const; /* ============================ INQUIRY =================================== */ /// Compare the this object to another like-object. virtual int compareTo(UtlContainable const *) const ; /**< * Results for designating a non-like object are undefined. * * @returns 0 if equal, < 0 if less then and >0 if greater. */ /// Test this object to another like-object for equality. virtual UtlBoolean isEqual(UtlContainable const *) const ; /**< * @returns false if unlike-objects are specified. */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: int64_t mValue ; ///< The long long int wrapped by this object } ; /* ============================ INLINE METHODS ============================ */ #endif // _UtlLongLongInt_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlNameValueTokenizer.h0000644000175000017500000000653012205613256026520 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlNameValueTokenizer_h_ #define _UtlNameValueTokenizer_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlString.h" // DEFINES #define NEWLINE '\n' #define CARRIAGE_RETURN '\r' #define CARRIAGE_RETURN_NEWLINE "\r\n" // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /// Parses name value pairs from multiple lines of text. class UtlNameValueTokenizer { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /// Constructor. UtlNameValueTokenizer(const char* multiLineText, int textLength = -1); /// Destructor. virtual ~UtlNameValueTokenizer(); /* ============================ MANIPULATORS ============================== */ /// Finds the index to the next line terminator. static int findNextLineTerminator(const char* text, int length, int* nextLineIndex); /**< * @param[in] text - The char array in which to search for the * terminator. * @param[in] length - The length of the text array. * @param[in] nextLineIndex - The index to the beginning of the next * line. This may be -1 if the end of the string is encountered. * * @note The line terminator may be 1 or 2 characters. * * @returns Index into the text char array to the line terminator. */ static UtlBoolean getSubField(const char* textField, int subfieldIndex, const char* subfieldSeparator, UtlString* subfieldText, int* lastCharIndex = NULL); static UtlBoolean getSubField(const char* textField, int textFieldLength, int subfieldIndex, const char* subfieldSeparators, const char*& subfieldPtr, int& subFieldLength, int* lastCharIndex); UtlBoolean getNextPair(char separator, UtlString* name, UtlString* value); /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ UtlBoolean isAtEnd(); int getProcessedIndex(); /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: const char* textPtr; int textLen; int bytesConsumed; /// Disabled Copy constructor UtlNameValueTokenizer(const UtlNameValueTokenizer& rNameValueTokenizer); /// Disabled Assignment operator UtlNameValueTokenizer& operator=(const UtlNameValueTokenizer& rhs); }; /* ============================ INLINE METHODS ============================ */ #endif // _UtlNameValueTokenizer_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlBool.h0000644000175000017500000000544212205613256023644 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2011 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UTLBOOL_H_ #define _UTLBOOL_H_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlCopyableContainable.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * UtlBool is a UtlContainable wrapper for a bool. */ class UtlBool : public UtlCopyableContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const UtlContainableType TYPE ; /** < Class type used for runtime checking */ /* ============================ CREATORS ================================== */ /** * Constructor */ UtlBool(bool bValue) ; /** * Destructor */ virtual ~UtlBool(); /// Make a copy of this virtual UtlCopyableContainable* clone() const; /* ============================ MANIPULATORS ============================== */ /** * Set a new bool value for this object. * */ void setValue(bool bValue) ; /* ============================ ACCESSORS ================================= */ /** * Get the bool wrapped by this object. */ bool getValue() const ; /** * Calculate a unique hash code for this object. If the equals * operator returns true for another object, then both of those * objects must return the same hashcode. */ virtual unsigned hash() const ; /** * Get the ContainableType for a UtlContainable derived class. */ virtual UtlContainableType getContainableType() const; /* ============================ INQUIRY =================================== */ /** * Compare the this object to another like-objects. Results for * designating a non-like object are undefined. * * @returns 0 if equal, < 0 if less then and >0 if greater. */ virtual int compareTo(UtlContainable const *) const ; /// @copydoc UtlContainable::isInstanceOf virtual UtlBoolean isInstanceOf(const UtlContainableType type) const; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: bool mValue ; /** < The bool wrapped by this object */ } ; /* ============================ INLINE METHODS ============================ */ #endif // _UTLBOOL_H_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlChainPool.h0000644000175000017500000000647612205613256024635 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2007 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef UtlChainPool_h__ #define UtlChainPool_h__ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlLink.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // FORWARD DECLARATIONS // STRUCTS // TYPEDEFS /// Pool of available objects derived from UtlChain. /** * This avoids excessive heap operations; rather than delete unused UtlChains, they are * stored on the mPool here. To limit the heap overhead associated with allocating * UtlChain, they are allocated in mBlockSize blocks, which are chained on * mBlocks. * * The actual allocation of the blocks and initial chaining is done by the allocator * function supplied by the UtlChain subclass. */ class UtlChainPool { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: friend class UtlLink; friend class UtlPair; friend class UtlInit; /// Allocate blocksize instances of the subclass and chain them into the pool. typedef void allocator(size_t blocksize, ///< number of instances to allocate UtlChain* blockList, ///< list header for first instance UtlChain* pool ///< list header for others ); /**< * This function is supplied by the subclass to the UtlChainPool constructor. * It is responsible for allocating a block of blocksize instances of its subclass. * The first instance in each block is added to the blockList, so that the UtlChainPool * destructor can delete the block. The remaining (blocksize-1) instances are * chained onto the pool list header. */ /// Create a UtlChainPool that uses blockAllocator to create UtlChain derived objects. UtlChainPool(allocator* blockAllocator, size_t blockSize); /// Get a UtlLink with chain pointers NULL UtlChain* get(); /// Return freeLink to the pool of available UtlLinks. void release(UtlChain* freeChain); /// Returns the total number of subclasses instances allocated by this pool. /** * The returned count does not include the 1 instance in each allocation that is * consumed to manage the pool. */ size_t totalAllocated() { return mAllocations * (mBlockSize-1); // one per block is overhead } /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /// Release all dynamic memory used by the UtlLinkPool. ~UtlChainPool(); OsBSem mLock; ///< lock for all the other member variables size_t mBlockSize; size_t mAllocations; allocator* mAllocator; UtlChain mPool; ///< list of available UtlLinks. UtlChain mBlocks; /**< list of memory blocks allocated by the mAllocator. * Each block is an mBlockSize array of objects derived from * UtlChain. The 0th element is used to form the linked list * of blocks. The rest are made a part of the mPool.*/ }; #endif // UtlChainPool_h__ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlCrc32.h0000644000175000017500000000412612205613256023623 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UrlCrc32_h_ #define _UrlCrc32_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsDefs.h" #include "utl/UtlString.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * Utility class for generating CRC-32s */ class UtlCrc32 { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /** * Default no-argument constructor */ UtlCrc32() ; /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ /** * Reset the Crc32 value */ void reset() ; /** * Adds a single byte to the checksum */ void calc(unsigned char ch) ; /** * Adds a sequence of bytes to the checksum */ void calc(unsigned char* pData, size_t nData) ; /** * Adds a sequence of bytes contained within a UtlString to the checksum */ void calc(const UtlString& data) ; /* ============================ ACCESSORS ================================= */ /** * Get the current CRC-32 value */ unsigned long getValue() const ; /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: unsigned long mCrc ; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: UtlCrc32(const UtlCrc32& rUtlCrc32); //:Copy constructor (not implemented for this class) UtlCrc32& operator=(const UtlCrc32& rhs); //:Assignment operator (not implemented for this class) }; /* ============================ INLINE METHODS ============================ */ #endif // _UrlCrc32_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlCryptoData.h0000644000175000017500000000502512205613256025020 0ustar00danieldaniel00000000000000// // Copyright (C) 2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2008 Mutualink, Inc. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // Author: Sergey Kostanbaev #ifndef _UtlCryptoData_h_ #define _UtlCryptoData_h_ // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlString.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * @brief Crypto data operations. */ class UtlCryptoData { /* //////////////////////////////// PUBLIC //////////////////////////////// */ public: /* =============================== CREATORS =============================== */ ///@name Creators //@{ /// Constructor UtlCryptoData(int initSize); /// Destructor ~UtlCryptoData(); //@} /* ============================= MANIPULATORS ============================= */ ///@name Manipulators //@{ /// Get first element inline unsigned char* data(); /// Get \p index element inline unsigned char& operator[] (int index); //@} /* ============================== ACCESSORS =============================== */ ///@name Accessors //@{ //@} /* =============================== INQUIRY ================================ */ ///@name Inquiry //@{ /// Get \p index element for read-only operation inline unsigned char operator[] (int index) const; /// Get size of data inline int size() const; /// Shrink to actual size void resize(int newSize); /// Dump data in humane-readable hex format UtlString dumpHex() const; //@} /* ////////////////////////////// PROTECTED /////////////////////////////// */ protected: /* /////////////////////////////// PRIVATE //////////////////////////////// */ private: unsigned char* mData; int length; }; /* ============================ INLINE METHODS ============================ */ unsigned char* UtlCryptoData::data() { return mData; } unsigned char& UtlCryptoData::operator[] (int index) { assert((0 <= index) && (index < length)); return mData[index]; } unsigned char UtlCryptoData::operator[] (int index) const { assert((0 <= index) && (index < length)); return mData[index]; } int UtlCryptoData::size() const { return length; } #endif // _UtlCryptoData_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlCryptoKey.h0000644000175000017500000002570612205613256024707 0ustar00danieldaniel00000000000000// // Copyright (C) 2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2008 Mutualink, Inc. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// #ifndef _UtlCryptoKey_h_ #define _UtlCryptoKey_h_ #include "utl/UtlString.h" #include "utl/UtlCryptoData.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // TYPEDEFS typedef struct rsa_st RSA; typedef struct evp_cipher_st EVP_CIPHER; typedef struct env_md_st EVP_MD; // DEFINES // MACROS // STATIC VARIABLE INITIALIZATIONS /** * @brief A generic cryptography key base class */ class UtlCryptoKey { /* //////////////////////////////// PUBLIC //////////////////////////////// */ public: /// What type of Key is this? enum KeyType { KEY_INVALID, ///< This key is not currently valid KEY_SYMMETRIC, ///< This is a symmetric key KEY_PRIVATE, ///< This is a private key (also includes a public key) KEY_PUBLIC, ///< This is only a public key NUM_KEY_TYPES ///< Number of key types defined }; /* =============================== CREATORS =============================== */ ///@name Creators //@{ /// Constructor UtlCryptoKey(); /// Destructor virtual ~UtlCryptoKey(); // Key loading & retrieval /// Generates a new RSA private/public key pair virtual int generateKey() = 0; /**< * @return 0 on success, non-0 error code on failure */ /// Imports a key from the given file virtual int importFromFile(const char* pFilename); /**< * @return 0 on success, non-0 error code on failure */ /// Loads a binary key value virtual int loadBinaryKey(const unsigned char* pSrc, int srcLen); /// Retrieves a binary key value (for later use by loadBinaryKey) virtual UtlCryptoData* getBinaryKey() const; // Encryption & decryption /// Returns the max encrypted size of srcLen bytes from encrypt() virtual int getMaxEncryptedSize(int srcLen) const = 0; /// Encrypts the given source data with the current key virtual int encrypt(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const = 0; /**< * @param[in] pSrc - Source data * @param[in] srcLen - Source data len * @param[out] pDest - Destination buffer * @param[in,out] pDestLen - Size of destination buffer and * actual encrypted size after operation * * @return Length of the encrypted data (0 on error) */ /// Encrypts the given source data with the current key virtual UtlCryptoData* encrypt(const unsigned char* pSrc, int srcLen) const; /**< * @param[in] pSrc - Source data * @param[in] srcLen - Source data len * * @return UtlCryptoData allocated object with encrypted data * NOTE: User must free returned object */ /// Returns the max decrypted size of srcLen bytes from decrypt() virtual int getMaxDecryptedSize(int srcLen) const = 0; /// Decrypts the given source data with the current key virtual int decrypt(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const = 0; /**< * @param[in] pSrc - Source data * @param[in] srcLen - Source data len * @param[out] pDest - Destination buffer * @param[in,out] pDestLen - Size of destination buffer and * actual decrypted size after operation * * @return Length of the decrypted data (0 on error) */ /// Decrypts the given source data with the current key virtual UtlCryptoData* decrypt(const unsigned char* pSrc, int srcLen) const; /**< * @param[in] pSrc - Source data * @param[in] srcLen - Source data len * * @return UtlCryptoData allocated object with decrypted data * NOTE: User must free returned object */ /// Signing & verifying virtual int getMaxSignatureSize(int srcLen) const; /// Signs source data virtual int sign(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const; /**< * @param[in] pSrc - Source data * @param[in] srcLen - Source data len * @param[out] pDest - Destination buffer * @param[in,out] pDestLen - Size of destination buffer and * actual decrypted size after operation * * @return Length of the decrypted data (0 on error) */ /// Signs source data virtual UtlCryptoData* sign(const unsigned char* pSrc, int srcLen) const; /**< * @param[in] pSrc - Source data * @param[in] srcLen - Source data len * * @return Valid signature * NOTE: User must free returned object */ /// Verifies that the signature is valid for the source data virtual int verify(const unsigned char* pSrc, int srcLen, const unsigned char* pSig, int sigLen) const; /**< * @param[in] pSrc - Source data * @param[in] srcLen - Source data len * @param[in] pSig - Signature data * @param[in] sigLen - Signature data len * * @return 0 if signature is valid, non-0 if not */ //@} /* ============================== ACCESSORS =============================== */ ///@name Accessors //@{ inline bool isValid() const; inline bool isPrivate() const; inline bool isPublic() const; inline bool isSymmetric() const; inline KeyType getKeyType() const; inline unsigned long getLastError() const; virtual UtlString output() const; //@} // STATICS /// Returns the digest algorithm type that computeDigest() will return static int getDigestAlgType(); /// Returns the max size of a digest that computeDigest() will return static int getMaxDigestSize(int srcLen); /// Computes message digest (MD) of given data static int computeDigest(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen); /**< * @param[in] pSrc - Source data * @param[in] srcLen - Source data len * @param[in] pDest - Destination buffer * @param[out] pDestLen - Size of destination buffer and * actual size after operation * * @return Valid signature */ /// Computes message digest (MD) of given data static UtlCryptoData* computeDigest(const unsigned char* pSrc, int srcLen); /**< * @param[in] pSrc - Source data * @param[in] srcLen - Source data len * * @return Valid signature */ /// Returns the max base64-encoded size of srcLen bytes from base64Encode static int getMaxBase64EncodedSize(int srcLen); /// Encodes the given binary data in base64 format static int base64Encode(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen); /**< * @param[in] pSrc - Source data * @param[in] srcLen - Source data len * @param[in] pDest - Destination buffer * @param[out] pDestLen - Size of destination buffer and * actual size after operation * * @return written characters */ /// Encodes the given binary data in base64 format static UtlString base64Encode(const unsigned char* pSrc, int srcLen); /**< * @param[in] pSrc - Source data * @param[in] srcLen - Source data len * * @return Encoded data */ /// Returns the max decoded size of srcLen bytes from base64Decode static int getMaxBase64DecodedSize(int srcLen); /// Decodes the given base64 data into binary format static int base64Decode(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen); /**< * @param[in] pSrc - Source data * @param[in] srcLen - Source data len * @param[in] pDest - Destination buffer * @param[out] pDestLen - Size of destination buffer and * actual size after operation * * @return written characters */ /// Decodes the given base64 data into binary format static int base64Decode(const UtlString& pSrc, unsigned char* pDest, int* pDestLen); /**< * @param[in] pSrc - Source data * @param[in] pDest - Destination buffer * @param[out] pDestLen - Size of destination buffer and * actual size after operation * * @return Length of the returned decoded data (0 on error) */ /// Decodes the given base64 data into binary format static UtlCryptoData* base64Decode(const unsigned char* pSrc, int srcLen); /**< * @param[in] pSrc - Source data * @param[in] srcLen - length of source data * * @return Decoded data */ /// Decodes the given base64 data into binary format static UtlCryptoData* base64Decode(const UtlString& pSrc); /**< * @param[in] pSrc - Source data * * @return Decoded data */ protected: inline KeyType setKeyType(KeyType type); unsigned long setLastError(unsigned long err) const; virtual void clearKey(); /// Decode base64 character static int getBase64Idx(unsigned char c); /// Returns true if the given char is a base64 char static bool isBase64(unsigned char c); static const char sBase64Chars[]; ///< Set of base64 chars private: KeyType mKeyType; ///< What type of key are we? mutable unsigned long mLastErr; ///< Saved error from last failing method // STATICS static const EVP_MD* spMdAlg; ///< Message Digest algorithm to use }; /* ============================ INLINE METHODS ============================ */ bool UtlCryptoKey::isValid() const { return mKeyType != KEY_INVALID; } bool UtlCryptoKey::isPrivate() const { return mKeyType == KEY_PRIVATE; } bool UtlCryptoKey::isPublic() const { return mKeyType == KEY_PUBLIC; } bool UtlCryptoKey::isSymmetric() const { return mKeyType == KEY_SYMMETRIC; } UtlCryptoKey::KeyType UtlCryptoKey::getKeyType() const { return mKeyType; } unsigned long UtlCryptoKey::getLastError() const { return mLastErr; } UtlCryptoKey::KeyType UtlCryptoKey::setKeyType(KeyType type) { mKeyType=type; return type; } #endif // Include guard sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlCryptoKeyRsa.h0000644000175000017500000001226212205613256025346 0ustar00danieldaniel00000000000000// // Copyright (C) 2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2008 Mutualink, Inc. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // Author: Sergey Kostanbaev #ifndef _UtlCryptoKeyRsa_h_ #define _UtlCryptoKeyRsa_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlCryptoKey.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * @brief Rsa private/public keypairs. */ class UtlCryptoKeyRsa : public UtlCryptoKey { /* //////////////////////////////// PUBLIC //////////////////////////////// */ public: /* =============================== CREATORS =============================== */ ///@name Creators //@{ /// Constructor UtlCryptoKeyRsa(); /// Destructor ~UtlCryptoKeyRsa(); //@} /* ============================= MANIPULATORS ============================= */ ///@name Manipulators //@{ int generateKey(); int importFromFile(const char* pFilename); int getMaxEncryptedSize(int srcLen) const; /// @copydoc UtlCryptoKey::encrypt int encrypt(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const; //UtlCryptoData* encrypt(const unsigned char* pSrc, int srcLen) const //{ return UtlCryptoKey::encrypt(pSrc, srcLen); } int getMaxDecryptedSize(int srcLen) const; /// @copydoc UtlCryptoKey::decrypt int decrypt(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const; /// Returns the max size of a signature that sign() will return int getMaxSignatureSize(int srcLen) const; /// @copydoc UtlCryptoKey::sign int sign(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const; /// @copydoc UtlCryptoKey::verify int verify(const unsigned char* pSrc, int srcLen, const unsigned char* pSig, int sigLen) const; /// Decrypts the given source data with the current PRIVATE key int encryptPrivate(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const; /**< * @param[in] pSrc - Source data * @param[in] srcLen - Source data len * @param[out] pDest - Destination buffer * @param[in,out] pDestLen - Size of destination buffer and * actual decrypted size after operation * * @return Length of the encrypted data (0 on error) */ /// Decrypts the given source data with the current PRIVATE key int decryptPrivate(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const; /**< * @param[in] pSrc - Source data * @param[in] srcLen - Source data len * @param[out] pDest - Destination buffer * @param[in,out] pDestLen - Size of destination buffer and * actual decrypted size after operation * * @return Length of the decrypted data (0 on error) */ /// Encrypts the given source data with the current PUBLIC key int encryptPublic(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const; /**< * @param[in] pSrc - Source data * @param[in] srcLen - Source data len * @param[out] pDest - Destination buffer * @param[in,out] pDestLen - Size of destination buffer and * actual decrypted size after operation * * @return Length of the encrypted data (0 on error) */ /// Decrypts the given source data with the current PUBLIC key int decryptPublic(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const; /**< * @param[in] pSrc - Source data * @param[in] srcLen - Source data len * @param[out] pDest - Destination buffer * @param[in,out] pDestLen - Size of destination buffer and * actual decrypted size after operation * * @return Length of the decrypted data (0 on error) */ //@} /* ============================== ACCESSORS =============================== */ ///@name Accessors //@{ //@} /* =============================== INQUIRY ================================ */ ///@name Inquiry //@{ /// Get humane-readable describe UtlString output() const; //@} /* ////////////////////////////// PROTECTED /////////////////////////////// */ protected: /* /////////////////////////////// PRIVATE //////////////////////////////// */ private: void clearKey(); RSA* mpRsa; ///< Internal (transparent) openssl struct }; /* ============================ INLINE METHODS ============================ */ #endif // _UtlCryptoKeyRsa_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlCryptoKeySym.h0000644000175000017500000000603112205613256025366 0ustar00danieldaniel00000000000000// // Copyright (C) 2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2008 Mutualink, Inc. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // Author: Sergey Kostanbaev #ifndef _UtlCryptoKeySym_h_ #define _UtlCryptoKeySym_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlCryptoKey.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * @brief A symmetric key implementation of UtlCryptoKey */ class UtlCryptoKeySym : public UtlCryptoKey { /* //////////////////////////////// PUBLIC //////////////////////////////// */ public: /* =============================== CREATORS =============================== */ ///@name Creators //@{ /// Constructor UtlCryptoKeySym(); /// Destructor ~UtlCryptoKeySym(); //@} /* ============================= MANIPULATORS ============================= */ ///@name Manipulators //@{ /// Generates a new key. int generateKey(); /**< * @NOTE: Don't use it due the not strong algorithm, for testing only * @return 0 on success, non-0 error code on failure */ /// Loads a binary key value int loadBinaryKey(const unsigned char* pSrc, int srcLen); /**< * @return 0 on success */ /// Retrieves a binary key value (for later use by loadBinaryKey) UtlCryptoData* getBinaryKey() const; /// Returns the max encrypted size of srcLen bytes from encrypt() int getMaxEncryptedSize(int srcLen) const; /// @copydoc UtlCryptoKey::encrypt int encrypt(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const; int getMaxDecryptedSize(int srcLen) const; /// @copydoc UtlCryptoKey::decrypt int decrypt(const unsigned char* pSrc, int srcLen, unsigned char* pDest, int* pDestLen) const; //@} /* ============================== ACCESSORS =============================== */ ///@name Accessors //@{ //@} /* =============================== INQUIRY ================================ */ ///@name Inquiry //@{ /// Return total key length int getTotalKeyLength(); /// Dump key to memeory UtlBoolean getBinaryKey(char* buffer, int bufferLength); /// Get humane-readable describe UtlString output() const; //@} /* ////////////////////////////// PROTECTED /////////////////////////////// */ protected: /* /////////////////////////////// PRIVATE //////////////////////////////// */ private: void clearKey(); const EVP_CIPHER* const mpCipher; const int mKeyLen; const int mIvLen; UtlCryptoData* mpKey; UtlCryptoData* mpIv; }; /* ============================ INLINE METHODS ============================ */ #endif // _UtlCryptoKeyRsa_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlLink.h0000644000175000017500000003537512205613256023656 0ustar00danieldaniel00000000000000// // Copyright (C) 2005 SIPfoundry Inc. // License by SIPfoundry under the LGPL license. // // Copyright (C) 2005 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // ////////////////////////////////////////////////////////////////////////////// #ifndef _UTLLINK_H_ #define _UTLLINK_H_ #include "assert.h" // SYSTEM INCLUDES #include "os/OsDefs.h" #include "os/OsBSem.h" // APPLICATION INCLUDES #include "utl/UtlContainable.h" // DEFINES #ifndef UTLLINK_BLOCK_SIZE #define UTLLINK_BLOCK_SIZE 1000 #endif // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlLink; class UtlChainPool; /** * UtlChain is the internal class that implements the linked list blocks * for other Utl classes. It may not be used directly because by itself * it is not thread safe. Use one of the lists types derived from UtlList. * * Each UltLinkChain links forward (next) and backward (prev) in the chain of links; * ends of a chain are indicated by NULL values. A UtlChain not in a chain, * including a newly constructed instance, have NULL pointers in both directions. * * A UtlChain can also be used as a list header whose links point to the ends * of a NULL terminated list. */ class UtlChain { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /// Constructor initializes to unlinked. UtlChain() : prev(NULL), next(NULL) { } /// Destructor ~UtlChain() { } /* //////////////////////////// PROTECTED //////////////////////////////////// */ protected: friend class UtlChainPool; friend class UtlLink; friend class UtlPair; friend class UtlContainer; friend class UtlList; friend class UtlHashMap; friend class UtlHashMapIterator; friend class UtlHashBag; friend class UtlHashBagIterator; friend class UtlChainTest; friend class UtlLinkTest; UtlChain* prev; ///< backward chain pointer UtlChain* next; ///< forward chain pointer // ================================================================ /** @name Chain Operations * * These methods manipulate the forward and backward links within a * chain. They do no do anything with respect to any header, so they * can be used to implement chains that are linear (NULL terminated) * or circular. */ ///@{ /// Is this block not linked to anything? bool isUnLinked() const { return (!(prev||next)); } /// Take the link out of its chain. void unchain() { if (prev) { prev->next = next; } if (next) { next->prev = prev; } prev=NULL; next=NULL; } /// Insert a new UtlChain before existing. /** * This may be called only on an unlinked UtlChain */ void chainBefore(UtlChain* existing) { assert(isUnLinked()); // not valid on a link that's in a chain next = existing; if (existing->prev) { prev = existing->prev; } if (prev) { prev->next = this; } existing->prev = this; } /// Insert a new UtlChain after existing.. /** * This may be called only on an unlinked UtlChain */ void chainAfter(UtlChain* existing) { assert(isUnLinked()); // not valid on a link that's in a chain prev = existing; next = existing->next; if (next) { next->prev = this; } existing->next = this; } ///@} // ================================================================ /** @name List Operations * * These methods do the special handling for using a UtlChain as a list * header. The UtlChain.next points to the head (first) UtlLink on the * list. The UtlChain.prev points to the tail (last) UtlLink. * * The UtlLink objects on the list form a NULL-terminated chain - * they do not point to the UtlChain that serves as the header. */ ///@{ /// Returns the head (first) UtlLink on the list (or NULL if the list is empty). UtlChain* listHead() const { return next; } /// Returns the tail (last) UtlLink on the list (or NULL if the list is empty). UtlChain* listTail() const { return prev; } /// Returns the head (first) UtlLink on the list (or NULL if the list is empty). UtlLink* head() const { return (UtlLink*)next; } /// Returns the tail (last) UtlLink on the list (or NULL if the list is empty). UtlLink* tail() const { return (UtlLink*)prev; } /// Insert this link into a list before an existing entry (before NULL == at the tail). void listBefore(UtlChain* list, ///< the list to insert into UtlChain* existing /**< the UtlLink for the position in the * list to insert before. NULL means * at the end of the list. */ ); /**< * @note * This method does not verify that the existing element is actually on the list; doing * so is the responsibility of the caller. If the list is empty, existing must be NULL. */ /// Insert this link into a list after an existing entry (after NULL == at the head). void listAfter(UtlChain* list, ///< the list to insert into UtlChain* existing /**< the UtlLink for the position in the * list to insert after. NULL means * at the beginning of the list. */ ); /**< * @note * This method does not verify that the existing element is actually on the list; doing * so is the responsibility of the caller. If the list is empty, existing must be NULL. */ /// Remove a link from a list. UtlChain* detachFromList(UtlChain* listHead); /**< * @note * This method does not verify that the UtlLink * object being detached is actually on the specified list; doing * so is the responsibility of the caller. */ ///@} /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /** * UtlLink implements linked lists of data blocks. * It may not be used directly because it is not thread safe; use one of the * classes derived from UtlList. * * In addition to the links forward (next) and backward (prev) provided by the * parent UtlChain, a UtlLink also points to an item whose place it implements * in the list (data). * * @nosubgrouping */ class UtlLink : public UtlChain { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: // ================================================================ /** @name Traversal Operations * * These methods move forward and back in a chain of UtlLinks. */ ///@{ /// Returns the next UtlLink forward in a chain (or NULL for the end). UtlLink* next() const { return static_cast(UtlChain::next); } /// Returns the next UtlLink backward in a chain (or NULL for the end). UtlLink* prev() const { return static_cast(UtlChain::prev); } /// Linear search starting at this link for a matching data value. UtlLink* findDataRef(UtlContainable* target) const { UtlLink* theLink; for (theLink=const_cast(this); theLink && theLink->data != target; theLink=theLink->next()) { } return theLink; } /// Linear search starting at this link for a matching data value. UtlLink* findNextHash(unsigned targetHash) const { UtlLink* theLink; for (theLink=const_cast(this); theLink && theLink->hash != targetHash; theLink=theLink->next()) { } return theLink; } /// The containable object whose place in the list this UtlLink is tracking. UtlContainable* data; /// The hash code for the containable object whose place in the list this UtlLink is tracking. unsigned hash; ///@} // ================================================================ ///@name Memory Management ///@{ /// Get the total number of UtlLink blocks allocated. /** * Because the underlying UtlLinkPool implementation allocates UtlLinks in blocks, * this number will usually be slightly higher than the maximum number ever in use * (rounded up to the nearest UTLLINK_BLOCK_SIZE) */ static size_t totalAllocated(); ///@} /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: friend class UtlChainPool; friend class UtlContainer; friend class UtlList; friend class UtlListIterator; friend class UtlSList; friend class UtlSListIterator; friend class UtlSortedList; friend class UtlHashBag; friend class UtlHashBagIterator; friend class UtlLinkTest; friend class UtlInit; // ================================================================ /** @name Link Manipulation in a Chain * * These methods insert and remove this UtlLink in a chain. They do not * do any special handling for the ends of a chain, so they can be used * in either NULL-terminated or circular chains. */ ///@{ /// Take the link block out of its list, and return the data pointer UtlContainable* unlink(); /**< * @note * After this call, the UtlLink has been released, and the pointer to it * may not be used. */ /// Insert a new UtlLink to newData before existing, returning the new UtlLink. static UtlLink* before(UtlChain* existing, UtlContainable* newData); /// Insert a new UtlLink to newData after existing, returning the new UtlLink. static UtlLink* after(UtlChain* existing, UtlContainable* newData); ///@} // ================================================================ /** @name List Operations * * These methods do the special handling for using a UtlChain as a list * header. The UtlChain.next points to the head (first) UtlLink on the * list. The UtlChain.prev points to the tail (last) UtlLink. * * The UtlLink objects on the list form a NULL-terminated chain - * they do not point to the UtlChain that serves as the header. */ ///@{ /// Insert a new item into a list before an existing entry (before NULL == at the tail). static UtlLink* listBefore(UtlChain* list, ///< the list to insert into UtlChain* existing,/**< the UtlLink for the position in the * list to insert before. NULL means * at the end of the list. */ UtlContainable* newData ///< the new data item to be inserted. ); /**< * @note * This method does not verify that the existing element is actually on the list; doing * so is the responsibility of the caller. If the list is empty, existing must be NULL. */ /// Insert a new item into a list before an existing entry (after NULL == at the head). static UtlLink* listAfter(UtlChain* list, ///< the list to insert into UtlChain* existing, /**< the UtlLink for the position in the * list to insert after. NULL means * at the beginning of the list. */ UtlContainable* newData ///< the new data item to be inserted. ); /**< * @note * This method does not verify that the existing element is actually on the list; doing * so is the responsibility of the caller. If the list is empty, existing must be NULL. */ /// Remove a link from a list. UtlContainable* detachFrom(UtlChain* listHead); /**< * @note * This method does not verify that the UtlLink * object being detached is actually on the specified list; doing * so is the responsibility of the caller. */ /// Find the first matching target in the list by reference. static UtlLink* findData(UtlChain* list, UtlContainable* target) { return list->next ? static_cast(list->next)->findDataRef(target) : NULL; } ///@} // ================================================================ /** @name Constructor and Destructor * * @see UtlLinkPool for how a UtlLink is allocated and freed. */ ///@{ /// The UtlLink constructor is protected. /** * A UtlLink should only be instantiated by a call to UtlLinkPool::get * because the UtlLinkPool recycles them rather than allocating and * deallocating from the system heap. */ UtlLink() : data(NULL), hash(0) { }; /// Destructor /** * A UtlLink is only destructed when the UtlLinkPool destructor is invoked. */ ~UtlLink() { }; /// Get a UtlLink from the pool. static UtlLink* get(); /// Return a UtlLink to the pool. void release(); /// Recalculate the hash for this item void rehash(); /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /// The allocator function to be passed to the UtlChainPool static void allocate(size_t blocksize, ///< number of instances to allocate UtlChain* blockList, ///< list header for first instance UtlChain* pool ///< list header for others ); /// The pool of available UltLink instances. static UtlChainPool* spLinkPool; }; /// Associate a key object (the parent UtlLink data) with its value object. class UtlPair : public UtlLink { protected: friend class UtlHashMap; friend class UtlHashMapIterator; friend class UtlHashBagIterator; friend class UtlInit; UtlContainable* value; UtlPair() : value(NULL) { }; ~UtlPair() { } static UtlChainPool* spPairPool; /// Get a UtlPair from the pool. static UtlPair* get(); /// Return a UtlPair to the pool. void release(); private: /// The allocator function to be passed to the UtlChainPool static void allocate(size_t blocksize, ///< number of instances to allocate UtlChain* blockList, ///< list header for first instance UtlChain* pool ///< list header for others ); }; #endif // _UTLLINK_H_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlContainable.h0000644000175000017500000001304312205613256025164 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2011 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlContainable_h_ #define _UtlContainable_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * An UtlContainable object is an abstract object that serves as the base * class for anything that can be contained in one of the UtlContainer- * derived classes. One of the largest values of a UtlContainable-derived * object is the ability for any UtlContainer to destroy objects, sort * objects, etc. */ class UtlContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const UtlContainableType TYPE ; /** < Class type used for runtime checking */ /* ============================ CREATORS ================================== */ /** * Destructor */ virtual ~UtlContainable(); /** * Get the ContainableType for a UtlContainable-derived class. */ virtual UtlContainableType getContainableType() const = 0 ; /// Calculate a hash code for this object. virtual unsigned hash() const = 0 ; /**< * The hash method should return a value that is a function of the key used to * locate the object. As much as possible, hash values should be uniformly * distributed over the range of legal unsigned values. * * \par Requirements * if A.isEqual(B) then A.hash() must == B.hash() */ /// Provides a hash function that uses the object pointer as the hash value. unsigned directHash() const; /**< * This may be used by any UtlContainable class for which generating a value hash * is difficult or not meaningful. Note that pointer values, since they are not * uniformly distributed, probably make poor hash codes so this should not be used * normally. @see stringHash * * To use this, define your hash function as just:

     * unsigned int Foo::hash() const
     * {
     * return directHash();
     * }
     * 
* * If you use directHash as the hash method, you probably want to * use pointer comparison as the compareTo method:
     * int Foo::compareTo(UtlContainable const* inVal) const
     * {
     *    int result ; 
     * 
     *    result =
     *       this > other ? 1 :
     *       this < other ? -1 :
     *       0;
     *
     *    return result;
     * }
     * 
*/ /// Provides a hash function appropriate for null-terminated string values. static unsigned stringHash(char const* value); /**< * To use this, define your hash function as just:
     * Foo hash()
     * {
     * return stringHash(value);
     * }
     * 
*/ /// Compare this object to another object. virtual int compareTo(UtlContainable const *) const = 0 ; /**< * Results of comparison to an object not of the same UtlContainableType * may be undefined. * * @returns 0 if equal, < 0 if less then and >0 if greater. * * \par Requirements * - if A.compareTo(B) == 0 then B.compareTo(A) must be == 0 * - if A.compareTo(B) < 0 then B.compareTo(A) must be > 0 * - if A.compareTo(B) > 0 then B.compareTo(A) must be < 0 * - if A.compareTo(B) < 0 and B.compareTo(C) < 0 then A.compareTo(C) must be < 0 * etc. * * Results for comparing with a non-like object are undefined, * other than that it must return non-equal. * Note that a copy of an object might not compare equal to the * original, unless the definition of its type requires it. */ /// Test this object to another object for equality. virtual UtlBoolean isEqual(UtlContainable const *) const; /**< * Results for objects not of the same UtlContainableType may be undefined. * * A default implementation of this is provided that should be adequate for any * UtlContainableType. */ /// Are UtlContainable types the same static UtlBoolean areSameTypes(const UtlContainableType type1, const UtlContainableType type2); /// Determine if this object is a derivative of the specified UtlContainableType virtual UtlBoolean isInstanceOf(const UtlContainableType type) const ; /**< * Determine if this object is an instance of the designated runtime * class identifer or one of its derivatives. For example: *
     * if (pMyObject->isInstanceOf(UtlInt::TYPE))
     * {
     *     ...
     * }
     * 
* * If you want to determine if this object is exactly the same type as * the given type (i.e. not a deriviative) use the following: *
     * if(myObject->getContainableType() == UtlInt::TYPE)
     * {
     *     ...
     * }
     * 
* * @returns TRUE/FALSE if this object is of the given type or a derivative of * the given type. */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: } ; /* ============================ INLINE METHODS ============================ */ #endif // _UtlContainable_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlCopyableContainable.h0000644000175000017500000000446212205613256026650 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2011 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlCopyableContainable_h_ #define _UtlCopyableContainable_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlSList.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * UtlCopyableContainable is a containable that must implement a clone method, that is * used by UtlCopyableSList in order to assign/copy list elements on list copy. * * Derived classes should also implement a copy constructor and an equals * operator. * * Sample clone implementation: * SampleClass* clone() const { return new SampleClass(*this); } * */ class UtlCopyableContainable : public UtlContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const UtlContainableType TYPE; /** < Class type used for runtime checking */ /// Make an off the heap copy of this object virtual UtlCopyableContainable* clone() const = 0; /* ============================ CREATORS ================================== */ UtlCopyableContainable(); virtual ~UtlCopyableContainable(); /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /// @copydoc UtlContainable::getContainableType virtual UtlContainableType getContainableType() const; /* ============================ INQUIRY =================================== */ /// @copydoc UtlContainable::isInstanceOf virtual UtlBoolean isInstanceOf(const UtlContainableType type) const; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: } ; /* ============================ INLINE METHODS ============================ */\ #endif // _UtlCopyableContainable_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlContainer.h0000644000175000017500000002173112205613256024672 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlContainer_h_ #define _UtlContainer_h_ // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlLink.h" #include "utl/UtlContainable.h" #include "utl/UtlIterator.h" #include "os/OsBSem.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * UtlContainer defines an abstract container designed to hold UtlContainable * derived objects. */ class UtlContainer : public UtlContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const UtlContainableType TYPE ; /** < Class type used for runtime checking */ /* ============================ CREATORS ================================== */ /** * Default Constructor */ UtlContainer(); /** * Destructor */ virtual ~UtlContainer(); /* ============================ MANIPULATORS ============================== */ /** * Inserts the designated containable object into the list * * @return the object if successful, otherwise null */ virtual UtlContainable* insert(UtlContainable* obj) = 0 ; /** * Removes the designated objects from the list and frees the object * by calling delete. */ virtual UtlBoolean destroy(UtlContainable*) = 0 ; /** * Removes all elements from the container and deletes each one. */ virtual void destroyAll() = 0 ; /** * Removes the designated object by reference * (as opposed to searching for an equality match). * * @return the object if successful, otherwise null */ virtual UtlContainable* removeReference(const UtlContainable* object) = 0; /** * Removes all elements from the container without freeing the objects. */ virtual void removeAll() = 0 ; /* ============================ ACCESSORS ================================= */ /** * Find the designated value within the container */ virtual UtlContainable* find(const UtlContainable*) const = 0 ; /** * Calculate a unique hash code for this object. If the equals * operator returns true for another object, then both of those * objects must return the same hashcode. */ virtual unsigned hash() const; /** * Get the ContainableType for a UtlContainable derived class. */ virtual UtlContainableType getContainableType() const; /* ============================ INQUIRY =================================== */ /** * Determine if the container is empty. */ virtual UtlBoolean isEmpty() const = 0 ; /** * Determine if the container includes the designated objects. */ virtual UtlBoolean contains(const UtlContainable *) const = 0 ; /** * Determine the number of elements within the container. */ virtual size_t entries() const = 0 ; /** * Compare the this object to another like-objects. Results for * designating a non-like object are undefined. * * @returns 0 if equal, < 0 if less then and >0 if greater. */ virtual int compareTo(const UtlContainable* otherObject) const; /// Lock the linkage between containers and iterators static void acquireIteratorConnectionLock(); /**< * This must be called by any code that will take both the * mContainerRefLock in an iterator and the mContainerLock in a * container. It can be released as soon as both those locks are * acquired, and should be, since most operations on any iterator * will need to take it briefly. */ /// Unlock the linkage between containers and iterators static void releaseIteratorConnectionLock(); /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: friend class UtlIterator; friend class UtlInit; /// Add an iterator to the list to be notified of changes to this container. void addIterator(UtlIterator* newIterator ///< to be notified of container changes ) const; // this const is a lie, but not a detectable one... /**< * * The caller must be holding this->mContainerLock and newIterator->mContainerRefLock * * * This also sets the mpMyContainer pointer in newIterator. */ /// Called from iterator destructor to prevent further notices. void removeIterator(UtlIterator* existingIterator ///< iterator to remove from notice list ) const; /**< * * The caller must be holding both this->mContainerLock and * existingIterator->mContainerRefLock; see also acquireIteratorConnectionLock. * * * Remove the existingIterator from the list to be called for * changes to this UtlContainer. */ /// Call the invalidate method on all iterators void invalidateIterators(); /**< * This is for use in subclasses that have other state that must * be cleaned up. * * :NOTE: the caller must be holding the iterator list lock; * see iteratorListLock */ /// Must be taken when making any change to container state mutable OsBSem mContainerLock; /** * mpIterator list is the list of existing UtlIterator objects * constructed using this UtlContainer * * This is used to invoke methods on each UtlIterator when changes are made to the UtlContainer * ->remove when an element is about to be removed from the UtlContainer, * ->invalidate when this UtlContainer is being deleted * see sIteratorConnectionLock */ UtlChain mIteratorList; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /// This lock prevent container/iterator deadlocks static OsBSem* spIteratorConnectionLock; /**< * UtlContainer/UtlIterator locking strategy * * The mpMyContainer pointer in a UtlIterator is protected by * the UtlIterator::mContainerRefLock. That lock must be held to * write mpMyContainer, and while an iterator method is accessing * its container, *mpMyContainer. * * All other member variables of any UtlContainer, and all other * member variables of any UtlIterator are protected by the * UtlContainer::mContainerLock. * * A UtlIterator must always take both, because it has to lock the * mpMyContainer value to find its UtlContainer, and then lock the * mContainerLock before looking at the UtlContainer state. * * A UtlContainer can usually take just the mContainerLock, but * when it is adding or removing a UtlIterator, it must lock the iterator's * mContainerRefLock as well so that it can change the mpMyContainer value. * * To prevent deadlocks, the sIteratorConnectionLock must be taken * before either lock when both are going to be needed. It can * (and should) be released as soon as both locks are taken. It does * not need to be held through the entire operation - once both * individual locks are taken, everything is safe and there can be no * deadlock. Since holding it will block any operation on any UtlIterator, * it should be released as early as possible. * * Thus, the common sequences of operations are: * * Iterator operations: * * UtlContainer::acquireIteratorConnectionLock(); * OsLock take(mContainerRefLock); * * UtlList* myList = static_cast(mpMyContainer); * OsLock take(myList->mContainerLock); * UtlContainer::releaseIteratorConnectionLock(); // as soon as both locks are taken * * // ... whatever the method does ... * * Container operations (that does not affect mpMyContainer in any iterator): * * { * OsLock take (mContainerLock); * * ... whatever the method does ... * } * * Container destructor (must take sIteratorConnectionLock to disconnect iterators): * * UtlContainer::acquireIteratorConnectionLock(); * OsLock take(mContainerRefLock); * * UtlList* myList = static_cast(mpMyContainer); * OsLock take(myList->mContainerLock); * UtlContainer::releaseIteratorConnectionLock(); // as soon as both locks are taken * * myList->removeIterator(this); * mpMyContainer = NULL; */ /** * There is no copy constructor */ UtlContainer(const UtlContainer& copy ); /** * There is no assignment operator */ UtlContainer& operator=(const UtlContainer& copy ); } ; /* ============================ INLINE METHODS ============================ */ #endif // _UtlContainer_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlContainableAtomic.h0000644000175000017500000000403512205613256026322 0ustar00danieldaniel00000000000000// // Copyright (C) 2004, 2005 Pingtel Corp. // // // $$ //////////////////////////////////////////////////////////////////////// ////// #ifndef _UtlContainableAtomic_h_ #define _UtlContainableAtomic_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlContainable.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * UtlContainableAtomic is a virtual subclass of UtlContainable that * is suitable as a base class for objects that need to be * containable, but are not otherwise "data items" that can be * compared. * A notable feature is that any two UtlContainableAtomic objects are * considered equal only if they are the same (their pointers are equal). * Comparison between objects in UtlContainableAtomic and its subclasses * provides a consistent (albeit arbitrary) linear ordering. * * A subclass of UtlContainableAtomic only needs to define * subclass::getContainableType() and subclass::TYPE, the remaining * necessary methods can be inherited from UtlContainableAtomic. */ class UtlContainableAtomic : public UtlContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /// Calculate a hash code for this object. virtual unsigned hash() const; /**< * Returns a hash of the pointer to the object. */ /// Compare this object to another object. virtual int compareTo(UtlContainable const *) const; /**< * For all members of subclasses of UtlContainableAtomic, * compareTo provides a consistent linear ordering. * A copy of an object is never equal to the original. */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: } ; /* ============================ INLINE METHODS ============================ */ #endif // _UtlContainableAtomic_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlContainablePair.h0000644000175000017500000000621612205613256026004 0ustar00danieldaniel00000000000000// // Copyright (C) 2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlContainablePair_h_ #define _UtlContainablePair_h_ // SYSTEM INCLUDES #include "os/OsDefs.h" // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlContainable.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /// A UtlContainable wrapper for a pair of UtlContainable objects. class UtlContainablePair : public UtlContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const UtlContainableType TYPE; ///< Class type used for runtime checking. /* ============================ CREATORS ================================== */ /// Constructor accepting an optional default value. UtlContainablePair(UtlContainable *pFirst, UtlContainable *pSecond); /// Destructor virtual ~UtlContainablePair(); /* ============================ MANIPULATORS ============================== */ /// Set a new first value for this object. UtlContainable* setFirst(UtlContainable *val); /**< * @returns The old first value. */ /// Set a new second value for this object. UtlContainable* setSecond(UtlContainable *val); /**< * @returns The old second value. */ /* ============================ ACCESSORS ================================= */ /// Get the first value wrapped by this object. UtlContainable* getFirst() const; /// Get the second value wrapped by this object. UtlContainable* getSecond() const; /// Calculate a unique hash code for this object. virtual unsigned hash() const; /**< * If the equals operator returns true for another object, then both of * those objects must return the same hashcode. */ /// Get the ContainableType for a UtlContainable derived class. virtual UtlContainableType getContainableType() const; /* ============================ INQUIRY =================================== */ /// Compare the this object to another like-objects. virtual int compareTo(UtlContainable const *) const; /**< * Compares mpFirst values, and return corresponding value if they're not * equal. If mpFirst values are equal, return result of mpSecond values * comparison. * * Results for designating a non-like object are undefined. * * @returns 0 if equal, < 0 if less then and >0 if greater. */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: UtlContainable *mpFirst; ///< The first value, wrapped by this object. UtlContainable *mpSecond; ///< The second value, wrapped by this object. }; /* ============================ INLINE METHODS ============================ */ #endif // _UtlContainablePair_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlDateTime.h0000644000175000017500000000507612205613256024450 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UTLDATETIME_H_ #define _UTLDATETIME_H_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlContainable.h" #include "os/OsDateTime.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * UtlDateTime is a UtlContainable wrapper for a OsDateTime object. */ class UtlDateTime : public UtlContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const UtlContainableType TYPE ; /** < Class type used for runtime checking */ /* ============================ CREATORS ================================== */ /** * Constructor */ UtlDateTime(OsDateTime time) ; /** * Destructor */ virtual ~UtlDateTime(); /* ============================ MANIPULATORS ============================== */ /** * Set a new time value for this object. * */ void setTime(const OsDateTime& time) ; /* ============================ ACCESSORS ================================= */ /** * Get the time wrapped by this object. */ void getTime(OsDateTime& time) const ; /** * Calculate a unique hash code for this object. If the equals * operator returns true for another object, then both of those * objects must return the same hashcode. */ virtual unsigned hash() const ; /** * Get the ContainableType for a UtlContainable derived class. */ virtual UtlContainableType getContainableType() const; /* ============================ INQUIRY =================================== */ /** * Compare the this object to another like-objects. Results for * designating a non-like object are undefined. * * @returns 0 if equal, < 0 if less then and >0 if greater. */ virtual int compareTo(UtlContainable const *) const ; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: OsDateTime mTime ; /** < The OsDateTime wrapped by this object */ } ; /* ============================ INLINE METHODS ============================ */ #endif // _UTLDATETIME_H_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlDList.h0000644000175000017500000000347012205613256023767 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlDList_h_ #define _UtlDList_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlSList.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * UtlDList is a doubly linked list designed to contain any number of * UtlContainable derived object. For more information on lists, please * look at UtlSList. * * @see UtlSList */ class UtlDList : public UtlSList { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static UtlContainableType TYPE ; /** < Class type used for runtime checking */ /** * Constructor */ UtlDList(); /** * Destructor */ virtual ~UtlDList() ; /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /** * Get the ContainableType for the hash bag as a contained object. */ virtual UtlContainableType getContainableType() const; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: } ; /* ============================ INLINE METHODS ============================ */\ #endif // _UtlDList_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlDListIterator.h0000644000175000017500000000330712205613256025500 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlDListIterator_h_ #define _UtlDListIterator_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlSListIterator.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * UtlDListIterator allows developers to iterate (walks through) a UtlDList. * * @see UtlIterator * @see UtlDList */ class UtlDList; class UtlDListIterator : public UtlSListIterator { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /** * Constructor accepting a source UtlDList */ UtlDListIterator(const UtlDList& list) ; /** * Destructor */ virtual ~UtlDListIterator(); /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: friend class UtlDList; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: UtlDListIterator(); }; /* ============================ INLINE METHODS ============================ */ #endif // _UtlDListIterator_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlDefs.h0000644000175000017500000000312712205617431023627 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlDefs_h_ #define _UtlDefs_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES // DEFINES #ifndef FALSE #define FALSE ((UtlBoolean)(1==0)) #endif #ifndef TRUE #define TRUE ((UtlBoolean)(1==1)) #endif #ifndef NULL #define NULL 0 #endif #define UTL_NOT_FOUND ((size_t)-1) // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS typedef int UtlBoolean ; #if defined(_MSC_VER) && !defined(__cplusplus) # define inline __inline #endif // _DEBUG #if _MSC_VER #define snprintf _snprintf #endif /** FORMAT_INTLL is a string containing the format length specifier * for printing an intll with the 'd', 'x', etc. format specifiers. E.g.: * intll xyz; * printf("The value is %" FORMAT_INTLL "d", xyz); * Note that the '%' before and the format specifier after must be provided. * This must be a \#define, since this specifier isn't standardized. */ #if defined(_WIN32) # define FORMAT_INTLL "I64" #elif defined(__pingtel_on_posix__) # if __WORDSIZE == 64 # define FORMAT_INTLL "l" # else # define FORMAT_INTLL "ll" # endif #else # error Unsupported target platform. #endif typedef const char* const UtlContainableType ; // FORWARD DECLARATIONS #endif // _UtlDefs_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlHashBag.h0000644000175000017500000001463412205613256024251 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlHashBag_h_ #define _UtlHashBag_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlContainer.h" #include "utl/UtlLink.h" // DEFINES // MACROS #define NUM_HASHBAG_BUCKETS(bits) (1<= 3 ) // mean bucket 3 or more && ( mIteratorList.isUnLinked() ) /* there are no iterators - * resizing moves elements to new buckets, * which could cause an iterator to miss some * and to return others more than once. */ ) { resize(); } } size_t mElements; ///< number of UtlContainable objects in this UtlHashMap size_t mBucketBits; ///< number of bits used to index the buckets UtlChain* mpBucket; ///< an array of 2**n UtlChain elements, each used as a list header. /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /// Insert a link into a bucket (the bucket list is ordered by hashcode). void insert(UtlLink* link, ///< The UtlLink for the entry if it was found. UtlChain* bucket ///< The bucket list header where the entry belongs. ); /// Allocate additional buckets and redistribute existing contents. void resize(); /** * This should only be called through resizeIfNeededAndSafe. */ /// Search for a given key value and return the the UtlPair and bucket for it. bool lookup(const UtlContainable* key, ///< The key to locate. UtlChain*& bucket, /**< The bucket list header in which it belongs. * This is set regardless of whether or not the * key was found in the table. */ UtlLink*& pair /**< If the key was found, the UtlPair for the entry. * If the key was not found, this is NULL. */ ) const; /**< * @return true if the key was found, and false if not. */ /// Insert a pair into a bucket. void insert(UtlPair* pair, /**< The UtlPair for the entry - data, value, and hash * are already set. */ UtlChain* bucket ///< The bucket list header where the entry belongs. ); /// Calculate the bucket number for a given hash. size_t bucketNumber(unsigned hash) const; // Don't allow the implicit copy constructor. UtlHashBag(UtlHashBag&); UtlHashBag& operator=(UtlHashBag&); }; /* ============================ INLINE METHODS ============================ */ #endif // _UtlHashBag_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlHashBagIterator.h0000644000175000017500000000647412205613256025766 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlHashBagIterator_h_ #define _UtlHashBagIterator_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlIterator.h" #include "utl/UtlHashBag.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlContainable ; /** * UtlHashBagIterator allows developers to iterator (walks through) an * UtlHashBag. * * @see UtlIterator * @see UtlSList */ class UtlHashBagIterator : public UtlIterator { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /** * Construct an iterator over all objects in a given UtlHashBag * If key is specified, iterate only over objects that match that key * (UtlHashBags may have any number of copies of a given object) */ UtlHashBagIterator(const UtlHashBag& hashBag, UtlContainable* key = NULL); /** * Destructor */ virtual ~UtlHashBagIterator(); /* ============================ MANIPULATORS ============================== */ /** * Return the next element. * * @return The next element or NULL if no more elements are available. */ virtual UtlContainable* operator()() ; /** * Reset the list by moving the iterator cursor to the location before the * first element. */ virtual void reset() ; /* ============================ ACCESSORS ================================= */ /** * Gets the key of the current element */ UtlContainable* key() const ; /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: friend class UtlHashBag; /** * removing is called by the UtlHashMap when an element is about to be * removed from the container. The iterator must ensure that the element * for the removed node is not returned by any subsequent call. */ virtual void removing(const UtlLink* node); /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: void init(const UtlHashBag& hashBag); UtlContainable* mpSubsetMatch; ///< if non-NULL, points to the key that defines the subset unsigned mSubsetHash; ///< if mpSubsetMatch != NULL, this is its hash code size_t mPosition; ///< current bucket number [0..numberOfBuckets-1] UtlLink* mpCurrentLink; ///< current UtlLink within the bucket, or BEFORE_FIRST bool mLinkIsValid; /**< true if mpCurrentLink is the valid current position * The only time this is false is when the UtlContainable * at the current position was removed while it was current. */ // no copy constructor UtlHashBagIterator(UtlHashBagIterator&); } ; /* ============================ INLINE METHODS ============================ */ #endif // _UtlHashBagIterator_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlHashMap.h0000644000175000017500000002062312205613256024270 0ustar00danieldaniel00000000000000// // Copyright (C) 2008-2011 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlHashMap_h_ #define _UtlHashMap_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlContainer.h" // DEFINES // MACROS #define NUM_HASHMAP_BUCKETS(bits) (1<operator==(the actual key) * * @return the key or NULL if not found */ /// Removes all elements from the hash map and deletes each element. virtual void destroyAll(); /// Removes all elements from the hash map without deleting the elements virtual void removeAll(); /* ============================ ACCESSORS ================================= */ /// Return the value for a given key or NULL if not found. UtlContainable* findValue(const UtlContainable* key) const; /// Return the designated key if found otherwise NULL. virtual UtlContainable* find(const UtlContainable* key) const; /* ============================ INQUIRY =================================== */ /// Return the total number of keys in the hash map size_t entries() const; /// Return true if the hash map is empty (entries() == 0), otherwise false. UtlBoolean isEmpty() const; /// Return true if the hash map includes an entry with the specified key. UtlBoolean contains(const UtlContainable* key) const; /// Get the ContainableType for the hash bag as a contained object. virtual UtlContainableType getContainableType() const; /// @brief Make a copy of all of the items BY POINTER in (*this) instance /// into the given map. void copyInto(UtlHashMap& map) const; /**< * It does not clear the given map. IF USING destroyAll call, be sure * to call this on only ONE map instance. */ OsStatus deepCopyInto(UtlHashMap& map) const; /**< * This does a deep copy of the object in this UtlHashMap. * WARNING: buyer beware, all objects (both keys and values) * MUST be derived from UtlCopyableContainable or this method will * fail. The clone method is invoked on both keys and values to * create copies into the given map. The given map does not need * to be empty, but if the key already exists, the copy will fail. * * @param map - target UtlHashMap to copy key/value pairs to. * * @returns OS_NAME_IN_USE if key already exists in map * OS_NOT_SUPPORTED if any key or object is not derived from UtlCopyableContainable * */ /// The current number of buckets in the hash. size_t numberOfBuckets() const { return NUM_HASHMAP_BUCKETS(mBucketBits); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: friend class UtlHashMapIterator; static const UtlContainable* INTERNAL_NULL; /// If the Hash is too full, add additional buckets. inline void resizeIfNeededAndSafe(); /**< * Assumes that the caller is holding the mContainerLock. * * This calls resize to actually do the resize if it is safe. */ size_t mElements; ///< number of UtlContainable objects in this UtlHashMap size_t mBucketBits; ///< number of bits used to index the buckets UtlChain* mpBucket; ///< an array of 2**n UtlChain elements, each used as a list header. /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /// Allocate additional buckets and redistribute existing contents. void resize(); /**< * This should only be called through resizeIfNeededAndSafe. */ /// Search for a given key value and return the the UtlPair and bucket for it. bool lookup(const UtlContainable* key, UtlChain*& bucket, UtlPair*& pair) const; /**< * @param[in] key - The key to locate. * @param[out] bucket - The bucket list header in which it belongs. * This is set regardless of whether or not the * key was found in the table. * @param[out] pair - If the key was found, the UtlPair for the entry. * If the key was not found, this is NULL * @return true if the key was found, and false if not. */ /// Insert a pair into a bucket. void insert(UtlPair* pair, UtlChain* bucket); /**< * @param[in] pair - The UtlPair for the entry - data, value, and hash * are already set. * @param[in] bucket - The bucket list header where the entry belongs. */ /// Calculate the bucket number for a given hash. size_t bucketNumber(unsigned hash) const; /// No copy constructor is provided. UtlHashMap(UtlHashMap&); /// Use copyInto instead UtlHashMap& operator=(const UtlHashMap&); /// Called before removing any entry from the UtlHashMap void notifyIteratorsOfRemove(const UtlPair* pair); }; void UtlHashMap::resizeIfNeededAndSafe() { // IF mean bucket 3 or more AND there are no iterators. // Resizing moves elements to new buckets, which could cause an iterator // to miss some and to return others more than once. if ( ( mElements / NUM_HASHMAP_BUCKETS(mBucketBits) >= 3 ) && ( mIteratorList.isUnLinked() )) { resize(); } } #endif // _UtlHashMap_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlHashMapIterator.h0000644000175000017500000000761612205613256026011 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlHashMapIterator_h_ #define _UtlHashMapIterator_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlIterator.h" #include "utl/UtlHashMap.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlContainable; class UtlPair; /** * UtlHashMapIterator allows developers to iterate (walks through) the * objects in a UtlHashMap. * * @see UtlIterator * @see UtlHashMap */ class UtlHashMapIterator : public UtlIterator { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /** * Constructor accepting a source UtlHashMap */ UtlHashMapIterator(const UtlHashMap& hashMap); /** * Destructor */ virtual ~UtlHashMapIterator(); /* ============================ MANIPULATORS ============================== */ /** * Return the key for the next element. * * @return The next element key or NULL if no more elements are available. */ virtual UtlContainable* operator()(); /** * Reset the list by moving the iterator cursor to the location before the * first element. */ virtual void reset(); /* ============================ ACCESSORS ================================= */ /** * Gets the key of the current element * * This method is undefined if the next element has not been called * (e.g. immediately after construction or after calling reset()). * If the current element has been removed from the hash (either through * the remove method on the iterator or directly on the UtlHashMap), * this method returns NULL. The remaining values in the iteration sequence * are not affected (the next call to () will return the next key). */ UtlContainable* key() const; /** * Gets the value of the current element * * This method is undefined if the next element has not been called * (e.g. immediately after construction or after calling reset()). * If the current element has been removed from the hash (either through * the remove method on the iterator or directly on the UtlHashMap), * this method returns NULL. The remaining values in the iteration sequence * are not affected (the next call to () will return the next key). */ UtlContainable* value() const; /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: friend class UtlHashMap; /** * removing is called by the UtlHashMap when an element is about to be * removed from the container. The iterator must ensure that the element * for the removed node is not returned by any subsequent call. */ virtual void removing(const UtlPair* key); /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: void init(); size_t mPosition; ///< current bucket number [0..numberOfBuckets-1] UtlPair* mpCurrentPair; ///< current UtlPair within the bucket, or BEFORE_FIRST bool mPairIsValid; /**< true if mpCurrentPair is the valid current position * The only time this is false is when the UtlContainable * at the current position was removed while it was current. */ // no copy constructor UtlHashMapIterator(UtlHashMapIterator&); }; /* ============================ INLINE METHODS ============================ */ #endif // _UtlHashMapIterator_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlHistogram.h0000644000175000017500000001042712205613256024705 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlHistogram_h_ #define _UtlHistogram_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlString.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * Record and dump counts in a series of bins. * * Recorded values are integers. The histogram has a specified number * of bins, each counting the number of values over a range, each of * which has the same specified width. * * The number of bins implemented is 2 more than the specified number, * to allow one bin for values lower than the range and one for values * higher than the range. * * The minimum of the range of bin 0 is Base, and each normal bin has * a range of Size values. * * The first normal bin is numbered 0, so the bin for too-low values * is numbered -1. Thus, the bins record: * * Bin -1 counts values less than "Base". * Bin 0 counts values from "Base" to "Base + Size - 1". * Bin 1 counts values from "Base + Size" to "Base + 2*Size - 1". * Bin n counts values from "Base + n*Size" to "Base + (n+1)*Size - 1". * Bin NoOfBins-1 counts values from "Base + (NoOfBins-1)*Size" to * "Base + NoOfBins*Size -1". * Bin NoOfBins counts values greater than or equal to "Base + NoOfBins*Size". * * The values of all the bins can be extracted in a string by setting * outputFormat and outputWidth when the histogram is created. * Calling show() formats each bin's value via * sprintf(buffer, outputFomat, bin-value), concatenates them * together, and returns the result as a UtlString. * outputFormat must be a format string for formatting a single int, * and it must always generate at most outputWidth characters. * * The outputFormat string must remain valid as long as the histogram * object exists; the returned UtlString must be freed by the caller. */ class UtlHistogram { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /** * Constructor. */ UtlHistogram(unsigned int bins, int base, unsigned int size, const char* outputFormat = "", unsigned int outputWidth = 0); /** * Destructor */ ~UtlHistogram(); /* ============================ MANIPULATORS ============================== */ /** * Record a value. * Returns the number of counts in the histogram. */ unsigned int tally(int); /** * Clear the histogram. */ void clear(); /* ============================ ACCESSORS ================================= */ /** * Get the specified number of bins (which is 2 less than the total number * of bins). */ unsigned int getNoOfBins(); /** * Get the lowest value for bin 0. */ unsigned int getBase(); /** * Get the size of each bin. */ unsigned int getBinSize(); /** * Get the total count. */ unsigned int getCount(); /** * Get the count in bin i. * i ranges from -1 to NoOfBins+1. */ unsigned int operator[](unsigned int i); /* ============================ INQUIRY =================================== */ /** * Get a string containing the formatted values from the bins. * The caller must free the returned UtlString. */ UtlString* show(); /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: // Number of bins. unsigned int mNoOfBins; // Lowest value in bin 0. int mBase; // Size of each bin: unsigned int mBinSize; // Pointer to an array of mNoOfBins int's. unsigned int* mpBins; // Total number of counts. unsigned int mCount; // Format used to output values. const char* mOutputFormat; // Width of output that format will generate. unsigned int mOutputWidth; }; /* ============================ INLINE METHODS ============================ */ #endif // _UtlHistogram_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlInit.h0000644000175000017500000000357412205613256023660 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 Jaroslav Libak // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef UtlInit_h__ #define UtlInit_h__ // SYSTEM INCLUDES // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // FORWARD DECLARATIONS // STRUCTS // TYPEDEFS /** * @brief Utl initializer class. Solves the problem with ordering of * constructors & destructors. * * The h file needs to be included in: * - all cpp files whose static members are initialized in UtlInit constructor, * in order to make sure they are initialized properly whenever they are linked * into program. * - it also has to be included as the first include in cpp files, that * initialize static members whose constructor or destructor tries to use any * static members we initialize here. */ class UtlInit { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ ///@name Creators //@{ /// Constructor UtlInit(void); /// Destructor ~UtlInit(void); //@} /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: static unsigned int msCount; ///< Class instance counter. }; /** * This fixes constructor/destructor ordering by declaring a static instance * of this Init class in every cpp file where this .h file is included. * Thus constructor of this class will be run first, and destructor as the last. */ static UtlInit gUtlInit; #endif // UtlInit_h__ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlInt.h0000644000175000017500000000740712205613256023506 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2011 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlInt_h_ #define _UtlInt_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * UtlInt is a UtlContainable wrapper for an int. */ class UtlInt : public UtlCopyableContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const UtlContainableType TYPE ; /** < Class type used for runtime checking */ /* ============================ CREATORS ================================== */ /** * Constructor accepting an optional default value. */ UtlInt(int initialValue = 0) ; UtlInt(const UtlInt& rhs) ; /** * Destructor */ virtual ~UtlInt(); UtlCopyableContainable* clone() const; /* ============================ OPERATORS ============================== */ // Declare prefix and postfix increment operators. UtlInt& operator++(); // Prefix increment operator UtlInt operator++(int); // Postfix increment operator // Declare prefix and postfix decrement operators. UtlInt& operator--(); // Prefix decrement operator UtlInt operator--(int); // Postfix decrement operator UtlInt& operator=(const UtlInt& rhs); // assigment operator // Conversion to int operator int() { return mValue; } /** * Convert the given int to a string representation */ static void toString(UtlString& stringInt, int valueToStringify); /* ============================ MANIPULATORS ============================== */ /** * Set a new int value for this object. * * @returns the old value */ int setValue(int iValue) ; /* ============================ ACCESSORS ================================= */ /** * Get the int wrapped by this object. */ int getValue() const ; /** * Calculate a unique hash code for this object. If the equals * operator returns true for another object, then both of those * objects must return the same hashcode. */ virtual unsigned hash() const ; /** * Get the ContainableType for a UtlContainable derived class. */ virtual UtlContainableType getContainableType() const; /* ============================ INQUIRY =================================== */ /** * Compare this object to another like-object. Results for * comparing to a non-like object are undefined. * * @returns 0 if equal, < 0 if less then and >0 if greater. */ virtual int compareTo(UtlContainable const *) const ; /** * Test this object to another like-object for equality. This method * returns false if unlike-objects are specified. */ virtual UtlBoolean isEqual(UtlContainable const *) const ; /// @copydoc UtlContainable::isInstanceOf virtual UtlBoolean isInstanceOf(const UtlContainableType type) const; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: int mValue ; /** < The int wrapped by this object */ } ; /* ============================ INLINE METHODS ============================ */ #endif // _UtlInt_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlIntPtr.h0000644000175000017500000000725212205613256024172 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2011 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlIntPtr_h_ #define _UtlIntPtr_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlCopyableContainable.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * UtlIntPtr is a UtlContainable wrapper for an intptr_t. */ class UtlIntPtr : public UtlCopyableContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const UtlContainableType TYPE ; /** < Class type used for runtime checking */ /* ============================ CREATORS ================================== */ /** * Constructor accepting an optional default value. */ UtlIntPtr(intptr_t initialValue = 0) ; UtlIntPtr(const UtlIntPtr& rhs) ; /** * Destructor */ virtual ~UtlIntPtr(); UtlCopyableContainable* clone() const; /* ============================ OPERATORS ============================== */ // Declare prefix and postfix increment operators. UtlIntPtr& operator++(); // Prefix increment operator UtlIntPtr operator++(int); // Postfix increment operator // Declare prefix and postfix decrement operators. UtlIntPtr& operator--(); // Prefix decrement operator UtlIntPtr operator--(int); // Postfix decrement operator UtlIntPtr& operator=(const UtlIntPtr& rhs); // assigment operator // Conversion to int operator intptr_t() { return mValue; } /* ============================ MANIPULATORS ============================== */ /** * Set a new int value for this object. * * @returns the old value */ intptr_t setValue(intptr_t iValue) ; /* ============================ ACCESSORS ================================= */ /** * Get the int wrapped by this object. */ intptr_t getValue() const ; /** * Calculate a unique hash code for this object. If the equals * operator returns true for another object, then both of those * objects must return the same hashcode. */ virtual unsigned hash() const ; /** * Get the ContainableType for a UtlContainable derived class. */ virtual UtlContainableType getContainableType() const; /* ============================ INQUIRY =================================== */ /** * Compare this object to another like-object. Results for * comparing to a non-like object are undefined. * * @returns 0 if equal, < 0 if less then and >0 if greater. */ virtual int compareTo(UtlContainable const *) const ; /** * Test this object to another like-object for equality. This method * returns false if unlike-objects are specified. */ virtual UtlBoolean isEqual(UtlContainable const *) const ; /// @copydoc UtlContainable::isInstanceOf virtual UtlBoolean isInstanceOf(const UtlContainableType type) const; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: intptr_t mValue ; ///< The int wrapped by this object } ; /* ============================ INLINE METHODS ============================ */ #endif // _UtlIntPtr_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlIterator.h0000644000175000017500000001040512205613256024535 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlIterator_h_ #define _UtlIterator_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "os/OsBSem.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlContainable ; class UtlContainer; /** * UltIterator defines an abstract Iterator for walking through the elements * of UtlContainer derived class. * *

* Example Code: *

 *    // Create an iterator that walks through the elements of myContentSource.
 *    FooIterator itor(myContentSource);
 *    MyObject* pObj;
 *    // Fetch a pointer to each element of myContentSource into pObj.
 *    while ((pObj = itor()))
 *    {
 *       // Do something to *pObj.
 *    }
 *    // Reset itor to its initial state, so itor() starts walking through the
 *    // elements of myContentSource all over again.
 *    itor.reset();
 *    while ((pObj = itor()))
 *    {
 *       // Do something else to *pObj.
 *    }
 * 
* (The extra parentheses in the while clauses are to mark that that * operation is an assignment, not a comparison.) */ class UtlIterator { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ UtlIterator(const UtlContainer& container); /** * Destructor */ virtual ~UtlIterator() = 0; /* ============================ MANIPULATORS ============================== */ /// Return the next element. virtual UtlContainable* operator()() = 0 ; /// Reset the iterator cursor so that it will again return all elements in the container. virtual void reset() = 0 ; /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: friend class UtlContainer; /****************************************************************** * @par Removing Method - Variable Signature. * * All iterators must have a 'removing' method so that they can be notified * by the container when an element is removed. * * There is no prototype for it here because the signature differs depending * on the container type. * * removing is called by the UtlContainer when an element is about to be * removed from the container. The iterator must ensure that the removed * element is not returned by any subsequent call. * if element != NULL, it points to the element to be removed. * if element == NULL, means all elements to be removed. */ // virtual void removing( ... type depends on the class of the iterator... ) = 0; void addToContainer(const UtlContainer* container); /** * invalidate is called by the UtlContainer from its destructor. * It disconnects the iterator from its container object (sets * mpContainerRef to NULL). * Any subsequent invocation of this iterator (other than its * destructor) must return an error. * * :NOTE: Both the sIiteratorListLock and the container lock must be held by the caller. */ virtual void invalidate(); /** * The mContainerRefLock must be held whenever the mpMyContainer value * is being used or modified. If the mpIteratorListLock in the container * is also held, then the mpIteratorListLock must be taken first. */ OsBSem mContainerRefLock; UtlContainer* mpMyContainer; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /** * There is no copy constructor */ UtlIterator(const UtlIterator& noCopyAllowed); /** * There is no assignment operator */ UtlIterator& operator=(const UtlIterator& noCopyAllowed); } ; /* ============================ INLINE METHODS ============================ */ #endif // _UtlIterator_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlList.h0000644000175000017500000001563112205613256023665 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlList_h_ #define _UtlList_h_ //#define GLIST_SANITY_TEST #ifdef LIST_SANITY_TEST # include "assert.h" #endif // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlLink.h" #include "utl/UtlContainer.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlContainable ; /** * UtlList is an abstract base class for list classes designed to contain any number * of objects derived from the UtlContainable class. Like any UtlContainer, a * UtlList may contain objects of different UtlContainableType * (e.g. UtlInts and UtlVoidPtrs), however, sorting and comparison behavior * may be non-obvious or undefined, so this is not recommended. * * Most list accessors and inquiry methods are performed by equality as * opposed to by reference. That is, the comparisons between UtlContainable * objects are made using the UtlContainable::isEqual or UtlContainable::compareTo * methods, so for example, two different UtlInt* values (having different pointer * values) would compare as equal if they both contained the same integer value. * * Some methods are concerned with references; these compare the actual UtlContainable* * pointer values, so for example list.containsReference(obj) call will search * for a pointer match with each UtlContainable* on the list, matching only when * the value of the 'obj' pointer is found. * * @see UtlContainable for the methods that must be implemented by a class for its * objects to be stored in any UtlContainer. * * Like other UtlContainer classes, UtlList is itself a UtlContainable, so one can have * lists of lists and other complex structures. */ class UtlList : public UtlContainer, public UtlChain { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static UtlContainableType TYPE ; /** < Class type used for runtime checking */ /* ============================ CREATORS ================================== */ // this base class cannot be instantiated directly - the constructor is protected // Destructor virtual ~UtlList(); /* ============================ MANIPULATORS ============================== */ /** * Removes and returns the first item in the list (pop). * * @return the first object if successful, otherwise null */ UtlContainable* get() ; /** * Remove the designated object by reference * (as opposed to searching for an equality match). * * @return the object if successful, otherwise null */ UtlContainable* removeReference(const UtlContainable* obj); /** * Remove the designated object by equality (as opposed to by reference). */ virtual UtlContainable* remove(const UtlContainable* object) = 0; /** * Remove the object at (zero-based) location N. * * @return the object removed from the list, or NULL if there was no object at index N */ UtlContainable* removeAt(const size_t N); /** * Removes the designated objects from the list and frees the object * by calling delete. */ virtual UtlBoolean destroy(UtlContainable*); /** * Removes all elements from the list and deletes each one. */ void destroyAll(); /** * Removes all elements from the list without freeing the objects. */ void removeAll(); /** * Re-calculates hashes for all items */ void rehash(); /* ============================ ACCESSORS ================================= */ /** * Find the first occurence of the designated object by equality (as * opposed to by reference). */ virtual UtlContainable* find(const UtlContainable*) const = 0; /** * Return the element at position N or null if N is out of bounds. */ virtual UtlContainable* at(size_t N) const; /** * Return the first element (head) of the list */ virtual UtlContainable* first() const ; /** * Return the last element (tail) of the list */ virtual UtlContainable* last() const ; /* ============================ INQUIRY =================================== */ /** * Return the total number of elements within the container */ virtual size_t entries() const; /** * Return true of the container is empty (entries() == 0), otherwise false. */ virtual UtlBoolean isEmpty() const; /** * Return true if the container includes the designated object. Each * element within the list is tested for equality against the designated * object using the equals() method. */ virtual UtlBoolean contains(const UtlContainable* object) const; /** * Return true if the list contains the designated object reference. */ virtual UtlBoolean containsReference(const UtlContainable *) const ; /** * Return the number of occurrences of the designated object */ virtual size_t occurrencesOf(const UtlContainable* obj) const = 0; /** * Return the list position of the designated object or UTL_NOT_FOUND if * not found. */ virtual size_t index(const UtlContainable* obj) const = 0; /** * Get the ContainableType for the list as a contained object. */ virtual UtlContainableType getContainableType() const; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /** * The UtlList constructor is protected - only subclasses may be instantiated */ UtlList(); friend class UtlListIterator; /** * notifyIteratorsOfRemove - called before removing any element in the collection */ void notifyIteratorsOfRemove(UtlLink* element); /** * removeLink is used internally to manipulate the links. * * :NOTE: the caller must hold the mContainerLock * * This does not return a new value for the current list position; * this is because it will call the ::removing method on the * removed element, passing the new value. This means the that current position * update is always done the same way no matter what routine did the removing. */ virtual void removeLink(UtlLink* toBeRemoved); #ifdef LIST_SANITY_TEST # define LIST_SANITY_CHECK { if (!sanityCheck()){ assert(FALSE); } } bool sanityCheck() const; #else # define LIST_SANITY_CHECK /* sanityCheck() */ #endif /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: } ; /* ============================ INLINE METHODS ============================ */ #endif // _UtlList_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlListIterator.h0000644000175000017500000000576712205613256025410 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlListIterator_h_ #define _UtlListIterator_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlLink.h" #include "utl/UtlIterator.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlContainable ; class UtlList ; /** * UtlListIterator allows developers to iterator (walks through) an UtlList. * * @see UtlIterator * @see UtlList */ class UtlListIterator : public UtlIterator { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /** * Constructor accepting a source UtlList */ UtlListIterator(const UtlList& list) ; /** * Destructor */ virtual ~UtlListIterator(); /* ============================ MANIPULATORS ============================== */ /** * Return the next element. * * @return The next element or NULL if no more elements are available. */ virtual UtlContainable* operator()() ; /** * Reset the list by moving the iterator cursor to the location before the * first element. */ virtual void reset() ; /** * Find the designated object, and reset the iterator so that it is the current position. * * @return The element or NULL if no more elements are available. */ virtual UtlContainable* findNext(const UtlContainable* objectToFind) = 0; /** * Move the iterator to the last element within the iterator. */ virtual UtlContainable* toLast() ; /* ============================ ACCESSORS ================================= */ /** * return the current value . */ UtlContainable* item() const; /* ============================ INQUIRY =================================== */ /** * Is the iterator positioned at the last element? */ UtlBoolean atLast() const ; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: UtlLink* mpCurrentNode; friend class UtlList; friend class UtlInit; /** * removing is called by the UtlList when an element is about to be * removed from the container. The iterator must ensure that the element * for the removed node is not returned by any subsequent call. */ virtual void removing(const UtlLink* node); static UtlLink const* OFF_LIST_END; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: static OsBSem sIteratorListLock; } ; /* ============================ INLINE METHODS ============================ */ #endif // _UtlListIterator_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlObservable.h0000644000175000017500000000510412205613256025030 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// class UtlObservable; /** * Generic interface for any object which is an observer * of an observable. */ class UtlObserver { public: virtual ~UtlObserver(){}; /** * Notification method which the observer must implement. The * observable's (also, subject) responsibility is to notify * the observers of state changes. The observable will notify * the observers by invoking this onNotify method. * * @param subject The observable which invoked this method. * @param code An integer notification value. For example, it * can be used to indicate the observable's state. * @param pUserData A reference to any object that the observable may * pass to the observer. */ virtual void onNotify(UtlObservable* subject, int code, void *pUserData) = 0; }; /** * Simple interface for any object which is observable, * meaning that observers can register to be notified * of the observable's state changes. */ class UtlObservable { public: virtual ~UtlObservable(){}; /** * Registers a listener of this observable. * Derived classes of UtlObservable should store * its observers in a collection. * * @param observer The observer that wants to "listen to" * this observable's state changes. */ virtual void registerObserver(UtlObserver* observer) = 0; /** * Removes a listener of this observable. * Derived classes of UtlObservable should remove * this observer from it's collection. * * @param observer The observer that no longer wants to "listen to" * this observable's state changes. */ virtual void removeObserver(UtlObserver* observer) = 0; protected: /** * The observable calls this to notify its * observers of a change. * Derived classes should iterate through their collection * of observers and call UtlObserver->onNotify . * * @param code An integer notification value. For example, it * can be used to indicate the observable's state. * @param pUserData A reference to any object that the observable may * pass to the observer. */ virtual void notify(int code, void *pUserData) = 0; }; sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlObservableImpl.h0000644000175000017500000000351112205613256025652 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlObservableImpl_h_ #define _UtlObservableImpl_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/OsLock.h" #include "os/OsMutex.h" #include "utl/UtlObservable.h" #include "utl/UtlSList.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlObservableImpl : public UtlObservable { public: /** * Constructor. */ UtlObservableImpl(); /** * Implementation of UtlObservable::registerObserver. * * @param observer The observer that wants to "listen to" * this observable's state changes. */ virtual void registerObserver(UtlObserver* observer) = 0; /** * Implementation of UtlObservable::removeObserver. * * @param observer The observer that no longer wants to "listen to" * this observable's state changes. */ virtual void removeObserver(UtlObserver* observer) = 0; protected: /** * Implementation of UtlObservable::notify. * * @param code An integer notification value. For example, it * can be used to indicate the observable's state. * @param pUserData A reference to any object that the observable may * pass to the observer. */ virtual void notify(int code, void *pUserData); private: /** * Collection of observers. */ UtlSList mObservers; /** * For synchronization locking */ OsMutex mMutex; }; #endif sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlRegex.h0000644000175000017500000004120012205613256024013 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _REGEX_H #define _REGEX_H #include #include #include "utl/UtlString.h" /** * RegEx implements Perl-compatible regular expressions * * A simple and small C++ wrapper for PCRE. * PCRE (or libprce) is the Perl Compatible Regular Expression library. * http://www.pcre.org/ * * Adapted for the sipXportLib from the regex.hpp wrapper: * * regex.hpp 1.0 Copyright (c) 2003 Peter Petersen (pp@on-time.de) * Simple C++ wrapper for PCRE * * This source file is freeware. You may use it for any purpose without * restriction except that the copyright notice as the top of this file as * well as this paragraph may not be removed or altered. * * Original wrapper by Peter Petersen, adapted to sipX by Scott Lawrence * * The regular expression is compiled in the constructor, and then may be applied * to target strings using one of the Search interfaces. The results are obtained * using the Results interfaces. * * This class is a wrapper around the PCRE package (see the project INSTALL for a * pointer to where PCRE can be found). All the Options variables are identical * to those in pcre.h * * @note * Compiling the regular expressions is usually expensive compared to executing * the actual search, so if an expression is frequently reused, it is best to * compile it only once and then construct the expression to use in the search * using the copy constructor. * * * @nosubgrouping */ class RegEx { public: // ================================================================ /** @name Constructors, Destructor, and Expression Information */ ///@{ /// Compile a regular expression to create the matching object. RegEx( const char * regex, //< the regular expression int options = 0, //< any sum of PCRE options bits unsigned long int maxDepth = MAX_RECURSION // see MAX_RECURSION ); /**< * If compiling the regular expression fails, an error message string is * thrown as an exception. * For options documentation, see 'man pcre' */ /// Default maximum for the recursion depth in searches. static const unsigned long int MAX_RECURSION; /**< * The PCRE internal match() function implements some searches by recursion. * This value is the default maximumm allowed depth for that recursion. It can * be changed to some other value by passing the maxDepth option argument to the * RegEx constructor. It is set at compile time from the SIPX_MAX_REGEX_RECURSION * macro, if that value is defined. * * If the maximum is exceeded, the match fails. * * If this or the maxDepth constructor argument are set to zero, then no limit * is enforced (use with caution). * * See the discussions of stack size in the pcre documentation. * * @note Caution * Test your limits carefully - in versions of PCRE prior to 6.5, there is no * way to limit recursive matches, so this is implemented as a limit on the * total number of calls to 'match' (PCRE_EXTRA_MATCH_LIMIT); this can dramatically * shorten the length of the strings that a pattern that has nested parenthesis * will match. */ /// Construct from a constant regex to save compilation time. RegEx( const RegEx& ); /**< * If you are using the same constant regular expression frequently, you can * use this constructor to save the time to compile and study it. First, declare * a private constant copy of your expression - this will be compiled by PCRE * just once when it is instantiated: * \code * static const RegEx FooNumbers("foo([0-9]+)"); * \endcode * Then in your method, construct a copy of it to use when matching strings: * \code * RegEx fooNumbers(FooNumbers); * fooNumbers.Search(someString); * \endcode * Constructing this copy does not require a PCRE call to compile the expression. */ ~RegEx(); /// Count the number of possible substrings returned by this expression int SubStrings(void) const; /**< * SubStrings() @returns the number of substrings defined by * the regular expression. * * The match of the entire expression is also considered a substring, so the return * value will always be >= 1. * * This method is especially useful when the regular expression is loaded * from some external source. For a hard-coded expression, the return is * a constant, so you really don't need this method. */ ///@} // ================================================================ /** @name Searching * * The searching methods apply a compiled regular expression to a subject * string. All searching methods return a boolean result indicating whether * or not some match was found in the subject. To get information about * the match, use the Results methods. */ ///@{ /// Search a string for matches to this regular expression bool Search( const char * subject, ///< the string to be searched for a match int len = -1, ///< the length of the subject string int options = 0 ///< sum of any PCRE options flags ); /**< * Apply the regular expression to the subject string. * Optional parameter len can be used to pass the subject's length to * Search(). If not specified (or less than 0), strlen() is used * internally to determine the length. Parameter options can contain * any combination of options; for options documentation, see 'man pcre' * @returns true if a match is found. */ /// Search a string starting at some offset for matches to this regular expression bool SearchAt(const char* subject, ///< the string to be searched for a match int offset, ///< offset to begin search in subject string int len = -1, ///< the length of the subject string int options = 0 ///< sum of any PCRE options flags ); /**< * Apply the regular expression to the subject string, starting at the given offset. * If the length is not specified, then strlen(subject) is used. * Parameter options can contain * any combination of options; for options documentation, see 'man pcre' * @returns true if a match is found. * @note * The start of this search is not considered the start of the subject for * the purposes of anchoring. So if the expresssion is "^xx", then subject * "fooxx" will not match, even if offset is passed as '3'. * */ /// Repeat the last search operation, starting immediately after the previous match bool SearchAgain( int options = 0 ///< sum of any PCRE options flags ); /**< * SearchAgain() applies the regular expression to the same * subject last passed to Search or SearchAt, but restarts the search after the last match. * Subsequent calls to SearchAgain() will find all matches in the subject. * @returns true if a further match is found. * Example: * \code * RegEx Pattern("A[0-9]"); * const char* value = "xyzA1abcA2def"; * for (matched = Pattern.Search(value); matched; matched = Pattern.SearchAgain()) * { * printf("%s\n", Pattern.Match()); * } * \endcode * Would print "A1\n" and then "A2\n". * * @note Prefer MatchString over the less efficient Match */ ///@} // ================================================================ /** @name Results * * The results methods provide information about the matches based on the * results of the most recent Searching method call. It is an error to * call any of these methods unless the most recent Searching call returned * 'true'. * * The substring index must be less than the result of RegEx::SubStrings on * the regular expression, but may also be zero or -1 as follows: * - (-1) returns the last searched subject. * - (0) returns the match of the complete regular expression. * - (1) returns $1, etc. * */ ///@{ /// Get the maximum substring value from the most recent search. int Matches(); /**< * May only be called after a successful search using one of the searching interfaces, * and applies to the results of that call. * - any negative return indicates a caller error - the preceeding search call did not match * - a return value of 1 indicates that the entire pattern matched, but no substrings * within it matched. * - a return value of N > 1 indicates that the full string and N-1 substrings are available * * @note * If the expression has internal optional matches, they may not be matched; for example the * expression "(foo|(bar))(bing)" matches subject "foobingo", and Matches would return 4 * because substring 3 "bing" was matched, but substring 2 would be the null string for * that match. * */ /// Append a match from the last search operation to a UtlString. bool MatchString(UtlString* matched, /**< string to append the match to - * may be NULL, in which case no string is returned, * but the return code still indicates whether or not * this substring was matched. */ int i = 0 /**< which substring to append from the last search * - Match(-1) returns the last searched subject. * - Match(0) returns the match of the complete regular expression. * - Match(i>0) returns $i */ ); /**< * May only be called after a successful search * and applies to the results of that call. * @returns true if there was an ith match, false if not * * Example:@code * RegEx matchBs("((B)B+)"); * UtlString getB; * UtlString getBs; * if (matchB.Search("xxaBBBBcyy")) * { * matchB.MatchString(&getBs,0); * matchB.MatchString(&getB,2); * } * @endcode * would set the UtlStrings * - getBs to "BBBB" * - getB to "B" */ /// Get the position and length of a match in the subject bool Match(const int i, ///< input - must be < SubStrings() */ int& offset, ///< output - offset in last subject of the n'th match int& length ///< output - length in last subject of the n'th match ); /**< * May only be called after a successful * call to one of the searching methods, and applies to the results of * that call. * * Parameter i must be less than SubStrings(). * - Match(-1) returns the last searched subject. * - Match(0) returns the match of the complete regular expression. * - Match(1) returns $1, etc. * * @returns true if the last search had an n'th match, false if not * * Example:@code * RegEx matchABCs("A+(B+)(C+)"); * UtlString subject("xAABBBBC"); * int offset = 1; * if (matchABCs.SearchAt(subject, offset)) * { * int all = matchABCs.Match(0, allStart, allLength); * int firstB = matchABCs.Match(1, firstB, numBs); * int firstC = matchABCs.Match(2, firstC, numCs); * } * @endcode * would set the values * - allStart = 1, allLength = 2 * - firstB = 3, numBs = 4 * - firstC = 7, numCs = 1 * * @note * The returned start position is relative to the beginning of the subject string, * not from any offset value. * */ /// Get the position of a match in the subject int MatchStart(const int i ///< input - must be < SubStrings() */ ); /**< * May only be called after a successful call to one of the searching * methods, and applies to the results of that call. * * Parameter i must be less than SubStrings(). * - Match(-1) returns the last searched subject. * - Match(0) returns the match of the complete regular expression. * - Match(1) returns $1, etc. * * This is useful when searching at an offset in a string to check whether or not * the match was at the offset or somewhere later in the string. * * Example:@code * RegEx matchABCs("A+(B+)(C+)"); * UtlString subject("xAABBBBC"); * int offset = 1; * bool result = ( (matchABCs.SearchAt(subject, offset)) * && (matchABCs.MatchStart(0) == offset)); * @endcode * Note that this is not the same as haveing written the regular expression so * that it is anchored: "^A+(B+)(C+)" because the anchor always refers to the * actual start of the string (in the example, before the 'x'), even when used * with an offset. So the 'result' variable in the example would be true. */ /// Append string preceeding the most recently matched value to a UtlString. bool BeforeMatchString(UtlString* before /**< string to append to - * may be NULL, in which case no string is returned, * but the return code still indicates whether or not * there was some string preceeding the last match. */ ); /**< * May only be called after a successful search and applies to * the results of that call. This is equivalent to the Perl $` variable. * * @returns true if there was a string before the match, false if not * Example:@code * RegEx matchB("B"); * UtlString getBefore; * if (matchB.Search("xxaBcyy")) * { * matchB.BeforeMatchString(&getBefore); * } * @endcode * * would set the UtlString getBefore to "xxa". */ /// Append string following the most recently matched value to a UtlString. bool AfterMatchString(UtlString* before /**< string to append to - * may be NULL, in which case no string is returned, * but the return code still indicates whether or not * there was some string following the last match. */ ); /**< * May only be called after a successful search and applies to * the results of that call. This is equivalent to the Perl $' variable. * * @returns true if there was a string following the match, false if not * Example:@code * RegEx matchB("B"); * UtlString getAfter; * if (matchB.Search("xxaBcyy")) * { * matchB.AfterMatchString(&getAfter); * } * @endcode * * would set the UtlString getAfter to "cyy". */ /// Get the offset of the first character past the matched value int AfterMatch(int i ///< the substring specifier ); /**< * May only be called after a successful search and applies to * the results of that call. * * Example:@code * RegEx matchBseq("A+(B+)C+"); * if (matchBseq.Search("xxAABBBCCCyy")) * { * int afterB = matchBseq.AfterMatch(1); * int afterC = matchBseq.AfterMatch(0); * } * @endcode * * would set * - afterB = 7 * - afterC = 10 */ /// Get a string matched by a previous search const char * Match(int i = 0 /**< must be < SubStrings() */ ); /**< * @note * This does more memory allocation and data copying than any of the other results methods; * use one of the others when possible. * * * May only be called after a successful search, and applies to the results of * that call. Parameter i must be less than * SubStrings(). * - Match(-1) returns the last searched subject. * - Match(0) returns the match of the complete regular expression. * - Match(1) returns $1, etc. * @returns a pointer to the ith matched substring. */ ///@} private: /* * Use the copy constructor above instead of the = operator. */ RegEx& operator=(const char *); void ClearMatchList(void); pcre * re; size_t re_size; pcre_extra * pe; bool allocated_study; size_t study_size; int substrcount; // maximum substrings in pattern const char * subjectStr; // original subject int subjectLen; // original length int lastStart; // offset of start for most recent Search or SearchAgain int lastMatches; // pcre_exec return for most recent Search or SearchAgain int * ovector; // results from (and workspace for) pcre_exec const char * * matchlist;// string cache for Match }; #endif // _REGEX_H sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlRscStore.h0000644000175000017500000001014112205613256024505 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlRscStore_h_ #define _UtlRscStore_h_ #include "utl/UtlRscTrace.h" #ifdef RSC_TEST // SYSTEM INCLUDES #include "os/OsDefs.h" #include "os/OsBSem.h" #include "os/OsRWMutex.h" #include "os/OsStatus.h" // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlRscTrace; //:Database of active Rscs. // The UtlRscStore maintains a database of active Rscs (i.e., those Rscs // that have been started by the low level OsSysRsc class). Since the // OsRscTask is the only task that should be accessing the Rsc database // there is no need to serialize access (and no locking).
//
// Each entry in the database is a key/value pair where the key corresponds // to a Rsc ID and the value is the pointer to the corresponding OsRsc // object. Duplicate keys are not allowed. class UtlRscStore { friend UtlRscTrace; /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: enum StoreInitSize { RSC_STORE_INIT_SIZE = 1000000 }; /* ============================ CREATORS ================================== */ UtlRscStore(int initialStoreSize = RSC_STORE_INIT_SIZE); //:Default constructor virtual ~UtlRscStore(); //:Destructor /* ============================ MANIPULATORS ============================== */ OsStatus insert(int RscId, char* pRsc); //:Insert the indicated Rsc into the database of active Rscs. // Return OS_SUCCESS if successful, OS_NAME_IN_USE if the key is // already in the database. OsStatus remove(int RscId); //:Remove the indicated Rsc from the database of active Rscs. // Return OS_SUCCESS if the indicated RscId is found, return // OS_NOT_FOUND if there is no match for the specified key. void cleanUp(); /* ============================ ACCESSORS ================================= */ int getActiveRscs(char* activeRscs[], int size); //:Get an array of pointers to the Rscs that are currently active. // The caller provides an array that can hold up to size OsRsc // pointers. This method will fill in the activeRscs array with // up to size pointers. The method returns the number of pointers // in the array that were actually filled in. void getStoreStats(unsigned& nInserts, unsigned& nRemoves) const; //:Get the number of insertions and removals for the Rsc database. int numEntries(void) const; //:Return the number of key-value pairs in the name database. /* ============================ INQUIRY =================================== */ UtlBoolean isEmpty(void) const; //:Return TRUE if the Rsc database is empty. /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: UtlHashMap mDict; // hash table used to store the key/value // pairs unsigned long mNumInserts; // number of insertions into the database unsigned long mNumRemoves; // number of removals from the database OsRWMutex mDictRWLock; UtlRscStore(const UtlRscStore& rUtlRscStore); //:Copy constructor (not implemented for this class) UtlRscStore& operator=(const UtlRscStore& rhs); //:Assignment operator (not implemented for this class) #ifdef TEST static bool sIsTested; //:Set to true after the tests for this class have been executed once void test(); //:Verify assertions for this class // Test helper functions void testCreators(); void testManipulators(); void testAccessors(); void testInquiry(); #endif TEST }; /* ============================ INLINE METHODS ============================ */ #endif // RSC_TEST #endif // _UtlRscStore_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlRscTrace.h0000644000175000017500000001526712205613256024465 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlRscTrace_h_ #define _UtlRscTrace_h_ #define RSC_TEST #undef RSC_TEST #ifdef RSC_TEST // SYSTEM INCLUDES #include "utl/UtlRscStore.h" #include // APPLICATION INCLUDES // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //:A class used to keep track of the number of resource allocations and frees // This class is used in conjunction with instrumented versions of the global // new and delete operators. class UtlRscTrace { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static unsigned long sAllocCnt; // Track the number of memory allocs static unsigned long sFreeCnt; // Track the number of memory frees static int sTraceFlag;// If non-zero, print a line of info // for every call to new()/delete() static unsigned long sStartTime; // static UtlRscStore mResourceStore; enum RscType { NONE = 0, MEMORY = 1, OSSOCKET = 2, OSMSGQ = 3, OSBSEM = 4, OSCSEM = 5, OSMUTEX = 6, OSRWMUTEX = 7, OSTIMER = 8, OSTASK = 9 }; /* ============================ CREATORS ================================== */ UtlRscTrace(); //:Default constructor (and take a checkpoint) UtlRscTrace(const UtlRscTrace& rRscTrace); //:Copy constructor virtual ~UtlRscTrace(); //:Destructor /* ============================ MANIPULATORS ============================== */ UtlRscTrace& operator=(const UtlRscTrace& rhs); //:Assignment operator virtual void checkpoint(); //:Remember the count of outstanding memory allocations static void setTraceFlag(int flag) { sTraceFlag = flag; }; //: Set trace flag, if non-zero, print a line of info static int enableMemTracking(int taskId = 0); //: Set trace flag, if non-zero, print a line of info static int enableMsgQTracking(int taskId = 0); //: Set trace flag, if non-zero, print a line of info static int enableBSemTracking(int taskId = 0); //: Set trace flag, if non-zero, print a line of info static int enableCSemTracking(int taskId = 0); //: Set trace flag, if non-zero, print a line of info static int enableMutexTracking(int taskId = 0); //: Set trace flag, if non-zero, print a line of info static int enableRWMutexTracking(int taskId = 0); //: Set trace flag, if non-zero, print a line of info static int enableTimerTracking(int taskId = 0); //: Set trace flag, if non-zero, print a line of info static int enableTaskTracking(int taskId = 0); //: Set trace flag, if non-zero, print a line of info static int enableSocketTracking(int taskId = 0); //: Set trace flag, if non-zero, print a line of info static int disableTracking(); //: Set trace flag, if non-zero, print a line of info static void addAllocCnt(int addr, int taskId); //: Add allocCnt for the task, used for OsSocket tracking static void addAllocCnt(int size, int addr, int taskId); //: Add allocCnt for the task, used for memory/OsMutex/OsRWMutex tracking static void addAllocCnt(int size, int addr, const char* name, int pArg, int priority, int options, int taskId); //: Add allocCnt for the task, used for OsTask tracking static void addAllocCnt(int state, int addr, int timerId, int type, int taskId); //: Add allocCnt for the task, used for OsTimer/OsCSem tracking static void addAllocCnt(int options, int addr, int state, int taskId); //: Add allocCnt for the task, used for OsBSem tracking static void addAllocCnt(int addr, const char* name, int taskId); //: Add allocCnt for the task, used for OsMsgQ tracking static void addFreeCnt(int addr, int taskId = 0); //: Add freeCnt for the task /* ============================ ACCESSORS ================================= */ static void showMem(int taskId = 0); static int delta(); //:Return the change to the number of outstanding memory allocations //:since the last checkpoint. static int delta(int taskId); //:Return the change to the number of outstanding memory allocations //:since the last checkpoint. static int allocCnt(int taskId = 0); //:Return the number of memory allocations (monotonically increasing) static int rscStatus(); //:Return the number of memory frees (monotonically increasing) static int freeCnt(int taskId = 0); //:Return the number of memory frees (monotonically increasing) static int netAllocCnt(); //:Return the net number of allocations (allocCnt - freeCnt) static int netAllocCnt(int taskId); //:Return the net number of allocations (allocCnt - freeCnt) /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: static long mCheckpoint; // Used to remember the net number of // allocations at time of checkpoint static OsMutex *mpResourceStoreLock; static UtlRscStore mUtlRscStore; static int mTaskId; }; /* ============================ INLINE METHODS ============================ */ #endif // RSC_TEST #endif // _UtlRscTrace_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlSerialized.h0000644000175000017500000001160412205613256025041 0ustar00danieldaniel00000000000000// // Copyright (C) 2009 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2009 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlSerialized_h_ #define _UtlSerialized_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS #define UTL_SERIALIZED_SIZE 1024 class UtlSerialized { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ ///@name Creators //@{ /// Constructor inline UtlSerialized() : mpEnd(mData) , mSize(0) { }; /// Copy constructor inline UtlSerialized(const UtlSerialized& rhs) : mpEnd(mData+(rhs.mpEnd-rhs.mData)) , mSize(rhs.mSize) { memcpy(mData, rhs.mData, rhs.getSize()); }; /// Destructor virtual ~UtlSerialized() { }; //@} /* ============================ MANIPULATORS ============================== */ ///@name Manipulators //@{ #define SERIALIZE_POD_DEFINE(type) \ inline OsStatus serialize(type val) \ { \ if (sizeof(type) > getFreeSize()) \ { \ return OS_LIMIT_REACHED; \ } \ *(type*)mpEnd = val; \ mpEnd += sizeof(type); \ mSize += sizeof(type); \ return OS_SUCCESS; \ } \ inline OsStatus deserialize(type &val) \ { \ if (sizeof(type) > getSize() - (mpEnd-mData)) \ { \ return OS_NO_MORE_DATA; \ } \ val = *(type*)mpEnd; \ mpEnd += sizeof(type); \ return OS_SUCCESS; \ } SERIALIZE_POD_DEFINE(char); SERIALIZE_POD_DEFINE(short); SERIALIZE_POD_DEFINE(int); SERIALIZE_POD_DEFINE(long); SERIALIZE_POD_DEFINE(unsigned char); SERIALIZE_POD_DEFINE(unsigned short); SERIALIZE_POD_DEFINE(unsigned int); SERIALIZE_POD_DEFINE(unsigned long); SERIALIZE_POD_DEFINE(void *); #undef SERIALIZE_POD_DEFINE inline OsStatus serialize(const UtlString &val) { // We add 1 to the length to include end-of-string \0 byte. size_t length = val.length() + 1; if (sizeof(int) + length > getFreeSize()) { return OS_LIMIT_REACHED; } serialize(length); memcpy(mpEnd, val.data(), length); mpEnd += length; mSize += length; return OS_SUCCESS; } inline OsStatus deserialize(UtlString &val) { OsStatus result; size_t length; result = deserialize(length); if (result != OS_SUCCESS) { return result; } if (length > getSize() - (mpEnd-mData)) { // Something is wrong - length of the string is bigger then available data. return OS_FAILED; } // Resize reserves space for last \0 internally, so we should exclude // it from the length. val.resize(length-1, FALSE); memcpy((void*)val.data(), mpEnd, length); mpEnd += length; return OS_SUCCESS; } /// Prepare for de-serialization. inline void finishSerialize() { mpEnd = mData; } /// Assignment operator inline UtlSerialized& operator=(const UtlSerialized& rhs) { if(&rhs == this) { return(*this); } memcpy(mData, rhs.mData, rhs.getSize()); mpEnd = mData+(rhs.mpEnd-rhs.mData); mSize = rhs.mSize; return *this; } //@} /* ============================ ACCESSORS ================================= */ ///@name Accessors //@{ /// Get size of available space (in bytes). inline size_t getMaxSize() const {return UTL_SERIALIZED_SIZE;} /// Get size of stored data (in bytes). inline size_t getSize() const {return mSize;} /// Get free size in storage (in bytes). inline size_t getFreeSize() const {return getMaxSize()-getSize();} //@} /* ============================ INQUIRY =================================== */ ///@name Inquiry //@{ //@} /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: uint8_t *mpEnd; ///< Pointer to the byte right after the end of data. uint8_t mData[UTL_SERIALIZED_SIZE]; ///< Array to serialize data to. size_t mSize; ///< Size of the serialized data. /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _UtlSerialized_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlSList.h0000644000175000017500000001011412205613256023777 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlSList_h_ #define _UtlSList_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlList.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlContainable; /** * UtlSList is a singularly linked list designed to contain any number * of UtlContainable derived object. The list may contain non-like objects * (e.g. UtlInts and UtlVoidPtrs), however, sorting and comparison behavior * may be non-obvious. * * Most list accessors and inquiry methods are performed by equality as * opposed to by referencing (pointers). For example, a list.contains(obj) * call will loop through all of the list objects and test equality by calling * the isEquals(...) method. A list.containsReference(obj) call will search * for a pointer match. * * @see UtlSListIterator * @see UtlList * @see UtlContainer * @see UtlContainable */ class UtlSList : public UtlList { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const UtlContainableType TYPE; /* ============================ CREATORS ================================== */ /** * Default Constructor */ UtlSList(); /* ============================ MANIPULATORS ============================== */ /** * Append the designated containable object to the end of this list. * * @return the object if successful, otherwise null */ virtual UtlContainable* append(UtlContainable* obj) ; /// Insert the designated containable object at the designated position. virtual UtlContainable* insertAt(size_t N, ///< zero-based position obj should be UtlContainable* obj ///< object to insert at N ); /**< * It is an error to specify N > entries() * * @return obj if successful, NULL if N > entries */ /** * Inserts the designated containable object at the end postion (tailer). * * @return the object if successful, otherwise null */ virtual UtlContainable* insert(UtlContainable* obj) ; /** * Remove the designated object by equality (as opposed to by reference). */ virtual UtlContainable* remove(const UtlContainable *); /** * Removes the designated objects from the list and frees the object * by calling delete. */ virtual UtlBoolean destroy(UtlContainable *); /* ============================ ACCESSORS ================================= */ /** * Find the first occurence of the designated object by equality (as * opposed to by reference). */ virtual UtlContainable* find(const UtlContainable *) const ; /* ============================ INQUIRY =================================== */ /** * Return the number of occurrences of the designated object */ virtual size_t occurrencesOf(const UtlContainable* obj) const ; /** * Return the list position of the designated object or UTL_NOT_FOUND if * not found. */ virtual size_t index(const UtlContainable* obj) const ; /** * Get the ContainableType for the hash bag as a contained object. */ virtual UtlContainableType getContainableType() const; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: friend class UtlSListIterator; /** * insertAfter is used by UtlListIterator::insertAfterPoint */ virtual UtlContainable* insertAfter(UtlLink* afterNode, UtlContainable* object); /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: } ; /* ============================ INLINE METHODS ============================ */ #endif // _UtlSList_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlCopyableSList.h0000644000175000017500000000564712205613256025475 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlCopyableSList_h_ #define _UtlCopyableSList_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlSList.h" #include "utl/UtlCopyableContainable.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * UtlCopyableSList is a linked list that provides a copy contructor and an * equals operator. A deep copy of the array elements is performed. * * @see UtlSList */ class UtlCopyableSList : public UtlSList { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /** * Constructor */ UtlCopyableSList(); /** * Copy Constructor */ UtlCopyableSList(const UtlCopyableSList& rhs); /** * Destructor */ virtual ~UtlCopyableSList() ; /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ /** * Assignment operator */ UtlCopyableSList& operator=(const UtlCopyableSList& rhs); /** * Append the designated containable object to the end of this list. * * @return the object if successful, otherwise null */ virtual UtlContainable* append(UtlCopyableContainable* obj) ; /// Insert the designated containable object at the designated position. virtual UtlContainable* insertAt(size_t N, ///< zero-based position obj should be UtlCopyableContainable* obj ///< object to insert at N ); /**< * It is an error to specify N > entries() * * @return obj if successful, NULL if N > entries */ /** * Inserts the designated containable object at the end postion (tailer). * * @return the object if successful, otherwise null */ virtual UtlContainable* insert(UtlCopyableContainable* obj) ; /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /** * Get the ContainableType for the hash bag as a contained object. */ virtual UtlContainableType getContainableType() const; static UtlContainableType TYPE ; /** < Class type used for runtime checking */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: } ; /* ============================ INLINE METHODS ============================ */\ #endif // _UtlCopyableSList_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlSListIterator.h0000644000175000017500000000360712205613256025522 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlSListIterator_h_ #define _UtlSListIterator_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlListIterator.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlContainable ; class UtlSList ; /** * UtlSListIterator allows developers to iterator (walks through) an UtlSList. * * @see UtlIterator * @see UtlSList */ class UtlSListIterator : public UtlListIterator { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /** * Constructor accepting a source UtlSList */ UtlSListIterator(const UtlSList& list) ; /** * Find the designated object, and reset the iterator so that it is the current position. * * @return The element or NULL if no more elements are available. */ virtual UtlContainable* findNext(const UtlContainable* objectToFind) ; /** * Insert the designated element after the current iterator * position. */ UtlContainable* insertAfterPoint(UtlContainable*) ; /* ============================ ACCESSORS ================================= */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: friend class UtlSList; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: } ; /* ============================ INLINE METHODS ============================ */ #endif // _UtlSListIterator_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlSortedList.h0000644000175000017500000000651012205613256025042 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlSortedList_h_ #define _UtlSortedList_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlList.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlContainable; /** * UtlSortedList is a list that is always sorted * * Most list accessors and inquiry methods are performed by equality as * opposed to by referencing (pointers). For example, a list.contains(obj) * call will loop through all of the list objects and test equality by calling * the isEquals(...) method. A list.containsReference(obj) call will search * for a pointer match. * * @see UtlSListIterator * @see UtlList * @see UtlContainer * @see UtlContainable */ class UtlSortedList : public UtlList { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const UtlContainableType TYPE; /* ============================ CREATORS ================================== */ /** * Default Constructor */ UtlSortedList(); /* ============================ MANIPULATORS ============================== */ /** * Inserts the designated containable object into the list * * @return the object if successful, otherwise null */ virtual UtlContainable* insert(UtlContainable* obj); /** * Remove the designated object by equality (as opposed to by reference). */ virtual UtlContainable* remove(const UtlContainable*); /* ============================ ACCESSORS ================================= */ /** * Find the first occurrence of the designated object by equality (as * opposed to by reference). */ virtual UtlContainable* find(const UtlContainable*) const; /* ============================ INQUIRY =================================== */ /** * Return the list position of the designated object or UTL_NOT_FOUND if * not found. */ virtual size_t index(const UtlContainable* obj) const; /** * Return the number of occurrences of the designated object */ virtual size_t occurrencesOf(const UtlContainable* obj) const; /** * Get the ContainableType for the list as a contained object. */ UtlContainableType getContainableType() const; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: friend class UtlSortedListIterator; typedef enum {POSITION, EXACTLY} MatchType; /** * Return the first UtlLink which is greater or equal to the designated * object, or NULL if not found. * * The caller must hold the mContainerLock */ UtlLink* findNode(UtlLink* starting, MatchType match, const UtlContainable* obj) const; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /* for now, don't provide a copy constructor */ UtlSortedList(UtlSortedList& rhs); }; /* ============================ INLINE METHODS ============================ */ #endif // _UtlSortedList_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlCopyableSortedList.h0000644000175000017500000000452212205613256026522 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlCopyableSortedList_h_ #define _UtlCopyableSortedList_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlSortedList.h" #include "utl/UtlCopyableContainable.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * UtlCopyableSortedList is a linked list that provides a copy contructor and an * equals operator. A deep copy of the array elements is performed. * * @see UtlSortedList */ class UtlCopyableSortedList : public UtlSortedList { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /** * Constructor */ UtlCopyableSortedList(); /** * Copy Constructor */ UtlCopyableSortedList(const UtlCopyableSortedList& rhs); /** * Destructor */ virtual ~UtlCopyableSortedList() ; /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ /** * Assignment operator */ UtlCopyableSortedList& operator=(const UtlCopyableSortedList& rhs); /** * Inserts the designated containable object into the list * * @return the object if successful, otherwise null */ virtual UtlContainable* insert(UtlCopyableContainable* obj); /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /** * Get the ContainableType for the hash bag as a contained object. */ virtual UtlContainableType getContainableType() const; static UtlContainableType TYPE ; /** < Class type used for runtime checking */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: } ; /* ============================ INLINE METHODS ============================ */\ #endif // _UtlCopyableSortedList_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlString.h0000644000175000017500000005346112205613256024223 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2011 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlString_h_ #define _UtlString_h_ // SYSTEM INCLUDES #include #include "os/OsDefs.h" // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlCopyableContainable.h" // DEFINES #define DEFAULT_UTLSTRING_CAPACITY 100 ///< initial capacity unless overridden by the constructor // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * UtlString is a resizable string which is also containable in * any UtlContainer. It may include null characters. * * A UtlString will grow as needed to hold any value stored * in it; because this expansion reallocates and copies memory, it is * a good idea to specify an expected size either when the object is * constructed or using the capacity method. * * @nosubgrouping */ class UtlString : public UtlCopyableContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const UtlContainableType TYPE; /** < Class type used for runtime checking */ static const char* ssNull; static const size_t UTLSTRING_NOT_FOUND; ///< Returned from a search that failed. static const size_t UTLSTRING_TO_END; /**< When specifying the length of a substring, * indicates that the substring should extend * to the end of the string. */ /** * Flags to the various strip methods */ typedef enum StripType { leading=1, /**< only strip from the beginning of the string */ trailing, /**< only strip from the end of the string */ both /**< strip from both ends of the string */ } StripType; /** * Case sensitivity control constants */ typedef enum CompareCase { matchCase, /**< Case sensitive comparison */ ignoreCase /**< Case insensitive comparison */ } CompareCase; // ================================================================ /** @name Constructors */ ///@{ /// Default Constructor UtlString(); /// Constructor accepting a null terminated source string. UtlString(const char* szSource /**< initial string value */ ); /**< * The source string is copied to this object. */ /// Constructor accepting a source string with an explicit length. UtlString(const char* szSource, size_t length); /**< * Any zero byte in the source string is ignored; all length chars of the source * string are copied to this object. */ /// Copy the source UtlString. UtlString(const UtlString& source); /// Copy an initial substring. UtlString(const UtlString& source, size_t length); /**< * Constructor accepting a reference to another string and a length. * Up to length characters are copied from the source string into * this object. If length is greater than the length of source * this becomes a copy of source with the same data and length. */ /// Clone method for UtlCopyableContainable requirements virtual UtlCopyableContainable* clone() const; ///@} // ================================================================ /** @name Assignment Operators * */ ///@{ /// Replace the contents of this string with a null terminated string. UtlString& operator=(const char* szStr); /// Replace the contents of this string with contents of a UtlString UtlString& operator=(const UtlString& str); ///@} // ================================================================ /** @name Accessors * */ ///@{ /// The current length of the string value size_t length() const; /// Return a read-only pointer to the stored string value.. const char* data() const; /**< * This pointer should not be stored, since operations on the UtlString * may free it. * * The returned pointer is never null, even if the UtlString is * null or newly-allocated. * * The stored value will have a null byte at the end, but may also have * null bytes at other positions within the value. */ /// Cast to a const char* - identical to the data() method. operator const char*() const; /**< * Cast this object to a const char* pointer. This is exactly the * same as calling data(). */ /// Return the current capacity allocated for this string. size_t capacity() const; ///@} // ================================================================ /** @name Substring Operators * * Extract a portion of the string value. */ ///@{ /// Allows references of the form stringVar(start,length) - also see append UtlString operator() (size_t start, /**< Starting character position * (zero based) */ size_t len /**< Number of characters to copy or * UTLSTRING_TO_END for * "the rest of the string" */ ) const; /**< * An empty string is returned if the start and/or len is invalid. * * @note * This method constructs a temporary UtlString object. It will usually * be more efficient to use the append method taking a UtlString, position, * and length. * */ /// Get the character at position N. char operator()(size_t N); /** * @returns the nth character (zero based) * @code * UtlString aString("abc"); * char secondChar = aString(1); * @endcode * Sets secondChar to 'b' */ ///@} // ================================================================ /** @name Comparison Operations * */ ///@{ /// Return true if this is an empty string. UtlBoolean isNull() const; /// Compare this string to a null terminated string (case sensitive). virtual int compareTo(const char *) const; /**< * @returns 0 if equal, < 0 if less then and >0 if greater. */ /// Compare this string to a null terminated string, with case sensitivity control int compareTo(const char *, CompareCase type) const; /// Compare this object to another string, with case sensitivity control int compareTo(UtlString const *, CompareCase type) const; /**< * @returns 0 if equal, < 0 if less then and >0 if greater. */ /// Check for a null terminated value in this string. UtlBoolean contains(const char *) const; /**< * This is equivalent to ( index(str) != UTL_NOT_FOUND ) * * @return true if this string contains the specified string. */ friend UtlBoolean operator!=(const char *, const UtlString& ); friend UtlBoolean operator!=(const char , const UtlString& ); friend UtlBoolean operator==(const char , const UtlString& ); friend UtlBoolean operator==(const char *, const UtlString& ); UtlBoolean operator==(const char *) const; UtlBoolean operator!=(const char *) const; UtlBoolean operator==(const UtlString&) const; UtlBoolean operator!=(const UtlString&) const; ///@} // ================================================================ /** @name Search Operations * * Also see the regular expression search operations in the RegEx class. */ ///@{ /// Find the first instance of a single character. size_t index(char c) const; /**< * @return the offset of the first c or UTL_NOT_FOUND */ /// Find the first instance of a single character starting at a specified offset. size_t index(char c, size_t offset) const; /**< * @return the offset from the beginning of the string of the first c after * offset or UTL_NOT_FOUND */ /// Find the first instance of a single character. size_t first(char c) const; /**< * @return the offset of the first c or UTL_NOT_FOUND * * (this is the same as index(c) ) */ /// Find the first instance of a null terminated string. size_t index(const char* ) const; /**< * @return the offset of the first matching string or UTL_NOT_FOUND */ /// Find the first instance of a specified length string. size_t index(const char* , size_t ) const; /**< * The search target value may contain null characters. * * @return the offset of the first matching string or UTL_NOT_FOUND */ /// Find the first instance of a specified length string, with case control size_t index(const char* , size_t , CompareCase ) const; /**< * The search target value may contain null characters. * * @return the offset of the first matching string or UTL_NOT_FOUND */ /// Find the first match for the specified string (which may contain null characters) size_t index(const UtlString& ) const; /**< * The search target value may contain null characters. * * @return the offset of the first matching string or UTL_NOT_FOUND */ /// Find a match for the specified string starting at offset size_t index(const UtlString& match, ///< string value to search for size_t offset ///< offset in target to start search ) const; /**< * The search target value (match) may contain null characters. * * @return the offset from the beginning of the string of the match value * after offset or UTL_NOT_FOUND */ /// Find a match for the specified string starting at offset, with case sensitivity control size_t index(const UtlString& , size_t , CompareCase ) const; /**< * The search target value (match) may contain null characters. * * @return the offset from the beginning of the string of the match value * after offset or UTL_NOT_FOUND */ /// Find the first instance of a null terminated string size_t first(const char* ) const; /**< * @return the offset of the string or UTL_NOT_FOUND */ /// Find the last instance of a character size_t last(char s) const; /**< * @return the offset of the string or UTL_NOT_FOUND */ ///@} // ================================================================ /** @name Append Operations * * Append operations add to the end of the current value of the string. */ ///@{ /// Append a null terminated string to the end of the lvalue. UtlString& operator+=(const char *); /// Append a null terminated string to the end of this string. UtlString& append(const char* szStr); /// Append a UtlString to this string. UtlString& operator+=(const UtlString& s); /// Append a UtlString to this string. UtlString& append(const UtlString& str ///< source string ); /// Append a substring of a UtlString to this string. UtlString& append(const UtlString& str, ///< source string size_t position, ///< offset into source to start copy size_t length ///< length of substring to copy ); /**< * Note the difference between these two copies: * @code * UtlString source("0123456789"); * * UtlString destA; * destA = source(1,3); * * UtlString destB; * destB.append(source, 6, 2); * @endcode * The assignment to destA actually constructs a temporary UtlString on the * stack as the output of the source(1,3), invokes the copy constructor to * copy its contents into destA, and then destructs it. * * The assignment to destB copies the string contents directly from source * to destB. */ /// Append up to N bytes of the designated string to the end of this string. UtlString& append(const char* szStr, size_t N); /// Append a single character to the end of this string. UtlString& operator+=(const char c); /// Append a single character to the end of this string. UtlString& append(const char c); /// Append format string like pritnf UtlString& appendFormat(const char* format, ... ) #ifdef __GNUC__ /* with the -Wformat switch, this enables format string checking */ __attribute__ ((format(printf, 2, 3))) #endif ; ///@} // ================================================================ /** @name Insertion Operators * * These methods insert values into the string; the capacity is increased * as needed to hold the additional value. * * Nothing is overwritten - Any existing value at the insertion point is * shifted to make room. */ ///@{ /// Insert a UtlString UtlString& insert(size_t position, ///< position to insert the src string. const UtlString& src ///< value to be inserted ); /**< * If an invalid position is specified, nothing is performed. */ /// Insert a single character UtlString& insert(size_t position, ///< position to insert newChar. const char newChar ///< character to insert ); /**< * If an invalid position is specified, nothing is performed. */ /// Insert a null terminated string UtlString& insert(size_t position, ///< position to insert src C string const char* src ///< null terminated string to insert ); /**< * If an invalid position is specified, nothing is performed. */ /// Prepend a null terminated string at the beginning of this string. UtlString& prepend(const char* szStr); /**< Equivalent to insert(0, szStr); */ /// Insert arbitrary length value UtlString& insert(size_t position, ///< position to insert src value const char* src, ///< value to insert (may contain null bytes) size_t sourceLenth ///< number of bytes to insert ); /**< * Insert the value at character position. * * If an invalid position is specified, nothing is performed. */ ///@} // ================================================================ /** @name Replacement Operations * */ ///@{ /// Replace a single character at the designated position. void replaceAt(size_t pos, ///< offset into data to replace - must be < the length char newChar ///< character to be put into that offset ); /// Replace all instances of character src with character tgt. UtlString& replace(const char src, const char tgt); /// Replace N characters from a char*. UtlString& replace(size_t pos, ///< position in string to begin replacing size_t N, ///< number of characters to replace const char* replaceStr ///< replacement value ); /**< * Replace N characters starting at the designated position with the * designated replacement string. Invalid position or length results * in no changes. */ /// Replace N characters from a char*, with specified length string. UtlString& replace(size_t pos, ///< starting position of the replacement size_t N, ///< number of characters to replace const char* replaceStr, ///< target replacement string size_t L ///< maximum number of characters of the replacement string to use. ); /**< * Replace N characters starting at the designated position with a subset * of the designated replacement string. Invalid position or length results * in no changes. */ /// Replace N characters from another UtlString. UtlString& replace(size_t pos, ///< position in string to begin replacing size_t N, ///< number of characters to replace const UtlString& replaceStr ///< replacement value ); /**< * Replace N characters starting at the designated position with the * designated replacement string. Invalid position or length results * in no changes. */ ///@} // ================================================================ /** @name Concatenation Operations * */ ///@{ /// Concatenate two UtlStrings as: s1 + s2 friend UtlString operator+(const UtlString& s1, const UtlString& s2); /// Concatenate a UtlString with a constant string as: s + c friend UtlString operator+(const UtlString& s, const char* c); /// Concatenate a constant string with a UtlString as: c + s friend UtlString operator+(const char* c, const UtlString& s); ///@} // ================================================================ /** @name Remove Operations * * Also see Stripping and Trimming, below */ ///@{ /// Remove all characters after the specified position. UtlString& remove(size_t pos); /**< * Nothing is performed if the position is invalid. */ /// Remove N characters from this string starting at designated position. UtlString& remove(size_t pos, size_t N); /**< * Invalid position or length results in no changes. */ ///@} // ================================================================ /** @name Stripping and Trimming Operations * */ ///@{ /// Removes whitespace (space, tab, Cr, Lf) from the end of the string. UtlString strip(); /// Removes whitespace (space, tab, Cr, Lf) from either or both ends of the string. UtlString strip(StripType whichEnd); /**< * Removes whitespace (space, tab, Cr, Lf) from the beginning of the string, * from the end of the string, or from both the beginning and end of the * string. */ /// Removes all instances of the specified character from either or both ends of the string. UtlString strip(StripType whichEnd, char charToStrip); /**< * Remove the designated character from the beginning of the string, * from the end of the string, or from both the beginning and end of * the string. */ ///@} // ================================================================ /** @name Case Conversion Operations * */ ///@{ /** * Convert the string to all lower case characters (e.g. AbC1 -> abc1) */ void toLower(); /** * Convert the string to all upper case characters (e.g. AbC1 -> ABC1) */ void toUpper(); ///@} // ================================================================ /** @name Capacity Management * */ ///@{ /// Set the minimum capacity a string can hold without reallocation. size_t capacity(size_t N); /**< * Set the string's storage capacity to the designated value. * This does not modify the value of the string, but rather * adjusts the dynamic memory allocated for this string. * * This never reduces the capacity - any size less then the * current capacity is a no-op. * * @return The new capacity that was set. In case of success, it * may be greater than the requested capacity. In case of failure, * it may be less than the requested capacity. */ /// Set a new size for the string. void resize(size_t N, UtlBoolean clearTail=TRUE); /**< * Resize the string to the specified size. If the requested size is less * then the the current size (string length), the string will be truncated. * If requested size is larger then current size and \a clearTail is TRUE * (default), the string will be padded with nulls. If \a clearTail is * FALSE, string will not be padded with nulls. */ ///@} // ================================================================ /** @name Container Support Operations * */ ///@{ /// Calculate a hash over the string contents. virtual unsigned hash() const; /**< * If the equals operator returns true for another object, then both * objects must return the same hashcode. */ /// Determine whether or not the values in a containable are comparable. virtual UtlContainableType getContainableType() const; /**< * This returns a unique type for UtlString */ /// Compare to any other UtlContainable virtual int compareTo(UtlContainable const *other) const; /**< * Compare this object to another containable object. * If the UtlContainableType of the other object is not the UtlString type, * this will return unequal. * * @returns 0 if equal, < 0 if less than, and > 0 if greater. */ virtual UtlBoolean isEqual(UtlContainable const *) const; /**< * Test this object to another like-object for equality. This method * returns false if unlike-objects are specified. */ /// @copydoc UtlContainable::isInstanceOf virtual UtlBoolean isInstanceOf(const UtlContainableType type) const; ///@} // ================================================================ /** @name Destructors * */ ///@{ /// Destructor virtual ~UtlString(); ///@} /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: char* mpData; //: The value of UtlString. size_t mSize; //: The number of bytes of data used. size_t mCapacity; //: The allocated size of data. char mBuiltIn[DEFAULT_UTLSTRING_CAPACITY]; }; /* ============================ INLINE METHODS ============================ */ #endif // _UtlString_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlVoidPtr.h0000644000175000017500000000606012205613256024335 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlVoidPtr_h_ #define _UtlVoidPtr_h_ // SYSTEM INCLUDES #include "os/OsDefs.h" // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlContainable.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /// UtlVoidPtr is a UtlContainable wrapper for a void ptr. /** * This class has serious potential to create memory leaks and type casting * errors. Please consider just making the class you want to put into a * container a UtlContainable - it just requires implementing a couple of * methods, and can often be done by just inheriting from one of the existing * UtlContainable classes. In the simplest case, you can use UtlContainableAtomic; * it requires only that you define a new UtlContainableType constant and the * method to read it. */ class UtlVoidPtr : public UtlContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: static const UtlContainableType TYPE ; /** < Class type used for runtime checking */ /* ============================ CREATORS ================================== */ /** * Constructor accepting an optional default value. */ UtlVoidPtr(void * pPtr = NULL) ; /** * Destructor */ virtual ~UtlVoidPtr() ; /* ============================ MANIPULATORS ============================== */ /** * Set a new void ptr value for this object. * * @returns the old value */ void* setValue(void *) ; /* ============================ ACCESSORS ================================= */ /** * Get the void ptr wrapped by this object. */ void* getValue() const ; /** * Calculate a unique hash code for this object. If the equals * operator returns true for another object, then both of those * objects must return the same hashcode. */ virtual unsigned hash() const ; /** * Get the ContainableType for a UtlContainable derived class. */ virtual UtlContainableType getContainableType() const; /* ============================ INQUIRY =================================== */ /** * Compare the this object to another like-objects. Results for * designating a non-like object are undefined. * * @returns 0 if equal, < 0 if less then and >0 if greater. */ virtual int compareTo(UtlContainable const *) const ; /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: void* mpValue ; /** < The void ptr wrapped by this object */ } ; /* ============================ INLINE METHODS ============================ */ #endif // _UtlVoidPtr_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlTokenizer.h0000644000175000017500000000413312205613256024717 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlTokenizer_h_ #define _UtlTokenizer_h_ // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * C++ version of strtok, but obvisously reentrant. */ class UtlTokenizer { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /** * Default constructor */ UtlTokenizer(const UtlString &tokens); /** * Destructor */ virtual ~UtlTokenizer(); /* ============================ MANIPULATORS ============================== */ static int nextDelim(const char *tokens, const int start, const int len, const char *delim); static UtlBoolean isDelim(const char c, const char *delim); /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ UtlBoolean next(UtlString &token, const char *delim); /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: char *m_tokens; int m_tokenPosition; /** * Copy constructor */ UtlTokenizer(const UtlTokenizer& rUtlTokenizer); /** * Assignment operator * * @param rhs right hand side of the equals operator */ UtlTokenizer& operator=(const UtlTokenizer& rhs); }; /* ============================ INLINE METHODS ============================ */ #endif // _UtlTokenizer_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/XmlContent.h0000644000175000017500000000537212205613256024361 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _XmlContent_h_ #define _XmlContent_h_ // SYSTEM INCLUDES #include "os/OsDefs.h" // APPLICATION INCLUDES #include "utl/UtlString.h" // DEFINES #define XML_VERSION_1_0 "\n" // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * XmlContent provides conversion functions for escaping and unescaping UtlStrings * as appropriate for use in XML attribute and element content. * * At present, this makes no accomodation for character set differences; input is assumed * to be 8 bits. The following characters are encoded using the mandatory character * entities: * - < => < * - & => & * - > => > * - ' => ' * - " => " * * Other character values outside the range of valid 8-bit characters in XML: * - #x09 | #x0A | #x0D | [#x20-#FF] * are encoded using the numeric entity encoding (&#x??;). * * While this is not strictly XML conformant (in that it does not explicitly deal with * larger-size character encodings), it is symmetric (esaping and unescaping any string * these routines will always produce the original string), and will interoperate correctly * for any 8 bit encoding. */ /// Append escaped source string onto destination string bool XmlEscape(UtlString& destination, const UtlString& source); /**< * The contents of the source string are appended to the destination string, with all * characters escaped as described above. * @returns true for success, false if an error was returned from any UtlString operation. */ /// Append unescaped source string onto destination string bool XmlUnEscape(UtlString& destination, const UtlString& source); /**< * The contents of the source string are appended to the destination string, with all * characters unescaped as described above. * @returns true for success, false if an error was returned from any UtlString operation. */ /// Append decimal string onto destination string bool XmlDecimal(UtlString& destination, int source, const char* format = NULL); /**< * The source value is converted into a decimal string according to * "format". The decimal string is appended to the destination string. * "format" defaults to "%d", and must generate no more than 20 characters, * (excluding the ending NUL). * @returns true for success, false if an error was returned from any UtlString operation. */ #endif // _XmlContent_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlSortedListIterator.h0000644000175000017500000000346112205613256026556 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlSortedListIterator_h_ #define _UtlSortedListIterator_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlDefs.h" #include "utl/UtlListIterator.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class UtlContainable; class UtlSortedList; /** * UtlSortedListIterator allows developers to iterator (walks through) an * UtlSortedList. * * @see UtlIterator * @see UtlSortedList */ class UtlSortedListIterator : public UtlListIterator { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /** * Constructor accepting a source UtlSortedList */ UtlSortedListIterator(const UtlSortedList& list); /* ============================ MANIPULATORS ============================== */ /** * Find the designated object, and reset the iterator so that it is the current position. * * @return The element or NULL if no more elements are available. */ virtual UtlContainable* findNext(const UtlContainable* objectToFind); /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: friend class UtlSortedList; /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _UtlSortedListIterator_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/UtlRandom.h0000644000175000017500000000351612205613256024171 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _UtlRandom_h_ #define _UtlRandom_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * A simple utility class that provides random number functionality. * Generally, you should create a UtlRandom class for each of your thread * contexts. The implementation uses rand() and srand(). */ class UtlRandom { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ /** * Default constructors, seeds the random number generator with the current * time. */ UtlRandom(); /** * Constructor accepting a seed for the random number generator. */ UtlRandom(int seed); /** * Destructor */ virtual ~UtlRandom(); /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /** * Generate a pseudo-random number between 0 and RAND_MAX (defined in * stdlib.h) */ int rand() ; /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _UtlRandom_h_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/Plugin.h0000644000175000017500000000760212205613256023522 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _PLUGIN_H_ #define _PLUGIN_H_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlString.h" class OsConfigDb; // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class Plugin; /** * A Plugin is a dynamically loaded object that is invoked by some component at some * well defined time (it's an abstract class - how specific can the * description be?). * * This class is the abstract base from which all plugins must inherit; it * decouples the configuration of what plugins should be invoked and the * configuration parameters specific to each plugin from the program that * uses them. * * @htmlinclude PluginOverview.html * * All Plugin classes must implement three methods to configure the plugin * into the component: * - An extern "C" factory routine * - The constructor for its class, which must ultimately derive from Plugin * - The readConfig method used to pass configuration data to the plugin (this decouples plugin * configuration from the component configuration). * * Each class derived from Plugin should also define the method(s) that * the program should invoke on the plugin, and all those methods must be virtual. * * @see PluginHooks for details of how a plugin is configured into a program, * and PluginIterator for how plugins are invoked by the calling component. * */ class Plugin { public: typedef Plugin* (*Factory)(const UtlString& pluginName); /**< * The Factory uses external C linkage to support dynamic loading of Plugin objects. * * In addition to the class derived from this base, a plugin must implement a * Factory routine with extern "C" linkage so that the OsSharedLib mechanism * can look it up in the dynamically loaded library (looking up C++ symbols * is problematic because of name mangling). The Factory routine looks like: * @code * class ExamplePlugin; * * extern "C" ExamplePlugin* getExamplePlugin(const UtlString& name) * { * return new ExamplePlugin; * } * * class ExamplePlugin : public Plugin * { * friend ExamplePlugin* getExamplePlugin(const UtlString& name); * ... * private: * ExamplePlugin(const UtlString& name); * } * @endcode */ /// The plugin destructor must be virtual. virtual ~Plugin() { }; /// Read (or re-read) whatever configuration the plugin requires. virtual void readConfig( OsConfigDb& configDb /**< a subhash of the individual configuration * parameters for this instance of this plugin. */ ) = 0; /**< * @note * The parent service may call the readConfig method at any time to * indicate that the configuration may have changed. The plugin * should reinitialize itself based on the configuration that exists when * this is called. The fact that it is a subhash means that whatever prefix * is used to identify the plugin (see PluginHooks) has been removed (see the * examples in PluginHooks::readConfig). */ protected: /// Derived constructors should be private so that only the Factory can call them. Plugin(const UtlString& instanceName) : mInstanceName(instanceName) { }; /// The instance name from the configuration directive - for logging and other identification. UtlString mInstanceName; private: /// There is no copy constructor. Plugin(const Plugin&); /// There is no assignment operator. Plugin& operator=(const Plugin&); }; #endif // _PLUGIN_H_ sipxtapi-3.3.0~test17/sipXportLib/include/utl/PluginHooks.h0000644000175000017500000001433412205613256024526 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _PLUGINHOOKS_H_ #define _PLUGINHOOKS_H_ // SYSTEM INCLUDES #include "utl/UtlSortedList.h" #include "utl/UtlSortedListIterator.h" // APPLICATION INCLUDES // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS class Plugin; class PluginIterator; class OsConfigDb; /** * A PluginHooks object is used to add dynamically loaded libraries (a "plugin") * to a program at run time. The module to be loaded must implement a class * derived from the Plugin abstract class. * * An object of this class manages all the configured plugin hooks for a program. * A class of plugin hooks is identified by a factory routine name used to obtain * a hook instance from the dynamic library, and an OsConfigDb prefix string: * @code * // to be called for each Action * PluginHooks ActionEventHooks("getFooAction", "ACTION_EVENT"); * @endcode * * The libraries are loaded and configured by the readConfig method: * @code * ActionEventHooks.readConfig(configDb); * @endcode * * To invoke the plugins, see PluginIterator. */ class PluginHooks { public: /// Construct a manager for a set of hooks. PluginHooks(const char* hookFactoryName, ///< The factory routine name for this hook class. const char* hookPrefix ///< The prefix name for the OsConfigDb values. ); ~PluginHooks(); /// Read what hooks are configured, and instantiate and configure each hook. void readConfig( OsConfigDb& configDb ); /**< * This method actually reads the program configuration from the configDb * passed in. Each entry that has the prefix followed by "_HOOK_LIBRARY" * configures a plugin library. * @code * [prefix]_HOOK_LIBRARY.[instance] : [path to libexamplereghook.so] * @endcode * For the example code above, it would look for entries like: * @code * ACTION_EVENT_HOOK_LIBRARY.RecordAction : /usr/local/lib/sipxpbx/librecordaction.so * ACTION_EVENT_HOOK_LIBRARY.CopyAction : /usr/local/lib/sipxpbx/libcopyaction.so * @endcode * The readConfig method: * - dynamically loads each library * - for each value of [instance] * - calls the factory method provided by the hook to instantiate a hook * object, passing its instance name to it (so that it can be used in * logging). * - passes the new hook object a configuration subhash of its * configuration entries (if any). * * Configuration entries for each hook instance are made with entries like: * @code * [prefix].[instance].FOO : foovalue * [prefix].[instance].BAR : barvalue * @endcode * Each instance has its own set of configuration entries: * @code * ACTION_EVENT.RecordAction.FOO : foovalue1 * ACTION_EVENT.RecordAction.BAR : barvalue1 * ACTION_EVENT.CopyAction.FOO : foovalue2 * ACTION_EVENT.CopyAction.BAR : barvalue2 * @endcode * * The readConfig method in the hook (which must inherit from Plugin) is * passed its own subhash of the configuration data, stripping everything * through the '.' following the instance name, so in the example above, * the CopyAction hook would be passed the equivalent of this configuration: * @code * FOO : foovalue2 * BAR : barvalue2 * @endcode * * readConfig can be called more than once. * - New plugin instances are instantiated as described above. * - Existing plugin instances that are no longer in the configuration * are deleted (their destructor is invoked). * - Existing plugin instances that are still in the configuration * are reconfigured (their Plugin::readConfig method is called). * */ /// Return the total number of plugins within. size_t entries() const; protected: friend class PluginIterator; UtlString mFactory; ///< The factory routine name for this hook class UtlString mPrefix; ///< The prefix name for the OsConfigDb values UtlSortedList mConfiguredHooks; ///< The list of configured hooks. }; /** * PluginIterator is used to obtain a sequence of Plugin objects to be invoked. * * The calling program gets the plugin objects by creating a PluginIterator * over a Plugin object and then calling the PluginIterator::next method to * get each instance of the Plugin (and optionally, its instance name). * * The PluginIterator always returns the configured Plugin objects in lexical * order by the instance name; this allows the configuration to control the * order in which they are invoked. * * Plugin libraries can implement any calling interface that's needed (a program * that uses the Plugin mechanism should create a base class that extends * Plugin to specify the interface). * * A typical usage would look like: * @code * PluginIterator actions(ActionEventHooks); * YourPluginClass* action; * while(action = static_cast(actions.next())) * { * action->invokeMethod(); * } * @endcode */ class PluginIterator { public: /// Create an iterator that returns each instance managed by a PluginHooks object. PluginIterator(const PluginHooks& pluginHooks); ~PluginIterator(); /// Advance to and return the next plugin. Plugin* next(UtlString* name = NULL /**< The instance name string for * the returned Plugin (for logging * purposes). May be NULL if the caller * does not need the name. */ ); /**< * No meaning should be attached to Plugin names, so that order of plugin * iteration can be controlled by the lexical order of plugin names. */ private: UtlSortedListIterator mConfiguredHooksIterator; }; #endif // _PLUGINHOOKS_H_ sipxtapi-3.3.0~test17/sipXportLib/include/xmlparser/0000755000175000017500000000000012321445025023313 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/include/xmlparser/ExtractContent.h0000644000175000017500000000110012205613256026425 0ustar00danieldaniel00000000000000// Functions for extracting the text content of an XML element. #include "xmlparser/tinyxml.h" #include "utl/UtlString.h" // Get the top-level text content of an XML element. void textContentShallow(UtlString& string, TiXmlElement *element); // Get the complete text content of an XML element (including sub-elements). void textContentDeep(UtlString& string, TiXmlElement *element); // Service function for textContentDeep. void textContentDeepRecursive(UtlString& string, TiXmlElement *element); sipxtapi-3.3.0~test17/sipXportLib/include/xmlparser/tinystr.h0000644000175000017500000001420412205613256025205 0ustar00danieldaniel00000000000000/* www.sourceforge.net/projects/tinyxml Original file by Yves Berquin. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "tinyxml.h" #ifndef TIXML_USE_STL #ifndef TIXML_STRING_INCLUDED #define TIXML_STRING_INCLUDED #ifdef _MSC_VER #pragma warning( disable : 4530 ) #pragma warning( disable : 4786 ) #endif #include /* TiXmlString is an emulation of the std::string template. Its purpose is to allow compiling TinyXML on compilers with no or poor STL support. Only the member functions relevant to the TinyXML project have been implemented. The buffer allocation is made by a simplistic power of 2 like mechanism : if we increase a string and there's no more room, we allocate a buffer twice as big as we need. */ class TiXmlString { public : // TiXmlString constructor, based on a string, mark explicit to force // us to find unnecessary casting. explicit TiXmlString (const char * instring); // TiXmlString empty constructor TiXmlString () { allocated = 0; cstring = NULL; current_length = 0; } // TiXmlString copy constructor explicit TiXmlString (const TiXmlString& copy); // TiXmlString destructor ~ TiXmlString () { empty_it (); } // Convert a TiXmlString into a classical char * const char * c_str () const { if (allocated) return cstring; return ""; } // Return the length of a TiXmlString size_t length () const { return ( allocated ) ? current_length : 0; } // TiXmlString = operator void operator = (const char * content); // = operator void operator = (const TiXmlString & copy); // += operator. Maps to append TiXmlString& operator += (const char * suffix) { append (suffix); return *this; } // += operator. Maps to append TiXmlString& operator += (char single) { append (single); return *this; } // += operator. Maps to append TiXmlString& operator += (TiXmlString & suffix) { append (suffix); return *this; } bool operator == (const TiXmlString & compare) const; bool operator == (const char* compare) const; bool operator < (const TiXmlString & compare) const; bool operator > (const TiXmlString & compare) const; // Checks if a TiXmlString is empty bool empty () const { return length () ? false : true; } // single char extraction const char& at (unsigned index) const { assert( index < length ()); return cstring [index]; } // find a char in a string. Return TiXmlString::notfound if not found unsigned find (char lookup) const { return find (lookup, 0); } // find a char in a string from an offset. Return TiXmlString::notfound if not found unsigned find (char tofind, unsigned offset) const; /* Function to reserve a big amount of data when we know we'll need it. Be aware that this function clears the content of the TiXmlString if any exists. */ void reserve (unsigned size) { empty_it (); if (size) { allocated = size; cstring = new char [size]; cstring [0] = 0; current_length = 0; } } // [] operator char& operator [] (unsigned index) const { assert( index < length ()); return cstring [index]; } // Error value for find primitive enum { notfound = 0xffffffff, npos = notfound }; void append (const char *str, size_t len ); protected : // The base string char * cstring; // Number of chars allocated size_t allocated; // Current string size size_t current_length; // New size computation. It is simplistic right now : it returns twice the amount // we need size_t assign_new_size (size_t minimum_to_allocate) { return minimum_to_allocate * 2; } // Internal function that clears the content of a TiXmlString void empty_it () { if (cstring) delete [] cstring; cstring = NULL; allocated = 0; current_length = 0; } void append (const char *suffix ); // append function for another TiXmlString void append (const TiXmlString & suffix) { append (suffix . c_str ()); } // append for a single char. void append (char single) { if ( cstring && current_length < (allocated-1) ) { cstring[ current_length ] = single; ++current_length; cstring[ current_length ] = 0; } else { char smallstr [2]; smallstr [0] = single; smallstr [1] = 0; append (smallstr); } } } ; /* TiXmlOutStream is an emulation of std::ostream. It is based on TiXmlString. Only the operators that we need for TinyXML have been developped. */ class TiXmlOutStream : public TiXmlString { public : TiXmlOutStream () : TiXmlString () {} // TiXmlOutStream << operator. Maps to TiXmlString::append TiXmlOutStream & operator << (const char * in) { append (in); return (* this); } // TiXmlOutStream << operator. Maps to TiXmlString::append TiXmlOutStream & operator << (const TiXmlString & in) { append (in . c_str ()); return (* this); } } ; #ifdef _MSC_VER #pragma warning( default : 4530 ) #pragma warning( default : 4786 ) #endif #endif // TIXML_STRING_INCLUDED #endif // TIXML_USE_STL sipxtapi-3.3.0~test17/sipXportLib/include/xmlparser/tinyxml.h0000644000175000017500000014065112205613256025203 0ustar00danieldaniel00000000000000/* www.sourceforge.net/projects/tinyxml Original code (2.0 and earlier )copyright (c) 2000-2002 Lee Thomason (www.grinninglizard.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef TINYXML_INCLUDED #define TINYXML_INCLUDED #ifdef _MSC_VER #pragma warning( disable : 4530 ) #pragma warning( disable : 4786 ) #endif #include #include #include #include #include // Help out windows: #if defined( _DEBUG ) && !defined( DEBUG ) #define DEBUG #endif #if defined( DEBUG ) && defined( _MSC_VER ) #define WIN32_LEAN_AND_MEAN #include #define TIXML_LOG OutputDebugString #else #define TIXML_LOG printf #endif #ifdef TIXML_USE_STL #include #include #define TIXML_STRING std::string #define TIXML_ISTREAM std::istream #define TIXML_OSTREAM std::ostream #else #include "tinystr.h" #define TIXML_STRING TiXmlString #define TIXML_OSTREAM TiXmlOutStream #endif class TiXmlDocument; class TiXmlElement; class TiXmlComment; class TiXmlUnknown; class TiXmlAttribute; class TiXmlText; class TiXmlDeclaration; class TiXmlParsingData; const int TIXML_MAJOR_VERSION = 2; const int TIXML_MINOR_VERSION = 3; const int TIXML_PATCH_VERSION = 4; /* Internal structure for tracking location of items in the XML file. */ struct TiXmlCursor { TiXmlCursor() { Clear(); } void Clear() { row = col = -1; } int row; // 0 based. int col; // 0 based. }; // Only used by Attribute::Query functions enum { TIXML_SUCCESS, TIXML_NO_ATTRIBUTE, TIXML_WRONG_TYPE }; // Used by the parsing routines. enum TiXmlEncoding { TIXML_ENCODING_UNKNOWN, TIXML_ENCODING_UTF8, TIXML_ENCODING_LEGACY }; const TiXmlEncoding TIXML_DEFAULT_ENCODING = TIXML_ENCODING_UNKNOWN; /** TiXmlBase is a base class for every class in TinyXml. It does little except to establish that TinyXml classes can be printed and provide some utility functions. In XML, the document and elements can contain other elements and other types of nodes. @verbatim A Document can contain: Element (container or leaf) Comment (leaf) Unknown (leaf) Declaration( leaf ) An Element can contain: Element (container or leaf) Text (leaf) Attributes (not on tree) Comment (leaf) Unknown (leaf) A Decleration contains: Attributes (not on tree) @endverbatim */ class TiXmlBase { friend class TiXmlNode; friend class TiXmlElement; friend class TiXmlDocument; public: TiXmlBase() : userData(0) {} virtual ~TiXmlBase() {} /** All TinyXml classes can print themselves to a filestream. This is a formatted print, and will insert tabs and newlines. (For an unformatted stream, use the << operator.) */ virtual void Print( FILE* cfile, int depth ) const = 0; /** The world does not agree on whether white space should be kept or not. In order to make everyone happy, these global, static functions are provided to set whether or not TinyXml will condense all white space into a single space or not. The default is to condense. Note changing this values is not thread safe. */ static void SetCondenseWhiteSpace( bool condense ) { condenseWhiteSpace = condense; } /// Return the current white space setting. static bool IsWhiteSpaceCondensed() { return condenseWhiteSpace; } /** Return the position, in the original source file, of this node or attribute. The row and column are 1-based. (That is the first row and first column is 1,1). If the returns values are 0 or less, then the parser does not have a row and column value. Generally, the row and column value will be set when the TiXmlDocument::Load(), TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set when the DOM was created from operator>>. The values reflect the initial load. Once the DOM is modified programmatically (by adding or changing nodes and attributes) the new values will NOT update to reflect changes in the document. There is a minor performance cost to computing the row and column. Computation can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value. @sa TiXmlDocument::SetTabSize() */ int Row() const { return location.row + 1; } int Column() const { return location.col + 1; } ///< See Row() void SetUserData( void* user ) { userData = user; } void* GetUserData() { return userData; } // Table that returns, for a given lead byte, the total number of bytes // in the UTF-8 sequence. static const int utf8ByteTable[256]; virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding /*= TIXML_ENCODING_UNKNOWN */ ) = 0; enum { TIXML_NO_ERROR = 0, TIXML_ERROR, TIXML_ERROR_OPENING_FILE, TIXML_ERROR_OUT_OF_MEMORY, TIXML_ERROR_PARSING_ELEMENT, TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, TIXML_ERROR_READING_ELEMENT_VALUE, TIXML_ERROR_READING_ATTRIBUTES, TIXML_ERROR_PARSING_EMPTY, TIXML_ERROR_READING_END_TAG, TIXML_ERROR_PARSING_UNKNOWN, TIXML_ERROR_PARSING_COMMENT, TIXML_ERROR_PARSING_DECLARATION, TIXML_ERROR_DOCUMENT_EMPTY, TIXML_ERROR_EMBEDDED_NULL, TIXML_ERROR_STRING_COUNT }; protected: // See STL_STRING_BUG // Utility class to overcome a bug. class StringToBuffer { public: StringToBuffer( const TIXML_STRING& str ); ~StringToBuffer(); char* buffer; }; static const char* SkipWhiteSpace( const char*, TiXmlEncoding encoding ); inline static bool IsWhiteSpace( char c ) { return ( isspace( (unsigned char) c ) || c == '\n' || c == '\r' ); } virtual void StreamOut (TIXML_OSTREAM *) const = 0; #ifdef TIXML_USE_STL static bool StreamWhiteSpace( TIXML_ISTREAM * in, TIXML_STRING * tag ); static bool StreamTo( TIXML_ISTREAM * in, int character, TIXML_STRING * tag ); #endif /* Reads an XML name into the string provided. Returns a pointer just past the last character of the name, or 0 if the function has an error. */ static const char* ReadName( const char* p, TIXML_STRING* name, TiXmlEncoding encoding ); /* Reads text. Returns a pointer past the given end tag. Wickedly complex options, but it keeps the (sensitive) code in one place. */ static const char* ReadText( const char* in, // where to start TIXML_STRING* text, // the string read bool ignoreWhiteSpace, // whether to keep the white space const char* endTag, // what ends this text bool ignoreCase, // whether to ignore case in the end tag TiXmlEncoding encoding ); // the current encoding // If an entity has been found, transform it into a character. static const char* GetEntity( const char* in, char* value, int* length, TiXmlEncoding encoding ); // Get a character, while interpreting entities. // The length can be from 0 to 4 bytes. inline static const char* GetChar( const char* p, char* _value, int* length, TiXmlEncoding encoding ) { assert( p ); if ( encoding == TIXML_ENCODING_UTF8 ) { *length = utf8ByteTable[ *((unsigned char*)p) ]; assert( *length >= 0 && *length < 5 ); } else { *length = 1; } if ( *length == 1 ) { if ( *p == '&' ) return GetEntity( p, _value, length, encoding ); *_value = *p; return p+1; } else if ( *length ) { strncpy( _value, p, *length ); return p + (*length); } else { // Not valid text. return 0; } } // Puts a string to a stream, expanding entities as it goes. // Note this should not contian the '<', '>', etc, or they will be transformed into entities! static void PutString( const TIXML_STRING& str, TIXML_OSTREAM* out ); static void PutString( const TIXML_STRING& str, TIXML_STRING* out ); // Return true if the next characters in the stream are any of the endTag sequences. // Ignore case only works for english, and should only be relied on when comparing // to Engilish words: StringEqual( p, "version", true ) is fine. static bool StringEqual( const char* p, const char* endTag, bool ignoreCase, TiXmlEncoding encoding ); static const char* errorString[ TIXML_ERROR_STRING_COUNT ]; TiXmlCursor location; /// Field containing a generic user pointer void* userData; // None of these methods are reliable for any language except English. // Good for approximation, not great for accuracy. static int IsAlpha( unsigned char anyByte, TiXmlEncoding encoding ); static int IsAlphaNum( unsigned char anyByte, TiXmlEncoding encoding ); inline static int ToLower( int v, TiXmlEncoding encoding ) { if ( encoding == TIXML_ENCODING_UTF8 ) { if ( v < 128 ) return tolower( v ); return v; } else { return tolower( v ); } } static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); private: TiXmlBase( const TiXmlBase& ); // not implemented. void operator=( const TiXmlBase& base ); // not allowed. struct Entity { const char* str; unsigned int strLength; char chr; }; enum { NUM_ENTITY = 5, MAX_ENTITY_LENGTH = 6 }; static Entity entity[ NUM_ENTITY ]; static bool condenseWhiteSpace; }; /** The parent class for everything in the Document Object Model. (Except for attributes). Nodes have siblings, a parent, and children. A node can be in a document, or stand on its own. The type of a TiXmlNode can be queried, and it can be cast to its more defined type. */ class TiXmlNode : public TiXmlBase { friend class TiXmlDocument; friend class TiXmlElement; public: #ifdef TIXML_USE_STL /** An input stream operator, for every class. Tolerant of newlines and formatting, but doesn't expect them. */ friend std::istream& operator >> (std::istream& in, TiXmlNode& base); /** An output stream operator, for every class. Note that this outputs without any newlines or formatting, as opposed to Print(), which includes tabs and new lines. The operator<< and operator>> are not completely symmetric. Writing a node to a stream is very well defined. You'll get a nice stream of output, without any extra whitespace or newlines. But reading is not as well defined. (As it always is.) If you create a TiXmlElement (for example) and read that from an input stream, the text needs to define an element or junk will result. This is true of all input streams, but it's worth keeping in mind. A TiXmlDocument will read nodes until it reads a root element, and all the children of that root element. */ friend std::ostream& operator<< (std::ostream& out, const TiXmlNode& base); /// Appends the XML node or attribute to a std::string. friend std::string& operator<< (std::string& out, const TiXmlNode& base ); #else // Used internally, not part of the public API. friend TIXML_OSTREAM& operator<< (TIXML_OSTREAM& out, const TiXmlNode& base); #endif /** The types of XML nodes supported by TinyXml. (All the unsupported types are picked up by UNKNOWN.) */ enum NodeType { DOCUMENT, ELEMENT, COMMENT, UNKNOWN, TEXT, DECLARATION, TYPECOUNT }; virtual ~TiXmlNode(); /** The meaning of 'value' changes for the specific type of TiXmlNode. @verbatim Document: filename of the xml file Element: name of the element Comment: the comment text Unknown: the tag contents Text: the text string @endverbatim The subclasses will wrap this function. */ const char * Value() const { return value.c_str (); } /** Changes the value of the node. Defined as: @verbatim Document: filename of the xml file Element: name of the element Comment: the comment text Unknown: the tag contents Text: the text string @endverbatim */ void SetValue(const char * _value) { value = _value;} #ifdef TIXML_USE_STL /// STL std::string form. void SetValue( const std::string& _value ) { StringToBuffer buf( _value ); SetValue( buf.buffer ? buf.buffer : "" ); } #endif /// Delete all the children of this node. Does not affect 'this'. void Clear(); /// One step up the DOM. TiXmlNode* Parent() { return parent; } const TiXmlNode* Parent() const { return parent; } const TiXmlNode* FirstChild() const { return firstChild; } ///< The first child of this node. Will be null if there are no children. TiXmlNode* FirstChild() { return firstChild; } const TiXmlNode* FirstChild( const char * value ) const; ///< The first child of this node with the matching 'value'. Will be null if none found. TiXmlNode* FirstChild( const char * value ); ///< The first child of this node with the matching 'value'. Will be null if none found. const TiXmlNode* LastChild() const { return lastChild; } /// The last child of this node. Will be null if there are no children. TiXmlNode* LastChild() { return lastChild; } const TiXmlNode* LastChild( const char * value ) const; /// The last child of this node matching 'value'. Will be null if there are no children. TiXmlNode* LastChild( const char * value ); #ifdef TIXML_USE_STL const TiXmlNode* FirstChild( const std::string& _value ) const { return FirstChild (_value.c_str ()); } ///< STL std::string form. TiXmlNode* FirstChild( const std::string& _value ) { return FirstChild (_value.c_str ()); } ///< STL std::string form. const TiXmlNode* LastChild( const std::string& _value ) const { return LastChild (_value.c_str ()); } ///< STL std::string form. TiXmlNode* LastChild( const std::string& _value ) { return LastChild (_value.c_str ()); } ///< STL std::string form. #endif /** An alternate way to walk the children of a node. One way to iterate over nodes is: @verbatim for( child = parent->FirstChild(); child; child = child->NextSibling() ) @endverbatim IterateChildren does the same thing with the syntax: @verbatim child = 0; while( child = parent->IterateChildren( child ) ) @endverbatim IterateChildren takes the previous child as input and finds the next one. If the previous child is null, it returns the first. IterateChildren will return null when done. */ const TiXmlNode* IterateChildren( const TiXmlNode* previous ) const; TiXmlNode* IterateChildren( TiXmlNode* previous ); /// This flavor of IterateChildren searches for children with a particular 'value' const TiXmlNode* IterateChildren( const char * value, const TiXmlNode* previous ) const; TiXmlNode* IterateChildren( const char * value, TiXmlNode* previous ); #ifdef TIXML_USE_STL const TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) const { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. TiXmlNode* IterateChildren( const std::string& _value, TiXmlNode* previous ) { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. #endif /** Add a new node related to this. Adds a child past the LastChild. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* InsertEndChild( const TiXmlNode& addThis ); /** Add a new node related to this. Adds a child past the LastChild. NOTE: the node to be added is passed by pointer, and will be henceforth owned (and deleted) by tinyXml. This method is efficient and avoids an extra copy, but should be used with care as it uses a different memory model than the other insert functions. @sa InsertEndChild */ TiXmlNode* LinkEndChild( TiXmlNode* addThis ); /** Add a new node related to this. Adds a child before the specified child. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ); /** Add a new node related to this. Adds a child after the specified child. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ); /** Replace a child of this node. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ); /// Delete a child of this node. bool RemoveChild( TiXmlNode* removeThis ); /// Navigate to a sibling node. const TiXmlNode* PreviousSibling() const { return prev; } TiXmlNode* PreviousSibling() { return prev; } /// Navigate to a sibling node. const TiXmlNode* PreviousSibling( const char * ) const; TiXmlNode* PreviousSibling( const char * ); #ifdef TIXML_USE_STL const TiXmlNode* PreviousSibling( const std::string& _value ) const { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. TiXmlNode* PreviousSibling( const std::string& _value ) { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. const TiXmlNode* NextSibling( const std::string& _value) const { return NextSibling (_value.c_str ()); } ///< STL std::string form. TiXmlNode* NextSibling( const std::string& _value) { return NextSibling (_value.c_str ()); } ///< STL std::string form. #endif /// Navigate to a sibling node. const TiXmlNode* NextSibling() const { return next; } TiXmlNode* NextSibling() { return next; } /// Navigate to a sibling node with the given 'value'. const TiXmlNode* NextSibling( const char * ) const; TiXmlNode* NextSibling( const char * ); /** Convenience function to get through elements. Calls NextSibling and ToElement. Will skip all non-Element nodes. Returns 0 if there is not another element. */ const TiXmlElement* NextSiblingElement() const; TiXmlElement* NextSiblingElement(); /** Convenience function to get through elements. Calls NextSibling and ToElement. Will skip all non-Element nodes. Returns 0 if there is not another element. */ const TiXmlElement* NextSiblingElement( const char * ) const; TiXmlElement* NextSiblingElement( const char * ); #ifdef TIXML_USE_STL const TiXmlElement* NextSiblingElement( const std::string& _value) const { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. TiXmlElement* NextSiblingElement( const std::string& _value) { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. #endif /// Convenience function to get through elements. const TiXmlElement* FirstChildElement() const; TiXmlElement* FirstChildElement(); /// Convenience function to get through elements. const TiXmlElement* FirstChildElement( const char * value ) const; TiXmlElement* FirstChildElement( const char * value ); #ifdef TIXML_USE_STL const TiXmlElement* FirstChildElement( const std::string& _value ) const { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. TiXmlElement* FirstChildElement( const std::string& _value ) { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. #endif /** Query the type (as an enumerated value, above) of this node. The possible types are: DOCUMENT, ELEMENT, COMMENT, UNKNOWN, TEXT, and DECLARATION. */ virtual int Type() const { return type; } /** Return a pointer to the Document this node lives in. Returns null if not in a document. */ const TiXmlDocument* GetDocument() const; TiXmlDocument* GetDocument(); /// Returns true if this node has no children. bool NoChildren() const { return !firstChild; } const TiXmlDocument* ToDocument() const { return ( this && type == DOCUMENT ) ? (const TiXmlDocument*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. const TiXmlElement* ToElement() const { return ( this && type == ELEMENT ) ? (const TiXmlElement*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. const TiXmlComment* ToComment() const { return ( this && type == COMMENT ) ? (const TiXmlComment*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. const TiXmlUnknown* ToUnknown() const { return ( this && type == UNKNOWN ) ? (const TiXmlUnknown*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. const TiXmlText* ToText() const { return ( this && type == TEXT ) ? (const TiXmlText*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. const TiXmlDeclaration* ToDeclaration() const { return ( this && type == DECLARATION ) ? (const TiXmlDeclaration*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlDocument* ToDocument() { return ( this && type == DOCUMENT ) ? (TiXmlDocument*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlElement* ToElement() { return ( this && type == ELEMENT ) ? (TiXmlElement*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlComment* ToComment() { return ( this && type == COMMENT ) ? (TiXmlComment*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlUnknown* ToUnknown() { return ( this && type == UNKNOWN ) ? (TiXmlUnknown*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlText* ToText() { return ( this && type == TEXT ) ? (TiXmlText*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. TiXmlDeclaration* ToDeclaration() { return ( this && type == DECLARATION ) ? (TiXmlDeclaration*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. /** Create an exact duplicate of this node and return it. The memory must be deleted by the caller. */ virtual TiXmlNode* Clone() const = 0; protected: TiXmlNode( NodeType _type ); // Copy to the allocated object. Shared functionality between Clone, Copy constructor, // and the assignment operator. void CopyTo( TiXmlNode* target ) const; #ifdef TIXML_USE_STL // The real work of the input operator. virtual void StreamIn( TIXML_ISTREAM* in, TIXML_STRING* tag ) = 0; #endif // Figure out what is at *p, and parse it. Returns null if it is not an xml node. TiXmlNode* Identify( const char* start, TiXmlEncoding encoding ); // Internal Value function returning a TIXML_STRING const TIXML_STRING& SValue() const { return value ; } TiXmlNode* parent; NodeType type; TiXmlNode* firstChild; TiXmlNode* lastChild; TIXML_STRING value; TiXmlNode* prev; TiXmlNode* next; private: TiXmlNode( const TiXmlNode& ); // not implemented. void operator=( const TiXmlNode& base ); // not allowed. }; /** An attribute is a name-value pair. Elements have an arbitrary number of attributes, each with a unique name. @note The attributes are not TiXmlNodes, since they are not part of the tinyXML document object model. There are other suggested ways to look at this problem. */ class TiXmlAttribute : public TiXmlBase { friend class TiXmlAttributeSet; public: /// Construct an empty attribute. TiXmlAttribute() : TiXmlBase() { document = 0; prev = next = 0; } #ifdef TIXML_USE_STL /// std::string constructor. TiXmlAttribute( const std::string& _name, const std::string& _value ) { name = _name; value = _value; document = 0; prev = next = 0; } #endif /// Construct an attribute with a name and value. TiXmlAttribute( const char * _name, const char * _value ) { name = _name; value = _value; document = 0; prev = next = 0; } const char* Name() const { return name.c_str (); } ///< Return the name of this attribute. const char* Value() const { return value.c_str (); } ///< Return the value of this attribute. const int IntValue() const; ///< Return the value of this attribute, converted to an integer. const double DoubleValue() const; ///< Return the value of this attribute, converted to a double. /** QueryIntValue examines the value string. It is an alternative to the IntValue() method with richer error checking. If the value is an integer, it is stored in 'value' and the call returns TIXML_SUCCESS. If it is not an integer, it returns TIXML_WRONG_TYPE. A specialized but useful call. Note that for success it returns 0, which is the opposite of almost all other TinyXml calls. */ int QueryIntValue( int* value ) const; /// QueryDoubleValue examines the value string. See QueryIntValue(). int QueryDoubleValue( double* value ) const; void SetName( const char* _name ) { name = _name; } ///< Set the name of this attribute. void SetValue( const char* _value ) { value = _value; } ///< Set the value. void SetIntValue( int value ); ///< Set the value from an integer. void SetDoubleValue( double value ); ///< Set the value from a double. #ifdef TIXML_USE_STL /// STL std::string form. void SetName( const std::string& _name ) { StringToBuffer buf( _name ); SetName ( buf.buffer ? buf.buffer : "error" ); } /// STL std::string form. void SetValue( const std::string& _value ) { StringToBuffer buf( _value ); SetValue( buf.buffer ? buf.buffer : "error" ); } #endif /// Get the next sibling attribute in the DOM. Returns null at end. const TiXmlAttribute* Next() const; TiXmlAttribute* Next(); /// Get the previous sibling attribute in the DOM. Returns null at beginning. const TiXmlAttribute* Previous() const; TiXmlAttribute* Previous(); bool operator==( const TiXmlAttribute& rhs ) const { return rhs.name == name; } bool operator<( const TiXmlAttribute& rhs ) const { return name < rhs.name; } bool operator>( const TiXmlAttribute& rhs ) const { return name > rhs.name; } /* Attribute parsing starts: first letter of the name returns: the next char after the value end quote */ virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); // Prints this Attribute to a FILE stream. virtual void Print( FILE* cfile, int depth ) const; virtual void StreamOut( TIXML_OSTREAM * out ) const; // [internal use] // Set the document pointer so the attribute can report errors. void SetDocument( TiXmlDocument* doc ) { document = doc; } private: TiXmlAttribute( const TiXmlAttribute& ); // not implemented. void operator=( const TiXmlAttribute& base ); // not allowed. TiXmlDocument* document; // A pointer back to a document, for error reporting. TIXML_STRING name; TIXML_STRING value; TiXmlAttribute* prev; TiXmlAttribute* next; }; /* A class used to manage a group of attributes. It is only used internally, both by the ELEMENT and the DECLARATION. The set can be changed transparent to the Element and Declaration classes that use it, but NOT transparent to the Attribute which has to implement a next() and previous() method. Which makes it a bit problematic and prevents the use of STL. This version is implemented with circular lists because: - I like circular lists - it demonstrates some independence from the (typical) doubly linked list. */ class TiXmlAttributeSet { public: TiXmlAttributeSet(); ~TiXmlAttributeSet(); void Add( TiXmlAttribute* attribute ); void Remove( TiXmlAttribute* attribute ); const TiXmlAttribute* First() const { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; } TiXmlAttribute* First() { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; } const TiXmlAttribute* Last() const { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; } TiXmlAttribute* Last() { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; } const TiXmlAttribute* Find( const char * name ) const; TiXmlAttribute* Find( const char * name ); private: //*ME: Because of hidden/disabled copy-construktor in TiXmlAttribute (sentinel-element), //*ME: this class must be also use a hidden/disabled copy-constructor !!! TiXmlAttributeSet( const TiXmlAttributeSet& ); // not allowed void operator=( const TiXmlAttributeSet& ); // not allowed (as TiXmlAttribute) TiXmlAttribute sentinel; }; /** The element is a container class. It has a value, the element name, and can contain other elements, text, comments, and unknowns. Elements also contain an arbitrary number of attributes. */ class TiXmlElement : public TiXmlNode { public: /// Construct an element. TiXmlElement (const char * in_value); #ifdef TIXML_USE_STL /// std::string constructor. TiXmlElement( const std::string& _value ); #endif TiXmlElement( const TiXmlElement& ); void operator=( const TiXmlElement& base ); virtual ~TiXmlElement(); /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. */ const char* Attribute( const char* name ) const; /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. If the attribute exists and can be converted to an integer, the integer value will be put in the return 'i', if 'i' is non-null. */ const char* Attribute( const char* name, int* i ) const; /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. If the attribute exists and can be converted to an double, the double value will be put in the return 'd', if 'd' is non-null. */ const char* Attribute( const char* name, double* d ) const; /** QueryIntAttribute examines the attribute - it is an alternative to the Attribute() method with richer error checking. If the attribute is an integer, it is stored in 'value' and the call returns TIXML_SUCCESS. If it is not an integer, it returns TIXML_WRONG_TYPE. If the attribute does not exist, then TIXML_NO_ATTRIBUTE is returned. */ int QueryIntAttribute( const char* name, int* value ) const; /// QueryDoubleAttribute examines the attribute - see QueryIntAttribute(). int QueryDoubleAttribute( const char* name, double* value ) const; /// QueryFloatAttribute examines the attribute - see QueryIntAttribute(). int QueryDoubleAttribute( const char* name, float* value ) const { double d; int result = QueryDoubleAttribute( name, &d ); *value = (float)d; return result; } /** Sets an attribute of name to a given value. The attribute will be created if it does not exist, or changed if it does. */ void SetAttribute( const char* name, const char * value ); #ifdef TIXML_USE_STL const char* Attribute( const std::string& name ) const { return Attribute( name.c_str() ); } const char* Attribute( const std::string& name, int* i ) const { return Attribute( name.c_str(), i ); } const char* Attribute( const std::string& name, double* d ) const { return Attribute( name.c_str(), d ); } int QueryIntAttribute( const std::string& name, int* value ) const { return QueryIntAttribute( name.c_str(), value ); } int QueryDoubleAttribute( const std::string& name, double* value ) const { return QueryDoubleAttribute( name.c_str(), value ); } /// STL std::string form. void SetAttribute( const std::string& name, const std::string& _value ) { StringToBuffer n( name ); StringToBuffer v( _value ); if ( n.buffer && v.buffer ) SetAttribute (n.buffer, v.buffer ); } ///< STL std::string form. void SetAttribute( const std::string& name, int _value ) { StringToBuffer n( name ); if ( n.buffer ) SetAttribute (n.buffer, _value); } #endif /** Sets an attribute of name to a given value. The attribute will be created if it does not exist, or changed if it does. */ void SetAttribute( const char * name, int value ); /** Sets an attribute of name to a given value. The attribute will be created if it does not exist, or changed if it does. */ void SetDoubleAttribute( const char * name, double value ); /** Deletes an attribute with the given name. */ void RemoveAttribute( const char * name ); #ifdef TIXML_USE_STL void RemoveAttribute( const std::string& name ) { RemoveAttribute (name.c_str ()); } ///< STL std::string form. #endif const TiXmlAttribute* FirstAttribute() const { return attributeSet.First(); } ///< Access the first attribute in this element. TiXmlAttribute* FirstAttribute() { return attributeSet.First(); } const TiXmlAttribute* LastAttribute() const { return attributeSet.Last(); } ///< Access the last attribute in this element. TiXmlAttribute* LastAttribute() { return attributeSet.Last(); } /// Creates a new Element and returns it - the returned element is a copy. virtual TiXmlNode* Clone() const; // Print the Element to a FILE stream. virtual void Print( FILE* cfile, int depth ) const; /* Attribtue parsing starts: next char past '<' returns: next char past '>' */ virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); protected: void CopyTo( TiXmlElement* target ) const; void ClearThis(); // like clear, but initializes 'this' object as well // Used to be public [internal use] #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif virtual void StreamOut( TIXML_OSTREAM * out ) const; /* [internal use] Reads the "value" of the element -- another element, or text. This should terminate with the current end tag. */ const char* ReadValue( const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding ); private: TiXmlAttributeSet attributeSet; }; /** An XML comment. */ class TiXmlComment : public TiXmlNode { public: /// Constructs an empty comment. TiXmlComment() : TiXmlNode( TiXmlNode::COMMENT ) {} TiXmlComment( const TiXmlComment& ); void operator=( const TiXmlComment& base ); virtual ~TiXmlComment() {} /// Returns a copy of this Comment. virtual TiXmlNode* Clone() const; /// Write this Comment to a FILE stream. virtual void Print( FILE* cfile, int depth ) const; /* Attribtue parsing starts: at the ! of the !-- returns: next char past '>' */ virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); protected: void CopyTo( TiXmlComment* target ) const; // used to be public #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif virtual void StreamOut( TIXML_OSTREAM * out ) const; private: }; /** XML text. Contained in an element. */ class TiXmlText : public TiXmlNode { friend class TiXmlElement; public: /// Constructor. TiXmlText (const char * initValue) : TiXmlNode (TiXmlNode::TEXT) { SetValue( initValue ); } virtual ~TiXmlText() {} #ifdef TIXML_USE_STL /// Constructor. TiXmlText( const std::string& initValue ) : TiXmlNode (TiXmlNode::TEXT) { SetValue( initValue ); } #endif TiXmlText( const TiXmlText& copy ) : TiXmlNode( TiXmlNode::TEXT ) { copy.CopyTo( this ); } void operator=( const TiXmlText& base ) { base.CopyTo( this ); } /// Write this text object to a FILE stream. virtual void Print( FILE* cfile, int depth ) const; virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); protected : /// [internal use] Creates a new Element and returns it. virtual TiXmlNode* Clone() const; void CopyTo( TiXmlText* target ) const; virtual void StreamOut ( TIXML_OSTREAM * out ) const; bool Blank() const; // returns true if all white space and new lines // [internal use] #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif private: }; /** In correct XML the declaration is the first entry in the file. @verbatim @endverbatim TinyXml will happily read or write files without a declaration, however. There are 3 possible attributes to the declaration: version, encoding, and standalone. Note: In this version of the code, the attributes are handled as special cases, not generic attributes, simply because there can only be at most 3 and they are always the same. */ class TiXmlDeclaration : public TiXmlNode { public: /// Construct an empty declaration. TiXmlDeclaration() : TiXmlNode( TiXmlNode::DECLARATION ) {} #ifdef TIXML_USE_STL /// Constructor. TiXmlDeclaration( const std::string& _version, const std::string& _encoding, const std::string& _standalone ); #endif /// Construct. TiXmlDeclaration( const char* _version, const char* _encoding, const char* _standalone ); TiXmlDeclaration( const TiXmlDeclaration& copy ); void operator=( const TiXmlDeclaration& copy ); virtual ~TiXmlDeclaration() {} /// Version. Will return an empty string if none was found. const char *Version() const { return version.c_str (); } /// Encoding. Will return an empty string if none was found. const char *Encoding() const { return encoding.c_str (); } /// Is this a standalone document? const char *Standalone() const { return standalone.c_str (); } /// Creates a copy of this Declaration and returns it. virtual TiXmlNode* Clone() const; /// Print this declaration to a FILE stream. virtual void Print( FILE* cfile, int depth ) const; virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); protected: void CopyTo( TiXmlDeclaration* target ) const; // used to be public #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif virtual void StreamOut ( TIXML_OSTREAM * out) const; private: TIXML_STRING version; TIXML_STRING encoding; TIXML_STRING standalone; }; /** Any tag that tinyXml doesn't recognize is saved as an unknown. It is a tag of text, but should not be modified. It will be written back to the XML, unchanged, when the file is saved. DTD tags get thrown into TiXmlUnknowns. */ class TiXmlUnknown : public TiXmlNode { public: TiXmlUnknown() : TiXmlNode( TiXmlNode::UNKNOWN ) {} virtual ~TiXmlUnknown() {} TiXmlUnknown( const TiXmlUnknown& copy ) : TiXmlNode( TiXmlNode::UNKNOWN ) { copy.CopyTo( this ); } void operator=( const TiXmlUnknown& copy ) { copy.CopyTo( this ); } /// Creates a copy of this Unknown and returns it. virtual TiXmlNode* Clone() const; /// Print this Unknown to a FILE stream. virtual void Print( FILE* cfile, int depth ) const; virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); protected: void CopyTo( TiXmlUnknown* target ) const; #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif virtual void StreamOut ( TIXML_OSTREAM * out ) const; private: }; /** Always the top level node. A document binds together all the XML pieces. It can be saved, loaded, and printed to the screen. The 'value' of a document node is the xml file name. */ class TiXmlDocument : public TiXmlNode { public: /// Create an empty document, that has no name. TiXmlDocument(); /// Create a document with a name. The name of the document is also the filename of the xml. TiXmlDocument( const char * documentName ); #ifdef TIXML_USE_STL /// Constructor. TiXmlDocument( const std::string& documentName ); #endif TiXmlDocument( const TiXmlDocument& copy ); void operator=( const TiXmlDocument& copy ); virtual ~TiXmlDocument() {} /** Load a file using the current document value. Returns true if successful. Will delete any existing document data before loading. */ bool LoadFile( TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); /// Save a file using the current document value. Returns true if successful. bool SaveFile() const; /// Load a file using the given filename. Returns true if successful. bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); /// Save a file using the given filename. Returns true if successful. bool SaveFile( const char * filename ) const; #ifdef TIXML_USE_STL bool LoadFile( const std::string& filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ) ///< STL std::string version. { StringToBuffer f( filename ); return ( f.buffer && LoadFile( f.buffer, encoding )); } bool SaveFile( const std::string& filename ) const ///< STL std::string version. { StringToBuffer f( filename ); return ( f.buffer && SaveFile( f.buffer )); } #endif /** Parse the given null terminated block of xml data. Passing in an encoding to this method (either TIXML_ENCODING_LEGACY or TIXML_ENCODING_UTF8 will force TinyXml to use that encoding, regardless of what TinyXml might otherwise try to detect. */ virtual const char* Parse( const char* p, TiXmlParsingData* data = 0, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); /** Get the root element -- the only top level element -- of the document. In well formed XML, there should only be one. TinyXml is tolerant of multiple elements at the document level. */ const TiXmlElement* RootElement() const { return FirstChildElement(); } TiXmlElement* RootElement() { return FirstChildElement(); } /** If an error occurs, Error will be set to true. Also, - The ErrorId() will contain the integer identifier of the error (not generally useful) - The ErrorDesc() method will return the name of the error. (very useful) - The ErrorRow() and ErrorCol() will return the location of the error (if known) */ bool Error() const { return error; } /// Contains a textual (english) description of the error if one occurs. const char * ErrorDesc() const { return errorDesc.c_str (); } /** Generally, you probably want the error string ( ErrorDesc() ). But if you prefer the ErrorId, this function will fetch it. */ const int ErrorId() const { return errorId; } /** Returns the location (if known) of the error. The first column is column 1, and the first row is row 1. A value of 0 means the row and column wasn't applicable (memory errors, for example, have no row/column) or the parser lost the error. (An error in the error reporting, in that case.) @sa SetTabSize, Row, Column */ int ErrorRow() { return errorLocation.row+1; } int ErrorCol() { return errorLocation.col+1; } ///< The column where the error occured. See ErrorRow() /** By calling this method, with a tab size greater than 0, the row and column of each node and attribute is stored when the file is loaded. Very useful for tracking the DOM back in to the source file. The tab size is required for calculating the location of nodes. If not set, the default of 4 is used. The tabsize is set per document. Setting the tabsize to 0 disables row/column tracking. Note that row and column tracking is not supported when using operator>>. The tab size needs to be enabled before the parse or load. Correct usage: @verbatim TiXmlDocument doc; doc.SetTabSize( 8 ); doc.Load( "myfile.xml" ); @endverbatim @sa Row, Column */ void SetTabSize( int _tabsize ) { tabsize = _tabsize; } int TabSize() const { return tabsize; } /** If you have handled the error, it can be reset with this call. The error state is automatically cleared if you Parse a new XML block. */ void ClearError() { error = false; errorId = 0; errorDesc = ""; errorLocation.row = errorLocation.col = 0; //errorLocation.last = 0; } /** Dump the document to standard out. */ void Print() const { Print( stdout, 0 ); } /// Print this Document to a FILE stream. virtual void Print( FILE* cfile, int depth = 0 ) const; // [internal use] void SetError( int err, const char* errorLocation, TiXmlParsingData* prevData, TiXmlEncoding encoding ); protected : virtual void StreamOut ( TIXML_OSTREAM * out) const; // [internal use] virtual TiXmlNode* Clone() const; #ifdef TIXML_USE_STL virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ); #endif private: void CopyTo( TiXmlDocument* target ) const; bool error; int errorId; TIXML_STRING errorDesc; int tabsize; TiXmlCursor errorLocation; }; /** A TiXmlHandle is a class that wraps a node pointer with null checks; this is an incredibly useful thing. Note that TiXmlHandle is not part of the TinyXml DOM structure. It is a separate utility class. Take an example: @verbatim @endverbatim Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very easy to write a *lot* of code that looks like: @verbatim TiXmlElement* root = document.FirstChildElement( "Document" ); if ( root ) { TiXmlElement* element = root->FirstChildElement( "Element" ); if ( element ) { TiXmlElement* child = element->FirstChildElement( "Child" ); if ( child ) { TiXmlElement* child2 = child->NextSiblingElement( "Child" ); if ( child2 ) { // Finally do something useful. @endverbatim And that doesn't even cover "else" cases. TiXmlHandle addresses the verbosity of such code. A TiXmlHandle checks for null pointers so it is perfectly safe and correct to use: @verbatim TiXmlHandle docHandle( &document ); TiXmlElement* child2 = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", 1 ).Element(); if ( child2 ) { // do something useful @endverbatim Which is MUCH more concise and useful. It is also safe to copy handles - internally they are nothing more than node pointers. @verbatim TiXmlHandle handleCopy = handle; @endverbatim What they should not be used for is iteration: @verbatim int i=0; while ( true ) { TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", i ).Element(); if ( !child ) break; // do something ++i; } @endverbatim It seems reasonable, but it is in fact two embedded while loops. The Child method is a linear walk to find the element, so this code would iterate much more than it needs to. Instead, prefer: @verbatim TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).FirstChild( "Child" ).Element(); for( child; child; child=child->NextSiblingElement() ) { // do something } @endverbatim */ class TiXmlHandle { public: /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. TiXmlHandle( TiXmlNode* node ) { this->node = node; } /// Copy constructor TiXmlHandle( const TiXmlHandle& ref ) { this->node = ref.node; } TiXmlHandle operator=( const TiXmlHandle& ref ) { this->node = ref.node; return *this; } /// Return a handle to the first child node. TiXmlHandle FirstChild() const; /// Return a handle to the first child node with the given name. TiXmlHandle FirstChild( const char * value ) const; /// Return a handle to the first child element. TiXmlHandle FirstChildElement() const; /// Return a handle to the first child element with the given name. TiXmlHandle FirstChildElement( const char * value ) const; /** Return a handle to the "index" child with the given name. The first child is 0, the second 1, etc. */ TiXmlHandle Child( const char* value, int index ) const; /** Return a handle to the "index" child. The first child is 0, the second 1, etc. */ TiXmlHandle Child( int index ) const; /** Return a handle to the "index" child element with the given name. The first child element is 0, the second 1, etc. Note that only TiXmlElements are indexed: other types are not counted. */ TiXmlHandle ChildElement( const char* value, int index ) const; /** Return a handle to the "index" child element. The first child element is 0, the second 1, etc. Note that only TiXmlElements are indexed: other types are not counted. */ TiXmlHandle ChildElement( int index ) const; #ifdef TIXML_USE_STL TiXmlHandle FirstChild( const std::string& _value ) const { return FirstChild( _value.c_str() ); } TiXmlHandle FirstChildElement( const std::string& _value ) const { return FirstChildElement( _value.c_str() ); } TiXmlHandle Child( const std::string& _value, int index ) const { return Child( _value.c_str(), index ); } TiXmlHandle ChildElement( const std::string& _value, int index ) const { return ChildElement( _value.c_str(), index ); } #endif /// Return the handle as a TiXmlNode. This may return null. TiXmlNode* Node() const { return node; } /// Return the handle as a TiXmlElement. This may return null. TiXmlElement* Element() const { return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); } /// Return the handle as a TiXmlText. This may return null. TiXmlText* Text() const { return ( ( node && node->ToText() ) ? node->ToText() : 0 ); } /// Return the handle as a TiXmlUnknown. This may return null; TiXmlUnknown* Unknown() const { return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); } private: TiXmlNode* node; }; #ifdef _MSC_VER #pragma warning( default : 4530 ) #pragma warning( default : 4786 ) #endif #endif sipxtapi-3.3.0~test17/sipXportLib/include/xmlparser/TiXmlIterator.h0000644000175000017500000000046612205613256026245 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// sipxtapi-3.3.0~test17/sipXportLib/include/SipXportLibInit.h0000644000175000017500000000265012205613256024521 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 Jaroslav Libak // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// /** * You SHOULD include SipXportLibInit.h as the first include in .cpp file if it * contains a definition of a static variable that uses sipXportLib static * objects in its constructor or destructor. Including SipXportLibInit.h will * ensure, that all dependencies will be initialized before the custom static * object, and destructed after destruction of the custom object. * * @note If you need only part of sipXportLib static objects (e.g only Utl ones) * you may inlcude only specific initializers headers (e.g. UtlInit.h for * Utl). * @see os/OsProtectEventMgrInit.h * @see utl/UtlInit.h * @see os/OsNameDbInit.h */ #ifndef SipXportLibInit_h__ #define SipXportLibInit_h__ // SYSTEM INCLUDES // APPLICATION INCLUDES // Be sure to include all dependencies in the right order! #include "os/OsProtectEventMgrInit.h" #include "utl/UtlInit.h" #include "os/OsNameDbInit.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // FORWARD DECLARATIONS // STRUCTS // TYPEDEFS #endif // SipXportLibInit_h__ sipxtapi-3.3.0~test17/sipXportLib/include/Makefile.am0000644000175000017500000001140112205617431023332 0ustar00danieldaniel00000000000000 # preserve header timestamps to preserve incremental builds across # projects nobase_pkgincludeHEADERS_INSTALL = $(INSTALL) -D -p -c -m 644 nobase_pkginclude_HEADERS = \ os/fstream \ os/HostAdapterAddress.h \ os/iostream \ os/istream \ os/IStunSocket.h \ os/linux/host_address.h \ os/linux/AdapterInfo.h \ os/linux/OsBSemLinux.h \ os/linux/OsCSemLinux.h \ os/linux/OsDateTimeLinux.h \ os/linux/OsDirLinux.h \ os/linux/OsFileInfoLinux.h \ os/linux/OsFileIteratorLinux.h \ os/linux/OsFileLinux.h \ os/linux/OsLinuxDefs.h \ os/linux/OsMutexLinux.h \ os/linux/OsPathLinux.h \ os/linux/OsProcessIteratorLinux.h \ os/linux/OsProcessLinux.h \ os/linux/OsRWMutexLinux.h \ os/linux/OsSharedLibMgrLinux.h \ os/linux/OsTaskLinux.h \ os/linux/OsUtilLinux.h \ os/linux/pt_csem.h \ os/linux/pt_mutex.h \ os/NatMsg.h \ os/OsAssert.h \ os/OsAtomics.h \ os/OsBSem.h \ os/OsCallback.h \ os/OsConfigDb.h \ os/OsConfigEncryption.h \ os/OsConnectionSocket.h \ os/OsContact.h \ os/OsContactList.h \ os/OsCSem.h \ os/OsDatagramSocket.h \ os/OsDateTime.h \ os/OsDefs.h \ os/OsDirBase.h \ os/OsEncryption.h \ os/OsEvent.h \ os/OsEventMsg.h \ os/OsExcept.h \ os/OsFileBase.h \ os/OsFileInfoBase.h \ os/OsFileIteratorBase.h \ os/OsFileSystem.h \ os/OsFS.h \ os/OsIntPtrMsg.h \ os/OsIntTypes.h \ os/OsLock.h \ os/OsLockingList.h \ os/OsMsg.h \ os/OsMsgPool.h \ os/OsMsgQ.h \ os/OsMsgDispatcher.h \ os/OsMulticastSocket.h \ os/OsMutex.h \ os/OsNameDb.h \ os/OsNameDbInit.h \ os/OsNatAgentTask.h \ os/OsNatConnectionSocket.h \ os/OsNatDatagramSocket.h \ os/OsNatKeepaliveListener.h \ os/OsNatSocketBaseImpl.h \ os/OsNotification.h \ os/OsPathBase.h \ os/OsProcess.h \ os/OsProcessIterator.h \ os/OsProcessMgr.h \ os/OsProtectEvent.h \ os/OsProtectEventMgr.h \ os/OsProtectEventMgrInit.h \ os/OsPtrMsg.h \ os/OsQueuedEvent.h \ os/OsReadLock.h \ os/OsRpcMsg.h \ os/OsRWMutex.h \ os/OsServerSocket.h \ os/OsServerTask.h \ os/OsSharedLibMgr.h \ os/OsSocket.h \ os/OsSocketCrypto.h \ os/OsSSL.h \ os/OsSSLConnectionSocket.h \ os/OsSSLServerSocket.h \ os/OsStatus.h \ os/OsSyncBase.h \ os/OsSysLog.h \ os/OsSysLogFacilities.h \ os/OsSysLogMsg.h \ os/OsSysLogTask.h \ os/OsTask.h \ os/OsTaskId.h \ os/OsTime.h \ os/OsTimeLog.h \ os/OsTimer.h \ os/OsTimerMsg.h \ os/OsTimerTask.h \ os/OsTLSServerSocket.h \ os/OsTLSConnectionSocket.h \ os/OsTLSClientConnectionSocket.h \ os/OsTokenizer.h \ os/OsTLS.h \ os/ostream \ os/OsUtil.h \ os/OsWriteLock.h \ os/shared/OsMsgQShared.h \ os/shared/OsTimerMessage.h \ os/StunMessage.h \ os/StunUtils.h \ os/TurnMessage.h \ xmlparser/ExtractContent.h \ xmlparser/tinystr.h \ xmlparser/tinyxml.h \ xmlparser/TiXmlIterator.h \ utl/UtlLongLongInt.h \ utl/UtlNameValueTokenizer.h \ utl/UtlBool.h \ utl/UtlChainPool.h \ utl/UtlCrc32.h \ utl/UtlCryptoData.h \ utl/UtlCryptoKey.h \ utl/UtlCryptoKeyRsa.h \ utl/UtlCryptoKeySym.h \ utl/UtlLink.h \ utl/UtlContainable.h \ utl/UtlCopyableContainable.h \ utl/UtlContainer.h \ utl/UtlContainableAtomic.h \ utl/UtlContainablePair.h \ utl/UtlDateTime.h \ utl/UtlDList.h \ utl/UtlDListIterator.h \ utl/UtlDefs.h \ utl/UtlHashBag.h \ utl/UtlHashBagIterator.h \ utl/UtlHashMap.h \ utl/UtlHashMapIterator.h \ utl/UtlHistogram.h \ utl/UtlInit.h \ utl/UtlInt.h \ utl/UtlIntPtr.h \ utl/UtlIterator.h \ utl/UtlList.h \ utl/UtlListIterator.h \ utl/UtlObservable.h \ utl/UtlObservableImpl.h \ utl/UtlRegex.h \ utl/UtlRscStore.h \ utl/UtlRscTrace.h \ utl/UtlSerialized.h \ utl/UtlSList.h \ utl/UtlCopyableSList.h \ utl/UtlSListIterator.h \ utl/UtlSortedList.h \ utl/UtlCopyableSortedList.h \ utl/UtlString.h \ utl/UtlVoidPtr.h \ utl/UtlTokenizer.h \ utl/XmlContent.h \ utl/UtlSortedListIterator.h \ utl/UtlRandom.h \ utl/Plugin.h \ utl/PluginHooks.h \ SipXportLibInit.h EXTRA_DIST= \ os/wnt/getWindowsDNSServers.h \ os/wnt/OsBSemWnt.h \ os/wnt/OsCSemWnt.h \ os/wnt/OsDateTimeWnt.h \ os/wnt/OsDirWnt.h \ os/wnt/OsFileInfoWnt.h \ os/wnt/OsFileIteratorWnt.h \ os/wnt/OsFileSystemWnt.h \ os/wnt/OsFileWnt.h \ os/wnt/OsMutexWnt.h \ os/wnt/OsPathWnt.h \ os/wnt/OsProcessIteratorWnt.h \ os/wnt/OsProcessWnt.h \ os/wnt/OsSharedLibMgrWnt.h \ os/wnt/OsTaskWnt.h \ os/wnt/OsUtilWnt.h \ os/wnt/WIndowsAdapterInfo.h sipxtapi-3.3.0~test17/sipXportLib/include/Makefile.in0000644000175000017500000005467412321445000023354 0ustar00danieldaniel00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = sipXportLib/include DIST_COMMON = $(nobase_pkginclude_HEADERS) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/general.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/sipXlib.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(pkgincludedir)" HEADERS = $(nobase_pkginclude_HEADERS) ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMRNB_INCLUDE = @AMRNB_INCLUDE@ AMRNB_LIB_ROOT = @AMRNB_LIB_ROOT@ AMRWB_INCLUDE = @AMRWB_INCLUDE@ AMRWB_LIB_ROOT = @AMRWB_LIB_ROOT@ AMRWB_TARGET = @AMRWB_TARGET@ AMR_TARGET = @AMR_TARGET@ AMTAR = @AMTAR@ ANT = @ANT@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CARBON_LIBS = @CARBON_LIBS@ CA_LIBS = @CA_LIBS@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPUNIT_CFLAGS = @CPPUNIT_CFLAGS@ CPPUNIT_CONFIG = @CPPUNIT_CONFIG@ CPPUNIT_LIBS = @CPPUNIT_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPS_PCRE_CFLAGS = @DEPS_PCRE_CFLAGS@ DEPS_PCRE_LIBS = @DEPS_PCRE_LIBS@ DLLTOOL = @DLLTOOL@ DOT = @DOT@ DOXYGEN = @DOXYGEN@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DYNEXT = @DYNEXT@ EAGC_LDFLAGS = @EAGC_LDFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EJBE_LDFLAGS = @EJBE_LDFLAGS@ EPLC_LDFLAGS = @EPLC_LDFLAGS@ EVAD_LDFLAGS = @EVAD_LDFLAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ G722_TARGET = @G722_TARGET@ G726_TARGET = @G726_TARGET@ GIPSINC = @GIPSINC@ GIPS_CE_OBJS = @GIPS_CE_OBJS@ GIPS_CPPFLAGS = @GIPS_CPPFLAGS@ GIPS_NEQ_OBJS = @GIPS_NEQ_OBJS@ GIPS_VE_OBJS = @GIPS_VE_OBJS@ GREP = @GREP@ GSM_CFLAGS = @GSM_CFLAGS@ GSM_CXXFLAGS = @GSM_CXXFLAGS@ GSM_LDFLAGS = @GSM_LDFLAGS@ GSM_LIBS = @GSM_LIBS@ GSM_TARGET = @GSM_TARGET@ ILBC_INCLUDE = @ILBC_INCLUDE@ ILBC_LIB_ROOT = @ILBC_LIB_ROOT@ ILBC_LIB_TARGET = @ILBC_LIB_TARGET@ ILBC_TARGET = @ILBC_TARGET@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTERFACE_FLAGS = @INTERFACE_FLAGS@ JAVA = @JAVA@ JAVAC_DEBUG = @JAVAC_DEBUG@ JAVAC_OPTIMIZED = @JAVAC_OPTIMIZED@ JAVA_HOME = @JAVA_HOME@ L16_TARGET = @L16_TARGET@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NAMED_PROGRAM = @NAMED_PROGRAM@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPUS_CFLAGS = @OPUS_CFLAGS@ OPUS_LIBS = @OPUS_LIBS@ OPUS_TARGET = @OPUS_TARGET@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PCMAPCMU_TARGET = @PCMAPCMU_TARGET@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ RTL_CXXFLAGS = @RTL_CXXFLAGS@ RTL_LDFLAGS = @RTL_LDFLAGS@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SIPXMEDIA_CE_LIBS = @SIPXMEDIA_CE_LIBS@ SIPXMEDIA_VE_LIBS = @SIPXMEDIA_VE_LIBS@ SIPXMEDIA_VE_STATIC_LIBS = @SIPXMEDIA_VE_STATIC_LIBS@ SIPXPBXUSER = @SIPXPBXUSER@ SIPXPHONECONF = @SIPXPHONECONF@ SIPXPHONEDATA = @SIPXPHONEDATA@ SIPXPHONELIB = @SIPXPHONELIB@ SIPX_BACKUPDIR = @SIPX_BACKUPDIR@ SIPX_BINDIR = @SIPX_BINDIR@ SIPX_CONFDIR = @SIPX_CONFDIR@ SIPX_CONFIGPHONEDIR = @SIPX_CONFIGPHONEDIR@ SIPX_DATADIR = @SIPX_DATADIR@ SIPX_DBDIR = @SIPX_DBDIR@ SIPX_DOCDIR = @SIPX_DOCDIR@ SIPX_INCDIR = @SIPX_INCDIR@ SIPX_LIBDIR = @SIPX_LIBDIR@ SIPX_LOGDIR = @SIPX_LOGDIR@ SIPX_PARKMUSICDIR = @SIPX_PARKMUSICDIR@ SIPX_RUNDIR = @SIPX_RUNDIR@ SIPX_SCHEMADIR = @SIPX_SCHEMADIR@ SIPX_TMPDIR = @SIPX_TMPDIR@ SIPX_UNIT_TARGET = @SIPX_UNIT_TARGET@ SIPX_VXMLDATADIR = @SIPX_VXMLDATADIR@ SPANDSP_CFLAGS = @SPANDSP_CFLAGS@ SPANDSP_CXXFLAGS = @SPANDSP_CXXFLAGS@ SPANDSP_LDFLAGS = @SPANDSP_LDFLAGS@ SPANDSP_LIBS = @SPANDSP_LIBS@ SPEEXDSP_CFLAGS = @SPEEXDSP_CFLAGS@ SPEEXDSP_LIBS = @SPEEXDSP_LIBS@ SPEEXDSP_STATIC_LIB = @SPEEXDSP_STATIC_LIB@ SPEEX_CFLAGS = @SPEEX_CFLAGS@ SPEEX_LIBS = @SPEEX_LIBS@ SPEEX_ROOT = @SPEEX_ROOT@ SPEEX_STATIC_LIB = @SPEEX_STATIC_LIB@ SPEEX_TARGET = @SPEEX_TARGET@ SS_LDFLAGS = @SS_LDFLAGS@ STATIC_CODEC_LIBS = @STATIC_CODEC_LIBS@ STRIP = @STRIP@ TONES_TARGET = @TONES_TARGET@ VERSION = @VERSION@ VIDEO_DEFINE = @VIDEO_DEFINE@ WXWIDGETS_CFLAGS = @WXWIDGETS_CFLAGS@ WXWIDGETS_CONFIG = @WXWIDGETS_CONFIG@ WXWIDGETS_CXXFLAGS = @WXWIDGETS_CXXFLAGS@ WXWIDGETS_LIBS = @WXWIDGETS_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ codeclibdir = @codeclibdir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ enable_dot = @enable_dot@ enable_html_docs = @enable_html_docs@ enable_latex_docs = @enable_latex_docs@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ jar = @jar@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ sipx_abs_srcdir = @sipx_abs_srcdir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ wwwdir = @wwwdir@ # preserve header timestamps to preserve incremental builds across # projects nobase_pkgincludeHEADERS_INSTALL = $(INSTALL) -D -p -c -m 644 nobase_pkginclude_HEADERS = \ os/fstream \ os/HostAdapterAddress.h \ os/iostream \ os/istream \ os/IStunSocket.h \ os/linux/host_address.h \ os/linux/AdapterInfo.h \ os/linux/OsBSemLinux.h \ os/linux/OsCSemLinux.h \ os/linux/OsDateTimeLinux.h \ os/linux/OsDirLinux.h \ os/linux/OsFileInfoLinux.h \ os/linux/OsFileIteratorLinux.h \ os/linux/OsFileLinux.h \ os/linux/OsLinuxDefs.h \ os/linux/OsMutexLinux.h \ os/linux/OsPathLinux.h \ os/linux/OsProcessIteratorLinux.h \ os/linux/OsProcessLinux.h \ os/linux/OsRWMutexLinux.h \ os/linux/OsSharedLibMgrLinux.h \ os/linux/OsTaskLinux.h \ os/linux/OsUtilLinux.h \ os/linux/pt_csem.h \ os/linux/pt_mutex.h \ os/NatMsg.h \ os/OsAssert.h \ os/OsAtomics.h \ os/OsBSem.h \ os/OsCallback.h \ os/OsConfigDb.h \ os/OsConfigEncryption.h \ os/OsConnectionSocket.h \ os/OsContact.h \ os/OsContactList.h \ os/OsCSem.h \ os/OsDatagramSocket.h \ os/OsDateTime.h \ os/OsDefs.h \ os/OsDirBase.h \ os/OsEncryption.h \ os/OsEvent.h \ os/OsEventMsg.h \ os/OsExcept.h \ os/OsFileBase.h \ os/OsFileInfoBase.h \ os/OsFileIteratorBase.h \ os/OsFileSystem.h \ os/OsFS.h \ os/OsIntPtrMsg.h \ os/OsIntTypes.h \ os/OsLock.h \ os/OsLockingList.h \ os/OsMsg.h \ os/OsMsgPool.h \ os/OsMsgQ.h \ os/OsMsgDispatcher.h \ os/OsMulticastSocket.h \ os/OsMutex.h \ os/OsNameDb.h \ os/OsNameDbInit.h \ os/OsNatAgentTask.h \ os/OsNatConnectionSocket.h \ os/OsNatDatagramSocket.h \ os/OsNatKeepaliveListener.h \ os/OsNatSocketBaseImpl.h \ os/OsNotification.h \ os/OsPathBase.h \ os/OsProcess.h \ os/OsProcessIterator.h \ os/OsProcessMgr.h \ os/OsProtectEvent.h \ os/OsProtectEventMgr.h \ os/OsProtectEventMgrInit.h \ os/OsPtrMsg.h \ os/OsQueuedEvent.h \ os/OsReadLock.h \ os/OsRpcMsg.h \ os/OsRWMutex.h \ os/OsServerSocket.h \ os/OsServerTask.h \ os/OsSharedLibMgr.h \ os/OsSocket.h \ os/OsSocketCrypto.h \ os/OsSSL.h \ os/OsSSLConnectionSocket.h \ os/OsSSLServerSocket.h \ os/OsStatus.h \ os/OsSyncBase.h \ os/OsSysLog.h \ os/OsSysLogFacilities.h \ os/OsSysLogMsg.h \ os/OsSysLogTask.h \ os/OsTask.h \ os/OsTaskId.h \ os/OsTime.h \ os/OsTimeLog.h \ os/OsTimer.h \ os/OsTimerMsg.h \ os/OsTimerTask.h \ os/OsTLSServerSocket.h \ os/OsTLSConnectionSocket.h \ os/OsTLSClientConnectionSocket.h \ os/OsTokenizer.h \ os/OsTLS.h \ os/ostream \ os/OsUtil.h \ os/OsWriteLock.h \ os/shared/OsMsgQShared.h \ os/shared/OsTimerMessage.h \ os/StunMessage.h \ os/StunUtils.h \ os/TurnMessage.h \ xmlparser/ExtractContent.h \ xmlparser/tinystr.h \ xmlparser/tinyxml.h \ xmlparser/TiXmlIterator.h \ utl/UtlLongLongInt.h \ utl/UtlNameValueTokenizer.h \ utl/UtlBool.h \ utl/UtlChainPool.h \ utl/UtlCrc32.h \ utl/UtlCryptoData.h \ utl/UtlCryptoKey.h \ utl/UtlCryptoKeyRsa.h \ utl/UtlCryptoKeySym.h \ utl/UtlLink.h \ utl/UtlContainable.h \ utl/UtlCopyableContainable.h \ utl/UtlContainer.h \ utl/UtlContainableAtomic.h \ utl/UtlContainablePair.h \ utl/UtlDateTime.h \ utl/UtlDList.h \ utl/UtlDListIterator.h \ utl/UtlDefs.h \ utl/UtlHashBag.h \ utl/UtlHashBagIterator.h \ utl/UtlHashMap.h \ utl/UtlHashMapIterator.h \ utl/UtlHistogram.h \ utl/UtlInit.h \ utl/UtlInt.h \ utl/UtlIntPtr.h \ utl/UtlIterator.h \ utl/UtlList.h \ utl/UtlListIterator.h \ utl/UtlObservable.h \ utl/UtlObservableImpl.h \ utl/UtlRegex.h \ utl/UtlRscStore.h \ utl/UtlRscTrace.h \ utl/UtlSerialized.h \ utl/UtlSList.h \ utl/UtlCopyableSList.h \ utl/UtlSListIterator.h \ utl/UtlSortedList.h \ utl/UtlCopyableSortedList.h \ utl/UtlString.h \ utl/UtlVoidPtr.h \ utl/UtlTokenizer.h \ utl/XmlContent.h \ utl/UtlSortedListIterator.h \ utl/UtlRandom.h \ utl/Plugin.h \ utl/PluginHooks.h \ SipXportLibInit.h EXTRA_DIST = \ os/wnt/getWindowsDNSServers.h \ os/wnt/OsBSemWnt.h \ os/wnt/OsCSemWnt.h \ os/wnt/OsDateTimeWnt.h \ os/wnt/OsDirWnt.h \ os/wnt/OsFileInfoWnt.h \ os/wnt/OsFileIteratorWnt.h \ os/wnt/OsFileSystemWnt.h \ os/wnt/OsFileWnt.h \ os/wnt/OsMutexWnt.h \ os/wnt/OsPathWnt.h \ os/wnt/OsProcessIteratorWnt.h \ os/wnt/OsProcessWnt.h \ os/wnt/OsSharedLibMgrWnt.h \ os/wnt/OsTaskWnt.h \ os/wnt/OsUtilWnt.h \ os/wnt/WIndowsAdapterInfo.h all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu sipXportLib/include/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu sipXportLib/include/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-nobase_pkgincludeHEADERS: $(nobase_pkginclude_HEADERS) @$(NORMAL_INSTALL) @list='$(nobase_pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(pkgincludedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(pkgincludedir)" || exit 1; \ fi; \ $(am__nobase_list) | while read dir files; do \ xfiles=; for file in $$files; do \ if test -f "$$file"; then xfiles="$$xfiles $$file"; \ else xfiles="$$xfiles $(srcdir)/$$file"; fi; done; \ test -z "$$xfiles" || { \ test "x$$dir" = x. || { \ echo " $(MKDIR_P) '$(DESTDIR)$(pkgincludedir)/$$dir'"; \ $(MKDIR_P) "$(DESTDIR)$(pkgincludedir)/$$dir"; }; \ echo " $(INSTALL_HEADER) $$xfiles '$(DESTDIR)$(pkgincludedir)/$$dir'"; \ $(INSTALL_HEADER) $$xfiles "$(DESTDIR)$(pkgincludedir)/$$dir" || exit $$?; }; \ done uninstall-nobase_pkgincludeHEADERS: @$(NORMAL_UNINSTALL) @list='$(nobase_pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \ $(am__nobase_strip_setup); files=`$(am__nobase_strip)`; \ dir='$(DESTDIR)$(pkgincludedir)'; $(am__uninstall_files_from_dir) ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(HEADERS) installdirs: for dir in "$(DESTDIR)$(pkgincludedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-nobase_pkgincludeHEADERS install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-nobase_pkgincludeHEADERS .MAKE: install-am install-strip .PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ clean-libtool ctags distclean distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-nobase_pkgincludeHEADERS \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags uninstall uninstall-am uninstall-nobase_pkgincludeHEADERS # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: sipxtapi-3.3.0~test17/sipXportLib/syslogviewer/0000755000175000017500000000000012321445025022415 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/syslogviewer/README0000644000175000017500000000214312205613256023301 0ustar00danieldaniel00000000000000"syslogviewer" is a simple program to reformat sipX log file lines into a more easily readable format. Normally, syslogviewer is in the SIPX_BINDIR directory. Its arguments are: Usage: syslogviewer [-h] [-i] [-f[nn]] [if=input] [of=output] -h Print this help message. -i Indent continued lines. -f[nn] Fold lines that are over nn (default 80) characters. if= Specify input file name. of= Specify output file name. Its basic operation is to locate "\n" in the log file lines and turn them into newlines, thus formatting SIP messages line they appear on the line. "\r" combinations are deleted entirely. If "-i" is specified, after the line breaks, the next line is indented with a tab character. If "-f" is specified, lines that occupy over 80 columns will be broken. "-fNN" specifies a line length of NN columns rather than 80. The latter parts of broken lines will each be indented 4 spaces. If "-i" is specified also, the leading tabs it generates will be counted as 8 columns, and a tabbed line that is broken will be indented 8 columns (one tab and 4 spaces). sipxtapi-3.3.0~test17/sipXportLib/syslogviewer/Makefile.am0000644000175000017500000000016712205613256024461 0ustar00danieldaniel00000000000000## Process this file with automake to produce Makefile.in bin_PROGRAMS = syslogviewer syslogviewer_SOURCES = main.c sipxtapi-3.3.0~test17/sipXportLib/syslogviewer/Makefile.in0000644000175000017500000004727712321445002024476 0ustar00danieldaniel00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ bin_PROGRAMS = syslogviewer$(EXEEXT) subdir = sipXportLib/syslogviewer DIST_COMMON = README $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/general.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/sipXlib.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__installdirs = "$(DESTDIR)$(bindir)" PROGRAMS = $(bin_PROGRAMS) am_syslogviewer_OBJECTS = main.$(OBJEXT) syslogviewer_OBJECTS = $(am_syslogviewer_OBJECTS) syslogviewer_LDADD = $(LDADD) DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) CCLD = $(CC) LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ SOURCES = $(syslogviewer_SOURCES) DIST_SOURCES = $(syslogviewer_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMRNB_INCLUDE = @AMRNB_INCLUDE@ AMRNB_LIB_ROOT = @AMRNB_LIB_ROOT@ AMRWB_INCLUDE = @AMRWB_INCLUDE@ AMRWB_LIB_ROOT = @AMRWB_LIB_ROOT@ AMRWB_TARGET = @AMRWB_TARGET@ AMR_TARGET = @AMR_TARGET@ AMTAR = @AMTAR@ ANT = @ANT@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CARBON_LIBS = @CARBON_LIBS@ CA_LIBS = @CA_LIBS@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPUNIT_CFLAGS = @CPPUNIT_CFLAGS@ CPPUNIT_CONFIG = @CPPUNIT_CONFIG@ CPPUNIT_LIBS = @CPPUNIT_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPS_PCRE_CFLAGS = @DEPS_PCRE_CFLAGS@ DEPS_PCRE_LIBS = @DEPS_PCRE_LIBS@ DLLTOOL = @DLLTOOL@ DOT = @DOT@ DOXYGEN = @DOXYGEN@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DYNEXT = @DYNEXT@ EAGC_LDFLAGS = @EAGC_LDFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EJBE_LDFLAGS = @EJBE_LDFLAGS@ EPLC_LDFLAGS = @EPLC_LDFLAGS@ EVAD_LDFLAGS = @EVAD_LDFLAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ G722_TARGET = @G722_TARGET@ G726_TARGET = @G726_TARGET@ GIPSINC = @GIPSINC@ GIPS_CE_OBJS = @GIPS_CE_OBJS@ GIPS_CPPFLAGS = @GIPS_CPPFLAGS@ GIPS_NEQ_OBJS = @GIPS_NEQ_OBJS@ GIPS_VE_OBJS = @GIPS_VE_OBJS@ GREP = @GREP@ GSM_CFLAGS = @GSM_CFLAGS@ GSM_CXXFLAGS = @GSM_CXXFLAGS@ GSM_LDFLAGS = @GSM_LDFLAGS@ GSM_LIBS = @GSM_LIBS@ GSM_TARGET = @GSM_TARGET@ ILBC_INCLUDE = @ILBC_INCLUDE@ ILBC_LIB_ROOT = @ILBC_LIB_ROOT@ ILBC_LIB_TARGET = @ILBC_LIB_TARGET@ ILBC_TARGET = @ILBC_TARGET@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTERFACE_FLAGS = @INTERFACE_FLAGS@ JAVA = @JAVA@ JAVAC_DEBUG = @JAVAC_DEBUG@ JAVAC_OPTIMIZED = @JAVAC_OPTIMIZED@ JAVA_HOME = @JAVA_HOME@ L16_TARGET = @L16_TARGET@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NAMED_PROGRAM = @NAMED_PROGRAM@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPUS_CFLAGS = @OPUS_CFLAGS@ OPUS_LIBS = @OPUS_LIBS@ OPUS_TARGET = @OPUS_TARGET@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PCMAPCMU_TARGET = @PCMAPCMU_TARGET@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ RTL_CXXFLAGS = @RTL_CXXFLAGS@ RTL_LDFLAGS = @RTL_LDFLAGS@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SIPXMEDIA_CE_LIBS = @SIPXMEDIA_CE_LIBS@ SIPXMEDIA_VE_LIBS = @SIPXMEDIA_VE_LIBS@ SIPXMEDIA_VE_STATIC_LIBS = @SIPXMEDIA_VE_STATIC_LIBS@ SIPXPBXUSER = @SIPXPBXUSER@ SIPXPHONECONF = @SIPXPHONECONF@ SIPXPHONEDATA = @SIPXPHONEDATA@ SIPXPHONELIB = @SIPXPHONELIB@ SIPX_BACKUPDIR = @SIPX_BACKUPDIR@ SIPX_BINDIR = @SIPX_BINDIR@ SIPX_CONFDIR = @SIPX_CONFDIR@ SIPX_CONFIGPHONEDIR = @SIPX_CONFIGPHONEDIR@ SIPX_DATADIR = @SIPX_DATADIR@ SIPX_DBDIR = @SIPX_DBDIR@ SIPX_DOCDIR = @SIPX_DOCDIR@ SIPX_INCDIR = @SIPX_INCDIR@ SIPX_LIBDIR = @SIPX_LIBDIR@ SIPX_LOGDIR = @SIPX_LOGDIR@ SIPX_PARKMUSICDIR = @SIPX_PARKMUSICDIR@ SIPX_RUNDIR = @SIPX_RUNDIR@ SIPX_SCHEMADIR = @SIPX_SCHEMADIR@ SIPX_TMPDIR = @SIPX_TMPDIR@ SIPX_UNIT_TARGET = @SIPX_UNIT_TARGET@ SIPX_VXMLDATADIR = @SIPX_VXMLDATADIR@ SPANDSP_CFLAGS = @SPANDSP_CFLAGS@ SPANDSP_CXXFLAGS = @SPANDSP_CXXFLAGS@ SPANDSP_LDFLAGS = @SPANDSP_LDFLAGS@ SPANDSP_LIBS = @SPANDSP_LIBS@ SPEEXDSP_CFLAGS = @SPEEXDSP_CFLAGS@ SPEEXDSP_LIBS = @SPEEXDSP_LIBS@ SPEEXDSP_STATIC_LIB = @SPEEXDSP_STATIC_LIB@ SPEEX_CFLAGS = @SPEEX_CFLAGS@ SPEEX_LIBS = @SPEEX_LIBS@ SPEEX_ROOT = @SPEEX_ROOT@ SPEEX_STATIC_LIB = @SPEEX_STATIC_LIB@ SPEEX_TARGET = @SPEEX_TARGET@ SS_LDFLAGS = @SS_LDFLAGS@ STATIC_CODEC_LIBS = @STATIC_CODEC_LIBS@ STRIP = @STRIP@ TONES_TARGET = @TONES_TARGET@ VERSION = @VERSION@ VIDEO_DEFINE = @VIDEO_DEFINE@ WXWIDGETS_CFLAGS = @WXWIDGETS_CFLAGS@ WXWIDGETS_CONFIG = @WXWIDGETS_CONFIG@ WXWIDGETS_CXXFLAGS = @WXWIDGETS_CXXFLAGS@ WXWIDGETS_LIBS = @WXWIDGETS_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ codeclibdir = @codeclibdir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ enable_dot = @enable_dot@ enable_html_docs = @enable_html_docs@ enable_latex_docs = @enable_latex_docs@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ jar = @jar@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ sipx_abs_srcdir = @sipx_abs_srcdir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ wwwdir = @wwwdir@ syslogviewer_SOURCES = main.c all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu sipXportLib/syslogviewer/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu sipXportLib/syslogviewer/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-binPROGRAMS: $(bin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p || test -f $$p1; \ then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ } \ ; done uninstall-binPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(bindir)" && rm -f $$files clean-binPROGRAMS: @list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list syslogviewer$(EXEEXT): $(syslogviewer_OBJECTS) $(syslogviewer_DEPENDENCIES) $(EXTRA_syslogviewer_DEPENDENCIES) @rm -f syslogviewer$(EXEEXT) $(LINK) $(syslogviewer_OBJECTS) $(syslogviewer_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/main.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(COMPILE) -c $< .c.obj: @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(PROGRAMS) installdirs: for dir in "$(DESTDIR)$(bindir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-binPROGRAMS install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-binPROGRAMS .MAKE: install-am install-strip .PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ clean-generic clean-libtool ctags distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-binPROGRAMS install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags uninstall uninstall-am \ uninstall-binPROGRAMS # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: sipxtapi-3.3.0~test17/sipXportLib/syslogviewer/main.c0000644000175000017500000001667012205613256023523 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #if defined(_WIN32) # include #elif defined(__pingtel_on_posix__) # include #endif #define BUFFER_SIZE 8192 // Configuration variables. // If 1, continuation lines produced by \n should be indented with a TAB. static int indent = 0; // If 1, long lines should be folded. static int fold = 0; // The line length for folding. static int width = 80; // Processing state. static char buffer[BUFFER_SIZE]; static int buffer_full = 0; static enum { StartLine, InTime, InFields, InMessage, Backslash } state; // The number of print spaces in the current line that have been consumed. static int position; // If 1, the current output line was indented with a tab, and any // folded lines from it should also have a tab. static int line_tabbed; static void flush_buffer(int fd) { write(fd, buffer, buffer_full); buffer_full = 0; } /* If folding is on, check the position in the line and break it if necessary * so there is room to insert another graphic character. */ static void check_position(int fd) { if (fold && position == width) { // Must break the line. // Insert a newline. if (buffer_full == BUFFER_SIZE) { flush_buffer(fd); } buffer[buffer_full++] = '\n'; position = 0; // Insert a tab if the line we are breaking had an added tab. if (line_tabbed) { if (buffer_full == BUFFER_SIZE) { flush_buffer(fd); } buffer[buffer_full++] = '\t'; position = 8; } // Insert 4 spaces. if (buffer_full == BUFFER_SIZE) { flush_buffer(fd); } buffer[buffer_full++] = ' '; if (buffer_full == BUFFER_SIZE) { flush_buffer(fd); } buffer[buffer_full++] = ' '; if (buffer_full == BUFFER_SIZE) { flush_buffer(fd); } buffer[buffer_full++] = ' '; if (buffer_full == BUFFER_SIZE) { flush_buffer(fd); } buffer[buffer_full++] = ' '; position += 4; } } static void process_char(char ch, int fd) { switch(state) { case StartLine: if (ch == '"') { state = InTime; } else { buffer[buffer_full++] = ch; position++; } break; case InTime: if (ch == '"') { state = InFields; } buffer[buffer_full++] = ch; position++; break; case InFields: if (ch == '"') { buffer[buffer_full++] = '\n'; check_position(fd); state = InMessage; buffer[buffer_full++] = '\t'; position = 0; line_tabbed = 1; } else { buffer[buffer_full++] = ch; position++; } break; case InMessage: if (ch == '\\') { state = Backslash; } else if (ch == '\n') { // Newline never forces a folding break, and position is 0 afterward. buffer[buffer_full++] = '\n'; position = 0; line_tabbed = 0; } else if (ch == '"') { // Unescaped End of the message state = indent ? StartLine : InMessage; position = 0; line_tabbed = 0; } else { // Ordinary characters. check_position(fd); buffer[buffer_full++] = ch; position++; } break; case Backslash: if (ch == '\\') { check_position(fd); buffer[buffer_full++] = '\\'; position++; } else if (ch == 'n') { // Insert newline. buffer[buffer_full++] = '\n'; // Indent the continuation line if it was requested. if (indent) { if (buffer_full == BUFFER_SIZE) { flush_buffer(fd); } buffer[buffer_full++] = '\t'; // Set the position to account for the tab. position = 8; line_tabbed = 1; } else { position = 0; } } else if (ch != 'r') { // Other backslash escapes are output as such. check_position(fd); buffer[buffer_full++] = '\\'; position++; if (buffer_full == BUFFER_SIZE) { flush_buffer(fd); } check_position(fd); buffer[buffer_full++] = ch; position++; } state = InMessage; break; } if (buffer_full == BUFFER_SIZE) flush_buffer(fd); } int main(int argc, char * argv[]) { char input_buffer[BUFFER_SIZE]; int i, ifd = 0, ofd = 1; for(i = 1; i < argc; i++) { if ( (!strcmp(argv[i], "-h")) || (!strcmp(argv[i], "--help")) ) { fprintf(stderr, "Usage:\n\t%s [-h | --help] [-i | --indent] [-f[nn]]\n" "\t\t[if=input] [of=output]\n", argv[0]); fprintf(stderr, "\n"); fprintf(stderr, "\t--help\tPrint this help message.\n"); fprintf(stderr, "\t--indent\tIndent messages and continued lines.\n"); fprintf(stderr, "\t-f[nn]\tFold lines that are over nn (default 80) characters.\n" "\t\tImplies --indent.\n" ); fprintf(stderr, "\tif=\tSpecify input file name.\n"); fprintf(stderr, "\tof=\tSpecify output file name.\n"); return 0; } else if ( (strcmp(argv[i], "-i") == 0) || (strcmp(argv[i], "--indent") == 0) ) { indent = 1; } else if (!strncmp(argv[i], "if=", 3)) { ifd = open(&argv[i][3], O_RDONLY); if (ifd == -1) { fprintf(stderr, "%s: %s\n", &argv[i][3], strerror(errno)); return 1; } } else if (!strncmp(argv[i], "of=", 3)) { ofd = open(&argv[i][3], O_WRONLY | O_CREAT, 0644); if (ofd == -1) { fprintf(stderr, "%s: %s\n", &argv[i][3], strerror(errno)); return 1; } } else if (!strncmp(argv[i], "-f", 2)) { fold = 1; indent = 1; if (strlen(argv[i]) > 2) { char* endptr; width = strtol(argv[i] + strlen("-f"), &endptr, 10); if (endptr != argv[i] + strlen(argv[i])) { fprintf(stderr, "Badly formatted width: '%s'\n", argv[i]); return 1; } else if (width < 9) { fprintf(stderr, "Width value too small: %d\n", width); return 1; } } } else { fprintf(stderr, "Unknown option: %s\n", argv[i]); return 1; } } position = 0; line_tabbed = 0; i = read(ifd, input_buffer, BUFFER_SIZE); state = indent ? StartLine : InMessage; while(i && i != -1) { int j; for(j = 0; j != i; j++) process_char(input_buffer[j], ofd); i = read(ifd, input_buffer, BUFFER_SIZE); } flush_buffer(ofd); return 0; } sipxtapi-3.3.0~test17/sipXportLib/doc/0000755000175000017500000000000012321445026020421 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXportLib/doc/Makefile.am0000644000175000017500000000204412205613305022453 0ustar00danieldaniel00000000000000include $(top_srcdir)/config/sipXcommon.am.inc images = \ PluginUml.png EXTRA_DIST = \ Doxyfile.in \ footer.html \ $(images) all: doc PROJECT = sipXportLib doc: $(PROJECT) external-docs Doxyfile: $(srcdir)/Doxyfile.in $(LocalizeSipXconfig) \ -e 's,@enable_html_docs\@,@enable_html_docs@,g' \ -e 's,@enable_latex_docs\@,@enable_latex_docs@,g' \ -e 's,@enable_dot\@,@enable_dot@,g' \ -e 's,@srcdir\@,$(srcdir),g' \ -e 's,@top_srcdir\@,$(top_srcdir),g' \ $(srcdir)/Doxyfile.in > Doxyfile install: install-doc .PHONY: install-doc install-doc: rm -rf $(DESTDIR)@docdir@/$(PROJECT) @INSTALL@ -d $(DESTDIR)@docdir@/$(PROJECT) find $(PROJECT) -type f -print \ | xargs --replace=% @INSTALL@ -m u=rw,go=r % $(DESTDIR)@docdir@/% clean-local: clean-doc .PHONY: clean-doc clean-doc: rm -rf $(PROJECT) Doxyfile $(PROJECT): Doxyfile rm -rf $(PROJECT) @DOXYGEN@ .PHONY: external-docs external-docs: $(PROJECT) $(foreach img,$(images),$(PROJECT)/$(img)) $(foreach img,$(images),$(PROJECT)/$(img)): $(PROJECT)/% : % $(PROJECT) cp $< $@ sipxtapi-3.3.0~test17/sipXportLib/doc/Makefile.in0000644000175000017500000004171412321445000022465 0ustar00danieldaniel00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # -*-makefile-*- VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ $(top_srcdir)/config/sipXcommon.am.inc subdir = sipXportLib/doc ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/general.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/sipXlib.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMRNB_INCLUDE = @AMRNB_INCLUDE@ AMRNB_LIB_ROOT = @AMRNB_LIB_ROOT@ AMRWB_INCLUDE = @AMRWB_INCLUDE@ AMRWB_LIB_ROOT = @AMRWB_LIB_ROOT@ AMRWB_TARGET = @AMRWB_TARGET@ AMR_TARGET = @AMR_TARGET@ AMTAR = @AMTAR@ ANT = @ANT@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CARBON_LIBS = @CARBON_LIBS@ CA_LIBS = @CA_LIBS@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPUNIT_CFLAGS = @CPPUNIT_CFLAGS@ CPPUNIT_CONFIG = @CPPUNIT_CONFIG@ CPPUNIT_LIBS = @CPPUNIT_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPS_PCRE_CFLAGS = @DEPS_PCRE_CFLAGS@ DEPS_PCRE_LIBS = @DEPS_PCRE_LIBS@ DLLTOOL = @DLLTOOL@ DOT = @DOT@ DOXYGEN = @DOXYGEN@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DYNEXT = @DYNEXT@ EAGC_LDFLAGS = @EAGC_LDFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EJBE_LDFLAGS = @EJBE_LDFLAGS@ EPLC_LDFLAGS = @EPLC_LDFLAGS@ EVAD_LDFLAGS = @EVAD_LDFLAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ G722_TARGET = @G722_TARGET@ G726_TARGET = @G726_TARGET@ GIPSINC = @GIPSINC@ GIPS_CE_OBJS = @GIPS_CE_OBJS@ GIPS_CPPFLAGS = @GIPS_CPPFLAGS@ GIPS_NEQ_OBJS = @GIPS_NEQ_OBJS@ GIPS_VE_OBJS = @GIPS_VE_OBJS@ GREP = @GREP@ GSM_CFLAGS = @GSM_CFLAGS@ GSM_CXXFLAGS = @GSM_CXXFLAGS@ GSM_LDFLAGS = @GSM_LDFLAGS@ GSM_LIBS = @GSM_LIBS@ GSM_TARGET = @GSM_TARGET@ ILBC_INCLUDE = @ILBC_INCLUDE@ ILBC_LIB_ROOT = @ILBC_LIB_ROOT@ ILBC_LIB_TARGET = @ILBC_LIB_TARGET@ ILBC_TARGET = @ILBC_TARGET@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTERFACE_FLAGS = @INTERFACE_FLAGS@ JAVA = @JAVA@ JAVAC_DEBUG = @JAVAC_DEBUG@ JAVAC_OPTIMIZED = @JAVAC_OPTIMIZED@ JAVA_HOME = @JAVA_HOME@ L16_TARGET = @L16_TARGET@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NAMED_PROGRAM = @NAMED_PROGRAM@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPUS_CFLAGS = @OPUS_CFLAGS@ OPUS_LIBS = @OPUS_LIBS@ OPUS_TARGET = @OPUS_TARGET@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PCMAPCMU_TARGET = @PCMAPCMU_TARGET@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ RTL_CXXFLAGS = @RTL_CXXFLAGS@ RTL_LDFLAGS = @RTL_LDFLAGS@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SIPXMEDIA_CE_LIBS = @SIPXMEDIA_CE_LIBS@ SIPXMEDIA_VE_LIBS = @SIPXMEDIA_VE_LIBS@ SIPXMEDIA_VE_STATIC_LIBS = @SIPXMEDIA_VE_STATIC_LIBS@ SIPXPBXUSER = @SIPXPBXUSER@ SIPXPHONECONF = @SIPXPHONECONF@ SIPXPHONEDATA = @SIPXPHONEDATA@ SIPXPHONELIB = @SIPXPHONELIB@ SIPX_BACKUPDIR = @SIPX_BACKUPDIR@ SIPX_BINDIR = @SIPX_BINDIR@ SIPX_CONFDIR = @SIPX_CONFDIR@ SIPX_CONFIGPHONEDIR = @SIPX_CONFIGPHONEDIR@ SIPX_DATADIR = @SIPX_DATADIR@ SIPX_DBDIR = @SIPX_DBDIR@ SIPX_DOCDIR = @SIPX_DOCDIR@ SIPX_INCDIR = @SIPX_INCDIR@ SIPX_LIBDIR = @SIPX_LIBDIR@ SIPX_LOGDIR = @SIPX_LOGDIR@ SIPX_PARKMUSICDIR = @SIPX_PARKMUSICDIR@ SIPX_RUNDIR = @SIPX_RUNDIR@ SIPX_SCHEMADIR = @SIPX_SCHEMADIR@ SIPX_TMPDIR = @SIPX_TMPDIR@ SIPX_UNIT_TARGET = @SIPX_UNIT_TARGET@ SIPX_VXMLDATADIR = @SIPX_VXMLDATADIR@ SPANDSP_CFLAGS = @SPANDSP_CFLAGS@ SPANDSP_CXXFLAGS = @SPANDSP_CXXFLAGS@ SPANDSP_LDFLAGS = @SPANDSP_LDFLAGS@ SPANDSP_LIBS = @SPANDSP_LIBS@ SPEEXDSP_CFLAGS = @SPEEXDSP_CFLAGS@ SPEEXDSP_LIBS = @SPEEXDSP_LIBS@ SPEEXDSP_STATIC_LIB = @SPEEXDSP_STATIC_LIB@ SPEEX_CFLAGS = @SPEEX_CFLAGS@ SPEEX_LIBS = @SPEEX_LIBS@ SPEEX_ROOT = @SPEEX_ROOT@ SPEEX_STATIC_LIB = @SPEEX_STATIC_LIB@ SPEEX_TARGET = @SPEEX_TARGET@ SS_LDFLAGS = @SS_LDFLAGS@ STATIC_CODEC_LIBS = @STATIC_CODEC_LIBS@ STRIP = @STRIP@ TONES_TARGET = @TONES_TARGET@ VERSION = @VERSION@ VIDEO_DEFINE = @VIDEO_DEFINE@ WXWIDGETS_CFLAGS = @WXWIDGETS_CFLAGS@ WXWIDGETS_CONFIG = @WXWIDGETS_CONFIG@ WXWIDGETS_CXXFLAGS = @WXWIDGETS_CXXFLAGS@ WXWIDGETS_LIBS = @WXWIDGETS_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ codeclibdir = @codeclibdir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ enable_dot = @enable_dot@ enable_html_docs = @enable_html_docs@ enable_latex_docs = @enable_latex_docs@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ jar = @jar@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ sipx_abs_srcdir = @sipx_abs_srcdir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ wwwdir = @wwwdir@ ConfigureArgs = $(shell sed \ -e '/^ *\$$ .*\/configure/!d' \ -e 's/^ *\$$ .*\/configure *//' \ $(top_builddir)/config.log \ ) LocalizeSipXconfig = sed \ -e 's,@PACKAGE\@,@PACKAGE@,g' \ -e 's,@VERSION\@,@VERSION@,g' \ -e 's,@abs_builddir\@,@abs_builddir@,g' \ -e 's,@abs_srcdir\@,@abs_srcdir@,g' \ -e 's,@abs_top_srcdir\@,@abs_top_srcdir@,g' \ -e 's,@sipx_abs_srcdir\@,@sipx_abs_srcdir@,g' \ -e 's!@CONFIGURE_OPTIONS@!$(ConfigureArgs)!g' \ -e 's,@bindir\@,$(bindir),g' \ -e 's,@datadir\@,$(datadir),g' \ -e 's,@htmldir\@,@htmldir@,g' \ -e 's,@INSTALL\@,@INSTALL@,g' \ -e 's,@install_sh\@,@install_sh@,g' \ -e 's,@libdir\@,$(libdir),g' \ -e 's,@localstatedir\@,$(localstatedir),g' \ -e 's,@pkgdatadir\@,@pkgdatadir@,g' \ -e 's,@prefix\@,$(prefix),g' \ -e 's,@profiledir\@,@profiledir@,g' \ -e 's,@wwwdir\@,@wwwdir@,g' \ -e 's,@host\@,@host@,g' \ -e 's,@PERL\@,@PERL@,g' \ -e 's,@APACHE2_HTTPD\@,@APACHE2_HTTPD@,g' \ -e 's,@APACHE2_MOD\@,@APACHE2_MOD@,g' \ -e 's,@CLOVER_HOME\@,@CLOVER_HOME@,g' \ -e 's,@JAVAC_DEBUG\@,@JAVAC_DEBUG@,g' \ -e 's,@JAVAC_OPTIMIZED\@,@JAVAC_OPTIMIZED@,g' \ -e 's,@JAVA\@,@JAVA@,g' \ -e 's,@JAVA_HOME\@,@JAVA_HOME@,g' \ -e 's,@JBOSS_HOME\@,@JBOSS_HOME@,g' \ -e 's,@JBOSS_SERVER_CONF\@,@JBOSS_SERVER_CONF@,g' \ -e 's,@SIPFOUNDRY_ORG\@,@SIPFOUNDRY_ORG@,g' \ -e 's,@SIPXCONFIG_LIBDIR\@,@SIPXCONFIG_LIBDIR@,g' \ -e 's,@SIPXPBXUSER\@,@SIPXPBXUSER@,g' \ -e 's,@SIPX_BINDIR\@,@SIPX_BINDIR@,g' \ -e 's,@SIPX_CONFDIR\@,@SIPX_CONFDIR@,g' \ -e 's,@SIPX_CONFIGPHONEDIR\@,@SIPX_CONFIGPHONEDIR@,g' \ -e 's,@SIPX_BACKUPDIR\@,@SIPX_BACKUPDIR@,g' \ -e 's,@SIPX_DATADIR\@,@SIPX_DATADIR@,g' \ -e 's,@SIPX_DBDIR\@,@SIPX_DBDIR@,g' \ -e 's,@SIPX_DOCDIR\@,@SIPX_DOCDIR@,g' \ -e 's,@SIPX_LOGDIR\@,@SIPX_LOGDIR@,g' \ -e 's,@SIPX_RUNDIR\@,@SIPX_RUNDIR@,g' \ -e 's,@SIPX_TMPDIR\@,@SIPX_TMPDIR@,g' \ -e 's,@SIPX_INCDIR\@,@SIPX_INCDIR@,g' \ -e 's,@SIPX_LIBDIR\@,@SIPX_LIBDIR@,g' \ -e 's,@SIPX_SCHEMADIR\@,@SIPX_SCHEMADIR@,g' \ -e 's,@SIPX_VXMLDATADIR\@,@SIPX_VXMLDATADIR@,g' \ -e 's,@SIPX_PARKMUSICDIR\@,@SIPX_PARKMUSICDIR@,g' \ -e 's,@SPRING_HOME\@,@SPRING_HOME@,g' \ -e 's,@XPRESSA_BUILD_NUMBER\@,@XPRESSA_BUILD_NUMBER@,g' \ -e 's,@XPRESSA_BUILD_COMMENT\@,@XPRESSA_BUILD_COMMENT@,g' \ -e 's,@SIPXPHONELIB\@,@SIPXPHONELIB@,g' \ -e 's,@SIPXPHONEDATA\@,@SIPXPHONEDATA@,g' \ -e 's,@SIPXPHONECONF\@,@SIPXPHONECONF@,g' \ -e 's,@NAMED_PROGRAM\@,@NAMED_PROGRAM@,g' images = \ PluginUml.png EXTRA_DIST = \ Doxyfile.in \ footer.html \ $(images) PROJECT = sipXportLib all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(top_srcdir)/config/sipXcommon.am.inc $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu sipXportLib/doc/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu sipXportLib/doc/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/config/sipXcommon.am.inc: $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile installdirs: install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-local mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ clean-local distclean distclean-generic distclean-libtool \ distdir dvi dvi-am html html-am info info-am install \ install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ uninstall uninstall-am all: doc doc: $(PROJECT) external-docs Doxyfile: $(srcdir)/Doxyfile.in $(LocalizeSipXconfig) \ -e 's,@enable_html_docs\@,@enable_html_docs@,g' \ -e 's,@enable_latex_docs\@,@enable_latex_docs@,g' \ -e 's,@enable_dot\@,@enable_dot@,g' \ -e 's,@srcdir\@,$(srcdir),g' \ -e 's,@top_srcdir\@,$(top_srcdir),g' \ $(srcdir)/Doxyfile.in > Doxyfile install: install-doc .PHONY: install-doc install-doc: rm -rf $(DESTDIR)@docdir@/$(PROJECT) @INSTALL@ -d $(DESTDIR)@docdir@/$(PROJECT) find $(PROJECT) -type f -print \ | xargs --replace=% @INSTALL@ -m u=rw,go=r % $(DESTDIR)@docdir@/% clean-local: clean-doc .PHONY: clean-doc clean-doc: rm -rf $(PROJECT) Doxyfile $(PROJECT): Doxyfile rm -rf $(PROJECT) @DOXYGEN@ .PHONY: external-docs external-docs: $(PROJECT) $(foreach img,$(images),$(PROJECT)/$(img)) $(foreach img,$(images),$(PROJECT)/$(img)): $(PROJECT)/% : % $(PROJECT) cp $< $@ # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: sipxtapi-3.3.0~test17/sipXportLib/doc/Doxyfile.in0000644000175000017500000005364212205613305022544 0ustar00danieldaniel00000000000000# Doxyfile 1.1.4 # This file describes the settings to be used by doxygen for a project # # All text after a hash (#) is considered a comment and will be ignored # The format is: # TAG = value [value, ...] # Values that contain spaces should be placed between quotes (" ") #--------------------------------------------------------------------------- # General configuration options #--------------------------------------------------------------------------- # The PROJECT_NAME tag is a single word (or a sequence of words surrounded # by quotes) that should identify the project. PROJECT_NAME = sipXportLib # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = "Version @VERSION@" # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Dutch, French, Italian, Czech, Swedish, German, Finnish, Japanese, # Spanish and Russian OUTPUT_LANGUAGE = English # The DISABLE_INDEX tag can be used to turn on/off the condensed index at # top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. DISABLE_INDEX = NO # If the EXTRACT_ALL tag is set to YES all classes and functions will be # included in the documentation, even if no documentation was available. EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members inside documented classes or files. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSESS tag is set to YES, Doxygen will hide all # undocumented classes. HIDE_UNDOC_CLASSES = NO # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = YES # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. STRIP_FROM_PATH = @sipx_abs_srcdir@ # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a class diagram (in Html and LaTeX) for classes with base or # super classes. Setting the tag to NO turns the diagrams off. CLASS_DIAGRAMS = YES # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the CASE_SENSE_NAMES tag is set to NO (the default) then Doxygen # will only generate file names in lower case letters. If set to # YES upper case letters are also allowed. This is useful if you have # classes or files whose names only differ in case and if your file system # supports case sensitive file names. CASE_SENSE_NAMES = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the JAVADOC_AUTOBRIEF tag is set to YES (the default) then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the Javadoc-style will # behave just like the Qt-style comments. JAVADOC_AUTOBRIEF = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # reimplements. INHERIT_DOCS = YES # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 8 # The ENABLE_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = YES # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. WARN_FORMAT = "$file:$line: $text" #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = @top_srcdir@/include @top_srcdir@/src # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. FILE_PATTERNS = *.cpp *.h # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. EXCLUDE = @top_srcdir@/src/test @top_srcdir@/include/tapi @top_srcdir@/src/xmlparser/tinystr.cpp # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. EXCLUDE_PATTERNS = config-*.h # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = @top_srcdir@/doc # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = *.cpp *.h *.html *.png # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = @top_srcdir@/doc # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. INPUT_FILTER = #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = YES # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = @enable_html_docs@ # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = sipXportLib # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. #HTML_FOOTER = @srcdir@/footer.html HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet HTML_STYLESHEET = # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. HTML_ALIGN_MEMBERS = YES # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compressed HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = @enable_latex_docs@ # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, a4wide, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = NO # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # For now this is experimental and is disabled by default. The RTF output # is optimised for Word 97 and may not look too pretty with other readers # or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using a WORD or other. # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. MACRO_EXPANSION = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # in the INCLUDE_PATH (see below) will be search if a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. PREDEFINED = # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED tag. EXPAND_ONLY_PREDEF = YES #--------------------------------------------------------------------------- # Configuration::addtions related to external references #--------------------------------------------------------------------------- # The TAGFILES tag can be used to specify one or more tagfiles. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = sipXportLib/sipXportLib.tag # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = @enable_dot@ # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # the CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the ENABLE_PREPROCESSING, INCLUDE_GRAPH, and HAVE_DOT tags are set to # YES then doxygen will generate a graph for each documented file showing # the direct and indirect include dependencies of the file with other # documented files. INCLUDE_GRAPH = YES # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # This tag can be used to specify the path where the dot tool can be found. # If left blank, it is assumed the dot tool can be found on the path. DOT_PATH = #--------------------------------------------------------------------------- # Configuration::addtions related to the search engine #--------------------------------------------------------------------------- # The SEARCHENGINE tag specifies whether or not a search engine should be # used. If set to NO the values of all tags below this one will be ignored. SEARCHENGINE = NO # Got these recommendations from Rich S. MULTILINE_CPP_IS_BRIEF = YES DETAILS_AT_TOP = YES HIDE_SCOPE_NAMES = YES SHOW_USED_FILES = NO sipxtapi-3.3.0~test17/sipXportLib/doc/footer.html0000644000175000017500000000016312205613256022610 0ustar00danieldaniel00000000000000

sipXportLib home page

sipxtapi-3.3.0~test17/sipXportLib/doc/PluginUml.png0000644000175000017500000012231612205613256023053 0ustar00danieldaniel00000000000000‰PNG  IHDRü®¢šysBITÛáOà pHYsÐй‹çŸ IDATxœìÝg\TÇ÷0ðs—Ž"ØÀ†¨¨(H ¨CSêªÑ¨±F±¡¨Kb *»h•X!XâÏ,ØÅŠˆ¾ì|øP{õ#Tã&Nœ¸}ûvy·B>,--oܸ!ïV $“'OŽŽŽ–w+B¨ÕbÐOÁ¹C¨aiä¯X†aäÝ„¢9tèÐðáÃåÝ „»]»vÕbÐOåææêééÕöQª¦èè耀y·!„ŸÏ—wjì!µôs8¯@õ&¹B¨ö 2äàÁƒònBÑøñããââ V§÷ „BÃ0JJJònB›ÖÄxð   @úfNNN ì[·Ž-éÔ©Ã0‡®ò¡à—_~Y±bEqqqu*A!Ô@a¦¿žjè9E„¢›7oÀÏ?ÿlddôõë×C‡ݹsÇßßß××÷Ñ£G………ZZZÆÆÆU«üãÇݺu+//ÏÎÎnÒ¤‰¤Íø|~ZZôìÙ“–|ýúõÙ³gP }vvöÛ·o9޹¹y•+A!ÔpaÐ/7Ç\¿L]]½K—.Ë—/÷õõ¥9ÅÂÂÂqãÆU¹þ§OŸ–••µk×NJxb}þüùÉ“'°páÂN:€¯¯¯½½}^^|;°°°¨r¦_GG§¬¬¬ÂÍ233¿|ùAÿýû÷@[[ÛÈȨj‡†oíïÞ½»¦¦f•+A!Ôpáô¹asŠK—. 100 9E¨©œb=¾~ýZ“FHq¥§§€ººz‡h ]ažÐ7¬¥¥%Ìž=›a˜àà`º™­­-Ã0 ÿMHH°²²RQQa§ чæÌ™Ã0LPP,[¶Œa˜Ñ£GoÞ¼¹k×®ÊÊÊ...ô”€¦ù›7oÞ¦MZaFFôîÝ›.»F‰‰‰±µµUSSkÒ¤‰ÏóçÏé–Rlÿ½{÷ttt~úé'BHAAAppp‡”••µ´´pº?B5.??æÌ™;wVUUåp8zzz¶¶¶W¯^¥>xðàÁƒ¥¥¥Ò+aþ«yóæ?ýôÓ»wïªÓ0]S¤ª˜é—z’SD±h´Ý­[7v5ñøøx5jü7hNMM+++àñx·oßfÚ¸qãŒ3ììì.\¸ ¤¤Ô·o_>ŸO·¬þ˜˜øæÍ‡ÇŸ={öåË—ÆÆÆìÜveeôÓpœ2~üøØØXkkëM›69sæÐ¡CoÞ¼¹qãHzˆaöè¹¹¹^^^¦¦¦üñÃ0'NÜ¿ÿ Aƒ–-[öåËÚµFkúôé3gΔw+d5{öì+VÈ»¨b\.÷Ò¥K666?þø£ªªjvvöµk×^¿~MíÞ½;<~ü¸sçÎV5kÖ¬æÍ›¿~ý:>>~ß¾}%%%Õ¹ÔG–CoÛ¶íÕ«W-[¶¬ò(éã€ê©5Í›7€wïÞÕÞ!® .€ºº:Ç£%W®\€Î;BfÏž ³fÍ"„мàܹséfß}÷ìß¿Ÿþ÷àÁƒ–––ÊÊÿÿä>$XÃÒ¥K`Ô¨Q›6mêÒ¥‹’’’³³sÝw¹žÛ¶mLœ8QÞ ‘ƒÿý,--åÝ9;v, 80##ãܹs~~~`oo_XXÈçóµµµàîÝ»åååZZZððáCBøµ´´ÊËË333UUU›4i’““C¡Áº¶¶6ŸÏ¬Ò¾}{X¼x1ŸÏõê0 SPP@8p ØÏꘘBÈü&&&tã÷ïßÓG_¿~-å!öˆgΜ±³³322ÊÍÍ¥½VSS€­[·òù|ùŒ{ý0iÒ¤ûZ­+!!!ò6™$$$À?ü ï†ÈÇ›7oèóõåËÁòòòòJÕC+yüø1ýï¾}û@SS³Æ*Ûq«¬¦ÆUÁ˜1c`÷îÝ8½G>j*§HO—/\¸põêUú³€”œâ¡C‡ÊËËÏž=[×n vïÞÝD~~øáy@£Fß•§OŸ655õððHKK[»vmJJІ†Fffæ§OŸ444LLL?~üåË—¦M›Òܘàïr;wî,--õðð )1ömÈ0Œ` ïÞ½{ùò%Ã0tÂ=7011¡³íi36mÚtÿþýû÷ïߺu‹¾µi¦óæÍD7VUU¥/++“ò="¬]»öêÕ«Û·ooÑ¢}ÔÉÉ ºtéYTTT7£]?mذ¡ !X¶l™¼‡ ÉŠý–ߺu«àû‹ý%ŸNס?þÓ¿/^¼èææ¦¢¢âì윓“#¶Z333àñxlIVVÖˆ#tttTUUíííïܹCË?}úäïﯧ§ÇN êØ±£è¡“’’lllÔÕÕUTTÚ·o ÞÞÞtË.]ºÌ;—ÝeÇŽúúúçÏŸ€Ë—/ÛÛÛ7iÒDEEÅÚÚúÚµk‚•³[V8’Ú/TÏÈ‘#†üEÎÒÒÒÁÁAö*|ÊYíX`¦_ ¹çåÜÿú‡fúåËËËK.}ÇL?!¤¨¨ˆ~'¥¦¦Š>J¯¹·³³#„ÐósúP`` |ûUÍÕÕ,X@¢?ÓÍ™3G¨†¤¤$011¡›ýöÛo@gسɰçÏŸÓGéi¿ššZii)!„†ò7nÜ ÒøæÍ›óx<)±Gôññ_ !<ïСCßÿ==nŸ>}jt\ šéß¶m›¼"“U«VfúšÎ]]ÝÀÀÀ;wî>J¢©tú·ƒƒƒžž 6Lt3BÈž={ß°%%%t­¿™3g®Y³†ÃátíÚµ¼¼œÏ绸¸€¿¿ÿ;w6lØ:tª³  €®ù»xñâ½{÷’o³ 22òæÍ›ì.ÚÚÚ;w¾xñ"!d×®]Ó§O‹‹£ÝìÖ­›`å‚[JIí­‡®¡ÜªU«²²2ò-øÙ²e‹ì5ÔÆS\ϱ™~ úå£W¯^l¨§®®nii¹víÚ’’B=çÖÐÐ(++{ðà4mÚ”¾pwïÞ ŽŽŽ„ ÀСCi…ôýÿý÷ß Õ@/`†þ vúôiÁ÷$bÑ üøñ_å~)bÐ/Gׯ_§±5} €©S§BæÌ™S¦L!„ýŸVrôèQèÒ¥ ýè°³³€[·nÑwMMÍ¢¢"BȹsçÄý/^¼ '&& Íô:Ù`ÏD»I׃oÙdÑ-¥Œƒ¤ö‹ÖSRRBÃˤ¤$BÈüùó•••ß½{'{ ôã…¼rP\\|ïÞ=HMM¥3pÑ)æææÊÊÊ4ÉÇ^Ñ+8i‡þ‚Æ®â/:Ÿ‡Ö@§ tíÚµiÓ¦B›!QÊÊÊMä±Â)W䈾5z÷îÍΊ}”¾qèegÿý÷ôéÓ=š••Å>Ô¥K—Ë—/oÞ¼ùÎ;?¦³ê­­­AÜ;”]'Gð!ú†µ²²b¯âe?è}}}ãããCCCÇðàÁ¿ÿþÛÁÁá×_•þ{DWW×nݺ=xð ..nòäÉîî¦tž]bhÊ”)5?¸5nJJJ“'Ož4iRJJÊüqøðá„„„²²²#GŽˆÝžËå [KKK³³³Ù 9‚×ü?~ÜÑÑ‘þýøñcú¯àú™™™tvPÇŽÕÕÕ¥´°]»v¾¾¾‰‰‰¾¾¾={ö ?~¼ŠŠŠ¤íÙi?ðîÝ»ðððË—/çææJßRÊ8Hj?ýt¬GUUuذaÛ·owuuÝ»w¯‡‡‡žžžì54f8§_îܹS^^®¦¦Æ®Ã-H48 ›=}ú”^¤O*,,:1îæÍ›111 yB¿Px«ò!$„FÛ666¢BßSC‡mÖ¬YVVÖÛ·oé´W:SæÍ›gbbÂçó544èeµ­[·¦WçKzW~üø133z÷î A?{t¡ ãÆcÇŽMOOŸ8qâ‹/ÂÃÃÿþûo é±Gdfúôéðûï¿óx<•½{÷úùù͘1ãÓ§OÛ·o_½zu­Œ/B‡ÃqssÛ·o"xòäÉ ·§Æë?æóùô°uëÖ•——Órš×311¹/ÀÙÙ™Nú¯p5?†aŽ=zòäI»wïúûû»»»óùü ;EqwwˆˆèÖ­Û´iÓ*Ü$Œƒ¤ö‹­á§Ÿ~€?ÿüóìٳϟ?§³†*UC£…™~9¨'9E„këÖ­[·nûÃ0tš5tèP:!‡"ß~;:%èZŠC‡¥9{ÁhFŠÒÑѬáСCBG§¿Î nOÏðEIyHðˆÓ¦Mc¿›él"„Pí)--åóù‚;½Œž©RÐ;‡´nݺU«V‚å Ãìܹ3--íìÙ³K–,¡ ôÑ”?}§wëÖݘ®7™™ùæÍ›6mÚÐ8[,†a<<<<<<.^¼èèèxþüù¬¬¬víÚыٳ !YYY4U±qãFvŽ!„ý­RÆqÔ~± ³²²üýý›6mJ/UªT ýrP©œâ©S§Øœ¢§§§`NñêÕ«Ïž=£9EggçÊæB5hÿþýׯ_çr¹Í›7ONN^²dIÇŽ.\(ïv!„äéåË—æææ}ûö555mÖ¬YNN½ÈaòäÉ’v9pà@ûöí#"" ((H4€ÖÖÖNHHèÓ§ÏòåËíííÝÝÝ{ôèñóÏ?ïÚµËÑÑqüøñššš7nܘ0a‚——WÛ¶m_¿~ݯ_?===ºT€h…™™™“&M0`€¡¡!ýuÑÀÀ€žl?yò$**jذa¢‰smmmUUÕÒÒRÿ·oßÒÂåË—ÿòË/•Ií2dˆèøp8œ‘#G®Y³&33sìØ±t½²JÕÐxÕÞux!oY¾|9LŸ>]Þ iÀä»N?]Ž/ämÐbccMMMÕÔÔ8NÇŽƒ‚‚òòòäÝ($+¼·ö4ò yß¾}ëêêÚ®];eeez']‡èèhv}zŒ ^ÈK¬X±Bìf]¥W__ÿÕ«W„²²²•+WvéÒ…ÃáhhhØØØ\»vrýúõîÝ»«ªªŽ1âÏ?ÿ€=zÕ™››ëêêJ× ÒÖÖöõõÍÈÈ Ûœ}‚o7_@¨A¸r劼› ]»vssó³gÏÊ»-ÉGPPPlllŸ>}äÝ„ª-µôÓ¬!æQÒ8ó|JJJô_]]]y·!ùPSSeeüõ»æÝ¸q>Œ’ Š_»v­?à´µµ?~üøøñcz—.„ê³ØØØÙ³gÛÙÙÉ»!!¤PØd &’#W‹A?½ÏsóæÍé=ުϚ4i***ònB)kkkðññùã?äÝ„£iÓ¦}:»YlllïÞ½===uttLLLnÞ¼™››Ë&ãéö0mÚ4†aâããíììôõõ###ٚŶ³ÂÆ×“AFÐׯ_÷îÝëë뫯¯ïççwüøñ ´k×î»ï¾[·nÝ«W¯äÝ@ñŸ|[œ´. öQðè’ú.T®««{åÊBÈÓ§OGUáî oÛ¶m0qâD¹=11¼¼¼ärôÿý,--Ù>ŸïääDñôôüðá-€””‡CÏui!ûV}ýúõÊ•+iaxxxii)!$##ƒÃáÐ ÍÌÌ¢££ !¯^½úá‡Øc ½äø|~=Nœ8A9qâ„©©©àÂÂÂJJJ/^¼XTT¤««{ñâEBHii©——}3Brss_Õ’°ßµk—£££àCB­bÿËîòáÃ%%¥óçÏBþùçŸ:Hß}ôèÑ%%%III:::l¹ØvŠÖÏAV0“&M€mÛ¶É»!2Yµj„„„ÔÍá :4lØ0MMM9p8—-[¶Œ5J]]-´··ß¸qãÛ·owOHHÁ¤Œè9ª››ÛÀ»víºÿþªµ_ÆïµE‹±w•QQQ„¨¨(ˆ¯ÊîÁƒnnnàëëÛ«W¯Y³fÕàá*ܽH#7fÌؽ{wýÇŽ:Ù˜9sæ¾}û`îܹÎÎÎS¦LéÓ§»¯PÐOSÚqqq¶¶¶zzzëÖ­£åëׯ·¶¶öññéׯßÒ¥K !3gÎ<Ê¢E‹è–‘‘‘ƒ êÚµëäÉ“¥ÔùèÑ#wwwOOOkkkö#5%%ÅÝÝËåöéÓ'&&†@¯^½N:EÂnÑIê¦Ø:Eû.‰hÐ/©ï¢ÛBôôô„>@Å¡G500ÐÓÓ»{÷nNN—Ëår¹‚uJϘ˜sssmmí®]»¦¦¦VØ5¹À _0è¿wïýQN0†oKïÑ;øÒBúr¥ÆG ß¿MCmvc¡ÈU4+&¶N±©²ãÇ Å@tw>ŸoeeE/°“~ ¡nJªSvlO9Äö]Ryiié®]»Ú·o/øÃŸèfb“b7OéÙÐzƒ~ÁL¿ŸŸßÇ·lÙ"˜Ù•ô³²³³ //ÏçïÚµ‹}ÔÞÞ~þüùtrˆ``ª¤¤DOÝi!yròäIBHbb¢ÐÌÑÆ»¸¸øûû/_¾\°°²Ó{D ½¶µµµ“’’Š‹‹GÅîbcc“žž.Ëî’‚þÊNïaÕ‡AV0 1èoÒ¤I륫««©©ÙªU+ö‹©W¯^+V¬xòäI¥š÷þýû;wº»»³w8VWW744ôo)úWRDæ“xz|úôé~ýú±åB}@jðàÁôÐiiiÚÚÚÅÅÅ’v¯fÐ/%Z¯`Ð/˜éo@^¿~-tZÝ(((077¿sçÇ;wîΡW0òäºÔ°‚þ/_¾dÕš«W¯.X° gÏžl°«¯¯ïïïöìÙ U÷îÝ[´h‘‰‰ »oëÖ­éz}Ò§÷ ñýZÉÍÍÕÑÑÙ·o‘œ2“}ºŒéBIû(=Æe'ÑIšYK–,iÛ¶íýû÷+l§Œ*õÝ]ãÓëá€4fuôËž;ÌËËãr¹lÂiðàÁ„I©2ooo+++oooggçõë׳‡Mk‰fÅ$Õ)6UöâÅ Ÿnݺ™™™¹ººòx<ºn=IIIa_è¢ÛM±uÒdœ®wÿþ};;;OOOvœhß%e.GŽÙ§Oooo;;;Ú±»‹MþU*)š ­ÄkŽ5i IDAT¨aÐ߃~6eH—¢ªKEEE PWWçp8íÛ·¯ãÔ9r]jXAÝxøðá’%KzôèÁFðmÚ´ ¼té’Ð"NOŸ>ýí·ßÌÍÍÙ-[¶l9eÊ” .”——KºWö Ÿ²aÃ##£ââbI)3Ù§Ûɘ.”t ƒ~±“è$ͬ£»ÇÇÇ·iÓæöíÛÒÛÙ ¦/Ö倠 É!Ó¡” Å ¿!ýÕ ú¥¸}ûöüùóÙ˜ÞÀÀ 88øÒ¥Kk×®ýî»ïØAÍ›7Ÿ0a™3ggɲzØìØo¿ýÆîXVVfffF’›2“qº©LºPô@baëÖ­€… B.\ôzVÑItb éd-º”yPP®®nBB‚”vÖÿé‹u< ¨Bô£ºÐ€²¡ôcÐ3 úeqýúõ9sæ´k×þKKKkÔ¨Q‰‰‰bg\Ty~Ù5 Sƒ€ã©`Ø _ª5êêê§OŸ–w+BÕ›ˆˆˆK—.8p௿þ²¶¶1b„——»H¿\p8œÖ­[ÛØØ”––¶mÛ6<<¼eË–rlOC‡ã©¨0èG!„¬è-ºè]ºäÝ–ÿƒ ¦š…㩨8ònB!„B¨vÕb¦ÿóçÏЪU+ö„ê-z³ëׯ˻!NllììÙ³¿~ýêææöÇ´hÑ‚–?xðÀØØXEE¥.s÷î]zÛ xöìYÇŽk°r¹ô!„¢j1ÓO£¨òòrBõ}¹–””ÔÞ;¢aÉÈÈ ·Ð¦kl‹õðáCwww†a¸\®™™YPPP¶qãÆ?êêê¾|ù’-ïÞ½{VVVUš."22’az»øððp†aÖ¬YCZ¼xñÇÙ-{öìI/{ªáСC¶¶¶¾¾¾¶¶¶k×®eË…v—®{„BUV-fú›5köéÓ§ôôtÚ; B5bß¾}óæÍ³±±‘wCê‹ÄÄÄAƒ]¸pÁÑÑQÒ6&&&Û·o722:vìXvv¶ÁÂ… õôô*u ììl[[[uuõ˜˜ÁrÑȻʂ‚‚fÏž!!!¡¡¡sçÎ¥-Y²düøñ~FMž<ùĉvvv™™™¿þú+[.ãîT ö!ù*..>zôèŸþÙ·oßÑ£GëëëË»E!ÔÞ A¸d'j@pÉNvÉÎcÇŽ }JÌœ9sß¾}0wî\ggç)S¦ôéÓ‡nÌ®]TTùùùÁÁÁt£Gèééݽ{—’’’âîîÎårûôéC¾-êÌòóó#ÿ½õ{ÿ—U«VijjÒ%ÿþþûov…oof'XÝ~æÌ™‚G_´h‘¤í !zzzû÷ïÜ@ìîbû.¶Gôg‡¸¸8[[[===ºˆ5!$&&ÆÜÜÜÃÃC[[»k×®ôVA¨à’²(**úóÏ?‡Þ¤IöÅÏápœœœ6oÞLï¥*ª–ì”"&&FOOOMMÍÛÛ[°…÷ïß/--­ƒ°··«~U¿ýö›‹‹Kvvvõ«R wîÜa_‡‚ŸØ•Ug/yÁuúú ú×éçóùNNN„OOOzsJB¤¤¤p8œ³gϲ_`l̽k×.z×m¶0,,¬¤¤$00ðâÅ‹999ºººYYY„ÜÜ\55µ/_¾°ÕŠý°*?pà€‘‘Ñ»w¢öîÝË–ËxsJÑ ¿RG?{ö¬‘‘—˽yó¦”ÍÄö]ÒÆ0zôè’’’¤¤$Bȇ”””Ο?OùçŸ:tèPa¿PMÁ _ŠÒÒÒ“'OŽ;V[[›X ÃôíÛ722rÈ!ìe*ÊÊÊîîî;wî|ÿþ½àîÕ úËËË#""ìíí}}}¿ÿþ{‡ÊÖЦM›}ûö;öÆly5ÃÄJa?'ããã **Šñññ•ªJÆfçååq¹\öþ\ƒfZ´hû©^Sj£N!ìíÆ|}}{õê5kÖ,ÁG«ùlV¸{CO úú úƒþ{÷îÑ ýlOåååBAÿ!CÞ¾}+XHoÉ™——WPPpüøq¡_222Øje » !aaaaaaUè#[½xCÊQ$•—––îÚµ«}ûö‚_6’‚~Á¾KÚèí0333i“>þÜ´iÓM›6•””DEEV¡§¨j0èÅãñRRR&Mš$8gÏÒÒ2<<üùóçìfŸ>}Šõòòb£UUUŸøøxzn/Ëy%Y¾|¹““û>jÛ¶me{™™™•Ý«f þ É~Èø+¥JE·bQg;usÅvçÍ›7Báe7@PƒO6èW%;¿|ùÂ0 Ã0Û·o¯©:cbb TUUøîÝ;ö@=’±†äää%K–µSöÝEÕF7å«úƒ,(((è—_~- ½qãFµÚ˜ 2¤G[·nUQQù矆¹}û6}HII 8áÏÇoÙ²¥U«V‚…ÊÊÊ ¯¯¯©©©¯¯ß¬Y3Ç~õèÑ£² c¦¨¨ˆFí•¥¡¡A'  ­ŸCd˜jîÜ9•ñãÇŸ?>**êíÛ·Òwì»”jéfìúfZZZ Ó¦MÓÐÐØ³gÏÁƒ+îB5réÒ¥ÀÀÀ¶mÛº¸¸DGGçç盚š.]ºôÑ£G©©©ÁÁÁ:t`·oÖ¬Ù˜1cŽ?þöíÛèèh—òòò¿þúkÔ¨Q-[¶6lصk×Ä(88˜ý{ÿþý û¸¸L:µoß¾Àçó###W¬XÁ¾^½z·nÝrrròññéß¿?ýtš6mÃ0ñññvvvúúú‘‘‘°páBúæêÔ©Ã0'N€ÜÜÜAƒ 4ˆa˜çÏŸ³ ˆíÝ»·§§§ŽŽŽ‰‰ÉÍ›7W¯^Ín3}útZUHHˆ¦¦&Ã0ÇŽ344Ô××ÏÈÈ€³gÏ0`РA}ûö¥uffföïß¿W¯^^^^ÒÇ\´G’ ©ääd –––Àï¿ÿnccãëëkoo¿lÙ2IG™5kí…‘‘Ã0‹/¦å¢—Ôͨ¨(OOÏÁƒ›˜˜H©S´ñ’ê€çÏŸWj™GšS–´‹Ø'Ä=Åb_ b_K k<¥©Á3 !uŸéïÒ¥ ýñîëׯAAAÎÎÎ^^^½{÷þçŸ*[Õ›7o444.]ºTXXèèèøñãGZ¾nÝ:Á„¨$<oÒ¤IÓ§OúFÆÝ¥c»)ÉíÛ·wîÜYµÊ?þ}º_¿~l¹’’7/ôV:úàÁƒiËÓÒÒ´µµ‹‹‹%í.%{"™~Ñ„ŸMzzz…ÝA5®Áeú·nÝÚ©¦jkkÓsQªsçÎ ,¸sçN¥ÚööíÛ 6ØÛÛ³ --­öíÛÿõ×_%%%ìfBï™@Hº‚?—Bø|~=Nœ8A9qâ„©©)»»Ð|9¶¼ÂOI3ëľIeŸ¾Ø·o_ú],”éŠÁÄöHJ7333CCC饦¦F?ˆòóóGÍ–Ë’™–Ôx±3ÃÃÃéÜ÷ŒŒ ‡#©NI—4ûQÆq±³IÅ6@ô‰“>yRtw±¯¥†2ž¢ä9½gïÞ½EEE5~¸>¨©©óx¼ï¿ÿ~Þ¼yôKz„ =ªlm±±±B/©J ™2eJ•w—‚í¦”m/^|˜¶ªI“&앯2þD~ÿþ};;;OOO‡[·n±åþþþmÚ´±±±Ù±c!äùóçBG§­9rdŸ>}¼½½íìì’’’$í.¶ï’zäÛÍ«V­"„ 0ÀØØØÜÜÜÜÜ|ìØ±‚¿ ZÕà‚þÕ«WWœÕ«eeå)S¦œ?ž=E—ÝÓ§O—,Yb``ÀÖ¦¦¦xïÞ=öÂVÖÊ•+‰¸ „ô'µÂÂBÁšsrrØÂÂÂB —ç‚È|9 dú%ͬÉA…Ó?|øŸ?&MïÛ#)Ý9rä/¿ü"Ø—#FtìØ1$$äôéÓ‚¤Ê¤Jš{)v¦âû÷£ƒƒƒÇŽ+e%5^ÊìGYˆM*¶¢ƒ,}ò¤èîb_K w<åôóùüž={ÒH‘òûï¿ÓŸíöìÙcbb¢©©IC‡»wïŽ;vذa¿þú+ÝxÅŠÞÞÞ?üðC=H ÏŸ?ïàà`ff¦««keeEÙ±cGÏž=E¿,Ož<éâââããcnnN£‡›7ojiiMœ8q„ mÚ´ñôô$„¼ÿ^è ûúõkqq1ýÚæp8‚ ã[·n 8ÐÛÛÛÐÐÐÕÕõÉ“'„´´´V­Z±×)BÄî.öè’ˆvSì€\¼xQ°åæææR†ŽræÌصkýïÎ;ûõëGŸ²²2xúô)!d÷îÝÎÎÎ>>>½zõ:tèÜùÝ»wJJJ_¿~%„Еõé)‡™™Ùúõë=<<š5k&ý§¥¥5mÚTÊcÐ_ýß P5˜››ß¹s‡Çã;wrrräݨƢý“&MzRÓ’’’f̘ѩS'öóÙÐÐpÖ¬YW®\a¿»%yöìÙªU«,,,Ø}õõõíííi¬&´1ˆdú…þåóù­[·¾pá‚àf‚PAA`4,v®<Èö[â©S§€ÃáXYY±_@ðíz€ÇÃ~Áª®^½*4}‘òúõk !øÓ§OA¶ Ÿí‘”n.Y²¤mÛ¶÷ïßgURR’––¶víÚ~ýúõìÙ“ý9ER*x‘ƒØÆ‹Ý·´´ÔÈÈ(<<<333--Mhë”Ôøª]Æ ¥I‚ ŠÚEŸ8±O±¤Ýž–îxÊ-èýúµ‡‡‡`Izz:Ã0k×®-))4hÐË—/=zôÝwßѯ_¿®ªªJ·œ;w.Í7üûï¿ô—k×®uèÐ^QéïïO±··_¿~½PcΜ9Ó¡CúƒKrrr›6mh¹““S¿~ýrrrnܸ¡¢¢ÂnïêêúÇU’““ÃápØs©¢¢¢V­Z¥¤¤B®^½úðáCZ>~üø¹s犈ÐîRŽ.Dl7Åell|îÜ9Á$myêÔ©Q£FÑ3ZBH¿~ý6mÚDÿ¦3ì_½z•››ËápèÓ™œœLä=ȧNbo¢D³)oß¾-((PRR ),,üûï¿›4i"Xmzzº²²²¤&ôcÐ_ 0@]]Ãá´oß><<\Þ-jDhÐ\{‡HKK 322b#x##£ÐÐд´4¡-³²²¢¢¢ìììØùÓÚÚÚãÇ?uêTii©¤ y+ ú !‘‘‘ÖÖÖyyyô¿©©©tªÃÉ“' !‰‰‰‚ó^ªô‹Y§­­””T\\>¾M›6·oßfOM¿Ù¸KlP(4)QÒÜKÑ}³³³ //ÏçïÚµKðQ¡:%5^RZÙé=¢„žM±Oœ”É“Õ úëáxŠ’CÐ߯_? ¤¤Dç¨lÛ¶Mr¿|ù’ÏçÓ_–}4555"""((hÀ€tªÆÀW¯^M>|8ý¼nҤɵkׄcgg·yófú÷7ÔÔÔ!<¯iÓ¦t¶â_ýÕ»woºŸÏ×ÑÑ¡‹‹ :yòd¯^½ØÿÒ»‡Þ»wïÇsæÌaç,µk׎N½’¾»¤£‹ÛM±BÉÍÍURRüAÒ–¢455/_¾LÿNNNnÑ¢ŸÏÿøñcëÖ­ûöí»qãF6ï(ßA^ºt);)99¹cÇŽ|>ÿÿûýƒråÊ¡ ÿÈ‘#ÆÆÆ’:N0èÇ 5nôKÂçó¯^½dhhÈ~//Z´(55uË–-NNNìÜý&MšŒ1âèÑ£‚sPeY½GìBzô7ZXX8888::Òè´´4{{{ooo''':[Oì|9Ù' 3ëÖ¬YC]‹‹€É“'Ë>}‘v¼E‹fffô>'&LX·n,\¸²páB 3E{$¶pÕªU@Ç ÒÕÕMHH „x{{[YYy{{;;;Ó|œ”%&…&%Šm¼¤nÒË»íììæÍ›ßn®"¶NÑÆKª“ȼŠM*iB¦è'ö)–}îeÃOQrËô/_¾<..N°d„ Ë–-,éß¿ÿï¿ÿ.T[hh¨‡‡Ç¥K—²³³‡J'´ijjÒГÏçwèО)))‰žÌ©ªª² loÚ´‰ÞZ(##£Y³fô$lÑ¢E“&M¢}Ú³g‡‡GóæÍé$où²··÷–-[èß?üðMˆFFFŽ1‚®ZµJ襩S§J¿Êƒ~ úQc†A…ÊËË/\¸0eÊ”–-[©««}€õë×/Y²¤oß¾/_¾<þ¼B Š‹‹Ã²³³{öì ô#ž={öõëWÐÕÕ¥?{eee…‡‡Ó•4¯_¿nmmMS7nÜ`›ñï¿ÿZ[[ÓÕ …ommÍþ·¨¨(;;»¨¨èéÓ§ÎÎÎl¹––m¼ôÝ%]”ØnŠZU·nÝàãÇ´DÒ–yyy£G>pà{ Þ½{ß¿®\¹ríÚµùó瀛››ššÚèÑ£ccc 鯷rdBÈõë×i=Û·oýúu`` ­ÐÖÖ^¾|¹eËv¡+ÈÏÏ?pàÀ¬Y³$0B!é8Ž££ãæÍ›³²²Îœ93a„–-[zzzÆÄÄäääÐ;õJ_£¶Þâp8­[·¶±±QUU7n\xx¸è‰ jÐð)þ?µwb!6Ó¿k×.6¹Ëår†qqqár¹ùùù´üÝ»wÞÞÞíÚµ³²²ruu¥×+Œ1¢U«Vt۵µ%„üúë¯ZZZîîîëׯçp8ìÏd–––½{÷0`@@@=ÜáÇÍÍÍ}}}ÝÜÜNŸ>Mù÷ß»wïÞ©S§¼¼¼hiiùøøäççs¹ÜnݺµoßžËåÒt2-är¹ZZZvvv\.—¦ÃŸxð`6ÃáããÃÎr‘´»Ø£KI±Ý; „øøx--­ï¾ûŽþž%eKzyLL { «W¯ZYYùúú>œNÍ'„ 6ÌÔÔ”Ëåúøø°Ó–ä5È_¿~??ÿëׯGŽQUUe¯4º}û6» $ª)ƒ,£§OŸŽ1bÑ¢E.:A?ý¨1à¿ö`Ð|)ÚyëÞ•+WæÍ›§¯¯ß®]»­[·&%%éëëÓ‡zõêuæÌ™+W®È·… @Ê Ëèĉ¡¡¡‹/®ÔÝþP]ŠÕ××WWW÷ññÉËËcË „äh÷îݘéGýGbb"]·˜õáÃ;;»‘#GÎ;÷æÍ›&&&ééé—/_æóù‘‘‘ÇŽc—ìxõêܺu+00°Y³f_¾|ùý÷ßÍÌ̦M›¶y󿏏¸ 6|ÈÎΞ8qbtttÝý¯¿þòõõmÚ´iûöíëþèEEEÏž=³´´¤÷ÄBÈ÷ßþüy//¯øøx:³‚a˜””77·¿ÿþÛÙÙ™’m``PPP ¸N!¤gÏžžžž'Ož ¹{÷.Ý}ôèÑ;wî¼páÂ?þHWw¥åbçx–üøQ__?%%ÅÉÉéâÅ‹cÆŒ¡sÖÙm£gúwXXØ’%K‚ƒƒ‡ Öµk×îݻ߹sÇÀÀ //¯]»vïÞ½kÚ´i¿~ýüüü&L˜ ¸»ÐÜšªí‘”nfffnÛ¶­mÛ¶Ó§O§•¨««_¾|ÙÒÒòýû÷3gÎܳg-ÏËË bqI‡‚aþÿ‡¶,CçÎóóó333[´h‘………”çHtèìííE+ÌÍÍ•}<¥œØU+i”$u³fùûûGGG·iÓ†þF]ÁÁÁãǯÑFICçz‡‡‡×ÙAB [íý¢WåN„äE¾Ó{äKpzϽ{÷ÊÊÊÙB 7 (//B½bµ°°P°/999laaa!ÐUw€Þ+133*9GåóçÏM›6Ý´iSIIITT”¡¡¡Ð6¢óIÊÊÊ!yyytuZAô¬ãóçϤ¢é=b{$¥›#GŽºÞˆ#:vìrúôéÒÒR™_ÂCA3è•:ª´´t×®]íÛ·Ÿ5k–¤‰:±Vj<¥LïªVÒ(Iêfͺ|¬]»¶¶)¨MïAÕµ8½çòåË48@5ˆÇãÙÚÚöìÙ3&&FÞmQ@ò:Síß¿?MµÊEFFÆðáÃÙÿ2„^B½uëV`æÖ­[tî ýÕŽÞj Z¶lÙºuëÿý×ÑÑQlÍä¿ù]eeeI¥ËBKK+!!ÁÃÃcÆŒ:„èíðè±èrOúúúÍš5{ÿþ½à¯ŽYYY ®®Nï‘Ô#±…ݺu‹ŽŽþé§Ÿèmò &&æÞ½{gÏž]¶lÙܹsSSSUUUe<"hhh@qq±ŠŠJ…írîܹï¿ÿ~üøñNNN:u eŸA±5ØÍª3ž'Nܱc‡Ø‡¤Œ’,ݬ‹-6lXe÷ ­ö „PM’ßùª ºòB ï¶ !z!¯ŸŸßÇ·lÙ²g϶¾Å^ì¿„ÈÈHkkköþ ©©©|>¿G'Ož$„$&&ššš²»‹½@dKWÛØØ¤§§ m£­­””T\\ݯ_?¶\II)55•V+eèLž––¦­­]\\,©ñ’²òBªÔxŠ>Ý’Ú)i”$u³fUçBÞ   ÀL?B¨Þà¿!)++£‰4œwPuý<¾º¼¼¼Þ¿O “’’€Nú§ÿ&%%Bø|þÆ-,,éü¨´´4{{{oo{çrŠ IDATo''§[·nB""" 00²`ÁXµjU\\½bØÍÍËåÒÉ?999ôÞÌl9=£0`€±±±¹¹¹¹¹ùرcéM ×¬Y£««keeE§ÅOžzÇ7 ŒxP£¥§§M›6•wCB¨¶à…¼õš”4?…Ëø „B¡ aÐ_¯IOóS¸ŒB!„’ƒþú«Â4?…É~Ô€¬ZµŠa†ajªÂØØX}}}uuuŸ¼¼<¶üÁƒt=– •——oß¾}ÿþý‚…²ï^ãªß#A[¶l ÈÏϯÑ6Ö€ºéæÆ:D©nsB¨áà¿þ’%ÍOa²5aaa‚¯R>Ÿ¿fÍ.—ëìììèèX… 7nÜøñãG]]Ý—/_²åÝ»wÏÊʪp÷òòòü1''gðàÁ‚å2î^ªÜ£ÀÀ@†a\]]íììÆŒóéÓ'5jÔ¶mÛ¾|ùRáq !Ë–-ëß¿¿»»ûìÙ³y<ž”åøÄUª›ãÆ;sæÌܹs+Û<„R}êääÔ³gÏ=zКËËËõôôþ÷¿ÿ 7==ÝÑÑÑÛÛÛÉÉéÖ­[„©S§@\\œ­­­žžÞºuë! ,|ñûùùBrrr¸\.—Ë€gÏž±uÆÄĘ››{xxhkkwíÚ555•–÷èÑ#99™ÝLìîb.É£GÜÝÝ===­­­CBBê¸Gì6jjj¥¥¥´ðÀæææ-Z´8|ø0[ýÉ…ý¯……ÅñãÇéß·oßnÙ²%ŸÏ'„¬_¿ÞÚÚÚÇǧ_¿~K—.­O\¥ºIÙ¶m›···”g2iÒ$ضm›ôÍÄ €µk×Vaß*[½z5×åAB ýõÔüùó}űµµ‡#öQ__ßÄÄDy·50²ýä[ŒVRRxñâÅœœ]]ݬ¬,BHnn®ššÚ—/_!ááá4ËÈÈàp8t÷¾}ûîܹ“ÄšoÞ¼€‚‚Á£ðùü=zœ8q‚râÄ SSS¶1£G.))IJJÒÑÑl¤`Œ(¶üÇJJJçÏŸ'„üóÏ?:t å?~€>Hß]ÊÑ…ðù|33³èèhBÈ«W¯~øá‡:î»MII ¼~ýšN:µ¤¤ääÉ“-[¶,//§çææŽ5Š­_EEåÁƒôoz¿¶·oßBÔÔÔh¨ŸŸ?zôhRž¸Ju“róæM]]]Ñc  !¤ð0èo`@MMMÞ AŠC(è_¹r¥Ð/H+W®$ß‚õ²²2BH^^^AAÁñãÇ…¶ÌÈÈ „¼ÿ>:::88xìØ±4¾ÿðá|þü™ýoß¾€ÂÂBÁÆäää°…………››K€ÇB233ÏFd‰?þÜ´iÓM›6•””DEEÒò/^€`t(©ZIGB{DÏ|ø|~NNN÷ˆÝ†ˆ6ž>}J¾…òô$M”šššPÐÿæÍBȈ#:vìrúôiz.'÷'®²Ý|òä {ò) ý!…‡ò"„þ#,,Œ~:À·-,,Œ}TYYôõõ555õõõ›5kÆãñØ”=z”••YYY}øðaÊ”)4€‚‚øv0>ŸO [¶lÙºukzÊ!ùïônzè*¬ü£¥¥•0mÚ4 ={ö~üøÝ»w¿|ù"÷'®RÝ€+W®Ta}!„R4uûê.œÞƒjœ¤9ý4x¥vìØáææôjËOŸ>Ñò/^øøøtëÖÍÌÌÌÕÕ•fýÛ¶mkggGž¢Wj&$$´hÑÂÌÌlß¾}0aÂBŸÏ߸q£………ƒƒƒ££ãĉ !iiiööö‚׃FDD@`` ùvèªU«âââèuŸnnn\.—Î!¼”–çååB `lllnnnnn>vìXö׉½{÷º»»Ó+V%í.öè’óÕ«W^^^;w677§»ÔYf̘®®®ß}÷]`` ŠC€víÚ™šš:88ùòåýû÷wss›1c»»···•••···³³óúõëÙåõÄU¶›ÅÅÅÝ»w¿|ù²¤§ŒÂé=!…‡AƒA?ªq’‚~…QPP`nn~çÎwîÜ9ø6 œÂçó'OžðîÝ;ù6²R¤ôH‘T¿›/_¾är¹«W¯®pK úB ×éG)8‡Óºuk›ÒÒÒ¶mÛ†‡‡³³í†Ù²eKbbâåË—}||äÛNÙIé‘"©~7Ïž=;g·Zj!B5 ô#„œººúéÓ§%=Ê0 UÒ€H~7ÇWSA¡†/äE!„BHÁaÐB!„‚Ãé=!€GÙÛÛË»ÉÇÓ§OåÝ„ª]ô#„¾~ýzéÒ%y·!„Bµƒ~„»nݺýóÏ?ònBò×¥Ky7!„j ý5vM›6Å5 B!ņò"„B!¤à0èG!„BHÁaÐB!„‚à!„B!‡A?B!„B ƒ~„B!„ý!„B)8 úB!„Rpô#„B!¤à0èG!„BHÁaÐB!„‚à!„B!‡A?B!„B ƒ~„B!„ý!„B)8 úB!„Rpô#„B!¤à0èG!„BHÁaÐB!„‚à!„B!‡A?B!„B ƒ~„B!„ý!„B)8 úB!„Rpô#„B!¤à0èG!„BHÁaÐB!„‚à!„B!‡A?B!„B ƒ~„B!„ý!„B)8 úB!„Rpô#„B!¤à0èG!„BHÁaÐB!„‚S–wäcîܹϟ?—w+ª";;ÊÊʆ*ï¶ j±±± •w+B!Ô(4Ò ?%%%==]Þ­¨:>Ÿøðay·U Ç“wB!ÔX4Ò Ÿ 722’w+*§¨¨èÖ­[æææòn ª¢ëׯGDDÈ»!„jDuÐïêêjaa!ïVTÚ˜1cäÝT-ÊÊú}‡B¡º‡ò"„B!¤à0èG!„BHÁaÐB!„‚à!„B!‡A?B!„B ƒ~„B!„ý!„B)8 úB!„Rpô#„B!¤à0èG!„BHÁaÐB!„‚à!„B!‡A?B!„B ƒ~„B!„ý!„B)8 úB!„Rpô#„B!¤à0èG!„BHÁaÐB!„‚à!„B!‡A?B!„B ƒ~„Bý?öî; ªcýøs–Þ–" ØPÁFQbKl1 $j,Ñhì1*ĘØcAE£1Xr-±cl7–hlhT”"v¥)ŠRT@Qi»óþ1¯ûÛ» ¸àÊÊòýüqïî윙gfÖðìÙ9g@Ë!éÐrHú´œ®¦¨Y=z$•J5¨M~~¾¦Cx;$ýUÊÍÍ-;;[ÓQ@Í‚¤@êÔ©££££é(@mLMM5@yôhÀ•+Wj×®­é( ¦À…¼ZI?€–CÒ åôh9$ýZI?€–CÒ åôh9$ýZI?€–CÒ åôh9$ýZNWÓ¨Á©S§öíÛ§é(T•’’BD×®] Òt,ªª[·nhh¨¦£€JR[ÒRPP ®ÖÞ·ôôt" ³±±Ñt,ª1b„›››¦£ø@ÅÅÅ­ZµJÓQTLJJJ5йU«VHúª/µ%ýÏŸ?WWkUcÇŽš¡:uꄤ¿|]ºtñ÷÷×tÚæñãÇ‹/ÖtðNÔ¼½gáÂ…FFFêm6nܘ é(ªww÷o¿ýVÓQh›«W¯"é¨îÔœô7ÎÜÜ\½mÂÙ³g‘ô@¥áî=ZI?€–CÒ åôh9ü8€ª>|xñâÅZµjuíÚU³‘¬^½:##cèСNNNšªœé¯ŒÕ«WÏœ9óÎ;šTríÚ5AŽH$jÒ¤ÉÎ;+ÚÎü¸qãFþ499ùöíÛ/_¾Tw¼DD ÙÈÈÈÅÅåàÁƒD$‘HBBB,X Uþßï{ >4U‘ô«+åR€” TGD-[¶œ7oÞŒ3Z´h‘’’2|øðüüü µsùòe"òðð ¢ÜÜ\ggç-ZT´‘²?~üçŸŽŠŠ’yĈsçÎ>}zݺu¯]»6zôh"º{÷î«W¯ÌÌÌš4iR¹¾Ô<|àªb{,å8pàëׯ8pãÆáÇûøø˜ššV®MžµH$’Ç›˜˜”Uíøñã—/_îØ±£··w%b1bDãÆóóó÷ìÙÃS®¾}ûª+åzkð .ñññDÔ»wï™3gQPPP:u ?~ìèè¨z;111ô&é·°°(..VcAAA·oß>vì=þ<))‰ˆfΜéàà@D}ûöíØ±cvv6½ysº»»Wúc§Úƒ€\Uœé—O¹,XpâÄ "â)W¥ÛäY‹T*­]»v9Õ‚‚‚~øá‡Â 5.Ÿrýøã‹/Þ²e ©7åzkð .|ÉœùS==="200¨_¿>/)**úù矛6mª««koo¿}ûv^.‘HÂÃÛ5k&‰Axðà nnnDôÝwß ‚LDÿýïApqq™5k–T*-«AÆØ®]»>ùässs‘Hdcc³hÑ"‰DR«V­Û·oQÏž=,XpåÊ"244´··çêèèÿÀ‡Ó¦M"š2eŠ Ó¦MãÕÚ·o/®]»øÓÈÈH===ÙwVü%ùàçÍ›'Â!CÖ¬YÓ¬Y3]]ÝO>ùäý­hDU$ý•N¹Hµ¬ååË—Ó¦M³··×ÕÕ533sww'"åDª¬^”36¤\ÚD¶ ²k^ÿøã"6l˜‘‘ûøøüðßþùܹsÓÒÒ¾þúëüü|ÆØðáçL™Ò AƒÍ›7O˜0ˆœù×Sòoþ8--mÍš5>>>‰¤Ô¥RéСCxãÆ‘#G.^¼8$$ä“O>),,üæ›oˆ¨nݺ;vì2dÿœìììÌßxD´mÛ6"¶„„"jÕª•ú–«¦³±±!¢ŒŒ MÕØâÅ‹ù_4MÕÆ{Oúù>™J¤\ÉÉÉzzz&&&Dôå—_òG¥œruèÐáÕ«W²4ëæÍ›%%%|G>ÏòùS ©Tªzð<åš3gŽT*MMM%"===…9DÒÿVå$ý²/^dÚµkÇ?ïq... AÈÏÏïÞ½;_ñjü³åòåËÙ›wµ‘‘Qqq1cŒguîܹòäû‚6oެ䀈hÑ¢EüiëÖ­eǶiÓfÙ²eüý)ß5ÿ"ËÔÔT"‘0Æ6mÚDDÞÞÞŒ±~øAþSÿr£k×® -ðk‚ ð 9zô(9;;Ëdž¤_íôûCÒõÞ·÷ð <ñðð˜5kV›6mÎ;gaaÁËÿóŸÿÑÆA066æ)ˆÝúõë‹‹‹ûôéÃÿ@ò”ÚÃÃC„¤¤¤üü|###¾a£sçÎD4vìXGGÇðððׯ_ó–ùe—mÛ¶-§YËAAAúúúò1=z´eË–Ÿ~úi\\ÜÒ¥KOž|(Ûë_Nƒ|}eÕäÉ¿W x ±±±Œ±×¯_ÇÆÆN™2…¿?廿{{d——ÈoÚ‰ŽŽ&¹MÊûyx ü­Þ¬Y3å=K MÞûÝ{xVñå—_nÛ¶íÈ‘#}úôá)—ì¾=² Iv3“‹/Q³fÍx¡|:ÂÛäY >|xÿþý¿þúë©S§¦L™yþüyúßDª¬^?~œ‘‘!‰dçV‹‹‹¯_¿NDÑÑÑíÚµSŽ,aÒÑÑá)W›6m”S.ƒ—mÝæß åzø$·oßžˆ|||>úè£ .Ì;wíÚµ¼‚‘‘Ñ‹/ŠŠŠd—p/^¼ "þ=ÒéÓ§“’’AàŸ”T¶ˆå4h``P\\œ””¤ðU@nnnrr2½ù€qíÚ5‰Db``ЪU+åá(§ï¼ZrròŸþ){‰Å?ÇÅÅmÞ¼™ÊÞÐ/û`£ð´Féç)WïÞ½;vìXPP0wî\Y~1%Ï8~Eù¬%&&†ïOPÎZˆHGG' àäÉ“;vì "¾³Y!‘*«ÞTóæÍùé"ºuëVaa¡žžž««kYÑÏöZ´hAD‰‰‰ûöí£ÒR®r‚WR.µco¶]ñw   .$¢ßÿ=11‘×ñõõ%¢‘#GN:uΜ9|½7nLD!!!AAAŸþ95kÖŒoîR^D¾¸å7øÙgŸñò°°°1cÆðwìÓ§Où7nLIIá º¹¹É¾z’'ßõljèŸþ™8qbçÎÓÓÓe/ñ·÷š5kzöìðìÙ3zóø­I?>vhŸ*MúAàѪ’rñÓäLD&&&¼wU‚gŒñœïäÉ“Œ1…K*åáBÞ·*çB^˜?>Mœ8±r‡ãB^µÃ…¼ðîp!/TÔûÝÓ_§NƘBá‘#G䟚››¯_¿žŸ§”çìì|çÎþxΜ9D(=yòDVíСC¥v-‰öîÝ+_Rj/|O޼+Vð[ý(A¾ëÀÀÀÀÀ@ÙSù‘ª¼ìë"²¶¶Vž+€Jعsç¥K—üüü,--?>gΜFñ_#€šé½_È[9²¬ÅÂÂâØ±cóçÏwpp˜1c†¦ãRIµ´@qqñ±cÇÖ¬YS\\ܰaÉ'Θ1ÃÚÚZÓq€Æ| Iqqñßÿͳ{{û   3fð1¾j|¸GýúõswwÿóÏ?c b±xÔ¨Q_ýµ]Ÿ>}xÍ+W®Ô®]ûùóçÊsÏ7‡¼£€€"ŠŒŒ|÷¦´ÕÒ¥K‰(88X¡üþýû²•â®\¹"²eËxÿàÁƒ»wï¶k×îéÓ§Œ±Ë—/ëëë3Æ¢££íííïß¿Ï =z´¬…ŒŒ ]]Ýׯ_W´Í}ûö999egg3Æ&Nœ(ÿ~kÒ¤ITT”|œ#FŒøî»ïJì•+Wtuu+1K•“@D­Zµª²µž eddh:¨Æ/^LDÓ¦MÓt Pm¼ß¤_9åb¥å7S§N•H$Œ±Ë—/[XX0Æ ÒÒÒf̘±fÍ^­ÔDŠ1vðàÁ¥K—Þ¾}[$³ fWL)ûûï¿5jôøñcÆØ?ÿücggÇË?ùä“?þ8333&&FOOVAr†¤ÿ­”“þ?þXþ3žžž^QQclíÚµŸ~ú)¯“––&•J¿ùæùšuëÖeŒõîÝ{ñâżZ@@ÀÚµke-:tÈÕÕU¾wÛtssÛºu+¯öôéÓ’’þ8++KGG'??_¾Í :t¨ÔÁîÛ·¯I“&•›¨J@Ò¯vHúáÝ!逊z_Û{:vì(‚½½ýáÇAÐ××/..&¢ììì{÷îµiÓF¾ò Aƒ–/_>eÊ”™3gzzzÑ7tuuƒ‚‚:vì8nÜ8^-,,ìÒ¥KµjÕÁÓÓÓÚÚšˆ¤Réš5kÆ_¿~}©TúèÑ#"š3gÎ?þÈ+Ì™3Gv f©½QlllË–- ùÓY³f…„„Ô©S‡ˆ,,,ž={Æ;Љ‰‰ˆˆ°µµ}üøqË–-yåþù§[·n¥NBjj*ÿ¥X¨zçÎcŒÍ™3gÛ¶mŒ±¢¢"¾É'::Zöy Aƒ‚ $&&þòË/²éééDÕ¥K"bŒEGGËï4‹‰‰‘¿¨Wõ6¯_¿Þºuk^ÍÊÊJGG‡?¾téR«V­LLLäÛLOOoРA©C;~üxÏž=ßq~ Fy_IY)—r~:sæÌ:LŸ>ÝÌÌÌËË‹ˆbbbÚ·oŸ››»k×.ƯYj"µsçΣG›ššßÖ_¡ìŠ”Ò¸¸¸¸öíÛóÇÑÑÑüCBRRc¬E‹¼>ÿpBHÎ>l±±±²•â.]ºÔ®];ù’–-[9r¤¤¤„ˆòòòøå㌱—/_LŸ>=++Kþ*^å¤_Å6ëÔ©sþüyÞxnn®|ƒNNND$_hjjÊWðôéÓ]»vMž<¹‚35šî{m=66vРAò%òù……­\¹2**ÊÓÓóÒ¥K§OŸ1b¯Ö©S§ &´mÛvÙ²eS§N¥7‰Ô¸qãtuuyellüÛo¿eggó“ú-Z´àI?Ï®\\\cyyy¼£R{—•÷îÝ[öÔÊÊ*''‡ˆÒÓÓ—,Y²~ýz"ºtéRÛ¶mE"¯ïççÇ+—Ÿœñ$4%00°iÓ¦üñ¶mÛöíÛwãÆåË—¯]»ö÷ß777'¢9sæ >ÜÁÁÁÖÖÖÒÒrûöíD4mÚ4ÿöíÛûøø”””üúë¯Ã† 3f >}úÙ³g'Ožœ7o^\\œêmþöÛo“&MZ¹r¥X,ž6mZÿþýy`ŽŽŽË–-óòòrss‹ˆˆà…;w¾xñ¢»»»üpc&L mÖ¬YÍ |`"""ä?BEDÑÑÑ‹-Òt, yúúúS¦LÑtðÁS×>¡R÷ôÿñDz«x¹mÛ¶™™™µoß~̘1¼dàÀµk×îÚµë÷ßODí۷ߺu«M@@clÓ¦M‚ „‡‡3Æž(Ó§OwppÐt yyyy+V¬ÐtP= éW$gð!CÒÚ#&&&,,LÓQh›Çk:xWjNúùåÙÝîA]îÞ½«éª‡³gÏ*üî2Ú“þŸ~úI½ ¨¢mÛ¶ü¾®ðžðߪ€jJmIÿ¤I“ ÔÕÚû–ššzýúu___MR¸5{9:wîܹsgMGðR[Ò?þ|u5U¼¼¼’’’¾úê+Ù÷h+‘¦Ѐ#GŽDGGK¥Ò¹sçj:Ð3gΜ9sæÓ§O5€¢š˜ôÏ™3‡?Ø»w/~oT'ü/33³.]ºÜºu‹¿º`Á‚ äääTºýÛ·oß¾}»¨¨¨œ:III¼÷J÷5PKúùi~[[Û‘#Gâd?TÂäÉ“çÎdjjzæÌ™ÀÀ@uý¼}óæÍ›7ož––¦ú!k×®9sfVV–Zx À‡@P×§ª //¯èèè°°°Aƒ5mÚ´¨¨èÊ•+ØÙUÆÖÖ6;;;##£víÚ=ÖÁÁ!55599¿È«)üüzbbbÓ¦M‰èêÕ«®®®DôèÑ#;;;…Wß“¤¤$GGG"âÁÕÞiÕŒÔ"//ÏÂÂB,çååi:øÐÕ¬3ý²ÓüãÆ«W¯Þ7ß|ƒ“ýPiÎÎÎüAqq±ÂK|NRR)mÈÉËË=zt­ZµdÛ„5j¤||ùòå!C†ÛÙÙíß¿_¡þÀÑё߹8==}àÀúúú;v”íbå­mذÁÚÚúôéÓDtþüùŽ;š˜˜èééµmÛ6::ºÔc+W®tppÐÑÑiҤɪU«d§ •Û€VÍJúùnþiÓ¦™˜˜QHHˆ¡¡!vö@åÄÄÄ‘¥¥e½zõT<„1°~ýúþýû_»vmÕªUå×ïß¿|||½zõ222‚ƒƒ^>}:>xðࢢ¢O>ùd×®]Ç_¸pá… ú÷ï/•Jeõ§Njii©««KDwïÞuww_·nÝ€bcc‡®Ü -_¾|òäÉ&&&FFFAAA+W®”A¾Møp±ãðáÃDdkk›ŸŸ/+œ4iõïß_ƒ@bccCD•8¶qãÆD”œœ¬ö¨@EüOçÑ£G¯^½úÇØÛÛQXX˜ü«‰‰‰ es/_¾LDÆÆÆ¯_¿fŒ:uŠˆìííËjaÊ”)‰$66VÖ‚|k ‡ð¯¥R)cÌËË‹ˆdÕÂÃÕ%»Y¹A‰DbmmMDçÎcŒEEEñ¿¤‰¤ü6¡jäææ‘X,Öt P Ô Ïå §ù¹õë×ó“ýØÙªèÝ»7¹ººÎ›7oÈ!ªËÓ÷FªRܸq"‘ÈÌÌL•Êüó@bb¢Hôß䧤¤¸¸¸ðDzÝ;DôäÉ“%K–œ?¾œkvÓÓÓŸ{ölŸ½{÷*enn®¯¯OD£Gæ—·Ñüùó‰D¡¡¡D4nܸßÿÿ Qø>|5âm9§ù9œìõZ¾|¹­­mZZZëÖ­ÿüóOY¹ÁÞ½{›7oþèÑ#GGÇ_ý•ˆŒ+ÝÑ/¿üR¯^½õë×?~œˆÖ­[·páB ‹eË–-Y²$++K¶ù^ž™™ÙêÕ«---:4räÈQ£FéèèìÞ½[¹ÁÉ“'¯\¹òåË—£G~ùòexx¸òM„àçý?ÎuäÈ‘>}úØÚÚ¦¤¤”•ôQPPЪU«ú÷ïY•á@Mƒçy¿ýöÛøñã}}}<¨éX úÁsê´ÿLÿ[Oós8ÙUàÁƒƒ>pàÀõë×÷íÛ7oÞ}úXXX899ÅÅÅ-^¼XVgâĉ¼©éÓ§ ‚pàÀzõêY[[߸qƒˆNž<Ù«W/ÿ:lÙ²…·™’’Ò¥K—Ö­[öÙgåϪòˆÊ*äŽ?nddÔ»woþ³¦¿üò‹§§gß¾};vì8oÞ¼²z™ýúõsrr;vl9m*_V›DtïÞ½Êm*«÷R ‚pÿþ}"rppغuk…âT}êHåu/ë­¨¼šªóƒ]b€w¢éOš3ý )üLÿ»P8Ó¯ð_r":qâ„H$:yò$éÑ£GD$;ÍÏI¥Ò-Z:tˆ1vèС–-[Ê2dHaaá±cÇ,,,ä›}ëiàœœÓ§O3Æ¢¢¢ìííê(Ÿ² -,, :{ölff¦••Uzz:c,++ËÀÀàÅ‹Œ±:üþûïLéL¿Âß²RGTÎ0SRRBBBV­Z%‹All,cìéÓ§C† ‘•«r¸¬à•‡É[²dIQQcìÆ"‘¨¬6Ë ¾Ô6y¿ªœz§w;ÓòäÉÆûùùÉþ†V4N§®Ôu/çL¿B³e­f©Ã¬.K¬ gúAuHúªTPPÐðÊ255•%ý .TH|.\È#¢’’"’H$<áW¬¾zõJ>ŒÌÌLYá«W¯ˆ(++‹ž˜˜ÈKII©hFøüùsSSÓ_ýµ°°pÅŠõêÕS¨£œ½3Ʋ³³_¾|ù×_)ŒèÆ999Dôüùsö¶í=¥Ž¨œa4èÇ”ËÀ5j4}úô£GòŒM>ÔrÎ+5øR‡É{öìÙúõë§M›6lذr&¹¬àKmSu²^¤Ri%’~ÆXQQÑÆ6l8yòäJÄ©ÊÔ•µîª'ýe­f¥“þs‰‘ôƒêð‹¼UŠ_~Z9gΜÉÏÏçCCCCCC‰Hö¿g¾uttˆH$úÿ8mmmëÔ©sùòå²®ßU8\WW—7[ÑðÌÌÌ"##?ýôÓI“&¹»»ïÞ½[¡ þiD¹/kkkþ¿b±øÙ³g<~Ž_šÉp”'©ªPQ©…ÎÎÎëׯÿòË/yÉæÍ›oÞ¼yòäÉyóæM:566V___Å^J ¾Ôa{xxŒ7nܸqyyy²Ý,åD^j¹|›bddôúõk"*((ÐÓÓS¥wy§NêÚµëðáÃ;wîìàà"{§©ç[§NÅu5jÔ† J}©œÕTe˜*Æ)óA-1@©°§@Ë ‚òÝwß=yò„—ÄÅÅÙØØ´hÑâôéÓDtâĉ–-[¾û¾#"úé§Ÿ®\¹"‘HbbbøDdnnž””TXXXþfñ¶mÛÚÛÛóý6DôàÁ©TZ§N›S§N/_¾¼œÃKQ9Ã6lØâÅ‹»uëvíÚ5^Ò±cGWW×)S¦üõ×_ׯ_/õ ~6šŸj-5øR|úôijjêˆ#5jtåÊ•rÚ¬èegg2¤œ \‡Nœ8ADQQQíÚµ+«÷²ÈƘ——gnnniiYÑ8U™:×ý÷ß/륲VSÅaªg©¾¿%x'UûŇÛ{ :zëÝ{Ž;FD±±±²ÿ=vìcL*•®^½ÚÝݽS§NÞÞÞ£FbŒÅÇÇwìØÑÇǧsçÎ ¼)" bŒýðÃD´hÑ¢­[·úùùQ=üüüøæŸÌÌL???ùòììlÆX¯^½š4iâêêêêê:lذ’’ÆØÒ¥K­¬¬<<<øuŸcƌٰaC=ˆˆ7’——Çã¿ÿ¾¯¯¯³³³‹‹K÷îÝùá‘‘‘666...;vì ¢¯¿þšg3gÎdŒÍœ9“ˆ–/_^êˆJ-\´hÍž=›1leeÉóñññðððññéÖ­ÛÊ•+cÙÙÙ~~~²Pûõë'›êÑ£GÛÙÙyzznذ¡¬àËfPPPýúõ½¼¼¾ÿþ{"9rdYm*_V›Lå;ÛܺuËËË«OŸ>:u’Í’rï÷îÝSXb¾ôƒ úè£|||¼¼¼ø»«¢qª2u¥®ûÖ­[y›ß ¢²ÞŠÊ«YjïÕk‰•a{¨NñKáÂÝÝýÊ•+qqqîî@U©©©ÉÉÉšŽ¥¯^½êСÃÖ­[›7o~öìÙ®]»fffÚÚÚj:.­•——gaa!‹óòò4 |è°§ÔC$Õ©SÇÓÓ³¨¨¨~ýúK–,AÆð@ÒêahhxôèQMG¥À…¼Zgúª ~'ïüQ,k:мââbÙÿ”I?@µñôéS"Ú¾}»¦€HAA¦C€jI?@µallüüùó¾}ûòŸæ€®¸¸822’ÿŒ@ùð.¨6jÕªõüùóðððó–PÅòòò"##ŒŒ4T¸@Ë!éÐrHú´’~P‰D"Y·nÝÎ;ùÓÕ«WïÙ³‡1¦®ö¯_¿.¼qïÞ½J·sûömÜÁ@’~ø³gÏÎÍÍU(”H$_|ñEfff¿~ýxÉW_}õ÷ßO:µ]ܹs§gÏž‚ øùù¹¸¸Q«V­cïþ)¢yóæéééo­–ŸŸoaa¡Æ-2$ýÕÛÒ¥KÕÛàœ9s”“þuëÖÑ?þh``ÀKÌÌÌ"""NŸ>}ìØ±ŠváääÄ'N”UÛ²e‹››[Ÿ>},,,œœœâââ²²²üýýýýýåw•:!‰¤S§NG]¼xñ… <==U ºb5’››ÅÅÅi:€ hܸ1%''Ë*ü—œˆ† RXXxìØ1¾}%33ÓÊÊ*==1–••e``ðâÅ ÆØ®]»7nüäÉ“+Vlß¾]¾…ÔÔTù6ù‰ÿœœåââ⬬¬äK²²²üÖ±¤¦¦òÈ7nÜèíí­0ùdOe‡äääèèèœ>}š1eoo_þá Â+((èÖ­ÛêÕ«‡ RRRòÖh>LüߦX,Öt P àL?@µ´hÑ"~Í+ñ‹-â/Íš5K__¿iÓ¦ûÌÄÄdùò弑ѣGÛÙÙyzznذAÖòöíÛ{öì)•Jå».((hÞ¼ùùóçå e;ïËqûöí=z‘ŸŸßÅ‹yá½{÷üüüüüüˆ¨G~~~‰‰‰Œ±¥K—ZYYyxxðcÆŒaŒõêÕ«I“&®®®®®®Ã† +))ÉÌÌT8<;;»¬ ÐØÓªSüR¸†HLL,((ÐtïêÞ½{}ûömR àÁ IDATÖ¬Ù;w4 T‡ÔÔÔääd‡*îš16nÜ8AæÏŸÏ7ù}zóêÕ«:lݺµyóægÏžíÚµkff¦­­m‡ qyyyb±—¦À[ÕÐí=ŽŽŽšA ôõõ5Ô‚ üöÛo<þ¼¯¯/Tw˜£â Ö®]ûàÁƒ   [[[Õ€ª¤_mc•>öñãÇÿþû/rùŽJ…rx/_¾411!¢ÐÐÐ-[¶Ìž={ûöíü+V‘¡¡á˜1c~þùçñãLJ††Êš277oÚ´éÙ³gK rGgΜá/…‡‡ÇÅÅ)µtéR"jÕªÕºuëZ¶lÉ«ÉGÞ°aÃ-Zð@5Rÿª¨8@D¾¾¾š´’~š5k–T*‹‹ãOO:%;1/_méÒ¥Œ±“'O‘¾¾~AA+#éç§«ù¬zyyQBB‚T*­]»6EGG+SRRáàà û$øìÙ3ùÊIú•ûÿ>éàÁƒòë+‘HxʾcÇ…ù‘åî %ò|ë<È?•H$ÖÖÖDtîÜ9ÆXTTÙÚÚò@¼Ú”)S$Ill¬ü j$ýPejôönÈ!‚ ÈvÒwéÒÅÀÀ@¹šŸŸñ ¾¨¨èñãÇe5È“òÄÄD‘H$¿OJJÊãÇù~WWWå£tttÆŒ“˜˜xìØ±êééEFF~ýõ×*ŽB9¼ ôíÛ—ˆúöíëââ²~ýúââb"zôèÑÓ§Oyy©MÉ¶ë¨ØQ9•ÓÓÓŸžž^·n]þêæÍ›+<þ²;""‰D¢PÍÎÎŽßÏ'&&†ˆø[[[;;»Jw …[vªj×®] 6 #¢àààrÎL·hÑbĈ7nôöö>|¸±±qLLÌ×_ýùçŸûûûGFF6oÞüÎ;²CÒÒÒ\]];tèвeK±Xœ™™IDcÆŒá6l˜––6`À==½ÜÜ\UÂKIIùæ›ozõêU¯^=žmót_$Í™3gìØ±“'O¾té’««ë³gÏJJJø±•›‡&Mš$%%­X±"00°[·n²Ê"‘(44tÊ”)ãÆ›|¸^½z:::òwâGI¥Ò•+W6nÜX$5jÔ(<<\öf+kþk\È UF%ýØT]>3ø}Ỹz#"cccM¢a˜€j IÿÛýõ×_šჀy¨¦°½@Ë!éÐrHú´’~-§Î¤ïÞ½{÷îUcƒUÐòåÕ«W400?~¼¦cQµ~ýzMG•¡Î¤ÿûï¿?s挺Z{öì™ »víR{Ë•àáá!²eËä ³³³Åb±®®nAAA@@@§Nd/I$GGGGGGùúÝ»wŸ7oùùùµmÛV¹—yóæ]¼x1>>~ñâÅïg•·råÊÈÈH…Bù5zÿüó 'Nœ/üÏþcnn.•Jß±qeYYYb±¸eË–joà䶤ÿùóçwïÞuwwWWƒ………aaa;wV{ËŒ±… ž:uJÅúEEE×®]#¢»wïÊ—ÏŸ?ÿÅ‹-Z´044‹ÅÏŸ?—½™”””-+‰½pá?…§<ÆØ–-[FÕ¢E 33³Ê ­rT™Rc–­Ñ;EDmÚ´Qè±mÛ¶"‘úw Íš5ëÅ‹wïÞ-..V{ã}wTµeTW®\!¥¼í]ØÙÙM:µN:jo9))iÆŒùùù*Ö¿yófqq±³³³|ÒŸ’’²yóæ ðTX>é—J¥?ÿü³X,ÎËË+**â…aaa£FªU«VvvöÇ•è‡>zôHÃTÝ['äÙ³g÷îÝsssS(—­Ñ;åàà`ii)_[ê÷!ïèÖ­[ëׯïÕ«WIIIRR’ÚÛ¯è»   ”—ôgee1¢víÚ:::ÖÖÖü·™–.]*‰^¼xÁëx{{:”ˆbccõõõóòò\]]õôôKJJÊj„ˆöíÛשS'ccc}}ý¦M›æää„……™ššnÛ¶ÍÚÚúìÙ³_}õ•§§g9-3Æ6mÚÔ¦M===KKËàà`¾¤¬¹ÀÀÀfÍšQß¾}GED{÷îõòòÒ××7776l˜ü {.>>¾víÚ;w–OúgΜ9f̘§OŸÊ’þ¼¼<þÒ¡C‡ÒÓÓÇGDüdJJʾ}û‚ƒƒykD¤ôïÞ½»aÆDôÙgŸÍž=»¬¨¦H¾…ÈÈHA.^¼èå奧§7tèP‰D2}út333±X¼zõj^mêÔ©NNNzzz?þøc©¢¼4víÚÕ®][WWW„ÐÐP…é-,,¼xñ¢‡‡‡|aIIIBBo¼Ô-kõË™"nÚ´i={öä«sóæMù—J µ¬ŽJ²Âd*D® @•’J¥LÉ'Ÿ|b``pìØ±ÌÌÌìì좢"ÆØgŸ}Ö¼ys^¡¤¤ÄÄÄdÙ²eŒ±Áƒ[YYµiÓf÷îÝß~û-:t¨¬Ff̘AD/^LKK{ðàclàÀæææ½zõú믿^¿~ݪU«Ñ£G—Óò¤I“tuu7nܘ““Ã7…ïÛ·¯¬ež={æëëkcc“ŸŸÏ7ÙÏ™3'--ï¤ R˜‡I“&õîÝ›oèñâc,66ÖÚÚúüùóDtúôiÆØ’%Kttt¤R©T*mß¾ýœ9sÖ®]KDñññŒ± &|ùå—¼µE‹ ‚ÀÛ‘yõêÕ”)Sj×®ýúõë²¢R˜"ùBCCõõõ}}}:4aÂ"êׯ_DDÄîÝ»‰¨U«VŒ±üüü%K–ܹsçæÍ›zzzÊRêÒ,^¼XooïåË—oÛ¶MÖ læÏŸ/B×®]ùå¾ÅŸWX¿~½……Ÿ¢‡ÑÎ;¦—ïíY´h‘|!ßO•ššZÖ‚–µúåLcìĉ‚ $$$ðÏosçΕ½TV¨euTê&S!r…`8@D¾¾¾ à=+/é×ÕÕ­U«Ö³gÏd%%%%æææC† áOù‰ÒS§N1Æš7oÞ¢E žÙ¤¦¦Ñ/¿üRj#<ÉóóóSèÔÉÉ©sçÎ………Œ±W¯^éèèDDD”ÕòßÿMD“'O–nmm½dÉ’R{”'•Jmmm?ýôSÆØ¥K—ˆhèСü¥×¯_‘«««Â!;vüþûïÿûßÿQ\\c¬{÷îË—/ߺu+åææ2Æ"""ˆèåË—'Nœ055}öìÙ¾}ûˆèرcYYYFFFü@ÆØ_|áä䤘Ï[£’Ÿ"½zõrtt|úô)clÆ "‘(**Š1öìÙ3"òññQ˜kkkggg… )ki `eeuýúuÆXNNoP~¬¬¬nܸ!_!##ÃØØxíÚµ¼¾dwîÜQˆ|þüùDtüøqùÂÍ›7תU‹‡¡¼ å¬~9S$‘HÜÜܾúê+ÆXqq±Á€øKe…ZNG¥Y~2K\’~¨2åmïéÕ«×Ó§OíííÇŸ‘‘AD yyy²Ö111Däææ–ŸŸûöí)S¦ð= |û ¿U¹~çÇÐÐPAd}åççß½{wøðáúúúDtíÚ5‰DÒ¦M›²Zþý÷߉h÷îÝÎo>ÞÅÅEOO÷_~ËD4räÈøøøôôô .>|¸¬åñ+8‹ŠŠJJJøþ–eË–=xð`Þ¼yüñÇܹsnïææÆÏO7kÖ,++kñâÅ"‘(---''GáLzzú´iÓd%úúúÓ§O—í–ágñ•·÷ÄÅʼnÅâÆÓ›­8ÊQ)L‘B¶¶¶õêÕ#¢[·n½~ýZþL¿···ŽŽNjjêëׯϞ=»eË–U«VóËUå'¤Ô¥‰‹‹355å7¥á vìØQWWW¶Fñññòbbbx…6mÚ¼xñbäÈ‘#FŒX³f cŒßGA—.]?~ýé§Ÿò”W/D¼¢Çã!¢ÈÈH"ª©©ijjR©TV«5--Íãñ„††ŠAP*•¾-„„„‘B¡ˆˆˆ À¦t¤P(bbb&&&Äœœœì7ø@%ýön2™l6Ûµk×êêêòóóù¡»¯0Ÿf¿zϾ}ûx~ãÆØØØ‡zˆˆbccûí7·Û]VV6½ÊñãÇW­ZKD:.%%¥¤¤Äét^¸paddD.—ëtºÊÊJÞì_ý5ëØÄŽÒÓÓãããÅP{zz¼^¯ßà•ôkùòå:î£>R*•üãü«êó)ÄïÞÊÊJq»¥¥…ˆ:::Ä×–––W^yeÉ’%«V­Š‹‹ûóÏ?d2mݺuíÚµ‰‰‰›7o®¯¯/((øòË/‰hõêÕ111r¹¼¦¦†7«R©4Í£>:::ZUUGDGŽ)((X¾|ydddfffUUÕ¡C‡¾ýö["2DT[[300`2™x;&“)""¢ººZ¡PLïH*•:΢¢¢„……)•Êææf"òüô’~{çý¼þúëíííü­ßŽf¨0on-°ãõz}Û€¹æp8 ƒ^¯w8  ¹9"/,,$ýAI?@CÒäô9$ýAI?@›eÒ¿gÏA ‰h×®]‚ ìÞ½û¾är¹A¸téÒ}i+++»—çû,$4C5IDATjþ“þ;fð›7o&¢ÒÒRñõý÷ß¿/Ùl¶¤¤¤¦¦¦ûÒ·cÇ$ýðŸå?é7›ÍâöÑ£GA0›ÍYYY………Z­v†æöîÝ«Ñhrrrt:Õjå;].Wvv¶ÑhÔjµµµµDTZZ!‚ÝnW«Õ …¢««‹ˆ¼^ï/¿üRRRÒØØ(¶Y[[›ššúꫯ.]ºô©§žêèèðÛæÆA¨¯¯_¹r¥B¡Ø³gó' '&& ‚PVVvOg `ñòz½ÌMyÛÚÚ*‘H\.—xˆˆº»»§”—ÉdçÏŸgŒ æçç3Æúûûåryoo/cl``@&“ŒŒ0ƺ»»‰Èb±¸ÝîM›6µµµ1ÆÎž=ûÁôõõI¥Ò«W¯2Æ®_¿.•JOŸ>Í;sæL||ü mQ~~¾Ûí>yòäÒ¥K}ãCx@Øív"Òëõ ¿ÛFú+**AàCã|£¢¢‚ÊÌÌôz½™™™Ó/câvnnn^^Þ–-[ÚÛÛ¿úê+"jooR«Õ‚ (•J·Û}åʱ¼Õj ÛºukZZ566æææªTª•+W~÷ÝwD$•JÃÃûºº<OGGÇÄÄÄÌmnß¾=,,ìÉ'ŸÄý<ÜmI¿Åbá—ôÏȽÅbᇤR)I$ÿ/~óæM" å;kjjšššT*•ÕjMKKóx< …"&&fbbB¼ÎHNN !"…BÁ³Ùl‚ œ={–ßáÝÐаqãÆðððo¾ùæØ±c¼| 6yƒüºÅ—ï• ÀÊì—ìÔjµ­­­DtæÌ™ŒŒ ¾S§Ó¥¤¤”””8Î .ŒŒŒ¤§§ÇÇÇïÛ·§Ý===^¯×oƒ/½ôOâ;;;O:544DDÛ¶mûñÇ'''Ï;ÇgÜ}›œT*½~ý:aøþƒü'ý•••âvKK ñé³ü•ïÙ¿}}ýš5k>þøãÏ?ÿœV©TF¯×çååUUUÅÅÅI¥R§Óér¹’““SRR6lØÀ;tèÉd""£Ñh4‡‡‡‰èÃ?üé§Ÿø¶Ýn—J¥Û¶m#"¹\ž———šššššº~ýúÉÉI¿mò‡øüÝêêj"Ú¹s'êí·ß~íµ×222l6ÛœœE€Ø­Û`¼^ïô[b£££Z­¶®®.))©­­íÅ_ìïïW*• À½r8ƒA¯×;Ž…Ž‚\ÈBp‰ä‘GÑh4gÙ²e»víBÆð¯<èIÿ’%Kš››: €Elöy`Q¸5Ò-æþé`ÞÜJúù2ü|þ Ä©7<IEND®B`‚sipxtapi-3.3.0~test17/sipXsdpLib/0000755000175000017500000000000012321445026017456 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXsdpLib/config/0000755000175000017500000000000012321445026020723 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXsdpLib/config/sipX-config.in0000644000175000017500000000550512205613256023451 0ustar00danieldaniel00000000000000#! /bin/sh ## ## @PACKAGE@-config ## ## Copyright (C) 2004 SIPfoundry Inc. ## Licensed by SIPfoundry under the LGPL license. ## ## Copyright (C) 2004, 2005 Pingtel Corp. ## ## Action=PRINT Info="" prefix=@prefix@ exec_prefix=@exec_prefix@ includedir=@includedir@ libdir=@libdir@ while [ $# -ne 0 ] do case ${1} in --bin) Info="${Info} @SIPX_BINDIR@" ;; --include) Info="${Info} @SIPX_INCDIR@" ;; --lib) Info="${Info} @SIPX_LIBDIR@" ;; --host) Info="${Info} @host@" ;; --version) Info="${Info} @VERSION@" ;; --build) Info="${Info} @SIPX_BUILDSTAMP@" ;; --conf) Info="${Info} @SIPX_CONFDIR@" ;; --data) Info="${Info} @SIPX_DATADIR@" ;; --log) Info="${Info} @SIPX_LOGDIR@" ;; --run) Info="${Info} @SIPX_RUNDIR@" ;; --db) Info="${Info} @SIPX_DBDIR@" ;; --all) Action=ALL break ;; --configopts) Info="${Info} @CONFIGURE_OPTIONS@" ;; --help) Action=USAGE break ;; ## ## handle an unknown switch ## -*) echo "Unknown switch '${1}'" 1>&2 Action=USAGE ;; esac shift # always consume 1 done if [ "${Action}" = "PRINT" -a "${Info}" = "" ] then Action=USAGE fi case ${Action} in USAGE) cat < config.properties .PHONY : rpm # Where rpmbuild will do its work. RPMBUILD_TOPDIR = $(shell rpm --eval '%{_topdir}') rpm : dist rpmbuild -ta $(BUILDPARM) $(PACKAGE)-$(VERSION).tar.gz mv -f $(RPMBUILD_TOPDIR)/SRPMS/$(PACKAGE)-$(VERSION)-*.rpm . mv -f $(RPMBUILD_TOPDIR)/RPMS/*/$(PACKAGE)*-$(VERSION)-*.rpm . md5sum $(PACKAGE)-$(VERSION).tar.gz >$(PACKAGE)-$(VERSION).tar.gz.md5 # RPM Spec file sipxsdplib.spec : sipxsdplib.spec.in $(LocalizeSipXconfig) $(srcdir)/sipxsdplib.spec.in > sipxsdplib.spec # 'rpmbuild -ta' searches root of tarball for pkgname.spec file to build # RPM from #dist-hook: sipxsdplib.spec # cp sipxsdplib.spec $(distdir) DISTCLEANFILES = config.properties sipxtapi-3.3.0~test17/sipXsdpLib/Makefile.in0000644000175000017500000006151212321445002021522 0ustar00danieldaniel00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # -*-makefile-*- VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ $(top_srcdir)/config/sipXcommon.am.inc \ $(top_srcdir)/config/sipXprojtop.mak subdir = sipXsdpLib ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/general.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/sipXlib.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ html-recursive info-recursive install-data-recursive \ install-dvi-recursive install-exec-recursive \ install-html-recursive install-info-recursive \ install-pdf-recursive install-ps-recursive install-recursive \ installcheck-recursive installdirs-recursive pdf-recursive \ ps-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ distdir ETAGS = etags CTAGS = ctags DIST_SUBDIRS = . include src doc DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMRNB_INCLUDE = @AMRNB_INCLUDE@ AMRNB_LIB_ROOT = @AMRNB_LIB_ROOT@ AMRWB_INCLUDE = @AMRWB_INCLUDE@ AMRWB_LIB_ROOT = @AMRWB_LIB_ROOT@ AMRWB_TARGET = @AMRWB_TARGET@ AMR_TARGET = @AMR_TARGET@ AMTAR = @AMTAR@ ANT = @ANT@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CARBON_LIBS = @CARBON_LIBS@ CA_LIBS = @CA_LIBS@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPUNIT_CFLAGS = @CPPUNIT_CFLAGS@ CPPUNIT_CONFIG = @CPPUNIT_CONFIG@ CPPUNIT_LIBS = @CPPUNIT_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPS_PCRE_CFLAGS = @DEPS_PCRE_CFLAGS@ DEPS_PCRE_LIBS = @DEPS_PCRE_LIBS@ DLLTOOL = @DLLTOOL@ DOT = @DOT@ DOXYGEN = @DOXYGEN@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DYNEXT = @DYNEXT@ EAGC_LDFLAGS = @EAGC_LDFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EJBE_LDFLAGS = @EJBE_LDFLAGS@ EPLC_LDFLAGS = @EPLC_LDFLAGS@ EVAD_LDFLAGS = @EVAD_LDFLAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ G722_TARGET = @G722_TARGET@ G726_TARGET = @G726_TARGET@ GIPSINC = @GIPSINC@ GIPS_CE_OBJS = @GIPS_CE_OBJS@ GIPS_CPPFLAGS = @GIPS_CPPFLAGS@ GIPS_NEQ_OBJS = @GIPS_NEQ_OBJS@ GIPS_VE_OBJS = @GIPS_VE_OBJS@ GREP = @GREP@ GSM_CFLAGS = @GSM_CFLAGS@ GSM_CXXFLAGS = @GSM_CXXFLAGS@ GSM_LDFLAGS = @GSM_LDFLAGS@ GSM_LIBS = @GSM_LIBS@ GSM_TARGET = @GSM_TARGET@ ILBC_INCLUDE = @ILBC_INCLUDE@ ILBC_LIB_ROOT = @ILBC_LIB_ROOT@ ILBC_LIB_TARGET = @ILBC_LIB_TARGET@ ILBC_TARGET = @ILBC_TARGET@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTERFACE_FLAGS = @INTERFACE_FLAGS@ JAVA = @JAVA@ JAVAC_DEBUG = @JAVAC_DEBUG@ JAVAC_OPTIMIZED = @JAVAC_OPTIMIZED@ JAVA_HOME = @JAVA_HOME@ L16_TARGET = @L16_TARGET@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NAMED_PROGRAM = @NAMED_PROGRAM@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPUS_CFLAGS = @OPUS_CFLAGS@ OPUS_LIBS = @OPUS_LIBS@ OPUS_TARGET = @OPUS_TARGET@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PCMAPCMU_TARGET = @PCMAPCMU_TARGET@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ RTL_CXXFLAGS = @RTL_CXXFLAGS@ RTL_LDFLAGS = @RTL_LDFLAGS@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SIPXMEDIA_CE_LIBS = @SIPXMEDIA_CE_LIBS@ SIPXMEDIA_VE_LIBS = @SIPXMEDIA_VE_LIBS@ SIPXMEDIA_VE_STATIC_LIBS = @SIPXMEDIA_VE_STATIC_LIBS@ SIPXPBXUSER = @SIPXPBXUSER@ SIPXPHONECONF = @SIPXPHONECONF@ SIPXPHONEDATA = @SIPXPHONEDATA@ SIPXPHONELIB = @SIPXPHONELIB@ SIPX_BACKUPDIR = @SIPX_BACKUPDIR@ SIPX_BINDIR = @SIPX_BINDIR@ SIPX_CONFDIR = @SIPX_CONFDIR@ SIPX_CONFIGPHONEDIR = @SIPX_CONFIGPHONEDIR@ SIPX_DATADIR = @SIPX_DATADIR@ SIPX_DBDIR = @SIPX_DBDIR@ SIPX_DOCDIR = @SIPX_DOCDIR@ SIPX_INCDIR = @SIPX_INCDIR@ SIPX_LIBDIR = @SIPX_LIBDIR@ SIPX_LOGDIR = @SIPX_LOGDIR@ SIPX_PARKMUSICDIR = @SIPX_PARKMUSICDIR@ SIPX_RUNDIR = @SIPX_RUNDIR@ SIPX_SCHEMADIR = @SIPX_SCHEMADIR@ SIPX_TMPDIR = @SIPX_TMPDIR@ SIPX_UNIT_TARGET = @SIPX_UNIT_TARGET@ SIPX_VXMLDATADIR = @SIPX_VXMLDATADIR@ SPANDSP_CFLAGS = @SPANDSP_CFLAGS@ SPANDSP_CXXFLAGS = @SPANDSP_CXXFLAGS@ SPANDSP_LDFLAGS = @SPANDSP_LDFLAGS@ SPANDSP_LIBS = @SPANDSP_LIBS@ SPEEXDSP_CFLAGS = @SPEEXDSP_CFLAGS@ SPEEXDSP_LIBS = @SPEEXDSP_LIBS@ SPEEXDSP_STATIC_LIB = @SPEEXDSP_STATIC_LIB@ SPEEX_CFLAGS = @SPEEX_CFLAGS@ SPEEX_LIBS = @SPEEX_LIBS@ SPEEX_ROOT = @SPEEX_ROOT@ SPEEX_STATIC_LIB = @SPEEX_STATIC_LIB@ SPEEX_TARGET = @SPEEX_TARGET@ SS_LDFLAGS = @SS_LDFLAGS@ STATIC_CODEC_LIBS = @STATIC_CODEC_LIBS@ STRIP = @STRIP@ TONES_TARGET = @TONES_TARGET@ VERSION = @VERSION@ VIDEO_DEFINE = @VIDEO_DEFINE@ WXWIDGETS_CFLAGS = @WXWIDGETS_CFLAGS@ WXWIDGETS_CONFIG = @WXWIDGETS_CONFIG@ WXWIDGETS_CXXFLAGS = @WXWIDGETS_CXXFLAGS@ WXWIDGETS_LIBS = @WXWIDGETS_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ codeclibdir = @codeclibdir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ enable_dot = @enable_dot@ enable_html_docs = @enable_html_docs@ enable_latex_docs = @enable_latex_docs@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ jar = @jar@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ sipx_abs_srcdir = @sipx_abs_srcdir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ wwwdir = @wwwdir@ ConfigureArgs = $(shell sed \ -e '/^ *\$$ .*\/configure/!d' \ -e 's/^ *\$$ .*\/configure *//' \ $(top_builddir)/config.log \ ) LocalizeSipXconfig = sed \ -e 's,@PACKAGE\@,@PACKAGE@,g' \ -e 's,@VERSION\@,@VERSION@,g' \ -e 's,@abs_builddir\@,@abs_builddir@,g' \ -e 's,@abs_srcdir\@,@abs_srcdir@,g' \ -e 's,@abs_top_srcdir\@,@abs_top_srcdir@,g' \ -e 's,@sipx_abs_srcdir\@,@sipx_abs_srcdir@,g' \ -e 's!@CONFIGURE_OPTIONS@!$(ConfigureArgs)!g' \ -e 's,@bindir\@,$(bindir),g' \ -e 's,@datadir\@,$(datadir),g' \ -e 's,@htmldir\@,@htmldir@,g' \ -e 's,@INSTALL\@,@INSTALL@,g' \ -e 's,@install_sh\@,@install_sh@,g' \ -e 's,@libdir\@,$(libdir),g' \ -e 's,@localstatedir\@,$(localstatedir),g' \ -e 's,@pkgdatadir\@,@pkgdatadir@,g' \ -e 's,@prefix\@,$(prefix),g' \ -e 's,@profiledir\@,@profiledir@,g' \ -e 's,@wwwdir\@,@wwwdir@,g' \ -e 's,@host\@,@host@,g' \ -e 's,@PERL\@,@PERL@,g' \ -e 's,@APACHE2_HTTPD\@,@APACHE2_HTTPD@,g' \ -e 's,@APACHE2_MOD\@,@APACHE2_MOD@,g' \ -e 's,@CLOVER_HOME\@,@CLOVER_HOME@,g' \ -e 's,@JAVAC_DEBUG\@,@JAVAC_DEBUG@,g' \ -e 's,@JAVAC_OPTIMIZED\@,@JAVAC_OPTIMIZED@,g' \ -e 's,@JAVA\@,@JAVA@,g' \ -e 's,@JAVA_HOME\@,@JAVA_HOME@,g' \ -e 's,@JBOSS_HOME\@,@JBOSS_HOME@,g' \ -e 's,@JBOSS_SERVER_CONF\@,@JBOSS_SERVER_CONF@,g' \ -e 's,@SIPFOUNDRY_ORG\@,@SIPFOUNDRY_ORG@,g' \ -e 's,@SIPXCONFIG_LIBDIR\@,@SIPXCONFIG_LIBDIR@,g' \ -e 's,@SIPXPBXUSER\@,@SIPXPBXUSER@,g' \ -e 's,@SIPX_BINDIR\@,@SIPX_BINDIR@,g' \ -e 's,@SIPX_CONFDIR\@,@SIPX_CONFDIR@,g' \ -e 's,@SIPX_CONFIGPHONEDIR\@,@SIPX_CONFIGPHONEDIR@,g' \ -e 's,@SIPX_BACKUPDIR\@,@SIPX_BACKUPDIR@,g' \ -e 's,@SIPX_DATADIR\@,@SIPX_DATADIR@,g' \ -e 's,@SIPX_DBDIR\@,@SIPX_DBDIR@,g' \ -e 's,@SIPX_DOCDIR\@,@SIPX_DOCDIR@,g' \ -e 's,@SIPX_LOGDIR\@,@SIPX_LOGDIR@,g' \ -e 's,@SIPX_RUNDIR\@,@SIPX_RUNDIR@,g' \ -e 's,@SIPX_TMPDIR\@,@SIPX_TMPDIR@,g' \ -e 's,@SIPX_INCDIR\@,@SIPX_INCDIR@,g' \ -e 's,@SIPX_LIBDIR\@,@SIPX_LIBDIR@,g' \ -e 's,@SIPX_SCHEMADIR\@,@SIPX_SCHEMADIR@,g' \ -e 's,@SIPX_VXMLDATADIR\@,@SIPX_VXMLDATADIR@,g' \ -e 's,@SIPX_PARKMUSICDIR\@,@SIPX_PARKMUSICDIR@,g' \ -e 's,@SPRING_HOME\@,@SPRING_HOME@,g' \ -e 's,@XPRESSA_BUILD_NUMBER\@,@XPRESSA_BUILD_NUMBER@,g' \ -e 's,@XPRESSA_BUILD_COMMENT\@,@XPRESSA_BUILD_COMMENT@,g' \ -e 's,@SIPXPHONELIB\@,@SIPXPHONELIB@,g' \ -e 's,@SIPXPHONEDATA\@,@SIPXPHONEDATA@,g' \ -e 's,@SIPXPHONECONF\@,@SIPXPHONECONF@,g' \ -e 's,@NAMED_PROGRAM\@,@NAMED_PROGRAM@,g' EXTRA_DIST = \ config/sipX-config.in \ config/sipX-buildstamp.cpp.in \ config/sipX-buildstamp.h.in \ config/sipXprojtop.mak \ config/sipXcommon.am.inc \ config.properties.in unconditional_SUBDIRS = . include src # # If Doxygen is enabled # @DOC_TRUE@doc_SUBDIRS = doc SUBDIRS = $(unconditional_SUBDIRS) $(doc_SUBDIRS) RELEASE = 1 # BUILT_SOURCES is special autoconf variable to be checked on every make BUILT_SOURCES = config.properties @USE_BLDNO_FALSE@BUILDPARM = --define="buildno $(RELEASE)" # Get the revision number @USE_BLDNO_TRUE@BUILDPARM = --define="buildno 0.$(shell cat $(srcdir)/SVN-VERSION)" # Where rpmbuild will do its work. RPMBUILD_TOPDIR = $(shell rpm --eval '%{_topdir}') # 'rpmbuild -ta' searches root of tarball for pkgname.spec file to build # RPM from #dist-hook: sipxsdplib.spec # cp sipxsdplib.spec $(distdir) DISTCLEANFILES = config.properties all: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) all-recursive .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(top_srcdir)/config/sipXcommon.am.inc $(top_srcdir)/config/sipXprojtop.mak $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu sipXsdpLib/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu sipXsdpLib/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/config/sipXcommon.am.inc $(top_srcdir)/config/sipXprojtop.mak: $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run `make' without going through this Makefile. # To change the values of `make' variables: instead of editing Makefiles, # (1) if the variable is set in `config.status', edit `config.status' # (which will cause the Makefiles to be regenerated when you run `make'); # (2) otherwise, pass the desired values on the `make' command line. $(RECURSIVE_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ list='$(SUBDIRS)'; for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" $(RECURSIVE_CLEAN_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ rev=''; for subdir in $$list; do \ if test "$$subdir" = "."; then :; else \ rev="$$subdir $$rev"; \ fi; \ done; \ rev="$$rev ."; \ target=`echo $@ | sed s/-recursive//`; \ for subdir in $$rev; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done && test -z "$$fail" tags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ done ctags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ done ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) check-recursive all-am: Makefile installdirs: installdirs-recursive installdirs-am: install: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) -test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(BUILT_SOURCES)" || rm -f $(BUILT_SOURCES) clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) all check \ ctags-recursive install install-am install-strip \ tags-recursive .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ all all-am check check-am clean clean-generic clean-libtool \ ctags ctags-recursive distclean distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-recursive \ uninstall uninstall-am # automake doesn't like this inside the conditional .PHONY : doc @DOC_TRUE@doc : @DOC_TRUE@ cd doc && $(MAKE) $(AM_MAKEFLAGS) all config.properties : config.properties.in Makefile $(LocalizeSipXconfig) $(srcdir)/config.properties.in > config.properties .PHONY : rpm rpm : dist rpmbuild -ta $(BUILDPARM) $(PACKAGE)-$(VERSION).tar.gz mv -f $(RPMBUILD_TOPDIR)/SRPMS/$(PACKAGE)-$(VERSION)-*.rpm . mv -f $(RPMBUILD_TOPDIR)/RPMS/*/$(PACKAGE)*-$(VERSION)-*.rpm . md5sum $(PACKAGE)-$(VERSION).tar.gz >$(PACKAGE)-$(VERSION).tar.gz.md5 # RPM Spec file sipxsdplib.spec : sipxsdplib.spec.in $(LocalizeSipXconfig) $(srcdir)/sipxsdplib.spec.in > sipxsdplib.spec # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: sipxtapi-3.3.0~test17/sipXsdpLib/config.properties.in0000644000175000017500000000062312205613256023452 0ustar00danieldaniel00000000000000 # G E N E R A L version=@VERSION@ top.dir=@abs_srcdir@/.. java=@JAVA@ java.home=@JAVA_HOME@ optimize=@JAVAC_OPTIMIZED@ deprecation=false debug=@JAVAC_DEBUG@ bin.dir=@bindir@ lib.dir=@libdir@ prefix.dir=@prefix@ # comma-separated combination of 'lines' 'source' and 'var' only valid # when debug is on debuglevel=lines # U T I L jdom.jar=${top.dir}/lib/jdom-b10.jar junit.jar=${top.dir}/lib/junit.jar sipxtapi-3.3.0~test17/sipXsdpLib/include/0000755000175000017500000000000012321445026021101 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXsdpLib/include/sdp/0000755000175000017500000000000012321445026021667 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXsdpLib/include/sdp/Sdp.h0000644000175000017500000004342212321267455022603 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2007 Plantronics // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Scott Godin (sgodin AT SipSpectrum DOT com) #ifndef _Sdp_h_ #define _Sdp_h_ // SYSTEM INCLUDES //#include <...> #include // APPLICATION INCLUDES #include #include #include #include #include #include #include "SdpCandidate.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //: Container for SDP specification // This class holds the information related to an SDP. // Included in this information is: TODO // class SdpMediaLine; class Sdp { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: typedef enum { // WARNING: this enum must stay in synch. with SdpNetTypeString NET_TYPE_NONE, NET_TYPE_IN // "IN" - Internet - RFC4566 } SdpNetType; static const char* SdpNetTypeString[]; typedef enum { // WARNING: this enum MUST stay in synch with SdpAddressTypeString ADDRESS_TYPE_NONE, ADDRESS_TYPE_IP4, // "IP4" - RFC4566 ADDRESS_TYPE_IP6 // "IP6" - RFC4566 } SdpAddressType; static const char* SdpAddressTypeString[]; typedef enum { BANDWIDTH_TYPE_NONE, BANDWIDTH_TYPE_CT, // "CT" - Conference Total - RFC4566 BANDWIDTH_TYPE_AS, // "AS" - Application Specific - RFC4566 BANDWIDTH_TYPE_TIAS, // "TIAS" - Transport Independent Application Specific - RFC3890, BANDWIDTH_TYPE_RS, // "RS" - RTCP bandwidth on active senders - RFC3556 BANDWIDTH_TYPE_RR // "RR" - RTCP bandwidth allocated to other participants - RFC3556 } SdpBandwidthType; static const char* SdpBandwidthTypeString[]; class SdpBandwidth : public UtlCopyableContainable { public: SdpBandwidth(SdpBandwidthType type, unsigned int bandwidth) : mType(type), mBandwidth(bandwidth) {} SdpBandwidth(const SdpBandwidth& rhs) : mType(rhs.mType), mBandwidth(rhs.mBandwidth) {} // Containable requirements UtlContainableType getContainableType() const { static char type[] = "SdpBandwidth"; return type;} unsigned hash() const { return directHash(); } int compareTo(UtlContainable const *) const { return 0; } // not implemented UtlCopyableContainable* clone() const { return new SdpBandwidth(*this); } // Accessors void setType(SdpBandwidthType type) { mType = type; } SdpBandwidthType getType() const { return mType; } static SdpBandwidthType getTypeFromString(const char * type); void setBandwidth(unsigned int bandwidth) { mBandwidth = bandwidth; } unsigned int getBandwidth() const { return mBandwidth; } private: SdpBandwidthType mType; unsigned int mBandwidth; }; class SdpTime : public UtlCopyableContainable { public: class SdpTimeRepeat : public UtlCopyableContainable { public: SdpTimeRepeat(unsigned int repeatInterval, unsigned int activeDuration) : mRepeatInterval(repeatInterval), mActiveDuration(activeDuration) {} SdpTimeRepeat(const SdpTimeRepeat& rhs) : mRepeatInterval(rhs.mRepeatInterval), mActiveDuration(rhs.mActiveDuration), mOffsetsFromStartTime(rhs.mOffsetsFromStartTime) {} // Containable requirements UtlContainableType getContainableType() const { static char type[] = "SdpTimeRepeat"; return type;} unsigned hash() const { return directHash(); } int compareTo(UtlContainable const *) const { return 0; } // not implemented UtlCopyableContainable* clone() const { return new SdpTimeRepeat(*this); } // Accessors void setRepeatInterval(unsigned int repeatInterval) { mRepeatInterval = repeatInterval; } unsigned int getRepeatInterval() const { return mRepeatInterval; } void setActiveDuration(unsigned int activeDuration) { mActiveDuration = activeDuration; } unsigned int getActiveDuration() const { return mActiveDuration; } void addOffsetFromStartTime(unsigned int offset) { mOffsetsFromStartTime.insert(new UtlInt(offset)); } void clearOffsetsFromStartTime() { mOffsetsFromStartTime.destroyAll(); } const UtlCopyableSList& getOffsetsFromStartTime() const { return mOffsetsFromStartTime; } private: unsigned int mRepeatInterval; unsigned int mActiveDuration; UtlCopyableSList mOffsetsFromStartTime; }; SdpTime(uint64_t startTime, uint64_t stopTime) : mStartTime(startTime), mStopTime(stopTime) {} SdpTime(const SdpTime& rhs) : mStartTime(rhs.mStartTime), mStopTime(rhs.mStopTime), mRepeats(rhs.mRepeats) {} // Containable requirements UtlContainableType getContainableType() const { static char type[] = "SdpTime"; return type;} unsigned hash() const { return directHash(); } int compareTo(UtlContainable const *) const { return 0; } // not implemented UtlCopyableContainable* clone() const { return new SdpTime(*this); } // Accessors void setStartTime(uint64_t startTime) { mStartTime = startTime; } uint64_t getStartTime() const { return mStartTime; } void setStopTime(uint64_t stopTime) { mStopTime = stopTime; } uint64_t getStopTime() const { return mStopTime; } void addRepeat(SdpTimeRepeat* sdpTimeRepeat) { mRepeats.insert(sdpTimeRepeat); } void clearRepeats() { mRepeats.destroyAll(); } const UtlCopyableSList& getRepeats() const { return mRepeats; } private: uint64_t mStartTime; uint64_t mStopTime; UtlCopyableSList mRepeats; }; class SdpTimeZone : public UtlCopyableContainable { public: SdpTimeZone(int adjustmentTime, int offset) : mAdjustmentTime(adjustmentTime), mOffset(offset) {} SdpTimeZone(const SdpTimeZone& rhs) : mAdjustmentTime(rhs.mAdjustmentTime), mOffset(rhs.mOffset) {} // Containable requirements UtlContainableType getContainableType() const { static char type[] = "SdpTimeZone"; return type;} unsigned hash() const { return directHash(); } int compareTo(UtlContainable const *) const { return 0; } // not implemented UtlCopyableContainable* clone() const { return new SdpTimeZone(*this); } // Accessors void setAdjustmentTime(int adjustmentTime) { mAdjustmentTime = adjustmentTime; } uint64_t getAdjustmentTime() const { return mAdjustmentTime; } void setOffset(int offset) { mOffset = offset; } uint64_t getOffset() const { return mOffset; } private: int mAdjustmentTime; int mOffset; }; typedef enum { CONFERENCE_TYPE_NONE, CONFERENCE_TYPE_BROADCAST, // "broadcast" - RFC4566 CONFERENCE_TYPE_MODERATED, // "moderated" - RFC4566 CONFERENCE_TYPE_TEST, // "test" - RFC4566 CONFERENCE_TYPE_H332 // "H332" - RFC4566 } SdpConferenceType; static const char* SdpConferenceTypeString[]; typedef enum { GROUP_SEMANTICS_NONE, GROUP_SEMANTICS_LS, // "LS" - Lip Sync - RFC3388 GROUP_SEMANTICS_FID, // "FID" - Flow Identifier - RFC3388 GROUP_SEMANTICS_SRF, // "SRF" - Single Reservation Flow - RFC3524 GROUP_SEMANTICS_ANAT // "ANAT" - Alternative Network Address Types - RFC4091 } SdpGroupSemantics; static const char* SdpGroupSemanticsString[]; class SdpGroup : public UtlCopyableContainable { public: SdpGroup(SdpGroupSemantics semantics) : mSemantics(semantics) {} SdpGroup(const SdpGroup& rhs) : mSemantics(rhs.mSemantics), mIdentificationTags(rhs.mIdentificationTags) {} // Containable requirements UtlContainableType getContainableType() const { static char type[] = "SdpGroup"; return type;} unsigned hash() const { return directHash(); } int compareTo(UtlContainable const *) const { return 0; } // not implemented UtlCopyableContainable* clone() const { return new SdpGroup(*this); } // Accessors void setSemantics(SdpGroupSemantics semantics) { mSemantics = semantics; } SdpGroupSemantics getSemantics() const { return mSemantics; } static SdpGroupSemantics getSemanticsFromString(const char * type); void addIdentificationTag(const char * identificationTag) { mIdentificationTags.insert(new UtlString(identificationTag)); } void clearIdentificationTags() { mIdentificationTags.destroyAll(); } const UtlCopyableSList& getIdentificationTags() const { return mIdentificationTags; } private: SdpGroupSemantics mSemantics; UtlCopyableSList mIdentificationTags; }; class SdpFoundation : public UtlCopyableContainable { public: SdpFoundation(SdpCandidate::SdpCandidateType candidateType, const char * baseAddress, const char * stunAddress) : mCandidateType(candidateType), mBaseAddress(baseAddress), mStunAddress(stunAddress) {} SdpFoundation(const SdpFoundation& rhs) : mCandidateType(rhs.mCandidateType), mBaseAddress(rhs.mBaseAddress), mStunAddress(rhs.mStunAddress) {} // Containable requirements UtlContainableType getContainableType() const { static char type[] = "SdpFoundationId"; return type;} unsigned hash() const { return mBaseAddress.hash() ^ mStunAddress.hash() ^ mCandidateType; } int compareTo(UtlContainable const *) const; UtlCopyableContainable* clone() const { return new SdpFoundation(*this); } private: SdpCandidate::SdpCandidateType mCandidateType; UtlString mBaseAddress; UtlString mStunAddress; }; /* ============================ CREATORS ================================== */ Sdp(); //:Default constructor Sdp(const Sdp& rSdp); //:Copy constructor virtual ~Sdp(); //:Destructor /* ============================ MANIPULATORS ============================== */ Sdp& operator=(const Sdp& rhs); //:Assignment operator void setSdpVersion(unsigned int sdpVersion) { mSdpVersion = sdpVersion; } void setOriginatorInfo(const char* userName, uint64_t sessionId, uint64_t sessionVersion, SdpNetType netType, SdpAddressType addressType, const char* unicastAddress); void setOriginatorUserName(const char* originatorUserName) { mOriginatorUserName = originatorUserName; } void setOriginatorSessionId(uint64_t originatorSessionId) { mOriginatorSessionId = originatorSessionId; } void setOriginatorSessionVersion(uint64_t originatorSessionVersion) { mOriginatorSessionVersion = originatorSessionVersion; } void setOriginatorNetType(SdpNetType originatorNetType) { mOriginatorNetType = originatorNetType; } void setOriginatorAddressType(SdpAddressType originatorAddressType) { mOriginatorAddressType = originatorAddressType; } void setOriginatorUnicastAddress(const char* originatorUnicastAddress) { mOriginatorUnicastAddress = originatorUnicastAddress; } void setSessionName(const char * sessionName) { mSessionName = sessionName; } void setSessionInformation(const char * sessionInformation) { mSessionInformation = sessionInformation; } void setSessionUri(const char * sessionUri) { mSessionUri = sessionUri; } void addEmailAddress(const char * emailAddress) { mEmailAddresses.insert(new UtlString(emailAddress)); } void clearEmailAddresses() { mEmailAddresses.destroyAll(); } void addPhoneNumber(const char * phoneNumber) { mPhoneNumbers.insert(new UtlString(phoneNumber)); } void clearPhoneNumbers() { mPhoneNumbers.destroyAll(); } void addBandwidth(SdpBandwidthType type, unsigned int bandwidth) { addBandwidth(new SdpBandwidth(type, bandwidth)); } void addBandwidth(SdpBandwidth* sdpBandwidth) { mBandwidths.insert(sdpBandwidth); } void clearBandwidths() { mBandwidths.destroyAll(); } void addTime(uint64_t startTime, uint64_t stopTime) { addTime(new SdpTime(startTime, stopTime)); } void addTime(SdpTime* time) { mTimes.insert(time); } void clearTimes() { mTimes.destroyAll(); } void addTimeZone(int adjustmentTime, int offset) { addTimeZone(new SdpTimeZone(adjustmentTime, offset)); } void addTimeZone(SdpTimeZone* timeZone) { mTimeZones.insert(timeZone); } void clearTimeZones() { mTimeZones.destroyAll(); } void setCategory(const char * category) { mCategory = category; } void setKeywords(const char * keywords) { mKeywords = keywords; } void setToolNameAndVersion(const char * toolNameAndVersion) { mToolNameAndVersion = toolNameAndVersion; } void setConferenceType(SdpConferenceType conferenceType) { mConferenceType = conferenceType; } void setCharSet(const char * charSet) { mCharSet = charSet; } void setIcePassiveOnlyMode(bool icePassiveOnlyMode) { mIcePassiveOnlyMode = icePassiveOnlyMode; } void addGroup(SdpGroup* group) { mGroups.insert(group); } void clearGroups() { mGroups.destroyAll(); } void setSessionLanguage(const char * sessionLanguage) { mSessionLanguage = sessionLanguage; } void setDescriptionLanguage(const char * descriptionLanguage) { mDescriptionLanguage = descriptionLanguage; } void setMaximumPacketRate(double maximumPacketRate) { mMaximumPacketRate = maximumPacketRate; } void addMediaLine(SdpMediaLine* mediaLine); void clearMediaLines(); /* ============================ ACCESSORS ================================= */ void toString(UtlString& sdpString) const; /* ============================ INQUIRY =================================== */ static SdpAddressType getAddressTypeFromString(const char * type); unsigned int getSdpVersion() const { return mSdpVersion; } const UtlString& getOriginatorUserName() const { return mOriginatorUserName; } uint64_t getOriginatorSessionId() const { return mOriginatorSessionId; } uint64_t getOriginatorSessionVersion() const { return mOriginatorSessionVersion; } SdpNetType getOriginatorNetType() const { return mOriginatorNetType; } SdpAddressType getOriginatorAddressType() const { return mOriginatorAddressType; } const UtlString& getOriginatorUnicastAddress() const { return mOriginatorUnicastAddress; } const UtlString& getSessionName() const { return mSessionName; } const UtlString& getSessionInformation() const { return mSessionInformation; } const UtlString& getSessionUri() const { return mSessionUri; } const UtlCopyableSList& getEmailAddresses() const { return mEmailAddresses; } const UtlCopyableSList& getPhoneNumbers() const { return mPhoneNumbers; } const UtlCopyableSList& getBandwidths() const { return mBandwidths; } const UtlCopyableSList& getTimes() const { return mTimes; } const UtlCopyableSList& getTimeZones() const { return mTimeZones; } const UtlString& getCategory() const { return mCategory; } const UtlString& getKeywords() const { return mKeywords; } const UtlString& getToolNameAndVersion() const { return mToolNameAndVersion; } SdpConferenceType getConferenceType() const { return mConferenceType; } static SdpConferenceType getConferenceTypeFromString(const char * type); const UtlString& getCharSet() const { return mCharSet; } bool isIcePassiveOnlyMode() const { return mIcePassiveOnlyMode; } const UtlCopyableSList& getGroups() const { return mGroups; } const UtlString& getSessionLanguage() const { return mSessionLanguage; } const UtlString& getDescriptionLanguage() const { return mDescriptionLanguage; } double getMaximumPacketRate() const { return mMaximumPacketRate; } const UtlCopyableSList& getMediaLines() const; UtlString getLocalFoundationId(SdpCandidate::SdpCandidateType candidateType, const char * baseAddress, const char * stunAddress=0); /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: // v= unsigned int mSdpVersion; // o= UtlString mOriginatorUserName; uint64_t mOriginatorSessionId; uint64_t mOriginatorSessionVersion; SdpNetType mOriginatorNetType; SdpAddressType mOriginatorAddressType; UtlString mOriginatorUnicastAddress; // s= UtlString mSessionName; // i= UtlString mSessionInformation; // u= UtlString mSessionUri; // e= UtlCopyableSList mEmailAddresses; // p= UtlCopyableSList mPhoneNumbers; // c= is only stored in sdpMediaLine // b= UtlCopyableSList mBandwidths; // t=, r= UtlCopyableSList mTimes; // z= UtlCopyableSList mTimeZones; // k= is only stored in sdpMediaLine // a= session level only attributes UtlString mCategory; // a=cat: - RFC4566 UtlString mKeywords; // a=keywds: - RFC4566 UtlString mToolNameAndVersion; // a=tool: - RFC4566 SdpConferenceType mConferenceType; // a=type: - RFC4566 UtlString mCharSet; // a=charset: - RFC4566 bool mIcePassiveOnlyMode; // a=ice-passive - ietf-draft-mmusic-ice-12 UtlCopyableSList mGroups; // a=group: ... - RFC3388 // a= attributes that have meaning when not associated to a particular media line UtlString mSessionLanguage; // a=lang: - RFC4566 UtlString mDescriptionLanguage; // a=sdplang: - RFC4566 double mMaximumPacketRate; // a=maxprate: in packets/s - RFC3890 // Media Lines UtlCopyableSList mMediaLines; // Foundation Id UtlHashMap mFoundationIds; }; /* ============================ INLINE METHODS ============================ */ #endif // _Sdp_h_ sipxtapi-3.3.0~test17/sipXsdpLib/include/sdp/SdpCandidate.h0000644000175000017500000001676512205613256024405 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2012 SIPez LLC. // // Copyright (C) 2007 Plantronics // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Scott Godin (sgodin AT SipSpectrum DOT com) #ifndef _SdpCandidate_h_ #define _SdpCandidate_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include "utl/UtlInt.h" #include "utl/UtlString.h" #include "utl/UtlCopyableSList.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //: Container for SdpCandidate specification // This class holds the information related to an SdpCandidate. // Included in this information is: TODO // class SdpCandidate : public UtlCopyableContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: typedef enum { CANDIDATE_TRANSPORT_TYPE_NONE, CANDIDATE_TRANSPORT_TYPE_UDP, // "udp" - draft-ietf-mmusic-ice-12 CANDIDATE_TRANSPORT_TYPE_TCP_SO, // "tcp-so" - TCP simultaneous-open - draft-ietf-mmusic-ice-tcp-02 CANDIDATE_TRANSPORT_TYPE_TCP_ACT, // "tcp-act" - TCP active - draft-ietf-mmusic-ice-tcp-02 CANDIDATE_TRANSPORT_TYPE_TCP_PASS, // "tcp-pass" - TCP passive - draft-ietf-mmusic-ice-tcp-02 CANDIDATE_TRANSPORT_TYPE_TLS_SO, // "tls-so" - TCP simultaneous-open - draft-ietf-mmusic-ice-tcp-02 CANDIDATE_TRANSPORT_TYPE_TLS_ACT, // "tls-act" - TCP active - draft-ietf-mmusic-ice-tcp-02 CANDIDATE_TRANSPORT_TYPE_TLS_PASS // "tls-pass" - TCP passive - draft-ietf-mmusic-ice-tcp-02 } SdpCandidateTransportType; static const char* SdpCandidateTransportTypeString[]; typedef enum { CANDIDATE_TYPE_NONE, CANDIDATE_TYPE_HOST, // "host" - draft-ietf-mmusic-ice-12 CANDIDATE_TYPE_SRFLX, // "srflx" - server reflexive - draft-ietf-mmusic-ice-12 CANDIDATE_TYPE_PRFLX, // "prflx" - peer reflexive - draft-ietf-mmusic-ice-12 CANDIDATE_TYPE_RELAY, // "relay" - draft-ietf-mmusic-ice-12 } SdpCandidateType; static const char* SdpCandidateTypeString[]; class SdpCandidateExtensionAttribute : public UtlCopyableContainable { public: SdpCandidateExtensionAttribute(const char * name, const char * value) : mName(name), mValue(value) {} SdpCandidateExtensionAttribute(const SdpCandidateExtensionAttribute& rhs) : mName(rhs.mName), mValue(rhs.mValue) {} // Containable requirements UtlContainableType getContainableType() const { static char type[] = "SdpCrypto"; return type;} unsigned hash() const { return directHash(); } int compareTo(UtlContainable const *) const { return 0; } // not implemented UtlCopyableContainable* clone() const { return new SdpCandidateExtensionAttribute(*this); } // Accessors void setName(const char * name) { mName = name; } const UtlString& getName() const { return mName; } void setValue(const char * value) { mValue = value; } const UtlString& getValue() const { return mValue; } private: UtlString mName; UtlString mValue; }; /* ============================ CREATORS ================================== */ SdpCandidate(const char * foundation = 0, unsigned int id = 0, SdpCandidateTransportType transport = CANDIDATE_TRANSPORT_TYPE_NONE, uint64_t priority = 0, const char * connectionAddress = 0, unsigned int port = 0, SdpCandidateType candidateType = CANDIDATE_TYPE_NONE, const char * relatedAddress = 0, unsigned int relatedPort = 0, bool inUse = false); //:Default constructor SdpCandidate(const SdpCandidate& rSdpCandidate); //:Copy constructor virtual ~SdpCandidate(); //:Destructor /* ============================ MANIPULATORS ============================== */ SdpCandidate& operator=(const SdpCandidate& rhs); //:Assignment operator void setFoundation(const char * foundation) { mFoundation = foundation; } void setId(unsigned int id) { mId = id; } void setTransport(SdpCandidateTransportType transport) { mTransport = transport; } void setPriority(uint64_t priority) { mPriority = priority; } void setConnectionAddress(const char * connectionAddress) { mConnectionAddress = connectionAddress; } void setPort(unsigned int port) { mPort = port; } void setCandidateType(SdpCandidateType candidateType) { mCandidateType = candidateType; } void setRelatedAddress(const char * relatedAddress) { mRelatedAddress = relatedAddress; } void setRelatedPort(unsigned int relatedPort) { mRelatedPort = relatedPort; } void addExtensionAttribute(const char * name, const char * value) { addExtensionAttribute(new SdpCandidateExtensionAttribute(name, value)); } void addExtensionAttribute(SdpCandidateExtensionAttribute* sdpCandidateExtensionAttribute) { mExtensionAttributes.insert(sdpCandidateExtensionAttribute); } void clearExtensionAttributes() { mExtensionAttributes.destroyAll(); } void setInUse(bool inUse) { mInUse = inUse; } /* ============================ ACCESSORS ================================= */ // UtlContainable requirements virtual UtlContainableType getContainableType() const; virtual unsigned hash() const; virtual int compareTo(UtlContainable const *) const; static const UtlContainableType TYPE; ///< Class type used for runtime checking UtlCopyableContainable* clone() const { return new SdpCandidate(*this); } void toString(UtlString& sdpCandidateString) const; /* ============================ INQUIRY =================================== */ virtual UtlBoolean isInstanceOf(const UtlContainableType type) const; const UtlString& getFoundation() const { return mFoundation; } unsigned int getId() const { return mId; } SdpCandidateTransportType getTransport() const { return mTransport; } static SdpCandidateTransportType getCandidateTransportTypeFromString(const char * type); uint64_t getPriority() const { return mPriority; } const UtlString& getConnectionAddress() const { return mConnectionAddress; } unsigned int getPort() const { return mPort; } SdpCandidateType getCandidateType() const { return mCandidateType; } static SdpCandidateType getCandidateTypeFromString(const char * type); const UtlString& getRelatedAddress() const { return mRelatedAddress; } unsigned int getRelatedPort() const { return mRelatedPort; } const UtlCopyableSList& getExtensionAttributes() const { return mExtensionAttributes; } bool isInUse() const { return mInUse; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: int compareNumber(uint64_t first, uint64_t second, bool reverse = false) const; UtlString mFoundation; unsigned int mId; SdpCandidateTransportType mTransport; uint64_t mPriority; UtlString mConnectionAddress; unsigned int mPort; SdpCandidateType mCandidateType; UtlString mRelatedAddress; unsigned int mRelatedPort; UtlCopyableSList mExtensionAttributes; bool mInUse; }; /* ============================ INLINE METHODS ============================ */ #endif // _SdpCandidate_h_ sipxtapi-3.3.0~test17/sipXsdpLib/include/sdp/SdpCandidatePair.h0000644000175000017500000000760112205613256025206 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 Plantronics // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Scott Godin (sgodin AT SipSpectrum DOT com) #ifndef _SdpCandidatePair_h_ #define _SdpCandidatePair_h_ // SYSTEM INCLUDES //#include <...> // APPLICATION INCLUDES #include #include #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //: Container for SdpCandidatePair specification // This class holds the information related to an SdpCandidatePair. // Included in this information is: TODO // class SdpCandidatePair : public UtlCopyableContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: typedef enum { CHECK_STATE_FROZEN, CHECK_STATE_WAITING, CHECK_STATE_INPROGRESS, CHECK_STATE_SUCCEEDED, CHECK_STATE_FAILED } SdpCandidatePairCheckState; static const char* SdpCandidatePairCheckStateString[]; typedef enum { OFFERER_LOCAL, OFFERER_REMOTE } SdpCandidatePairOffererType; static const char* SdpCandidatePairOffererTypeString[]; /* ============================ CREATORS ================================== */ SdpCandidatePair(const SdpCandidate& localCandidate, const SdpCandidate& remoteCandidate, SdpCandidatePairOffererType offerer); //:Default constructor SdpCandidatePair(const SdpCandidatePair& rSdpCandidatePair); //:Copy constructor virtual ~SdpCandidatePair(); //:Destructor /* ============================ MANIPULATORS ============================== */ SdpCandidatePair& operator=(const SdpCandidatePair& rhs); //:Assignment operator void setLocalCandidate(const SdpCandidate& localCandidate) { mLocalCandidate = localCandidate; resetPriority(); } void setRemoteCandidate(const SdpCandidate& remoteCandidate) { mRemoteCandidate = remoteCandidate; resetPriority(); } void setOfferer(SdpCandidatePairOffererType offerer) { mOfferer = offerer; resetPriority(); } bool setCheckState(SdpCandidatePairCheckState checkState); /* ============================ ACCESSORS ================================= */ // UtlContainable requirements virtual UtlContainableType getContainableType() const; virtual unsigned hash() const; virtual int compareTo(UtlContainable const *) const; static const UtlContainableType TYPE; ///< Class type used for runtime checking UtlCopyableContainable* clone() const { return new SdpCandidatePair(*this); } void toString(UtlString& sdpCandidateString) const; /* ============================ INQUIRY =================================== */ const SdpCandidate& getLocalCandidate() const { return mLocalCandidate; } const SdpCandidate& getRemoteCandidate() const { return mRemoteCandidate; } SdpCandidatePairOffererType getOfferer() const { return mOfferer; } uint64_t getPriority() const { return mPriority; } SdpCandidatePairCheckState getCheckState() const { return mCheckState; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: int compareNumber(uint64_t first, uint64_t second, bool reverse = false) const; void resetPriority(); SdpCandidate mLocalCandidate; SdpCandidate mRemoteCandidate; SdpCandidatePairOffererType mOfferer; uint64_t mPriority; SdpCandidatePairCheckState mCheckState; }; /* ============================ INLINE METHODS ============================ */ #endif // _SdpCandidatePair_h_ sipxtapi-3.3.0~test17/sipXsdpLib/include/sdp/SdpCodec.h0000644000175000017500000004603512321276601023535 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2007 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _SdpCodec_h_ #define _SdpCodec_h_ // SYSTEM INCLUDES //#include <...> // APPLICATION INCLUDES #include #include // DEFINES // Mime major types #define MIME_TYPE_AUDIO "audio" #define MIME_TYPE_VIDEO "video" #define MIME_TYPE_APPLICATION "application" // Mime Sub types #define MIME_SUBTYPE_PCMU "PCMU" #define MIME_SUBTYPE_PCMA "PCMA" #define MIME_SUBTYPE_G729A "G729" #define MIME_SUBTYPE_G729AB "G729" #define MIME_SUBTYPE_G729ACISCO7960 "G729a" #define MIME_SUBTYPE_G723 "G723" #define MIME_SUBTYPE_G726_16 "G726-16" #define MIME_SUBTYPE_G726_24 "G726-24" #define MIME_SUBTYPE_G726_32 "G726-32" #define MIME_SUBTYPE_G726_40 "G726-40" #define MIME_SUBTYPE_G722 "G722" #define MIME_SUBTYPE_DTMF_TONES "telephone-event" #define MIME_SUBTYPE_IPCMU "EG711U" #define MIME_SUBTYPE_IPCMA "EG711A" #define MIME_SUBTYPE_IPCMWB "IPCMWB" #define MIME_SUBTYPE_ILBC "iLBC" #define MIME_SUBTYPE_ISAC "ISAC" #define MIME_SUBTYPE_GSM "GSM" #define MIME_SUBTYPE_OPUS "opus" #define MIME_SUBTYPE_SPEEX "speex" #define MIME_SUBTYPE_AMR "amr" #define MIME_SUBTYPE_AMRWB "amr-wb" #define MIME_SUBTYPE_AAC_LC "aac_lc" #define MIME_SUBTYPE_MPEG4_GENERIC "mpeg4-generic" #define MIME_SUBTYPE_VP71 "VP71" #define MIME_SUBTYPE_IYUV "IYUV" #define MIME_SUBTYPE_I420 "I420" #define MIME_SUBTYPE_RGB24 "RGB24" #define MIME_SUBTYPE_H263 "H263" #define MIME_SUBTYPE_H263_1998 "H263-1998" #define MIME_SUBTYPE_H264 "H264" // Canonical internal case represation #define SDP_MIME_TO_CASE toLower #define SDP_MIME_SUBTYPE_TO_CASE toUpper // Bandwidth requirements for SDP Codecs #define SDP_CODEC_BANDWIDTH_VARIABLE 0 #define SDP_CODEC_BANDWIDTH_LOW 1 #define SDP_CODEC_BANDWIDTH_NORMAL 2 #define SDP_CODEC_BANDWIDTH_HIGH 3 #define SDP_CODEC_BANDWIDTH_VERY_HIGH 4 // Video formats - must be bitmap values #define SDP_VIDEO_FORMAT_SQCIF 0x0001 #define SDP_VIDEO_FORMAT_QCIF 0x0002 #define SDP_VIDEO_FORMAT_CIF 0x0004 #define SDP_VIDEO_FORMAT_QVGA 0x0008 #define SDP_VIDEO_FORMAT_VGA 0x0010 #define SDP_VIDEO_FORMAT_NTSC 0x0020 #define SDP_VIDEO_FORMAT_4CIF 0x0040 #define SDP_VIDEO_FORMAT_EDTV 0x0080 #define SDP_VIDEO_FORMAT_QHD 0x0100 #define SDP_VIDEO_FORMAT_HD720 0x0200 #define SDP_VIDEO_FORMAT_16CIF 0x0400 #define SDP_VIDEO_FORMAT_HD1088 0x0800 // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /// Container for SDP/RTP codec specification /** * This class holds the SDP definition of a codec. Included information is: * sample rate, number of channels, the mapping from an internal codec id * to the public SDP format and RTP payload type id. * * This is the base class. Specific codec types may implement sub classes * which define the codec specific parameters. All specific codec types * MUST be registered with the SdpCodecFactory to be usable. Generally * codecs are constructed ONLY by the SdpCodecFactory. * * The method that is used on SdpCodec::getCodecType() retrieves the static * codec type/id. Now there is defined an enum in SdpCodec which contains * the current values as well as some additional ones. The idea is that these * are private, internally assigned ids to the codecs we support. * * A new method SdpCodec::getCodecPayloadFormat() has been added which returns * the RTP payload id to be used in RTP and the SDP. For static codec ID, the * returned value for both of these methods would typically be the same, * however for the dynamic codecs they will mostly be different. * * The intent is that eventually we will support a factory which will allow * registration of new codec types. */ class SdpCodec : public UtlInt { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /// Unique identifier used for each supported codec /** * Note it is possible that the format id/type used in the SDP "m" field * and RTP header is different than these internally used ids. */ enum SdpCodecTypes { SDP_CODEC_UNKNOWN = -1, SDP_CODEC_PCMU = 0, ///< G.711 mu-law SDP_CODEC_GSM = 3, ///< GSM codec SDP_CODEC_G723 = 4, ///< G.723 SDP_CODEC_PCMA = 8, ///< G.711 a-law SDP_CODEC_G722 = 9, ///< G.722 SDP_CODEC_L16_44100_STEREO = 10, ///< PCM 16 bit/sample 44100 samples/sec. SDP_CODEC_L16_44100_MONO = 11, ///< PCM 16 bit/sample 44100 samples/sec. SDP_CODEC_G729 = 18, ///< G.729, with or without Annexes A or B SDP_CODEC_H263 = 34, ///< H.263 video codec SDP_CODEC_MAXIMUM_STATIC_CODEC = 95, ///< Payload types for codecs below ///< will be assigned dynamically. SDP_CODEC_SPEEX, ///< Speex NB, 8,000bps SDP_CODEC_SPEEX_5, ///< Speex NB, 5,950bps SDP_CODEC_SPEEX_15, ///< Speex NB, 15,000bps SDP_CODEC_SPEEX_24, ///< Speex NB, 24,600bps SDP_CODEC_SPEEX_WB, ///< Speex WB 9,800bps SDP_CODEC_SPEEX_WB_5, ///< Speex WB 5,750bps SDP_CODEC_SPEEX_WB_21, ///< Speex WB 20,600bps SDP_CODEC_SPEEX_WB_42, ///< Speex WB 42,200bps SDP_CODEC_SPEEX_UWB, ///< Speex UWB 11,600bps SDP_CODEC_SPEEX_UWB_8, ///< Speex UWB 7,550bps SDP_CODEC_SPEEX_UWB_22, ///< Speex UWB 22,400bps SDP_CODEC_SPEEX_UWB_44, ///< Speex UWB 44,000bps SDP_CODEC_ILBC, ///< Internet Low Bit Rate Codec, 30ms (RFC3951) SDP_CODEC_ILBC_20MS, ///< Internet Low Bit Rate Codec, 20ms (RFC3951) SDP_CODEC_TONES, ///< AVT/DTMF Tones, RFC 2833 SDP_CODEC_G729A, ///< G.729A SDP_CODEC_G7221, ///< Siren SDP_CODEC_G7231, ///< G.723.1 SDP_CODEC_AMR, ///< AMR Bandwidth Efficient mode SDP_CODEC_AMR_ALIGNED, ///< AMR Octet Aligned mode SDP_CODEC_AMRWB, ///< AMR-WB Bandwidth Efficient mode SDP_CODEC_AMRWB_ALIGNED, ///< AMR-WB Octet Aligned mode SDP_CODEC_L16_8000_STEREO, ///< PCM 16 bit/sample 8000 samples/sec stereo. SDP_CODEC_L16_8000_MONO, ///< PCM 16 bit/sample 8000 samples/sec mono. SDP_CODEC_L16_11025_STEREO, ///< PCM 16 bit/sample 11025 samples/sec stereo. SDP_CODEC_L16_11025_MONO, ///< PCM 16 bit/sample 11025 samples/sec mono. SDP_CODEC_L16_16000_STEREO, ///< PCM 16 bit/sample 16000 samples/sec stereo. SDP_CODEC_L16_16000_MONO, ///< PCM 16 bit/sample 16000 samples/sec mono. SDP_CODEC_L16_22050_STEREO, ///< PCM 16 bit/sample 22050 samples/sec stereo. SDP_CODEC_L16_22050_MONO, ///< PCM 16 bit/sample 22050 samples/sec mono. SDP_CODEC_L16_24000_STEREO, ///< PCM 16 bit/sample 24000 samples/sec stereo. SDP_CODEC_L16_24000_MONO, ///< PCM 16 bit/sample 24000 samples/sec mono. SDP_CODEC_L16_32000_STEREO, ///< PCM 16 bit/sample 32000 samples/sec stereo. SDP_CODEC_L16_32000_MONO, ///< PCM 16 bit/sample 32000 samples/sec mono. SDP_CODEC_L16_48000_STEREO, ///< PCM 16 bit/sample 48000 samples/sec stereo. SDP_CODEC_L16_48000_MONO, ///< PCM 16 bit/sample 48000 samples/sec mono. SDP_CODEC_G729AB, ///< G.729A SDP_CODEC_G729ACISCO7960, SDP_CODEC_G726_16, SDP_CODEC_G726_24, SDP_CODEC_G726_32, SDP_CODEC_G726_40, SDP_CODEC_AAC_LC_32000, SDP_CODEC_MPEG4_GENERIC_AAC_LC_16000, SDP_CODEC_MPEG4_GENERIC_AAC_LC_32000, SDP_CODEC_MPEG4_GENERIC_AAC_LC_48000, SDP_CODEC_OPUS, ///< Default OPUS VoIP codec upto 48000 samples/sec /// GIPS specific codecs //@{ SDP_CODEC_GIPS_IPCMA, SDP_CODEC_GIPS_IPCMU, SDP_CODEC_GIPS_IPCMWB, SDP_CODEC_GIPS_ISAC, //@} /// Video codecs //@{ SDP_CODEC_VP71_CIF, SDP_CODEC_VP71_QCIF, SDP_CODEC_VP71_SQCIF, SDP_CODEC_VP71_QVGA, SDP_CODEC_IYUV_CIF, SDP_CODEC_IYUV_QCIF, SDP_CODEC_IYUV_SQCIF, SDP_CODEC_IYUV_QVGA, SDP_CODEC_I420_CIF, SDP_CODEC_I420_QCIF, SDP_CODEC_I420_SQCIF, SDP_CODEC_I420_QVGA, SDP_CODEC_RGB24_CIF, SDP_CODEC_RGB24_QCIF, SDP_CODEC_RGB24_SQCIF, SDP_CODEC_RGB24_QVGA, SDP_CODEC_H263_CIF, SDP_CODEC_H263_QCIF, SDP_CODEC_H263_SQCIF, SDP_CODEC_H263_QVGA, SDP_CODEC_H264, // 166 SDP_CODEC_H264_CIF_256, SDP_CODEC_H264_NTSC_256, SDP_CODEC_H264_4CIF_512, SDP_CODEC_H264_EDTV_512, SDP_CODEC_H264_QHD_1024, SDP_CODEC_H264_HD720_1024, SDP_CODEC_H264_HD720_2048, SDP_CODEC_H264_HD1088_2048, SDP_CODEC_H264_HD1088_4096, SDP_CODEC_H264_PM1_CIF_256, SDP_CODEC_H264_PM1_NTSC_256, SDP_CODEC_H264_PM1_4CIF_512, SDP_CODEC_H264_PM1_EDTV_512, SDP_CODEC_H264_PM1_QHD_1024, SDP_CODEC_H264_PM1_HD720_1024, SDP_CODEC_H264_PM1_HD720_2048, SDP_CODEC_H264_PM1_HD1088_2048, SDP_CODEC_H264_PM1_HD1088_4096 //@} }; /// Identifies the relative CPU cost for a SDP Codec. enum SdpCodecCPUCost { SDP_CODEC_CPU_LOW = 0, SDP_CODEC_CPU_HIGH = 1, SDP_CODEC_CPU_VERY_HIGH = 2 }; /* ============================ CREATORS ================================== */ ///@name Creators //@{ ///Default constructor SdpCodec(enum SdpCodecTypes sdpCodecType = SDP_CODEC_UNKNOWN, int payloadFormat = -1, const char* mimeType = MIME_TYPE_AUDIO, const char* mimeSubtype = "", int sampleRate = 8000, ///< samples per second int preferredPacketLength = 20000, ///< micro seconds int numChannels = 1, const char* formatSpecificData = "", const SdpCodecCPUCost CPUCost = SDP_CODEC_CPU_LOW, const int BWCost = SDP_CODEC_BANDWIDTH_NORMAL, const int videoFormat = SDP_VIDEO_FORMAT_QCIF, const int videoFmtp = 0); SdpCodec(int payloadFormat, const char* mimeType, const char* mimeSubType, int sampleRate, int preferredPacketLength, int numChannels, const char* formatSpecificData); ///Copy constructor SdpCodec(const SdpCodec& rSdpCodec); ///Destructor virtual ~SdpCodec(); //@} /* ============================ MANIPULATORS ============================== */ ///@name Manipulators //@{ ///Assignment operator SdpCodec& operator=(const SdpCodec& rhs); UtlCopyableContainable* clone() const { return new SdpCodec(*this); } /// Set the SDP/RTP payload id to be used for this codec void setCodecPayloadFormat(int formatId); /// Set the video format bitmap void setVideoFmtp(const int videoFmtp); /// Set the video format string void setVideoFmtpString(int videoFmtp); /// Clears the format string void clearVideoFmtpString(); ///Set the packet size void setPacketSize(const int packetSize); //@} /* ============================ ACCESSORS ================================= */ ///@name Accessors //@{ /// Get the internal/sipX codec type id enum SdpCodecTypes getCodecType() const; /**< * @note It is possible that the format id/type used in the SDP "m" field * and RTP header is different than these internally used ids. */ /// Get the SDP/RTP payload id to be used for this codec int getCodecPayloadFormat() const; /**< * This is the id used in the SDP "m" format sub-field and RTP header. */ /// Get the format specific parameters for the SDP virtual void getSdpFmtpField(UtlString& formatSpecificData) const; /**< * This is what goes in the SDP "a" field in the format: * "a=fmtp " */ /// Set the format specific parameters for the SDP virtual void setSdpFmtpField(const UtlString& formatSpecificData); /**< * This is what goes in the SDP "a" field in the format: * "a=fmtp " */ /// Get the named parameter in the format field (fmtp parameter) virtual UtlBoolean getFmtpParameter(const UtlString& parameterName, UtlString& parameterValue, char nameValueSeperator = '=') const; /// Get the named parameter from the given format field (fmtp parameter) static UtlBoolean getFmtpParameter(const UtlString& fmtpField, const UtlString& parameterName, UtlString& parameterValue, char nameValueSeperator = '='); /** * Assumes the "a=fmtp:" of the fmtp field has be stripped off * "a=fmtp: " */ /// Get the named parameter from the given format field (fmtp parameter) static UtlBoolean getFmtpParameter(const UtlString& fmtpField, const UtlString& parameterName, int& parameterValue, char nameValueSeperator = '='); /** * Assumes the "a=fmtp:" of the fmtp field has be stripped off * "a=fmtp: " */ /// Get the video video sizes from the FMTP parameter static OsStatus getVideoSizes(const UtlString& fmtpField, int maxSizes, int& numSizes, int videoSizes[]); /** * Assumes the "a=fmtp:" of the fmtp field has be stripped off * "a=fmtp: " */ /// Get the media type for the codec void getMediaType(UtlString& mimeMajorType) const; /**< * This is the mime major type (i.e. video, audio, etc) */ /// MimeSubtype used as encoding name void getEncodingName(UtlString& mimeSubtype) const; /**< * This is the encoding name used in the SDP * "a=rtpmap: " removed) * @param fmpt2 - fmtp string from 2nd codec (Must have "a:fmtp " removed) * @param compares greater than, equal or less than zero based upon how the fmtp * parameters compare * @returns TRUE/FALSE if the codecs are compatible */ //@} /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: // enum SdpCodecTypes mCodecType; ///< Internal id int mCodecPayloadFormat; ///< The id which appears in SDP & RTP UtlString mMimeType; ///< audio, video, etc. UtlString mMimeSubtype; ///< a=rtpmap mime subtype value int mSampleRate; ///< samples per second int mPacketLength; ///< micro seconds int mNumChannels; UtlString mFormatSpecificData; ///< a=fmtp parameter SdpCodecCPUCost mCPUCost; ///< relative cost of a SDP codec int mBWCost; int mVideoFormat; int mVideoFmtp; UtlString mVideoFmtpString; ///< video format string }; /* ============================ INLINE METHODS ============================ */ #endif // _SdpCodec_h_ sipxtapi-3.3.0~test17/sipXsdpLib/include/sdp/SdpCodecList.h0000644000175000017500000001430312205613256024364 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _SdpCodecList_h_ #define _SdpCodecList_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /// List of codecs, used for storing supported codecs and for codec negotiation. class SdpCodecList { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* =============================== CREATORS =============================== */ ///@name Creators //@{ /// Constructor. SdpCodecList(int numCodecs = 0, SdpCodec* codecArray[] = NULL); /// Copy constructor. SdpCodecList(const SdpCodecList& rSdpCodecFactory); /// Assignment operator. SdpCodecList& operator=(const SdpCodecList& rhs); /// Destructor. virtual ~SdpCodecList(); //@} /* ============================= MANIPULATORS ============================= */ ///@name Manipulators //@{ /// Add a new codec type to the list of known codecs. void addCodec(const SdpCodec& newCodec); /// Add copies of the array of codecs. void addCodecs(int numCodecs, SdpCodec* newCodecs[]); /// Add specified codecs to the list. int addCodecs(const UtlString &codecList); /**< * @returns Number of unknown codecs in the list. Zero for full success. */ /// Add codecs specified by array of codec token names and assign given payload ID int addCodecs(int numTokens, const char* codecTokens[], int payloadIds[]); /// Add specified codecs to the list. int addCodecs(int codecCount, SdpCodec::SdpCodecTypes codecTypes[]); /**< * @returns Number of unknown codecs in the list. Zero for full success. */ /// Assign any unset payload type ids. void bindPayloadTypes(); /// @brief unbind any codec with the given dynamic payload type int unbindPayloadType(int payloadId); /* * @param payloadId - no op if not a dynamic payload ID (> SDP_CODEC_MAXIMUM_STATIC_CODEC), * codec payload ID to unbind (set to SDP_CODEC_UNKNOWN) * * @returns number of codecs unbound */ /// @brief If there is a matching codec in this factory, set its /// payload type to that of the given codec. void copyPayloadType(const SdpCodec& codec); /// @brief For all matching codecs, copy the payload type from /// the codecArray to the matching codec in this factory. void copyPayloadTypes(int numCodecs, const SdpCodec* codecArray[]); /// @brief For all matching codecs, copy the payload type from /// the given codecList to the matching codec in this factory. void copyPayloadTypes(const SdpCodecList& codecList); /// @brief Remove any codecs in this list that are not equivalent to those in the given list void limitCodecs(const SdpCodecList& includeOnlyCodecList); /// Clear the list. void clearCodecs(void); /// Limits the advertised codec by CPU limit level. void setCodecCPULimit(int iLimit); /**< * @param[in] iLimit - The limit level for codecs. A value of * SDP_CODEC_CPU_LOW indicates only low cpu intensity codecs and * a value of SDP_CODEC_CPU_HIGH indicates either low or high * cpu intensity. */ //@} /* ============================== ACCESSORS =============================== */ ///@name Accessors //@{ /// Get a codec given an internal codec id. const SdpCodec* getCodec(SdpCodec::SdpCodecTypes internalCodecId) const; /// Get a codec given the payload type id. const SdpCodec* getCodecByType(int payloadTypeId, UtlBoolean shouldLock = TRUE) const; /// Get a codec given the MIME type, subtype and other parameters. const SdpCodec* getCodec(const char* MIMEType, const char* MIMESubType, int sampleRate, int numChannels, const UtlString &fmtp) const; /// Get the number of codecs. int getCodecCount() const; /// Get the number of codecs by MIME type. int getCodecCount(const char* MIMEType) const; /// Get codecs from this list, taking into account maximum CPU cost. void getCodecs(int& numCodecs, SdpCodec**& codecArray) const; /// @brief Get codecs from this list, taking into account maximum CPU cost /// and given MIME type. void getCodecs(int& numCodecs, SdpCodec**& codecArray, const char* MIMEType) const; /// Returns a copy of all the codecs. void getCodecs(int& numCodecs, SdpCodec**& codecArray, const char* MIMEType, const char* subMimeType) const; /// Frees up codecs and codec pointer array static void freeArray(int arraySize, SdpCodec**& codecArray); /* * getCodecs allocates a codec pointer array and codecs. This frees them. */ /// String representation of factory and codecs. void toString(UtlString& serializedFactory) const; /// Gets the codec CPU limit level. int getCodecCPULimit() const; //@} /* =============================== INQUIRY ================================ */ ///@name Inquiry //@{ /// Query if equivalent codec is in the list UtlBoolean containsCodec(const SdpCodec& codec, UtlBoolean exeact = FALSE) const; //@} /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: /// Add a new codec type to the list of known codecs (without locking). void addCodecNoLock(const SdpCodec& newCodec); UtlDList mCodecs; OsRWMutex mReadWriteMutex; int mCodecCPULimit; }; /* ============================ INLINE METHODS ============================ */ #endif // _SdpCodecList_h_ sipxtapi-3.3.0~test17/sipXsdpLib/include/sdp/SdpDefaultCodecFactory.h0000644000175000017500000000701012205613256026362 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _SdpDefaultCodecFactory_h_ #define _SdpDefaultCodecFactory_h_ // SYSTEM INCLUDES // APPLICATION INCLUDES #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS /** * @brief Factory class for generating SDPs for known codec types and * converting readable codec names to codec types and vice versa. * * @nosubgrouping */ class SdpDefaultCodecFactory { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: /* ============================ CREATORS ================================== */ ///@name Creators //@{ //@} /* ============================= MANIPULATORS ============================= */ ///@name Manipulators //@{ //@} /* ============================== ACCESSORS =============================== */ ///@name Accessors //@{ /// Get a codec given an internal codec id. static SdpCodec getCodec(SdpCodec::SdpCodecTypes internalCodecId); /// Converts the readable text codec name into a codec type. static SdpCodec::SdpCodecTypes getCodecType(const char* pCodecName); /// Get specific codec identified by iCodec. static OsStatus getCodecNameByType(SdpCodec::SdpCodecTypes codecType, UtlString& codecName); /// Get MIME-subtype and fmtp strings for given codec type. static OsStatus getMimeInfoByType(SdpCodec::SdpCodecTypes codecType, UtlString& mimeSubtype, UtlString& fmtp); /**< * @param[in] codecType - codec type to look for. * @param[out] mimeSubtype - MIME-subtype string (if found). * @param[out] fmtp - fmtp string (if found). * * @retval OS_SUCESS if appropriate mapping found and \p mimeSubtype and * \p fmtp parameters filled with data. * @retval OS_NOT_FOUND if appropriate mapping not found. */ /// Get codec type by MIME-subtype/sample rate/channels number/fmtp combination. static OsStatus getCodecType(const UtlString &mimeSubtype, unsigned sampleRate, unsigned numChannels, const UtlString &fmtp, SdpCodec::SdpCodecTypes &codecType); /**< * @param[in] mimeSubtype - MIME-subtype string to look for. * @param[in] sampleRate - sample rate of codec to look for. * @param[in] numChannels - number of channels of codec to look for. * @param[in] fmtp - fmtp string to look for. * @param[out] codecType - codec type (if found). * * @retval OS_SUCESS if appropriate mapping found and \p codecType set. * @retval OS_NOT_FOUND if appropriate mapping not found. */ //@} /* =============================== INQUIRY ================================ */ ///@name Inquiry //@{ //@} /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: }; /* ============================ INLINE METHODS ============================ */ #endif // _SdpDefaultCodecFactory_h_ sipxtapi-3.3.0~test17/sipXsdpLib/include/sdp/SdpMediaLine.h0000644000175000017500000011772212205613256024353 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2007 Plantronics // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Scott Godin (sgodin AT SipSpectrum DOT com) #ifndef _SdpMediaLine_h_ #define _SdpMediaLine_h_ // SYSTEM INCLUDES //#include <...> // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS //: Container for SDP specification // This class holds the information related to an SDP. // Included in this information is: TODO // class SdpMediaLine : public UtlCopyableContainable { /* //////////////////////////// PUBLIC //////////////////////////////////// */ public: typedef enum { // WARNING: this enum must stay in synch. with SdpMediaTypeString MEDIA_TYPE_NONE, MEDIA_TYPE_AUDIO, // "audio" - RFC4566 MEDIA_TYPE_VIDEO, // "video" - RFC4566 MEDIA_TYPE_TEXT, // "text" - RFC4566 MEDIA_TYPE_APPLICATION, // "application" - RFC4566 MEDIA_TYPE_MESSAGE // "message" - RFC4566 } SdpMediaType; static const char* SdpMediaTypeString[]; typedef enum { // WARNING: this enum must stay in synch. with SdpTransportProtocolTypeString PROTOCOL_TYPE_NONE, PROTOCOL_TYPE_UDP, // "udp" - RFC4566 PROTOCOL_TYPE_RTP_AVP, // "RTP/AVP" - RFC4566 PROTOCOL_TYPE_RTP_SAVP, // "RTP/SAVP" - RFC4566 PROTOCOL_TYPE_RTP_SAVPF, // "RTP/SAVPF" - RFC3711 PROTOCOL_TYPE_TCP, // "TCP" - RFC4145 PROTOCOL_TYPE_TCP_RTP_AVP, // "TCP/RTP/AVP" - RFC4571 PROTOCOL_TYPE_TCP_TLS, // "TCP/TLS" - RFC4572 PROTOCOL_TYPE_UDP_TLS, // "UDP/TLS" - draft-fischl-mmusic-sdp-dtls-04 PROTOCOL_TYPE_DCCP_TLS, // "DCCP/TLS" - draft-fischl-mmusic-sdp-dtls-04 PROTOCOL_TYPE_DCCP_TLS_RTP_SAVP, // "DCCP/TLS/RTP/SAVP" - draft-fischl-mmusic-sdp-dtls-04 PROTOCOL_TYPE_UDP_TLS_RTP_SAVP, // "UDP/TLS/RTP/SAVP" - draft-fischl-mmusic-sdp-dtls-04 PROTOCOL_TYPE_TCP_TLS_RTP_SAVP // "TCP/TLS/RTP/SAVP" - draft-fischl-mmusic-sdp-dtls-04 } SdpTransportProtocolType; static const char* SdpTransportProtocolTypeString[]; class SdpConnection : public UtlCopyableContainable { public: SdpConnection(Sdp::SdpNetType netType = Sdp::NET_TYPE_NONE, Sdp::SdpAddressType addressType = Sdp::ADDRESS_TYPE_NONE, const char * address = 0, unsigned int port = 0, unsigned int multicastIpV4Ttl=0) : mNetType(netType), mAddressType(addressType), mAddress(address), mPort(port), mMulticastIpV4Ttl(multicastIpV4Ttl) {} SdpConnection(const SdpConnection& rhs) : mNetType(rhs.mNetType), mAddressType(rhs.mAddressType), mAddress(rhs.mAddress), mPort(rhs.mPort), mMulticastIpV4Ttl(rhs.mMulticastIpV4Ttl) {} // Containable requirements UtlContainableType getContainableType() const { static char type[] = "SdpConnection"; return type;} unsigned hash() const { return directHash(); } int compareTo(UtlContainable const *) const { return 0; } // not implemented UtlCopyableContainable* clone() const { return new SdpConnection(*this); } // Accessors void setNetType(Sdp::SdpNetType netType) { mNetType = netType; } Sdp::SdpNetType getNetType() const { return mNetType; } const char* getNetTypeToken() const { return(Sdp::SdpNetTypeString[mNetType]); } void setAddressType(Sdp::SdpAddressType addressType) { mAddressType = addressType; } Sdp::SdpAddressType getAddressType() const { return mAddressType; } const char* getAddressTypeToken() const { return(Sdp::SdpAddressTypeString[mAddressType]); } void setAddress(const char * address) { mAddress = address; } const UtlString& getAddress() const { return mAddress; } void setPort(unsigned int port) { mPort = port; } unsigned int getPort() const { return mPort; } void setMulticastIpV4Ttl(unsigned int multicastIpV4Ttl) { mMulticastIpV4Ttl = multicastIpV4Ttl; } unsigned int getMulticastIpV4Ttl() const { return mMulticastIpV4Ttl; } private: Sdp::SdpNetType mNetType; Sdp::SdpAddressType mAddressType; UtlString mAddress; unsigned int mPort; unsigned int mMulticastIpV4Ttl; }; typedef enum { ENCRYPTION_METHOD_NONE, ENCRYPTION_METHOD_CLEAR, // "clear" - RFC4566 ENCRYPTION_METHOD_BASE64, // "base64" - RFC4566 ENCRYPTION_METHOD_URI, // "uri" - RFC4566 ENCRYPTION_METHOD_PROMPT // "prompt" - RFC4566 } SdpEncryptionMethod; static const char* SdpEncryptionMethodString[]; typedef enum { DIRECTION_TYPE_NONE, DIRECTION_TYPE_SENDRECV, // "sendrecv" - RFC4566 DIRECTION_TYPE_SENDONLY, // "sendonly" - RFC4566 DIRECTION_TYPE_RECVONLY, // "recvonly" - RFC4566 DIRECTION_TYPE_INACTIVE // "inactive" - RFC4566 } SdpDirectionType; static const char* SdpDirectionTypeString[]; typedef enum { ORIENTATION_TYPE_NONE, ORIENTATION_TYPE_PORTRAIT, // "portrait" - RFC 4566 ORIENTATION_TYPE_LANDSCAPE,// "landscape" - RFC 4566 ORIENTATION_TYPE_SEASCAPE // "seascape" - RFC 4566 } SdpOrientationType; static const char* SdpOrientationTypeString[]; typedef enum { TCP_SETUP_ATTRIBUTE_NONE, TCP_SETUP_ATTRIBUTE_ACTIVE, // "active" - RFC4145 TCP_SETUP_ATTRIBUTE_PASSIVE, // "passive" - RFC4145 TCP_SETUP_ATTRIBUTE_ACTPASS, // "actpass" - RFC4145 TCP_SETUP_ATTRIBUTE_HOLDCONN // "holdconn" - RFC4145 } SdpTcpSetupAttribute; static const char* SdpTcpSetupAttributeString[]; typedef enum { TCP_CONNECTION_ATTRIBUTE_NONE, TCP_CONNECTION_ATTRIBUTE_NEW, // "new" - RFC4145 TCP_CONNECTION_ATTRIBUTE_EXISTING // "existing" - RFC4145 } SdpTcpConnectionAttribute; static const char* SdpTcpConnectionAttributeString[]; typedef enum { CRYPTO_SUITE_TYPE_NONE, CRYPTO_SUITE_TYPE_AES_CM_128_HMAC_SHA1_80, // "AES_CM_128_HMAC_SHA1_80" - RFC4568 CRYPTO_SUITE_TYPE_AES_CM_128_HMAC_SHA1_32, // "AES_CM_128_HMAC_SHA1_32" - RFC4568 CRYPTO_SUITE_TYPE_F8_128_HMAC_SHA1_80 // "F8_128_HMAC_SHA1_80" - RFC4568 } SdpCryptoSuiteType; static const char* SdpCryptoSuiteTypeString[]; typedef enum { CRYPTO_KEY_METHOD_NONE, CRYPTO_KEY_METHOD_INLINE // "inline" - RFC4568 } SdpCryptoKeyMethod; static const char* SdpCryptoKeyMethodString[]; typedef enum { CRYPTO_SRTP_FEC_ORDER_NONE, CRYPTO_SRTP_FEC_ORDER_FEC_SRTP, // "FEC_SRTP" - RFC 4568 CRYPTO_SRTP_FEC_ORDER_SRTP_FEC // "SRTP_FEC" - RFC 2568 } SdpCryptoSrtpFecOrderType; static const char* SdpCryptoSrtpFecOrderTypeString[]; class SdpCrypto : public UtlCopyableContainable { public: class SdpCryptoKeyParam : public UtlCopyableContainable { public: SdpCryptoKeyParam(SdpCryptoKeyMethod keyMethod=SdpMediaLine::CRYPTO_KEY_METHOD_NONE, const char * keyValue=0, unsigned int srtpLifetime=0, unsigned int srtpMkiValue=0, unsigned int srtpMkiLength=0) : mKeyMethod(keyMethod), mKeyValue(keyValue), mSrtpLifetime(srtpLifetime), mSrtpMkiValue(srtpMkiValue), mSrtpMkiLength(srtpMkiLength) {} SdpCryptoKeyParam(const SdpCryptoKeyParam& rhs) : mKeyMethod(rhs.mKeyMethod), mKeyValue(rhs.mKeyValue), mSrtpLifetime(rhs.mSrtpLifetime), mSrtpMkiValue(rhs.mSrtpMkiValue), mSrtpMkiLength(rhs.mSrtpMkiLength) {} // Containable requirements UtlContainableType getContainableType() const { static char type[] = "SdpCryptoKeyParam"; return type;} unsigned hash() const { return directHash(); } int compareTo(UtlContainable const *) const { return 0; } // not implemented UtlCopyableContainable* clone() const { return new SdpCryptoKeyParam(*this); } void setKeyMethod(SdpCryptoKeyMethod keyMethod) { mKeyMethod = keyMethod; } SdpCryptoKeyMethod getKeyMethod() const { return mKeyMethod; } void setKeyValue(const char * keyValue) { mKeyValue = keyValue; } const UtlString& getKeyValue() const { return mKeyValue; } void setSrtpLifetime(unsigned int srtpLifetime) { mSrtpLifetime = srtpLifetime; } unsigned int getSrtpLifetime() const { return mSrtpLifetime; } void setSrtpMkiValue(unsigned int srtpMkiValue) { mSrtpMkiValue = srtpMkiValue; } unsigned int getSrtpMkiValue() const { return mSrtpMkiValue; } void setSrtpMkiLength(unsigned int srtpMkiLength) { mSrtpMkiLength = srtpMkiLength; } unsigned int getSrtpMkiLength() const { return mSrtpMkiLength; } private: SdpCryptoKeyMethod mKeyMethod; UtlString mKeyValue; // srtp key-salt or generic key-info unsigned int mSrtpLifetime; unsigned int mSrtpMkiValue; unsigned int mSrtpMkiLength; }; SdpCrypto() : mTag(0), mSuite(SdpMediaLine::CRYPTO_SUITE_TYPE_NONE), mSrtpKdr(0), mEncryptedSrtp(1), mEncryptedSrtcp(1), mAuthenticatedSrtp(1), mSrtpFecOrder(SdpMediaLine::CRYPTO_SRTP_FEC_ORDER_FEC_SRTP), mSrtpWsh(0) {} SdpCrypto(const SdpCrypto& rSdpCandidatePair); ~SdpCrypto() { } // Containable requirements UtlContainableType getContainableType() const { static char type[] = "SdpCrypto"; return type;} unsigned hash() const { return directHash(); } int compareTo(UtlContainable const *) const { return 0; } // not implemented SdpCrypto& operator=(const SdpCrypto& rhs); UtlCopyableContainable* clone() const { return new SdpCrypto(*this); } // Accessors void setTag(unsigned int tag) { mTag = tag; } unsigned int getTag() const { return mTag; } void setSuite(SdpCryptoSuiteType suite) { mSuite = suite; } SdpCryptoSuiteType getSuite() const { return mSuite; } void addCryptoKeyParam(SdpCryptoKeyMethod keyMethod, const char * keyValue, unsigned int srtpLifetime=0, unsigned int srtpMkiValue=0, unsigned int srtpMkiLength=0) { addCryptoKeyParam(new SdpCryptoKeyParam(keyMethod, keyValue, srtpLifetime, srtpMkiValue, srtpMkiLength)); } void addCryptoKeyParam(SdpCryptoKeyParam* keyParam) { mCryptoKeyParams.insert(keyParam); } void clearCryptoKeyParams() { mCryptoKeyParams.destroyAll(); } const UtlCopyableSList& getCryptoKeyParams() const { return mCryptoKeyParams; } void setSrtpKdr(unsigned int srtpKdr) { mSrtpKdr = srtpKdr; } unsigned int getSrtpKdr() const { return mSrtpKdr; } void setEncryptedSrtp(bool encryptedSrtp) { mEncryptedSrtp = encryptedSrtp; } bool getEncryptedSrtp() const { return mEncryptedSrtp; } void setEncryptedSrtcp(bool encryptedSrtcp) { mEncryptedSrtcp = encryptedSrtcp; } bool getEncryptedSrtcp() const { return mEncryptedSrtcp; } void setAuthenticatedSrtp(bool authenticatedSrtp) { mAuthenticatedSrtp = authenticatedSrtp; } bool getAuthenticatedSrtp() const { return mAuthenticatedSrtp; } void setSrtpFecOrder(SdpCryptoSrtpFecOrderType srtpFecOrder) { mSrtpFecOrder = srtpFecOrder; } SdpCryptoSrtpFecOrderType getSrtpFecOrder() const { return mSrtpFecOrder; } static SdpCryptoSrtpFecOrderType getSrtpFecOrderFromString(const char * order); void setSrtpFecKey(SdpCryptoKeyMethod keyMethod, const char * keyValue, unsigned int srtpLifetime=0, unsigned int srtpMkiValue=0, unsigned int srtpMkiLength=0) { mSrtpFecKey.setKeyMethod(keyMethod); mSrtpFecKey.setKeyValue(keyValue); mSrtpFecKey.setSrtpLifetime(srtpLifetime); mSrtpFecKey.setSrtpMkiValue(srtpMkiValue); mSrtpFecKey.setSrtpMkiLength(srtpMkiLength); } const SdpCryptoKeyParam& getSrtpFecKey() const { return mSrtpFecKey; } void setSrtpWsh(unsigned int srtpWsh) { mSrtpWsh = srtpWsh; } unsigned int getSrtpWsh() const { return mSrtpWsh; } void addGenericSessionParam(const char * sessionParam) { mGenericSessionParams.insert(new UtlString(sessionParam)); } void clearGenericSessionParams() { mGenericSessionParams.destroyAll(); } const UtlCopyableSList& getGenericSessionParams() const { return mGenericSessionParams; } private: unsigned int mTag; SdpCryptoSuiteType mSuite; UtlCopyableSList mCryptoKeyParams; unsigned int mSrtpKdr; bool mEncryptedSrtp; bool mEncryptedSrtcp; bool mAuthenticatedSrtp; SdpCryptoSrtpFecOrderType mSrtpFecOrder; SdpCryptoKeyParam mSrtpFecKey; unsigned int mSrtpWsh; UtlCopyableSList mGenericSessionParams; }; typedef enum { FINGERPRINT_HASH_FUNC_NONE, FINGERPRINT_HASH_FUNC_SHA_1, // "sha-1" - RFC4572 FINGERPRINT_HASH_FUNC_SHA_224, // "sha-224" - RFC4572 FINGERPRINT_HASH_FUNC_SHA_256, // "sha-256" - RFC4572 FINGERPRINT_HASH_FUNC_SHA_384, // "sha-384" - RFC4572 FINGERPRINT_HASH_FUNC_SHA_512, // "sha-512" - RFC4572 FINGERPRINT_HASH_FUNC_MD5, // "md5" - RFC4572 FINGERPRINT_HASH_FUNC_MD2 // "md2" - RFC4572 } SdpFingerPrintHashFuncType; static const char* SdpFingerPrintHashFuncTypeString[]; typedef enum { KEYMANAGEMENT_PROTOCOL_NONE, KEYMANAGEMENT_PROTOCOL_MIKEY // 'mikey' - RFC4567 } SdpKeyManagementProtocolType; static const char* SdpKeyManagementProtocolTypeString[]; typedef enum { PRECONDITION_TYPE_NONE, PRECONDITION_TYPE_QOS // "qos" - RFC3312 } SdpPreConditionType; static const char* SdpPreConditionTypeString[]; typedef enum { PRECONDITION_STRENGTH_MANDATORY, // "mandatory" - RFC3312 PRECONDITION_STRENGTH_OPTIONAL, // "optional" - RFC3312 PRECONDITION_STRENGTH_NONE, // "none" - RFC3312 PRECONDITION_STRENGTH_FAILURE, // "failure" - RFC3312 PRECONDITION_STRENGTH_UNKNWOWN // "unknown" - RFC3312 } SdpPreConditionStrengthType; static const char* SdpPreConditionStrengthTypeString[]; typedef enum { PRECONDITION_STATUS_NONE, PRECONDITION_STATUS_E2E, // "e2e" - RFC3312 PRECONDITION_STATUS_LOCAL, // "local" - RFC3312 PRECONDITION_STATUS_REMOTE, // "remote" - RFC3312 } SdpPreConditionStatusType; static const char* SdpPreConditionStatusTypeString[]; typedef enum { PRECONDITION_DIRECTION_NONE, // "none" - RFC3312 PRECONDITION_DIRECTION_SEND, // "send" - RFC3312 PRECONDITION_DIRECTION_RECV, // "recv" - RFC3312 PRECONDITION_DIRECTION_SENDRECV, // "sendrecv" - RFC3312 } SdpPreConditionDirectionType; static const char* SdpPreConditionDirectionTypeString[]; class SdpPreCondition : public UtlCopyableContainable { public: SdpPreCondition(SdpPreConditionType type, SdpPreConditionStatusType status, SdpPreConditionDirectionType direction) : mType(type), mStatus(status), mDirection(direction) {} SdpPreCondition(const SdpPreCondition& rhs) : mType(rhs.mType), mStatus(rhs.mStatus), mDirection(rhs.mDirection) {} // Containable requirements UtlContainableType getContainableType() const { static char type[] = "SdpPreCondition"; return type;} unsigned hash() const { return directHash(); } int compareTo(UtlContainable const *) const { return 0; } // not implemented UtlCopyableContainable* clone() const { return new SdpPreCondition(*this); } // Accessors void setType(SdpPreConditionType type) { mType = type; } SdpPreConditionType getType() const { return mType; } void setStatus(SdpPreConditionStatusType status) { mStatus = status; } SdpPreConditionStatusType getStatus() const { return mStatus; } void setDirection(SdpPreConditionDirectionType direction) { mDirection = direction; } SdpPreConditionDirectionType getDirection() const { return mDirection; } private: SdpPreConditionType mType; SdpPreConditionStatusType mStatus; SdpPreConditionDirectionType mDirection; }; class SdpPreConditionDesiredStatus : public SdpPreCondition { public: SdpPreConditionDesiredStatus(SdpPreConditionType type, SdpPreConditionStrengthType strength, SdpPreConditionStatusType status, SdpPreConditionDirectionType direction) : SdpPreCondition(type, status, direction), mStrength(strength) {} SdpPreConditionDesiredStatus(const SdpPreConditionDesiredStatus& rhs) : SdpPreCondition(rhs), mStrength(rhs.mStrength) {} // Containable requirements UtlContainableType getContainableType() const { static char type[] = "SdpPreConditionDesiredStatus"; return type;} UtlCopyableContainable* clone() const { return new SdpPreConditionDesiredStatus(*this); } // Accessors void setStrength(SdpPreConditionStrengthType strength) { mStrength = strength; } SdpPreConditionStrengthType getStrength() const { return mStrength; } private: SdpPreConditionStrengthType mStrength; }; class SdpRemoteCandidate : public UtlCopyableContainable { public: SdpRemoteCandidate(unsigned int componentId, const char * connectionAddress, unsigned int port) : mComponentId(componentId), mConnectionAddress(connectionAddress), mPort(port) {} SdpRemoteCandidate(const SdpRemoteCandidate& rhs) : mComponentId(rhs.mComponentId), mConnectionAddress(rhs.mConnectionAddress), mPort(rhs.mPort) {} // Containable requirements UtlContainableType getContainableType() const { static char type[] = "SdpRemoteCandidate"; return type;} unsigned hash() const { return directHash(); } int compareTo(UtlContainable const *) const { return 0; } // not implemented UtlCopyableContainable* clone() const { return new SdpRemoteCandidate(*this); } // Accessors void setComponentId(unsigned int componentId) { mComponentId = componentId; } unsigned int getComponentId() const { return mComponentId; } void setConnectionAddress(const char * connectionAddress) { mConnectionAddress = connectionAddress; } const UtlString& getConnectionAddress() const { return mConnectionAddress; } void setPort(unsigned int port) { mPort = port; } unsigned int getPort() const { return mPort; } private: unsigned int mComponentId; UtlString mConnectionAddress; unsigned int mPort; }; class SdpTransportProtocolCapabilities : public UtlCopyableContainable { public: SdpTransportProtocolCapabilities(unsigned int id, SdpTransportProtocolType type) : mId(id), mType(type) {} SdpTransportProtocolCapabilities(const SdpTransportProtocolCapabilities& rhs) : mId(rhs.mId), mType(rhs.mType) {} // Containable requirements UtlContainableType getContainableType() const { static char type[] = "SdpTransportProtocolCapabilities"; return type;} unsigned hash() const { return directHash(); } int compareTo(UtlContainable const *) const { return 0; } // not implemented UtlCopyableContainable* clone() const { return new SdpTransportProtocolCapabilities(*this); } // Accessors void setId(unsigned int id) { mId = id; } const unsigned int getId() const { return mId; } void setType(SdpTransportProtocolType type) { mType = type; } SdpTransportProtocolType getType() const { return mType; } private: unsigned int mId; SdpTransportProtocolType mType; }; class SdpPotentialConfiguration : public UtlCopyableContainable { public: class ConfigIdItem : public UtlCopyableContainable { public: ConfigIdItem(unsigned id, bool optional=false) : mId(id), mOptional(optional) {} ConfigIdItem(const ConfigIdItem& rhs) : mId(rhs.mId), mOptional(rhs.mOptional) {} // Containable requirements UtlContainableType getContainableType() const { static char type[] = "ConfigIdItem"; return type;} unsigned hash() const { return directHash(); } int compareTo(UtlContainable const *) const { return 0; } // not implemented UtlCopyableContainable* clone() const { return new ConfigIdItem(*this); } // Accessors void setId(unsigned int id) { mId = id; } const unsigned int getId() const { return mId; } void setOptional(bool optional) { mOptional = optional; } const bool getOptional() const { return mOptional; } private: unsigned int mId; bool mOptional; }; SdpPotentialConfiguration(unsigned int id, bool deleteMediaAttributes, bool deleteSessionAttributes, unsigned int transportId) : mId(id), mDeleteMediaAttributes(deleteMediaAttributes), mDeleteSessionAttributes(deleteSessionAttributes), mTransportId(transportId) {} SdpPotentialConfiguration(const SdpPotentialConfiguration& rhs) : mId(rhs.mId), mDeleteMediaAttributes(rhs.mDeleteMediaAttributes), mDeleteSessionAttributes(rhs.mDeleteSessionAttributes), mTransportId(rhs.mTransportId), mAttributeIdList(rhs.mAttributeIdList) {} // Containable requirements UtlContainableType getContainableType() const { static char type[] = "SdpPotentialConfiguration"; return type;} unsigned hash() const { return directHash(); } int compareTo(UtlContainable const *) const { return 0; } // not implemented UtlCopyableContainable* clone() const { return new SdpPotentialConfiguration(*this); } // Accessors void setId(unsigned int id) { mId = id; } const unsigned int getId() const { return mId; } void setDeleteMediaAttributes(bool deleteMediaAttributes) { mDeleteMediaAttributes = deleteMediaAttributes; } const bool getDeleteMediaAttributes() const { return mDeleteMediaAttributes; } void setDeleteSessionAttributes(bool deleteSessionAttributes) { mDeleteSessionAttributes = deleteSessionAttributes; } const bool getDeleteSessionAttributes() const { return mDeleteSessionAttributes; } void setTransportId(unsigned int transportId) { mTransportId = transportId; } const unsigned int getTransportId() const { return mTransportId; } void addAttributeId(unsigned int id, bool optional) { addAttributeId(new ConfigIdItem(id, optional)); } void addAttributeId(ConfigIdItem* configIdItem) { mAttributeIdList.insert(configIdItem); } void clearAttributeIds() { mAttributeIdList.destroyAll(); } const UtlCopyableSList& getAttributeIds() const { return mAttributeIdList; } private: unsigned int mId; bool mDeleteMediaAttributes; bool mDeleteSessionAttributes; unsigned int mTransportId; UtlCopyableSList mAttributeIdList; }; /* ============================ CREATORS ================================== */ SdpMediaLine(); //:Default constructor SdpMediaLine(const SdpMediaLine& rSdpMediaLine); //:Copy constructor virtual ~SdpMediaLine(); //:Destructor UtlCopyableContainable* clone() const { return new SdpMediaLine(*this); } /* ============================ MANIPULATORS ============================== */ SdpMediaLine& operator=(const SdpMediaLine& rhs); //:Assignment operator void setMediaType(SdpMediaType mediaType) { mMediaType = mediaType; } void setTransportProtocolType(SdpTransportProtocolType transportProtocolType) { mTransportProtocolType = transportProtocolType; } void addCodec(SdpCodec* codec) { mCodecs.addCodec(*codec); delete codec;} void clearCodecs() { mCodecs.clearCodecs(); } void setCodecs(const SdpCodecList& codecs) { mCodecs.clearCodecs(); mCodecs = codecs; } void setTitle(const char * title) { mTitle = title; } void addConnection(Sdp::SdpNetType netType, Sdp::SdpAddressType addressType, const char * address, unsigned int port, unsigned int multicastIpV4Ttl=0) { addConnection(new SdpConnection(netType, addressType, address, port, multicastIpV4Ttl)); } void addConnection(SdpConnection *connection) { mConnections.insert(connection); } void clearConnections() { mConnections.destroyAll(); } void addRtcpConnection(Sdp::SdpNetType netType, Sdp::SdpAddressType addressType, const char * address, unsigned int port, unsigned int multicastIpV4Ttl=0) { addRtcpConnection(new SdpConnection(netType, addressType, address, port, multicastIpV4Ttl)); } void addRtcpConnection(SdpConnection *connection) { mRtcpConnections.insert(connection); } void clearRtcpConnections() { mRtcpConnections.destroyAll(); } void addBandwidth(Sdp::SdpBandwidthType type, unsigned int bandwidth) { addBandwidth(new Sdp::SdpBandwidth(type, bandwidth)); } void addBandwidth(Sdp::SdpBandwidth* sdpBandwidth) { mBandwidths.insert(sdpBandwidth); } void clearBandwidths() { mBandwidths.destroyAll(); } void setEncryptionKey(SdpEncryptionMethod method, const char * key) { mEncryptionMethod = method; mEncryptionKey = key; } void setDirection(SdpDirectionType direction) { mDirection = direction; } void setPacketTime(unsigned int packetTime) { mPacketTime = packetTime; } void setMaxPacketTime(unsigned int maxPacketTime) { mMaxPacketTime = maxPacketTime; } void setOrientation(SdpOrientationType orientation) { mOrientation = orientation; } void setDescriptionLanguage(const char * descriptionLanguage) { mDescriptionLanguage = descriptionLanguage; } void setLanguage(const char * language) { mLanguage = language; } void setFrameRate(unsigned int frameRate) { mFrameRate = frameRate; } void setQuality(unsigned int quality) { mQuality = quality; } void setTcpSetupAttribute(SdpTcpSetupAttribute tcpSetupAttribute) { mTcpSetupAttribute = tcpSetupAttribute; } void setTcpConnectionAttribute(SdpTcpConnectionAttribute tcpConnectionAttribute) { mTcpConnectionAttribute = tcpConnectionAttribute; } // void addCryptoSettings(unsigned int tag, SdpCryptoSuiteType suite, SdpCryptoKeyMethod keyMethod, const char * keyValue) { addCryptoSettings(new SdpCrypto(tag, suite, keyMethod, keyValue)); } void addCryptoSettings(SdpCrypto* crypto) { mCryptos.insert(crypto); } void clearCryptoSettings() { mCryptos.destroyAll(); } void setFingerPrint(SdpFingerPrintHashFuncType fingerPrintHashFunction, const char * fingerPrint) { mFingerPrintHashFunction = fingerPrintHashFunction; mFingerPrint = fingerPrint; } void setKeyManagementProtocol(SdpKeyManagementProtocolType protocol, const char* data) { mKeyManagementProtocol = protocol; mKeyManagementData = data; } void addPreConditionCurrentStatus(SdpPreConditionType type, SdpPreConditionStatusType status, SdpPreConditionDirectionType direction) { addPreConditionCurrentStatus(new SdpPreCondition(type, status, direction)); } void addPreConditionCurrentStatus(SdpPreCondition* preCondition) { mPreConditionCurrentStatus.insert(preCondition); } void clearPreConditionCurrentStatus() { mPreConditionCurrentStatus.destroyAll(); } void addPreConditionConfirmStatus(SdpPreConditionType type, SdpPreConditionStatusType status, SdpPreConditionDirectionType direction) { addPreConditionConfirmStatus(new SdpPreCondition(type, status, direction)); } void addPreConditionConfirmStatus(SdpPreCondition* preCondition) { mPreConditionConfirmStatus.insert(preCondition); } void clearPreConditionConfirmStatus() { mPreConditionConfirmStatus.destroyAll(); } void addPreConditionDesiredStatus(SdpPreConditionType type, SdpPreConditionStrengthType strength, SdpPreConditionStatusType status, SdpPreConditionDirectionType direction) { addPreConditionDesiredStatus(new SdpPreConditionDesiredStatus(type, strength, status, direction)); } void addPreConditionDesiredStatus(SdpPreConditionDesiredStatus* preConditionDesiredStatus) { mPreConditionDesiredStatus.insert(preConditionDesiredStatus); } void clearPreConditionDesiredStatus() { mPreConditionDesiredStatus.destroyAll(); } void setMaximumPacketRate(double maximumPacketRate) { mMaximumPacketRate = maximumPacketRate; } void setLabel(const char * label) { mLabel = label; } void setIdentificationTag(const char * identificationTag) { mIdentificationTag = identificationTag; } void setIceUserFrag(const char * iceUserFrag) { mIceUserFrag = iceUserFrag; } void setIcePassword(const char * icePassword) { mIcePassword = icePassword; } void addRemoteCandidate(unsigned int componentId, const char * connectionAddress, unsigned int port) { addRemoteCandidate(new SdpRemoteCandidate(componentId, connectionAddress, port)); } void addRemoteCandidate(SdpRemoteCandidate* remoteCandidate) { mRemoteCandidates.insert(remoteCandidate); } void clearRemoteCandidates() { mRemoteCandidates.destroyAll(); } // Note: Candidates should be added after m/c line and rtcp information is set, so that the in-use candidate // can be properly tagged and CandidatePresents flag can be properly set void addCandidate(const char * foundation, unsigned int id, SdpCandidate::SdpCandidateTransportType transport, uint64_t priority, const char * connectionAddress, unsigned int port, SdpCandidate::SdpCandidateType candidateType, const char * relatedAddress = 0, unsigned int relatedPort = 0) { addCandidate(new SdpCandidate(foundation, id, transport, priority, connectionAddress, port, candidateType, relatedAddress, relatedPort)); } void addCandidate(SdpCandidate* candidate); void clearCandidates() { mCandidates.destroyAll(); mRtpCandidatePresent = false; mRtcpCandidatePresent = false; } void addCandidatePair(const SdpCandidate& localCandidate, const SdpCandidate& remoteCandidate, SdpCandidatePair::SdpCandidatePairOffererType offerer) { addCandidatePair( new SdpCandidatePair(localCandidate, remoteCandidate, offerer)); } void addCandidatePair(SdpCandidatePair* sdpCandidatePair) { mCandidatePairs.insert(sdpCandidatePair); } void clearCandidatePairs() { mCandidatePairs.destroyAll(); } void addPotentialMediaView(SdpMediaLine* potentialMediaView) { mPotentialMediaViews.insert(potentialMediaView); } void clearPotentialMediaViews() { mPotentialMediaViews.destroyAll(); } void setPotentialMediaViewString(const char *potentialMediaViewString) { mPotentialMediaViewString = potentialMediaViewString; } /* ============================ ACCESSORS ================================= */ // Get the SdpMediaType enum for the Mime type of this SdpMediaLine SdpMediaType getMediaType() const { return mMediaType; } // Get SdpMediaType enum for Mime type string static SdpMediaLine::SdpMediaType getMediaTypeFromString(const UtlString& type); // Get Mime type for SdpMediaType static const char* getStringForMediaType(SdpMediaType type); // Get the enum for the media line transport protocol SdpTransportProtocolType getTransportProtocolType() const { return mTransportProtocolType; } // Convert the tranport protocol string token from the m line to enum static SdpTransportProtocolType getTransportProtocolTypeFromString(const UtlString& type); // Get the m line transport protocol string token for the given enum static const char* getStringForTransportProtocolType(SdpTransportProtocolType type); const SdpCodecList* getCodecs() const { return &mCodecs; } const UtlString& getTitle() const { return mTitle; } const UtlCopyableSList& getConnections() const { return mConnections; } const UtlCopyableSList& getRtcpConnections() const { return mRtcpConnections; } const UtlCopyableSList& getBandwidths() const { return mBandwidths; } SdpEncryptionMethod getEncryptionMethod() const { return mEncryptionMethod; } const UtlString& getEncryptionKey() const { return mEncryptionKey; } SdpDirectionType getDirection() const { return mDirection; } unsigned int getPacketTime() const { return mPacketTime; } unsigned int getMaxPacketTime() const { return mMaxPacketTime; } SdpOrientationType getOrientation() const { return mOrientation; } static SdpOrientationType getOrientationTypeFromString(const char * type); const UtlString& getDescriptionLanguage() const { return mDescriptionLanguage; } const UtlString& getLanguage() const { return mLanguage; } unsigned int getFrameRate() const { return mFrameRate; } unsigned int getQuality() const { return mQuality; } SdpTcpSetupAttribute getTcpSetupAttribute() const { return mTcpSetupAttribute; } static SdpTcpSetupAttribute getTcpSetupAttributeFromString(const char * attrib); SdpTcpConnectionAttribute getTcpConnectionAttribute() const { return mTcpConnectionAttribute; } static SdpTcpConnectionAttribute getTcpConnectionAttributeFromString(const char * attrib); const UtlCopyableSList& getCryptos() const { return mCryptos; } static SdpCryptoSuiteType getCryptoSuiteTypeFromString(const char * type); static SdpCryptoKeyMethod getCryptoKeyMethodFromString(const char * type); SdpFingerPrintHashFuncType getFingerPrintHashFunction() const { return mFingerPrintHashFunction; } static SdpFingerPrintHashFuncType getFingerPrintHashFuncTypeFromString(const char * type); const UtlString& getFingerPrint() const { return mFingerPrint; } SdpKeyManagementProtocolType getKeyManagementProtocol() const { return mKeyManagementProtocol; } static SdpKeyManagementProtocolType getKeyManagementProtocolTypeFromString(const char * type); const UtlString& getKeyManagementData() const { return mKeyManagementData; } const UtlCopyableSList& getPreConditionCurrentStatus() const { return mPreConditionCurrentStatus; } const UtlCopyableSList& getPreConditionConfirmStatus() const { return mPreConditionConfirmStatus; } const UtlCopyableSList& getPreConditionDesiredStatus() const { return mPreConditionDesiredStatus; } static SdpPreConditionType getPreConditionTypeFromString(const char * type); static SdpPreConditionStatusType getPreConditionStatusTypeFromString(const char * type); static SdpPreConditionDirectionType getPreConditionDirectionTypeFromString(const char * type); static SdpPreConditionStrengthType getPreConditionStrengthTypeFromString(const char * type); double getMaximumPacketRate() const { return mMaximumPacketRate; } const UtlString& getLabel() const { return mLabel; } const UtlString& getIdentificationTag() const { return mIdentificationTag; } const UtlString& getIceUserFrag() const { return mIceUserFrag; } const UtlString& getIcePassword() const { return mIcePassword; } const UtlCopyableSList& getRemoteCandidates() const { return mRemoteCandidates; } const UtlCopyableSortedList& getCandidates() const { return mCandidates; } const UtlCopyableSortedList& getCandidatePairs() const { return mCandidatePairs; } UtlCopyableSortedList& getCandidatePairs() { return mCandidatePairs; } // non-const version for manipulation const UtlCopyableSList& getPotentialMediaViews() const { return mPotentialMediaViews; } const UtlString& getPotentialMediaViewString() const { return mPotentialMediaViewString; } void setControlTrackId(const UtlString& trackId) {mControlTrackId = trackId; } const char* getControlTrackId() { return(mControlTrackId); } // UtlContainable stuff virtual UtlContainableType getContainableType() const { static char type[] = "SdpMediaLine"; return type;} virtual unsigned hash() const { return directHash(); } virtual int compareTo(UtlContainable const *) const { return 0; } // not implemented void toString(UtlString& sdpMediaLineString) const; /* ============================ INQUIRY =================================== */ const bool isRtcpEnabled() const { return mRtcpConnections.entries() > 0; } const bool isRtpCandidatePresent() const { return mRtpCandidatePresent; } const bool isRtcpCandidatePresent() const { return mRtcpCandidatePresent; } const bool isIceSupported() const { return mRtpCandidatePresent && (!isRtcpEnabled() || mRtcpCandidatePresent); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ protected: /* //////////////////////////// PRIVATE /////////////////////////////////// */ private: // m= Note: port is stored in each connection SdpMediaType mMediaType; SdpTransportProtocolType mTransportProtocolType; SdpCodecList mCodecs; // i= UtlString mTitle; // c= UtlCopyableSList mConnections; // includes port from m- line UtlCopyableSList mRtcpConnections; // a=rtcp [ ] - RFC3605 // b= UtlCopyableSList mBandwidths; // k= SdpEncryptionMethod mEncryptionMethod; UtlString mEncryptionKey; // a= media level attributes (including defaults copied from session level attributes) SdpDirectionType mDirection; // a=sendrecv, a=sendonly, a=recvonly, a=inactive - RFC4566 unsigned int mPacketTime; // a=ptime: in ms - RFC4566 unsigned int mMaxPacketTime; // a=maxptime: in ms - RFC4566 SdpOrientationType mOrientation; // a=orient: - RFC4566 UtlString mDescriptionLanguage; // a=sdplang: - RFC4566 UtlString mLanguage; // a=lang: - RFC4566 unsigned int mFrameRate; // a=framerate: in video frames/sec - RFC4566 unsigned int mQuality; // a=quality: 0-10 for vidoe (0 is worst, 10 is best) - RFC4566 UtlString mControlTrackId; // a=control:trackId= SdpTcpSetupAttribute mTcpSetupAttribute;// a=setup: - RFC4145 SdpTcpConnectionAttribute mTcpConnectionAttribute; // a=connection: - RFC4145 UtlCopyableSList mCryptos; // a=crypto: : [] - RFC4568 SdpFingerPrintHashFuncType mFingerPrintHashFunction; // a=fingerprint: - RFC4572 UtlString mFingerPrint; SdpKeyManagementProtocolType mKeyManagementProtocol; // a=key-mgmt: - RFC4567 UtlString mKeyManagementData; UtlCopyableSList mPreConditionCurrentStatus; // a=curr:
   - RFC3312
   UtlCopyableSList mPreConditionConfirmStatus; // a=conf:
   - RFC3312 - are multiple allowed?
   UtlCopyableSList mPreConditionDesiredStatus; // a=des:
    - RFC3312

   double         mMaximumPacketRate;     // a=maxprate: in packets/s - RFC3890
   UtlString      mLabel;                 // a=label:
* * CONNECTED indicates that both RTP is flowing and the call is attached * to the local. This is the normal state for a connected call. * * BRIDGED indicates that RTP is flowing, but the call is out of focus. * This event is generally caused by holding a conference (conference * will bridge by default) or if you accept/place a new call without * explicitly holding the active call. * * REMOTE_HELD indicates that RTP has stopped flowing. This is generally * caused when the remote side places you on hold. The call is still * locally in focus and audio will automatically resume once your are * take off remote hold. * * HELD indicates that both RTP has stopped flowing and the call is out * of focus. * * Developers can also expect media events (e.g. MEDIA_LOCAL_STOP) * whenever RTP is stopped (REMOTE_HELD and HELD). Since media is still * flowing for CONNECTED and BRIDGED, no media stop events are sent. * * NOTE: If this call is part of a conference, sipxCallHold will only * change the remote held state (RTP). You must use * sipxConferenceHold to change call focus. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param bStopRemoteAudio Flag which controls whether sipXtapi takes * the call out of focus (stops engaging local audio microphone * and speaker) or stops sending/receiving audio. Specify true * to stop audio (default) or false to take the call out of * focus. To play audio or generate tones to a remote connection * while on hold, please specify false. This parameter is * ignored (and assumed true) if the call is part of a conference. */ SIPXTAPI_API SIPX_RESULT sipxCallHold(const SIPX_CALL hCall, bool bStopRemoteAudio = true) ; /** * Take the specified call off hold. This API will take the call off * both local hold and remote/full hold. * * @see sipxCallHold for a description of expected events * associated with hold events. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. */ SIPXTAPI_API SIPX_RESULT sipxCallUnhold(const SIPX_CALL hCall) ; /** * Drop/Destroy the specified call. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. */ SIPXTAPI_API SIPX_RESULT sipxCallDestroy(SIPX_CALL& hCall) ; /** * Get the SIP call ID of the call represented by the specified call handle. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szId Buffer to store the ID. A zero-terminated string will be * copied into this buffer on success. * @param iMaxLength Max length of the ID buffer */ SIPXTAPI_API SIPX_RESULT sipxCallGetID(const SIPX_CALL hCall, char* szId, const size_t iMaxLength) ; /** * Get the SIP identity of the local connection. The identity represents * either 1) who was called in the case of a inbound call, or 2) the * line identity used in an outbound call. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szId Buffer to store the ID. A zero-terminated string will be * copied into this buffer on success. * @param iMaxLength Max length of the ID buffer. */ SIPXTAPI_API SIPX_RESULT sipxCallGetLocalID(const SIPX_CALL hCall, char* szId, const size_t iMaxLength) ; /** * Get the line handle for the given call if it has one. * * @param hCall - Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param hLine - handle to call for local side of call. * Note: not all calls have a line handle. Set to SIPX_LINE_NULL if * line handle does not exist for call. */ SIPXTAPI_API SIPX_RESULT sipxCallGetLine(const SIPX_CALL hCall, SIPX_LINE& hLine); /** * Get the SIP identity of the remote connection. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szId Buffer to store the ID. A zero-terminated string will be * copied into this buffer on success. * @param iMaxLength Max length of the ID buffer. */ SIPXTAPI_API SIPX_RESULT sipxCallGetRemoteID(const SIPX_CALL hCall, char* szId, const size_t iMaxLength) ; /** * Get the SIP identity of the contact connection. The identity represents * the originator of the message. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szId Buffer to store the ID. A zero-terminated string will be * copied into this buffer on success. * @param iMaxLength Max length of the ID buffer. */ SIPXTAPI_API SIPX_RESULT sipxCallGetContactID(const SIPX_CALL hCall, char* szId, const size_t iMaxLength) ; /** * Gets the media interface connection ID. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param connectionId Reference to the returned connection identifier. */ SIPXTAPI_API SIPX_RESULT sipxCallGetConnectionId(const SIPX_CALL hCall, int& connectionId); /** * Get the conference handle for the specified call * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * * @param hConf Conference handle for this call (if the call is part of a * conference) */ SIPXTAPI_API SIPX_RESULT sipxCallGetConference(const SIPX_CALL hCall, SIPX_CONF& hConf) ; /** * Get the SIP request URI. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szUri Buffer to store the request URI. A zero-terminated string will * be copied into this buffer on success. * @param iMaxLength Max length of the request URI buffer. */ SIPXTAPI_API SIPX_RESULT sipxCallGetRequestURI(const SIPX_CALL hCall, char* szUri, const size_t iMaxLength) ; /** * Get the SIP remote contact. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szContact Buffer to store the remote contact. A zero-terminated * string will be copied into this buffer on success. * @param iMaxLength Max length of the remote contact buffer. */ SIPXTAPI_API SIPX_RESULT sipxCallGetRemoteContact(const SIPX_CALL hCall, char* szContact, const size_t iMaxLength) ; /** * Get the remote user agent of the call represented by the specified call handle. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szAgent Buffer to store the user agent name. A zero-terminated string * will be copied into this buffer on success. * @param iMaxLength Max length of the buffer */ SIPXTAPI_API SIPX_RESULT sipxCallGetRemoteUserAgent(const SIPX_CALL hCall, char* szAgent, const size_t iMaxLength) ; /** * Play a tone (DTMF, dialtone, ring back, etc) to the local and/or * remote party. See the DTMF_ constants for built-in tones. * If a sipxCallDestroy is attempted while a tone is playing, * sipxCallDestroy will fail with a SIPX_RESULT_BUSY return code. * Call sipxCallStopTone before making the call to * sipxConferenceDestroy. DTMF is sent via RFC 2833 method. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param toneId ID of the tone to play * @param bLocal Should the tone be played locally? * @param bRemote Should the tone be played to the remote party? */ SIPXTAPI_API SIPX_RESULT sipxCallStartTone(const SIPX_CALL hCall, const SIPX_TONE_ID toneId, const bool bLocal, const bool bRemote) ; /** * Stop playing a tone (DTMF, dialtone, ring back, etc). to local * and remote parties. Under a GIPS VoiceEngine build, this method * is a NOP -- VoiceEngine only plays tones for a specific time * interval. * If a sipxCallDestroy is attempted while a tone is playing, * sipxCallDestroy will fail with a SIPX_RESULT_BUSY return code. * Call sipxCallStopTone before making the call to * sipxConferenceDestroy. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. */ SIPXTAPI_API SIPX_RESULT sipxCallStopTone(const SIPX_CALL hCall) ; /** * Play the designated file. The file may be a raw 16 bit signed PCM at * 8000 samples/sec, mono, little endian or a .WAV file. * If a sipxCallDestroy is attempted while an audio file is playing, * sipxCallDestroy will fail with a SIPX_RESULT_BUSY return code. * Call sipxCallAudioPlayFileStop before making the call to * sipxCallDestroy. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. Audio files can only be played in the * context of a call. * @param szFile Filename for the audio file to be played. * @param bRepeat True if the file is supposed to be played repeatedly * @param bLocal True if the audio file is to be rendered locally. * @param bRemote True if the audio file is to be rendered by the remote * endpoint. * @param bMixWithMicrophone True to mix the audio with the microphone * data or false to replace it. This option is only supported * when sipXtapi is bundled with GIPS VoiceEngine. * @param fVolumeScaling Volume down scaling for the audio file. Valid * values are between 0 and 1.0, where 1.0 is the no down-scaling. * This option is only supported when sipXtapi is bundled with GIPS * VoiceEngine. */ SIPXTAPI_API SIPX_RESULT sipxCallAudioPlayFileStart(const SIPX_CALL hCall, const char* szFile, const bool bRepeat, const bool bLocal, const bool bRemote, const bool bMixWithMicrophone = false, const float fVolumeScaling = 1.0) ; /** * Stop playing a file started with sipxCallPlayFileStart * If a sipxCallDestroy is attempted while an audio file is playing, * sipxCallDestroy will fail with a SIPX_RESULT_BUSY return code. * Call sipxCallAudioPlayFileStop before making the call to * sipxCallDestroy. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. Audio files can only be played and stopped * in the context of a call. */ SIPXTAPI_API SIPX_RESULT sipxCallAudioPlayFileStop(const SIPX_CALL hCall) ; /** * Record a call session (including other parties if this is a multi-party * call / conference) to a file. The resulting file will be a PCM WAV file. * Conference join operation on this call will cause the recording to stop. * In case of conference recording, this function should be called for single * conference call only. Conference recording will continue even after the * original call had been dropped/split, as long as there is at least one call * left in the conference. If the original call has been dropped, use handle * of other call in the conference to stop recording. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szFile Filename for the resulting audio file. */ SIPXTAPI_API SIPX_RESULT sipxCallAudioRecordFileStart(const SIPX_CALL hCall, const char* szFile) ; /** * Stop recording a call to file. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. */ SIPXTAPI_API SIPX_RESULT sipxCallAudioRecordFileStop(const SIPX_CALL hCall) ; /** * Record a call session (including other parties if this is a multi-party * call / conference) to a buffer. * Conference join operation on this call will cause the recording to stop. * In case of conference recording, this function should be called for single * conference call only. Conference recording will continue even after the * original call had been dropped/split, as long as there is at least one call * left in the conference. If the original call has been dropped, use handle * of other call in the conference to stop recording. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param pBuffer Buffer to record data to. * @param bufferSize Size of the buffer in bytes. * @param bufferType The audio encoding format for the data as specified by * the SIPX_AUDIO_DATA_FORMAT enumerations. Currently only RAW_PCM_16 * is supported. * @param maxRecordTime Maximum time to record in milliseconds. Recording stops * automatically when this amount of time is recorded. Pass -1 to disable * time limit. * @param maxSilence Maximum silence time before recording is stopped * automatically. Pass -1 to disable stop on silence. */ SIPXTAPI_API SIPX_RESULT sipxCallAudioRecordBufferStart(const SIPX_CALL hCall, const char* pBuffer, const int bufferSize, const int bufferType = RAW_PCM_16, const int maxRecordTime = -1, const int maxSilence = -1) ; /** * Stop recording a call to buffer. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. */ SIPXTAPI_API SIPX_RESULT sipxCallAudioRecordBufferStop(const SIPX_CALL hCall) ; /** * Play the specified audio data. Currently the only data format that * is supported is raw 16 bit signed PCM at 8000 samples/sec, mono, * little endian. * If a sipxCallDestroy is attempted while an audio buffer is playing, * sipxCallDestroy will fail with a SIPX_RESULT_BUSY return code. * Call sipxCallPlayBufferStop before making the call to * sipxCallDestroy. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. Audio can only be played in the context * of a call. * @param szBuffer Pointer to the audio data to be played. * @param bufSize Length, in bytes, of the audio data. * @param bufType The audio encoding format for the data as specified * by the SIPX_AUDIO_DATA_FORMAT enumerations. Currently * only RAW_PCM_16 is supported. * @param bRepeat True if the audio is supposed to be played repeatedly * @param bLocal True if the audio is to be rendered locally. * @param bRemote True if the audio is to be rendered by the remote endpoint. */ SIPXTAPI_API SIPX_RESULT sipxCallPlayBufferStart(const SIPX_CALL hCall, const char* szBuffer, const int bufSize, const int bufType, const bool bRepeat, const bool bLocal, const bool bRemote) ; /** * Stop playing the audio started with sipxCallPlayBufferStart * If a sipxCallDestroy is attempted while an audio buffer is playing, * sipxCallDestroy will fail with a SIPX_RESULT_BUSY return code. * Call sipxCallPlayBufferStop before making the call to * sipxCallDestroy. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. Audio can only be played and stopped * in the context of a call. */ SIPXTAPI_API SIPX_RESULT sipxCallPlayBufferStop(const SIPX_CALL hCall) ; /** * Set the address and port to which the given media stream is to be recieved. * This is generally used when a separate process is to recieve the media stream. * @param hCall - call handle for the RTP stream * @param mediaType - audio or video * @param mediaTypeStreamIndex - connection Id * @param streamReceiveAddress - IP address on which RTP stream is to be received * @param rtpPort - RTP port on which to receive stream * @param rtcpPort - RTCP port on which to recieve stream */ SIPXTAPI_API SIPX_RESULT sipxCallSetMediaPassThrough(const SIPX_CALL hCall, MEDIA_TYPE mediaType, int mediaTypeStreamIndex, const char* streamReceiveAddress, int rtpPort, int rtcpPort); /** * Subscribe for NOTIFY events which may be published by the other end-point * of the call. This API differs from sipxConfigSubscribe in that it allows * you to use the contact address from the remote party as the subscription * target (see the bRemoteContactIsGruu parameter). * * sipXtapi will automatically refresh subscriptions until sipxCallUnsubscribe * is called. Please make sure you call sipxCallUnsubscribe before tearing * down your call. * * @param hCall The call handle of the call associated with the subscription. * @param szEventType A string representing the type of event that can be * published. This string is used to populate the "Event" header in * the SIP SUBSCRIBE request. For example, if checking voicemail * status, your would use "message-summary". * @param szAcceptType A string representing the types of NOTIFY events that * this client will accept. This string is used to populate the * "Accept" header in the SIP SUBSCRIBE request. For example, if * checking voicemail status, you would use * "application/simple-message-summary" * @param phSub Pointer to a subscription handle whose value is set by this * function. This handle allows you to cancel the subscription and * differentiate between NOTIFY events. * @param bRemoteContactIsGruu indicates whether the Contact for the remote * side of the call can be assumed to be a Globally Routable Unique URI * (GRUU). Normally one cannot assume that a contact is a GRUU and the * To or From address for the remote side is assumed to be an Address Of * Record (AOR) that is globally routable. */ SIPXTAPI_API SIPX_RESULT sipxCallSubscribe(const SIPX_CALL hCall, const char* szEventType, const char* szAcceptType, SIPX_SUB* phSub, bool bRemoteContactIsGruu = false); /** * Unsubscribe from previously subscribed NOTIFY events. This method will * send another subscription request with an expires time of 0 (zero) to end * your subscription. * * @param hSub The subscription handle obtained from the call to * sipxCallSubscribe. */ SIPXTAPI_API SIPX_RESULT sipxCallUnsubscribe(const SIPX_SUB hSub) ; /** * Sends an INFO event to the specified call. * * This method will fail with an SIPX_RESULT_INVALID_STATE return code * if an existing INFO message transaction is still outstanding (sipXtapi * has not received a final response to the initial request). * * @param phInfo Pointer to an INFO message handle, whose value is set by * this method. * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szContentType String representation of the INFO content type * @param szContent Pointer to the INFO messasge's content * @param nContentLength Size of the INFO content */ SIPXTAPI_API SIPX_RESULT sipxCallSendInfo(SIPX_INFO* phInfo, const SIPX_CALL hCall, const char* szContentType, const char* szContent, const size_t nContentLength); /** * Blind transfer the specified call to another party. Monitor the * TRANSFER state events for details on the transfer attempt. If the * call is not already on hold, the party will be placed on hold. * * Assuming that all parties are using sipXtapi, all of the calls * are active (not held), and the transfer works, you should expect the * following event sequence: * *

Transferee (party being transfered):

* * The transferee's original call will be placed on remote hold from the * transfer controller and will then put itself on full hold before starting * the transfer. The transfer is implemented as a new call -- this allows * the developer to reclaim the original call if the transfer fails. The * NEWCALL event will include a cause for of CALLSTATE_CAUSE_TRANSFER and * the hAssociatedCall member of the SIPX_CALLSTATE_INFO structure will * include the handle of the original call. * *
 * Original Call: MEDIA_LOCAL_STOP
 * Original Call: MEDIA_REMOTE_STOP
 * Original Call: CALLSTATE_REMOTE_HELD
 * Original Call: CALLSTATE_HELD
 *
 * New Call: CALLSTATE_NEWCALL
 * New Call: CALLSTATE_REMOTE_OFFERING
 * New Call: CALLSTATE_REMOTE_ALERTING
 * New Call: CALLSTATE_CONNECTED
 * New Call: MEDIA_LOCAL_START
 * New Call: MEDIA_REMOTE_START
 * 
* * After the transfer completes, the application developer must destroy * the original call using sipxCallDestroy. If the new call fails for * any reason, the application layer should resume the original call by * taking it off hold. * *

Transfer Controller (this user agent):

* * The transfer controller will automatically take the call out of * focus and place it on hold. Afterwards, the transfer controller * will receive CALLSTATE_TRANSFER_EVENTs indicating the status of * the transfer. * *
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_CAUSE_TRANSFER_INITIATED
 * Source Call: CALLSTATE_BRIDGED
 * Source Call: CALLSTATE_HELD
 * Source Call: MEDIA_CAUSE_HOLD
 * Source Call: MEDIA_CAUSE_HOLD
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_CAUSE_TRANSFER_ACCEPTED
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_CAUSE_TRANSFER_RINGING
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_CAUSE_TRANSFER_SUCCESS
 * Source Call: CALLSTATE_DISCONNECTED
 * 
* * Upon success, the call will automatically be disconnected, however, * the application layer needs to call sipXcallDestroy to free the handle * and call processing resources. * *

Transfer Target (identified by szAddress):

* * The transferee will go through the normal event progression for an incoming * call: * *
 * New Call: CALLSTATE_NEWCALL
 * New Call: CALLSTATE_OFFERING
 * New Call: CALLSTATE_ALERTING
 * New Call: CALLSTATE_CONNECTED
 * 
* * If the transfer target rejects the call or fails to answer, the transfer * will fail. * * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szAddress SIP url identifing the transfer target (who the call * identified by hCall will be transfered to). * * @see SIPX_CALLSTATE_EVENT * @see SIPX_CALLSTATE_CAUSE */ SIPXTAPI_API SIPX_RESULT sipxCallBlindTransfer(const SIPX_CALL hCall, const char* szAddress) ; /** * Transfer the source call to the target call. This method can be used * to implement consultative transfer (transfer initiator can speak with * the transfer target prior to transferring). If you wish to consult * privately, create a new call to the transfer target. If you wish * consult and allow the source (transferee) to participant in the * conversation, create a conference and then transfer one leg to * another. * * If not already on hold, the transferee (hSourceCall) is placed on * hold as part of the transfer operation. * * The event sequence may differ slightly depending on whether the calls * are part of a conference (attended transfer) or individual calls (semi- * attended transfer). * * Assuming the calls are part of a conference and not on hold, the event * sequences are as follows: * *

Transfer Controller (this user agent):

* *
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_CAUSE_TRANSFER_INITIATED
 * Source Call: CALLSTATE_REMOTE_HELD
 * Source Call: MEDIA_LOCAL_STOP
 * Source Call: MEDIA_REMOTE_STOP
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_CAUSE_TRANSFER_ACCEPTED
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_CAUSE_TRANSFER_SUCCESS
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_DISCONNECTED
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_DESTROYED
 * 
* * The source call will automatically be disconnected if the transfer is * successful. Also, if the source call is part of a conference, the call * will automatically be destroyed. If not part of a conference, the * application must destroy the call using sipxCallDestroy. * *
 * Target Call: CALLSTATE_REMOTE_HELD
 * Target Call: MEDIA_LOCAL_STOP
 * Target Call: MEDIA_REMOTE_STOP
 * Target Call: CALLSTATE_DISCONNECTED
 * Target Call: CALLSTATE_DESTROYED
 * 
* * The target call is remote held as part of the transfer operation. If the * target call is part of a conference, it will automatically be destroyed. * Otherwise, the application layer is responsible for calling * sipxCallDestroy. * *

Transferee (user agent on other side of hSourceCall):

* * The transferee will create a new call to the transfer target and * automatically disconnect the original call upon success. The new call * will be created with a cause of CALLSTATE_CAUSE_TRANSFER in the * SIPX_CALLSTATE_INFO event data. The application layer can look at * the hAssociatedCall member to connect the new call to the original * call. * *
 * Original Call: MEDIA_LOCAL_STOP
 * Original Call: MEDIA_REMOTE_STOP
 * Original Call: CALLSTATE_REMOTE_HELD
 * Original Call: CALLSTATE_HELD
 * Original Call: CALLSTATE_DISCONNECTED
 *
 * New Call: CALLSTATE_NEWCALL::CALLSTATE_CAUSE_TRANSFER
 * New Call: CALLSTATE_REMOTE_OFFERING
 * New Call: CALLSTATE_CONNECTED
 * New Call: MEDIA_LOCAL_START
 * New Call: MEDIA_REMOTE_START
 * 
* * The application is responsible for calling sipxCallDestroy on the original * call after the CALLSTATE_DISCONNECT event. * *

Transfer Target (user agent on other side of hTargetCall):

* * The transfer target will automatically receive and answer the inbound call * from the transferee. After this completes, the original call is * disconnected. * *
 * CALLSTATE_NEWCALL::CALLSTATE_CAUSE_TRANSFERRED
 * CALLSTATE_CONNECTED
 * MEDIA_LOCAL_START
 * MEDIA_REMOTE_START
 * 
* * Please note that no offering event was fired. The target does not have * the option to accept or reject the call. If this call was part of a * conference, the new call is automatically added to the same conference. * * @param hSourceCall Handle to the source call (transferee). * @param hTargetCall Handle to the target call (transfer target). * * @see SIPX_CALLSTATE_EVENT * @see SIPX_CALLSTATE_CAUSE */ SIPXTAPI_API SIPX_RESULT sipxCallTransfer(const SIPX_CALL hSourceCall, const SIPX_CALL hTargetCall) ; /** * Updates the Video window with a new frame buffer. Should be called * when the window receives a PAINT message. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param hWnd Window handle of the video preview window. */ SIPXTAPI_API SIPX_RESULT sipxCallUpdateVideoWindow(const SIPX_CALL hCall, const SIPX_WINDOW_HANDLE hWnd); /** * Resizes the video window. Should be called when the window receives a SIZE message. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param hWnd Window handle of the video window. */ SIPXTAPI_API SIPX_RESULT sipxCallResizeWindow(const SIPX_CALL hCall, const SIPX_WINDOW_HANDLE hWnd); /** * Gets energy levels for a call. The call must be in the connected state * for this request to succeed. * * This API is only supported when sipXtapi is bundled with VoiceEngine from * GIPS. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param iInputEnergyLevel Input/Microphone energy level ranging from 0 to 9. * @param iOutputEnergyLevel Output/Speaker energy level ranging from 0 to 9. * The output energy level is pre-mixed (before mixing any files/tones or * other parties). sipxConferenceGetEnergyLevels provides an API to * obtain post-mixed energy levels. * @param nMaxContributors Max number of contributors/energy levels. * Contributors are derived by looking at the contributing RTP source * IDs from the RTP stream. * @param CCSRCs Array of contributing source ids. This array will be filled * in up to a max of nMaxContributors. See nActualContributors for * the actual number of elements returned. * @param iEnergyLevels Energy level for each contributing source id ranging * from 0 to 9. This array in up to a max of nMaxContributors. See * nActualContributors for the actual number of elements returned. * @param nActualContributors The actual number of contributing source ids and * energy levels returned. */ SIPXTAPI_API SIPX_RESULT sipxCallGetEnergyLevels(const SIPX_CALL hCall, int& iInputEnergyLevel, int& iOutputEnergyLevel, const size_t nMaxContributors, unsigned int CCSRCs[], int iEnergyLevels[], size_t& nActualContributors) ; /** * Gets the sending and receiving Audio RTP SSRC IDs. The SSRC ID is used to * identify the RTP/audio stream. The call must be in the connected state * for this request to succeed. * * This API is only supported when sipXtapi is bundled with VoiceEngine from * GIPS. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param iSendSSRC The RTP SSRC used when sending audio * @param iReceiveSSRC The RTP SSRC used by the remote party to sending audio */ SIPXTAPI_API SIPX_RESULT sipxCallGetAudioRtpSourceIds(const SIPX_CALL hCall, unsigned int& iSendSSRC, unsigned int& iReceiveSSRC) ; /** * Obtain RTCP stats for the specified call. * * This API is only supported when sipXtapi is bundled with VoiceEngine from * GIPS. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * * @param pStats Structure to place call stats, the structure's cbSize * member must be filled out prior to calling this API. For example: * myStats.cbSize = sizeof(SIPX_RTCP_STATS); */ SIPXTAPI_API SIPX_RESULT sipxCallGetAudioRtcpStats(const SIPX_CALL hCall, SIPX_RTCP_STATS* pStats) ; /** * Restrict the set of codecs that are allowed to be used for the given call. * This method does not force signalling to occur. Codecs must be restricted before * the offer or answer SDP is sent from this side. * * @param hCall - call handle for call on which to restrict codec set * @param codecNames - space delimited list of codec names. * Note: codecNames MUST be a subset of the codecs enabled via sipxConfigSetAudioCodecByName * TELEPHONE-EVENT is implicitly included */ SIPXTAPI_API SIPX_RESULT sipxCallLimitCodecs(const SIPX_CALL hCall, const char* codecNames); /** * Limits the codec preferences on a per-call basis. This API will force a * codec renegotiation with the specified call regardless if the codecs * changed. A renegotiation includes sending a new INVITE with an updated SDP * list. Local audio will be stopped and restarted during this process, * however, hold events are not sent to the application. * * NOTE: If a call is on remote hold, it will be taken off remote hold. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param audioBandwidth A bandwidth id to limit audio codecs. Pass in * AUDIO_CODEC_BW_DEFAULT to leave audio codecs unchanged. * @param videoBandwidth A bandwidth id to limit video bitrate and framerate. * (see sipxConfigSetVideoBandwidth for an explanation on how * bandwidth ids affect bitrate and framerate). Pass in AUDIO_CODEC_BW_DEFAULT * to leave these parameters unchanged. * @param szVideoCodecName Codec name that limits the supported video codecs * to this one video codec. * * @see sipxConfigSetVideoBandwidth */ SIPXTAPI_API SIPX_RESULT sipxCallLimitCodecPreferences(const SIPX_CALL hCall, const SIPX_AUDIO_BANDWIDTH_ID audioBandwidth, const SIPX_VIDEO_BANDWIDTH_ID videoBandwidth, const char* szVideoCodecName); /** * Sets the gain of the microphone for a given call. This gain is applied * digitally inside of the media engine. * * @note Right now this is implemented for sipXmediaLib with Topology enabled * only. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param gain Floating point gain to apply. Gain should be >0. Internally, * inside of a media engine, it may be represented as fixed point value. */ SIPXTAPI_API SIPX_RESULT sipxCallSetMicGain(const SIPX_CALL hCall, float gain); /** * Sets the gain for all inputs to the given bridge output, except for * the input of the same index which is set to 0.0f gain. * @param hCall - handle to call using the bridge mixer. * @param bridgeOutputIndex - output index on the bridge whose input * gains are to be set. * @param gain - new gain value to set for inputs. */ SIPXTAPI_API SIPX_RESULT sipxCallSetMixOutputGain(const SIPX_CALL hCall, int bridgeOutputIndex, float gain); //@} /** @name Publishing Methods */ //@{ /** * Creates a publishing context, which performs the processing necessary * to accept SUBSCRIBE requests, and to publish NOTIFY messages to subscribers. * The resource may be specific to a single call, conference or global * to this user agent. The naming of the resource ID determines the scope. * * @param hInst Instance pointer obtained by sipxInitialize. * @param phPub Pointer to a publisher handle - this method modifies the value * to refer to the newly created publishing context. * @param szResourceId The resourceId to the state information being * published. This must match the request URI of the incoming * SUBSCRIBE request (only the user ID, host and port are significant * in matching the request URI). Examples: fred\@10.0.0.1:5555, * sip:conference1\@192.160.0.1, sip:kate\@example.com * @param szEventType A string representing the type of event that can be * published. * @param szContentType String representation of the content type being * published. * @param pContent Pointer to the NOTIFY message's body content. * @param nContentLength Size of the content to be published. * * @return If the resource already has a a publisher created for the given * event type, SIPX_RESULT_INVALID_ARGS is returned. */ SIPXTAPI_API SIPX_RESULT sipxPublisherCreate(const SIPX_INST hInst, SIPX_PUB* phPub, const char* szResourceId, const char* szEventType, const char* szContentType, const char* pContent, const size_t nContentLength); /** * Tears down the publishing context. Any existing subscriptions * are sent a final NOTIFY request. If pFinalContent is not NULL and * nContentLength > 0 the given publish state is given otherwise * the final NOTIFY requests are sent with no body or state. * * @param hPub Handle of the publishing context to destroy * (returned from a call to sipxCreatePublisher) * @param szContentType String representation of the content type being * published * @param pFinalContent Pointer to the NOTIFY message's body content * @param nContentLength Size of the content to be published */ SIPXTAPI_API SIPX_RESULT sipxPublisherDestroy(const SIPX_PUB hPub, const char* szContentType, const char* pFinalContent, const size_t nContentLength); /** * Publishes an updated state to specific event via NOTIFY to its subscribers. * * @param hPub Handle of the publishing context * (returned from a call to sipxCreatePublisher) * @param szContentType String representation of the content type being * published * @param pContent Pointer to the NOTIFY message's body content * @param nContentLength Size of the content to be published */ SIPXTAPI_API SIPX_RESULT sipxPublisherUpdate(const SIPX_PUB hPub, const char* szContentType, const char* pContent, const size_t nContentLength); //@} /** @name Conference Methods */ //@{ /** * Create a conference handle. Conferences are an association of calls * where the audio media is mixed. sipXtapi supports conferences up to * 4 (CONF_MAX_CONNECTIONS) parties in its default configuration. * * @param hInst Instance pointer obtained by sipxInitialize. * @param phConference Pointer to a conference handle. Upon success, * this value is replaced with a valid conference handle. * Success is determined by the SIPX_RESULT result code. */ SIPXTAPI_API SIPX_RESULT sipxConferenceCreate(const SIPX_INST hInst, SIPX_CONF* phConference) ; /** * Join (add) an existing held call into a conference. * * An existing call can be added to a virgin conference without restriction. * Additional calls, must be connected and on remote hold for this operation * to succeed. A remote hold can be accomplished by calling sipxCallHold on * the joining party. The application layer must wait for the * CALLSTATE_HELD event prior to calling join. No events * are fired as part of the operation and the newly joined call is left on * hold. The application layer should call sipxCallUnhold on the new * participant to finalize the join. * * @param hConf Conference handle obtained by calling sipxConferenceCreate. * @param hCall Call handle of the call to join into the conference. */ SIPXTAPI_API SIPX_RESULT sipxConferenceJoin(const SIPX_CONF hConf, const SIPX_CALL hCall) ; /** * Split (remove) a held call from a conference. This method will remove * the specified call from the conference. * * The call must be connected and on remote hold for this operation to * succeed. A remote hold can be accomplished by calling sipxCallHold on * the conference participant or by placing the entire conference on hold * with bridging disabled. The application layer must wait for the * CALLSTATE_HELD event prior to calling split. No events * are fired as part of the operation and the split call is left on hold. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. * @param hCall Call handle of the call that should be removed from the * the conference. */ SIPXTAPI_API SIPX_RESULT sipxConferenceSplit(const SIPX_CONF hConf, const SIPX_CALL hCall) ; /** * Add a new party to an existing conference. A connection is automatically * initiated for the specified address. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. * @param hLine Line Identity for the outbound call. The line identity * helps defines the "From" caller-id. The line identity can't be * SIPX_LIINE_NULL, as it's an outbound call. * @param szAddress SIP URL of the conference participant to add * @param phNewCall Pointer to a call handle to store new call. * @param contactId Id of the desired contact record to use for this call. * The id refers to a Contact Record obtained by a call to * sipxConfigGetLocalContacts. The application can choose a * contact record of type LOCAL, NAT_MAPPED, CONFIG, or RELAY. * The Contact Type allows you to control whether the * user agent and media processing advertises the local address * (e.g. LOCAL contact of 10.1.1.x or * 192.168.x.x), the NAT-derived address to the target party, * or, local contact addresses of other types. * @param pDisplay Pointer to an object describing the display object for * rendering remote video. * @param pSecurity Pointer to an object describing the security attributes * for the call. * @param bTakeFocus Should SIPxua place the newly answered call in focus * (engage local microphone and speaker). In some cases, application * developer may want to answer the call in the background and play * audio while the user finishes up with their active (in focus) call. * @param options Pointer to a SIPX_CALL_OPTIONS structure. * * @see sipxConferenceCreate * @see sipxConfigSetLocationHeader * @see sipxConfigGetLocalContacts * @see sipxConfigSetAudioCodecPreferences */ SIPXTAPI_API SIPX_RESULT sipxConferenceAdd(const SIPX_CONF hConf, const SIPX_LINE hLine, const char* szAddress, SIPX_CALL* phNewCall, SIPX_CONTACT_ID contactId = 0, SIPX_VIDEO_DISPLAY* const pDisplay = NULL, SIPX_SECURITY_ATTRIBUTES* const pSecurity = NULL, bool bTakeFocus = true, SIPX_CALL_OPTIONS* options = NULL); /** * Removes a participant from conference by hanging up on them. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. * @param hCall Call handle identifying which call to remove from the * conference by hanging up. */ SIPXTAPI_API SIPX_RESULT sipxConferenceRemove(const SIPX_CONF hConf, const SIPX_CALL hCall) ; /** * Gets all of the calls participating in a conference. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. * @param calls An array of call handles filled in by the API. * @param iMax The maximum number of call handles to return. * @param nActual The actual number of call handles returned. */ SIPXTAPI_API SIPX_RESULT sipxConferenceGetCalls(const SIPX_CONF hConf, SIPX_CALL calls[], const size_t iMax, size_t& nActual) ; /** * Places a conference on hold. This API can be used to place a * conference on local hold (continue to bridge participants) or full hold * (remaining participants cannot talk to each other). The default is * local hold/bridged. The bBridged flag can be used to change this * behavior (false for full hold). * * Developers may also hold/unhold individual conference participants by * calling sipxCallHold and sipxCallUnhold on individual call handles. The * sipxConferenceGetCalls API can be used to enumerate conference * participants. * * @see sipxCallHold for a description of the expected * events. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. * @param bBridging true for a bridging conference hold, * false for a non-bridging conference hold. */ SIPXTAPI_API SIPX_RESULT sipxConferenceHold(const SIPX_CONF hConf, bool bBridging = true); /** * Removes conference members from a held state. This method will take a call * off either local or remote/full hold. * * @see sipxConferenceHold for details on holding * conferences. * @see sipxCallHold for a description of the expected * events. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. */ SIPXTAPI_API SIPX_RESULT sipxConferenceUnhold(const SIPX_CONF hConf); /** * Play the designated audio file to all conference participants and/or the * local speaker. The file may be a raw 16 bit signed PCM at 8000 * samples/sec, mono, little endian or a .WAV file. * If a sipxConferenceDestroy is attempted while an audio file is playing, * sipxConferenceDestroy will fail with a SIPX_RESULT_BUSY return code. * Call sipxConferencePlayAudioFileStop before making the call to * sipxConferenceDestroy. * * * @param hConf Conference handle obtained by calling sipxConferenceCreate. * @param szFile Filename for the audio file to be played. * @param bRepeat True if the file is supposed to be played repeatedly * @param bLocal True if the audio file is to be rendered locally. * @param bRemote True if the audio file is to be rendered by the remote * endpoint. * @param bMixWithMicrophone True to mix the audio with the microphone * data or false to replace it. This option is only supported * when sipXtapi is bundled with GIPS VoiceEngine. * @param fVolumeScaling Volume down scaling for the audio file. Valid * values are between 0 and 1.0, where 1.0 is the no down-scaling. * This option is only supported when sipXtapi is bundled with GIPS * VoiceEngine. */ SIPXTAPI_API SIPX_RESULT sipxConferencePlayAudioFileStart(const SIPX_CONF hConf, const char* szFile, const bool bRepeat, const bool bLocal, const bool bRemote, const bool bMixWithMicrophone = false, const float fVolumeScaling = 1.0) ; /* * Stop playing a file started with sipxConferencePlayAudioFileStart * If a sipxConferenceDestroy is attempted while an audio file is playing, * sipxConferenceDestroy will fail with a SIPX_RESULT_BUSY return code. * Call sipxConferencePlayAudioFileStop before making the call to * sipxConferenceDestroy. * * @param hConf Conference handle obtained by calling sipxConferenceCreate. */ SIPXTAPI_API SIPX_RESULT sipxConferencePlayAudioFileStop(const SIPX_CONF hConf) ; /** * Destroys a conference. All participants within a conference are * dropped. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. */ SIPXTAPI_API SIPX_RESULT sipxConferenceDestroy(SIPX_CONF hConf) ; /** * Gets energy levels for a conference. The conference must be in the * connected state (not held or bridged) for this request to succeed. * * This API is only supported when sipXtapi is bundled with VoiceEngine from * GIPS. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. * @param iInputEnergyLevel Input/Microphone energy level ranging from 0 to 9. * @param iOutputEnergyLevel Output/Speaker energy level ranging from 0 to 9. * The output energy level is post-mixed (after mixing all files/tones * and other parties. sipxCallGetEnergyLevel provides an API to obtain * pre-mixed energy levels. */ SIPXTAPI_API SIPX_RESULT sipxConferenceGetEnergyLevels(const SIPX_CONF hConf, int& iInputEnergyLevel, int& iOutputEnergyLevel) ; /** * Limits the codec preferences on a conference. This API will force a * codec renegotiation with the specified calls regardless if the codecs * changed. A renegotiation includes sending a new INVITE with an updated SDP * list. Local audio will be stopped and restarted during this process, * however, hold events are not sent to the application. * * NOTE: If any calls are on remote hold, they will be taken off hold. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. * @param audioBandwidth A bandwidth id to limit audio codecs. Pass in * AUDIO_CODEC_BW_DEFAULT to leave audio codecs unchanged. * @param videoBandwidth A bandwidth id to limit video bitrate and framerate. * (see sipxConfigSetVideoBandwidth for an explanation on how * bandwidth ids affect bitrate and framerate). Pass in AUDIO_CODEC_BW_DEFAULT * to leave these parameters unchanged. * @param szVideoCodecName Codec name that limits the supported video codecs * to this one video codec. * * @see sipxConfigSetVideoBandwidth */ SIPXTAPI_API SIPX_RESULT sipxConferenceLimitCodecPreferences(const SIPX_CONF hConf, const SIPX_AUDIO_BANDWIDTH_ID audioBandwidth, const SIPX_VIDEO_BANDWIDTH_ID videoBandwidth, const char* szVideoCodecName) ; /** * Create a new media connetion that is indpendent of any existing call legs in the conference. * This media connection is for independent control independent of SIP call control. * RTP streams may be stopped and started manually via the sipXtapi methods: * sipxConferenceRtpSetDestination * sipxConferenceRtpStartSend * sipxConferenceRtpStopSend * * @param[in] hConf - conference handle indicating which media interface in which the new * media connection is to be created. * @param[out] connectionId - handle/id for the media connection created. */ SIPXTAPI_API SIPX_RESULT sipxMediaConnectionCreate(const SIPX_CONF hConf, int& connectionId); /** * Set the destination to which RTP streams are to be sent. * * @param[in] hConf - conference handle indicating which media interface the connection * belongs. * @param[in] connectionId - handle/id for media connection * @param[in] mediaType - media stream type (e.g. VIDEO_MEDIA, AUDIO_MEDIA) * @param[in] mediaTypeStreamIndex - index to which stream for the given type of media * for now limited to 1 stream (i.e. index = 0) * @param[in] streamSendAddress - remote IP address to send RTP to * @param[in] rtpPort - port at remote address to send RTP stream to * @param[in] rtcpPort - port at remote address to send RTCP stream to */ SIPXTAPI_API SIPX_RESULT sipxMediaConnectionRtpSetDestination(const SIPX_CONF hConf, int connectionId, MEDIA_TYPE mediaType, int mediaTypeStreamIndex, const char* streamSendAddress, int rtpPort, int rtcpPort); /** * Start sending the RTP/RTCP stream * @param[in] hConf - conference handle indicating which media interface the connection * belongs. * @param[in] connectionId - handle/id for media connection * @param[in] numTokens - number of codec tokens in codecTokens array * @param[in] codecTokens - array of codec names * @param[in] payloadIds - payload ID to use for corresponding codec in codecTokens array * */ SIPXTAPI_API SIPX_RESULT sipxMediaConnectionRtpStartSend(const SIPX_CONF hConf, int connectionId, int numTokens, const char* codecTokens[], int payloadIds[]); /** * Stop sending RTP/RTCP * @param[in] hConf - conference handle indicating which media interface the connection * belongs. * @param[in] connectionId - handle/id for media connection */ SIPXTAPI_API SIPX_RESULT sipxMediaConnectionRtpStopSend(const SIPX_CONF hConf, int connectionId); //@} /** @name Audio Methods */ //@{ /** * Set the local microphone gain. If the microphone is muted, * resetting the gain will not enable audio -- you must unmute * the microphone. * * @param hInst Instance pointer obtained by sipxInitialize. * @param iLevel The level of the local microphone gain */ SIPXTAPI_API SIPX_RESULT sipxAudioSetGain(const SIPX_INST hInst, const int iLevel) ; /** * Get the current microphone gain. * * @param hInst Instance pointer obtained by sipxInitialize. * @param iLevel The level of the gain of the microphone */ SIPXTAPI_API SIPX_RESULT sipxAudioGetGain(const SIPX_INST hInst, int& iLevel) ; /** * Mute or unmute the microphone. * * @param hInst Instance pointer obtained by sipxInitialize. * @param bMute True if the microphone is to be muted and false if it * is not to be muted */ SIPXTAPI_API SIPX_RESULT sipxAudioMute(const SIPX_INST hInst, const bool bMute) ; /** * Gets the mute state of the microphone. * * @param hInst Instance pointer obtained by sipxInitialize. * @param bMuted True if the microphone has been muted and false if it * is not mute */ SIPXTAPI_API SIPX_RESULT sipxAudioIsMuted(const SIPX_INST hInst, bool &bMuted) ; /** * Enables one of the speaker outputs. * * @param hInst Instance pointer obtained by sipxInitialize. * @param type The type of the speaker either the logical ringer * (used to alert user of in inbound call) or speaker * (in call audio device). */ SIPXTAPI_API SIPX_RESULT sipxAudioEnableSpeaker(const SIPX_INST hInst, const SPEAKER_TYPE type) ; /** * Gets the enabled speaker selection. * * @param hInst Instance pointer obtained by sipxInitialize. * @param type The type of the speaker either the logical ringer * (used to alert user of in inbound call) or speaker * (in call audio device). */ SIPXTAPI_API SIPX_RESULT sipxAudioGetEnabledSpeaker(const SIPX_INST hInst, SPEAKER_TYPE& type) ; /** * Sets the audio level for the designated speaker type. If the speaker type * is enabled, the change it audio will be heard instantly. * * @param hInst Instance pointer obtained by sipxInitialize. * @param type The type of the speaker either the logical ringer * (used to alert user of in inbound call) or speaker * (in call audio device). * @param iLevel The level of the gain of the microphone */ SIPXTAPI_API SIPX_RESULT sipxAudioSetVolume(const SIPX_INST hInst, const SPEAKER_TYPE type, const int iLevel) ; /** * Gets the audio level for the designated speaker type * * @param hInst Instance pointer obtained by sipxInitialize. * @param type The type of the speaker either the logical ringer * (used to alert user of in inbound call) or speaker * (in call audio device). * @param iLevel The level of the gain of the microphone */ SIPXTAPI_API SIPX_RESULT sipxAudioGetVolume(const SIPX_INST hInst, const SPEAKER_TYPE type, int& iLevel) ; /** * Enables or disables Acoustic Echo Cancellation (AEC). By default, sipXtapi * assumes SIPX_AEC_CANCEL_AUTO. Change this parameter will modify the policy * for both existing and new calls. * * Note: This API is only supported when bundled with VoiceEngine from * Global IP Sound or Speex library. * * @param hInst Instance pointer obtained by sipxInitialize. * @param mode AEC mode. * * @see SIPX_AEC_MODE */ SIPXTAPI_API SIPX_RESULT sipxAudioSetAECMode(const SIPX_INST hInst, const SIPX_AEC_MODE mode) ; /** * Get the mode of Acoustic Echo Cancellation (AEC). * * Note: This API is only supported when bundled with VoiceEngine from * Global IP Sound or Speex library. * * @param hInst Instance pointer obtained by sipxInitialize. * @param mode AEC mode. * * @see SIPX_AEC_MODE */ SIPXTAPI_API SIPX_RESULT sipxAudioGetAECMode(const SIPX_INST hInst, SIPX_AEC_MODE& mode) ; /** * Enable/Disable Automatic Gain Control (AGC). By default, AGC is disabled. * * Note: This API is only supported when bundled with VoiceEngine from * Global IP Sound or Speex library. * * @param hInst Instance pointer obtained by sipxInitialize. * @param bEnable true to enable AGC or false to disable */ SIPXTAPI_API SIPX_RESULT sipxAudioSetAGCMode(const SIPX_INST hInst, const bool bEnable) ; /** * Get the enable/disable state of Automatic Gain Control (AGC). * Note: This API is only supported when bundled with VoiceEngine from * Global IP Sound or Speex library. * * @param hInst Instance pointer obtained by sipxInitialize. * @param bEnabled true if AGC is enabled; otherwise false. */ SIPXTAPI_API SIPX_RESULT sipxAudioGetAGCMode(const SIPX_INST hInst, bool& bEnabled) ; /** * Set the noise reduction mode/policy for suppressing background noise. By * default sipXtapi assumes SIPX_NOISE_REDUCTION_LOW. Change this parameter * will modify the policy for both existing and new calls. * * Note: This API is only supported when bundled with VoiceEngine from * Global IP Sound or Speex library. * * @param hInst Instance pointer obtained by sipxInitialize. * @param mode noise reduction mode. * * @see SIPX_NOISE_REDUCTION_MODE */ SIPXTAPI_API SIPX_RESULT sipxAudioSetNoiseReductionMode(const SIPX_INST hInst, const SIPX_NOISE_REDUCTION_MODE mode) ; /** * Get the mode/policy for Noise Reduction (NR). * * Note: This API is only supported when bundled with VoiceEngine from * Global IP Sound or Speex library. * * @param hInst Instance pointer obtained by sipxInitialize. * @param mode noise reduction mode. * * @see SIPX_NOISE_REDUCTION_MODE */ SIPXTAPI_API SIPX_RESULT sipxAudioGetNoiseReductionMode(const SIPX_INST hInst, SIPX_NOISE_REDUCTION_MODE& mode) ; /** * Get the number of input devices available on this system. * * @param hInst Instance pointer obtained by sipxInitialize. * @param numDevices The number of input devices available * on this system. */ SIPXTAPI_API SIPX_RESULT sipxAudioGetNumInputDevices(const SIPX_INST hInst, size_t& numDevices) ; /** * Get the name/identifier for input device at position index * * @param hInst Instance pointer obtained by sipxInitialize. * @param index Zero based index of the input device to be queried. * @param szDevice Reference an character string pointer to receive * the device name. */ SIPXTAPI_API SIPX_RESULT sipxAudioGetInputDevice(const SIPX_INST hInst, const int index, const char*& szDevice) ; /** * Get the number of output devices available on this system * @param hInst Instance pointer obtained by sipxInitialize. * @param numDevices The number of output devices available * on this system. */ SIPXTAPI_API SIPX_RESULT sipxAudioGetNumOutputDevices(const SIPX_INST hInst, size_t& numDevices) ; /** * Get the name/identifier for output device at position index * * @param hInst Instance pointer obtained by sipxInitialize. * @param index Zero based index of the output device to be queried. * @param szDevice Reference an character string pointer to receive * the device name. */ SIPXTAPI_API SIPX_RESULT sipxAudioGetOutputDevice(const SIPX_INST hInst, const int index, const char*& szDevice) ; /** * Set the call input device (in-call microphone). * * @param hInst Instance pointer obtained by sipxInitialize. * @param szDevice Character string pointer to be set to * a string name of the output device. */ SIPXTAPI_API SIPX_RESULT sipxAudioSetCallInputDevice(const SIPX_INST hInst, const char* szDevice) ; /** * Set the call ringer/alerting device. * @param hInst Instance pointer obtained by sipxInitialize. * @param szDevice The call ringer/alerting device. */ SIPXTAPI_API SIPX_RESULT sipxAudioSetRingerOutputDevice(const SIPX_INST hInst, const char* szDevice) ; /** * Set the call output device (in-call speaker). * @param hInst Instance pointer obtained by sipxInitialize. * @param szDevice The call output device. */ SIPXTAPI_API SIPX_RESULT sipxAudioSetCallOutputDevice(const SIPX_INST hInst, const char* szDevice) ; //@} /** @name Line / Identity Methods*/ //@{ /** * Adds a line appearance. A line appearance defines your address of record * and is used both as your "From" caller-id and as the public identity to * which you will receive calls for. Directing calls to a particular user * agent is achieved using registrations. * * @param hInst Instance pointer obtained by sipxInitialize. * @param szLineURL The address of record for the line identity. Can be * prepended with a Display Name. * e.g. - "Zaphod Beeblebrox" * @param phLine Pointer to a line handle. Upon success, a handle to the * newly added line is returned. * @param contactId Id of the desired contact record to use for this line. * The id refers to a Contact Record obtained by a call to * sipxConfigGetLocalContacts. The application can choose a * contact record of type LOCAL, NAT_MAPPED, CONFIG, or RELAY. * The Contact Type allows you to control whether the * user agent and media processing advertises the local address * (e.g. LOCAL contact of 10.1.1.x or * 192.168.x.x), the NAT-derived address to the target party, * or, local contact addresses of other types. * * @see sipxConfigGetLocalContacts */ SIPXTAPI_API SIPX_RESULT sipxLineAdd(const SIPX_INST hInst, const char* szLineURL, SIPX_LINE* phLine, SIPX_CONTACT_ID contactId = 0) ; /** * Adds an alias for a line definition. Line aliases are used to map an * inbound call request to an existing line definition. You should only * need to an a alias if your network infrastructure directs calls to this * user agent using multiple identities. For example, if user agent * registers as "sip:bandreasen\@example.com"; however, calls can also be * directed to you via an exention (e.g. sip:122\@example.com). * * If sipXtapi receives a call with an unknown line, you can still answer * and interact wtih the call; however, the line handle will be SIPX_LINE_NULL * in all event callbacks. Adding an aliases allows you to correlate another * line url with your line definition and receive real line handles with event * callbacks. * * Line aliases are not used for outbound calls. * * @see sipxConfigGetLocalContacts */ SIPXTAPI_API SIPX_RESULT sipxLineAddAlias(const SIPX_LINE hLine, const char* szLineURL) ; /** * Registers a line with the proxy server. Registrations will be re-registered * automatically, before they expire. * * Unless your user agent is designated a static IP address or DNS name and * that routing information is provisioned into a SIP server, you should * register the line by calling this function. * * Please unregister your line before calling sipxLineRemove. * * @param hLine Handle to a line appearance. Line handles are obtained by * creating a line using the sipxLineAdd function or by receiving * a line event notification. * @param bRegister true if Registration is desired, otherwise, an Unregister * is performed. */ SIPXTAPI_API SIPX_RESULT sipxLineRegister(const SIPX_LINE hLine, const bool bRegister); /** * Remove the designated line appearance. If the line was previous registered * using the sipxLineRegister API, please unregister the line and wait for the * unregistered event before calling sipxLineRemove. Otherwise, the line will * be removed without unregistering. * * @param hLine Handle to a line appearance. Line handles are obtained by * creating a line using the sipxLineAdd function or by receiving * a line event notification. */ SIPXTAPI_API SIPX_RESULT sipxLineRemove(SIPX_LINE hLine) ; /** * Adds authentication credentials to the designated line appearance. * Credentials are often required by registration services to verify that the * line is being used by the line appearance/address of record owner. * * @param hLine Handle to a line appearance. Line handles are obtained by * creating a line using the sipxLineAdd function or by receiving * a line event notification. * @param szUserID user id used for the line appearance. * @param szPasswd passwd used for the line appearance. * @param szRealm realm for which the user and passwd are valid. Supply * NULL for automatic realm. */ SIPXTAPI_API SIPX_RESULT sipxLineAddCredential(const SIPX_LINE hLine, const char* szUserID, const char* szPasswd, const char* szRealm) ; /** * Gets the active list of line identities. * * @param hInst Instance pointer obtained by sipxInitialize. * @param lines Pre-allocated array of line handles. * @param max Maximum number of lines to return. * @param actual Actual number of valid lines returned. */ SIPXTAPI_API SIPX_RESULT sipxLineGet(const SIPX_INST hInst, SIPX_LINE lines[], const size_t max, size_t& actual) ; /** * Get the Line URI for the designated line handle * * @param hLine Handle to a line appearance. Line handles are obtained by * creating a line using the sipxLineAdd function or by receiving * a line event notification. * @param szBuffer Buffer to place line URL. A NULL value will return * the amount of storage needed in nActual. * @param nBuffer Size of szBuffer in bytes (not to exceed) * @param nActual Actual number of bytes written */ SIPXTAPI_API SIPX_RESULT sipxLineGetURI(const SIPX_LINE hLine, char* szBuffer, const size_t nBuffer, size_t& nActual) ; /** * Get the contact ID for the designated line handle * * @param hLine Handle to a line appearance. Line handles are obtained by * creating a line using the sipxLineAdd function or by receiving * a line event notification. * @param contactId contact Id specified during line creation */ SIPXTAPI_API SIPX_RESULT sipxLineGetContactId(const SIPX_LINE hLine, SIPX_CONTACT_ID& contactId) ; /** * Find a line definition given a URI. * * @param hInst Instance pointer obtained by sipxInitialize. * @param szURI URI used to search for a line definition * @param hLine line handle if successful */ SIPXTAPI_API SIPX_RESULT sipxLineFindByURI(const SIPX_INST hInst, const char* szURI, SIPX_LINE& hLine) ; //@} /** @name Configuration Methods*/ //@{ /** * The sipxConfigEnableLog method enables logging for the sipXtapi API, * media processing, call processing, SIP stack, and OS abstraction layer. * Logging is disabled by default. The underlying framework makes no attempts * to bound the log file to a fixed size. * * Log Format: * time:event id:facility:priority:host name:task name:task id:process id:log message * * @param logLevel Designates the amount of detail includes in the log. See * SIPX_LOG_LEVEL for more details. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetLogLevel(SIPX_LOG_LEVEL logLevel) ; /** * The sipxConfigSetlogFile method sets the filename of the log file and * directs output to that file * * NOTE: At this time no validation is performed on the specified filename. * Please make sure the directories exist and the appropriate permissions * are available. * * @param szFilename The filename for the log file. Designated a NULL * filename will disable logging, however, threads/resources will not * be deallocated. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetLogFile(const char *szFilename) ; /** * Set a callback function to collect logging information. This function * directs logging output to the specified function. * * @param pCallback is a pointer to a callback function. This callback function * gets passed three strings, first string is the priority level, * second string is the source id of the subsystem that generated * the message, and the third string is the message itself. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetLogCallback(sipxLogCallback pCallback); /** * Enables GIPS tracing in sipXtapi (if bundled with sipXtapi). Log entries * are under the facility "VIDEOENGINE" and "VOICEENGINE" and are Base64 * encoded (to avoid issues with binary data. * * NOTE: Tracing must be enabled prior to setting up a call. * * @param hInst Instance pointer obtained by sipxInitialize. * @param bEnable true to enable GIPS tracing or false to disable. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableGIPSTracing(SIPX_INST hInst, bool bEnable) ; /** * Designate a callback routine as a microphone replacement or supplement. * The callback is invoked with microphone data and the data can be reviewed, * modified, replaced, or discarded. * * This callback proc must *NOT* block and must return data quickly. * Additionally, the method should not call any blocking function (i.e. IO * operations, malloc, new, etc). * * Data must be formatted as mono 16-bit signed PCM, little endian, 8000 * samples per second. The callback is handed 80 samples (10ms) of data at * a time. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetMicAudioHook(fnMicAudioHook hookProc) ; /** * Designate a callback routine for post-mixing audio data (e.g. to speaker * data). The hook may review, modify, replace, or discard data. * * This callback proc must *NOT* block and must return data quickly. * Additionally, the method should not call any blocking function (i.e. IO * operations, malloc, new, etc). * * Data must be formatted as mono 16-bit signed PCM, little endian, 8000 * samples per second. The callback is handed 80 samples (10ms) of data at * a time. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetSpkrAudioHook(fnSpkrAudioHook hookProc) ; /* * Set the period of time between stream (e.g. mic, RTP) energy * level notifications. * @ param */ SIPXTAPI_API SIPX_RESULT sipxConfigSetEnergyLevelNotificationPeriod(const SIPX_INST hInst, int periodMs); /** * Sets the User-Agent name to be used with outgoing SIP messages. * * @param hInst Instance pointer obtained by sipxInitialize. * @param szName The user-agent name. * @param bIncludePlatformName Indicates whether or not to append the * platform description onto the user agent name. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetUserAgentName(const SIPX_INST hInst, const char* szName, const bool bIncludePlatformName = true); /** * Defines the SIP proxy used for outbound requests. * * @param hInst Instance pointer obtained by sipxInitialize. * @param szProxy the new outbound proxy */ SIPXTAPI_API SIPX_RESULT sipxConfigSetOutboundProxy(const SIPX_INST hInst, const char* szProxy) ; /** * Modifies the timeout values used for DNS SRV lookups. In generally, * you shouldn't need to modified these, however, if you find yourself * in a situation where a router/network fails to send responses to * DNS SRV requests these values can be tweaked. Note, failing to send * responses is different then a receiving an no-such-animal response. *

* The default values are initialTimeout = 5 seconds, and 4 retries. The * time waited is doubled after each timeout, so with the default settings, * a single DNS SRV can block for 75 seconds (5 + 10 + 20 + 40). In general, * 4 DNS SRV requests are made for each hostname (e.g. domain.com): *

    *
  • _sip._udp.domain.com
  • *
  • _sip._tcp.domain.com
  • *
  • _sip._udp.domain.com.domain.com
  • *
  • _sip._tcp.domain.com.domain.com
  • *
* * If DNS response are dropped in the network (or your DNS server is down), * the API will block for 3 minutes. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetDnsSrvTimeouts(const int initialTimeoutInSecs, const int retries) ; /** * Specifies the time to wait for a REGISTER response before sending a * LINESTATE_REGISTER_FAILED (or LINESTATE_UNREGISTER_FAILED) message. * If not set, the user-agent will use a 4 second timeout. * * @param hInst Instance pointer obtained by sipxInitialize. * @param seconds The number of seconds to wait for a REGISTER response, before it is considered a failure. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetRegisterResponseWaitSeconds(const SIPX_INST hInst, const int seconds); /** * Specifies the time to wait before trying the next DNS SRV record. The user * agent will attempt to obtain DNS SRV resolutions for the child DNS SRV * records. This setting is the time allowed for attempting a lookup - if the * time expires without a lookup, then next child is attempted. * * @param hInst Instance pointer obtained by sipxInitialize. * @param failoverTimeoutInSecs Number of seconds until the next DNS SRV * record is tried. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetDnsSrvFailoverTimeout(const SIPX_INST hInst, const int failoverTimeoutInSecs); /** * Enable or disable the use of "rport". If rport is included on a via, * responses should be sent back to the originating port -- not what is * advertised as part of via. Additionally, the sip stack will not * receive messages sent to the originating port unless this is enabled. * * @param hInst Instance pointer obtained by sipxInitialize. * @param bEnable Enable or disable the use of rport. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableRport(const SIPX_INST hInst, const bool bEnable) ; /** * Enable or diable the use of IP and port provided in the response via (rport) for * mapping of NAT/public IP address and port in the contact database. By default * rport mapping is enabled. * * @param bEnable - true/false if IP address and port provided via rport should be * used for contact database NAT address mapping. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableRportMapping(const SIPX_INST hInst, const bool bEnable); /** * Specifies the expiration period for registration. After setting this * configuration, all subsequent REGISTER messages will be sent with the new * registration period. * * @param hInst Instance pointer obtained by sipxInitialize. * @param nRegisterExpirationSecs Number of seconds until the expiration of a * REGISTER message */ SIPXTAPI_API SIPX_RESULT sipxConfigSetRegisterExpiration(const SIPX_INST hInst, const int nRegisterExpirationSecs); /** * Specifies the expiration period for subscription. After setting this * configuration, all subsequent SUBSCRIBE messages will be sent with the new * subscribe period. * * @param hInst Instance pointer obtained by sipxInitialize. * @param nSubscribeExpirationSecs Number of seconds until the expiration of a * SUBSCRIBE message */ SIPXTAPI_API SIPX_RESULT sipxConfigSetSubscribeExpiration(const SIPX_INST hInst, const int nSubscribeExpirationSecs); /** * Enables STUN (Simple Traversal of UDP through NAT) support for both * UDP SIP signaling and UDP audio/video (RTP). STUN helps user agents * determine thier external IP address from the inside of NAT/Firewall. * This method should be invoked immediately after calling sipxInitialize * and before creating any lines or calls. Enabling STUN while calls are * setup should not effect the media path of existing calls. The "contact" * address uses for UDP signaling may change on the next request. * * TODO :: STUN conforms to IETF RFC/DRAFT XXXX with the following exceptions: * * @param hInst Instance pointer obtained by sipxInitialize * @param szServer The stun server that should be used for discovery. * @param iServerPort The port of the stun server that should be used for * discovery. * @param iKeepAliveInSecs This setting controls how often to refresh the stun * binding. The most aggressive NAT/Firewall solutions free port * mappings after 30 seconds of non-use. We recommend a value of 28 * seconds to be safe. * */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableStun(const SIPX_INST hInst, const char* szServer, int iServerPort, int iKeepAliveInSecs) ; /** * Disable the use of STUN. See sipxConfigEnableStun for details on STUN. * * @param hInst Instance pointer obtained by sipxInitialize. */ SIPXTAPI_API SIPX_RESULT sipxConfigDisableStun(const SIPX_INST hInst) ; /** * Enable TURN for support for UDP audio/video (RTP). TURN allows VoIP * communications while operating behind a symmetric NAT or firewall (cannot * only receive data from the same IP/port that you have sent to). * * This implementation is based on draft-rosenberg-midcom-turn-04. * * @param hInst Instance pointer obtained by sipxInitialize. * @param szServer The TURN server that should be used for relaying. * @param iServerPort The TURN sever port that should be used for relaying * @param szUsername TURN username for authentication * @param szPassword TURN password for authentication * @param iKeepAliveInSecs This setting controls how often to refresh the TURN * binding. The recommended value is 28 seconds. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableTurn(const SIPX_INST hInst, const char* szServer, const int iServerPort, const char* szUsername, const char* szPassword, const int iKeepAliveInSecs) ; /** * Disable the use of TURN. See sipxConfigEnableTurn for details TURN. * * @param hInst Instance pointer obtained by sipxInitialize. */ SIPXTAPI_API SIPX_RESULT sipxConfigDisableTurn(const SIPX_INST hInst) ; /** * Enables an ICE-like mechanism for determining connectivity of remote * parties dynamically. By default, ICE is disabled. * * The current sipXtapi implementation is a bastardization of * draft-ietf-mmusic-ice-04. In subsequent release, this will * conform to draft-ietf-mmusic-ice-05 or the latest draft. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableIce(const SIPX_INST hInst) ; /** * Disable the use of ICE. See sipxConfigEnableICE for details. * * @param hInst Instance pointer obtained by sipxInitialize. */ SIPXTAPI_API SIPX_RESULT sipxConfigDisableIce(const SIPX_INST hInst) ; /** * Add a signaling keep alive to a remote ip address. * * @param hInst Instance pointer obtained by sipxInitialize * @param contactId Contact ID used for the keep alive. sipXtapi will * send keep alives from the interface identified by the * contactId. Specify a contactId of -1 to send keep alives from * all interfaces. * @param type Designates the method of keep alives. * @param remoteIp Remote IP address used to send keep alives. The caller is * responsible for converting hostnames to IP address. * @param remotePort Remote port used to send keep alives. * @param keepAliveSecs The number of seconds to wait before resending. If * the value is <= 0, only one keep alive will be sent (calling * sipxConfigKeepAliveRemove will fail). * * @see sipxConfigGetLocalContacts */ SIPXTAPI_API SIPX_RESULT sipxConfigKeepAliveAdd(const SIPX_INST hInst, SIPX_CONTACT_ID contactId, SIPX_KEEPALIVE_TYPE type, const char* remoteIp, int remotePort, int keepAliveSecs) ; /** * Remove a signaling keepalive. * * @param hInst Instance pointer obtained by sipxInitialize * @param contactId Contact ID used for the keep alive. sipXtapi will * remove keep alives from the interface identified by the * contactId. Specify a contactId of -1 to remove keep alives from * all interfaces. * @param type Designates the method of keep alives. * @param remoteIp Remote IP address used to send keep alives. The caller is * responsible for converting hostnames to IP address. This value must * match what was specified in sipxConfigKeepAliveAdd. * @param remotePort Remote port used to send keep alives. * * @see sipxConfigGetLocalContacts */ SIPXTAPI_API SIPX_RESULT sipxConfigKeepAliveRemove(const SIPX_INST hInst, SIPX_CONTACT_ID contactId, SIPX_KEEPALIVE_TYPE type, const char* remoteIp, int remotePort) ; /** * Enable/disable sending of RFC 2833 DTMF tones. If disabled the tones * will be sent in-band (if in-band DTMF is enabled). RFC 2833 DTMF * is enabled by default. * * Generally, out-of-band DTMF should always be enabled. In-band DTMF * can be distorted and unrecognized by gateways/IVRs/ACDs when using * compressed codecs such as G729. By nature, many compressed codecs * are lossy and cannot regenerate DTMF signals. If you find that you * need to disable out-of-band DTMF (due to duplicate DTMF signals) on * another device, please consider reconfiguring that other device. * * This function is currently not implemented. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnable Enable or disable out-of-band DTMF tones. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableOutOfBandDTMF(const SIPX_INST hInst, const bool bEnable) ; /** * Enable/disable sending of in-band DTMF tones. In-band DTMF * is disabled by default. * * This function is currently not implemented. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnable Enable or disable in-band DTMF tones. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableInBandDTMF(const SIPX_INST hInst, const bool bEnable) ; /** * Enable or disable sending RTCP reports. By default, RTCP is enabled and * sends reports every ~5 seconds. RTCP is enabled by default. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnable Enable or disable sending of RTCP reports. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableRTCP(const SIPX_INST hInst, const bool bEnable) ; /** * Enables/disables sending of DNS SRV request for all sipXtapi instances. * DNS SRV is enabled by default. * * @param bEnable Enable or disable DNS SRV resolution. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableDnsSrv(const bool bEnable); /** * Determines if sending of out-of-band DTMF tones is enabled or disabled. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnable Out-of-band DTMF tones enabled or disabled. */ SIPXTAPI_API SIPX_RESULT sipxConfigIsOutOfBandDTMFEnabled(const SIPX_INST hInst, bool& bEnable) ; /** * Determines if sending of in-band DTMF tones is enabled or disabled. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnable in-band DTMF tones enabled or disabled. */ SIPXTAPI_API SIPX_RESULT sipxConfigIsInBandDTMFEnabled(const SIPX_INST hInst, bool& bEnable) ; /** * Get the sipXtapi API version string. * * @param szVersion Buffer to store the version string. A zero-terminated * string will be copied into this buffer on success. * @param nBuffer Size of szBuffer in bytes (not to exceed). A size of 48 bytes * should be sufficient in most cases. */ SIPXTAPI_API SIPX_RESULT sipxConfigGetVersion(char* szVersion, const size_t nBuffer) ; /** * Get the local UDP port for SIP signaling. The port is supplied in the * call to sipXinitialize; however, the port may be allocated dynamically. * This method will return SIPX_RESULT_SUCCESS if able to return the port * value. SIPX_RESULT_FAILURE is returned if the protocol is not enabled. * * @param hInst Instance pointer obtained by sipxInitialize * @param pPort Pointer to a port number. This value must not be NULL. * */ SIPXTAPI_API SIPX_RESULT sipxConfigGetLocalSipUdpPort(SIPX_INST hInst, int* pPort) ; /** * Add a contact using the given IP address and port. This can be used for * IP address spoofing in the SIP Contact and SDP/RTP c address. * * @param szSipContactAddress - IP address to use in SIP Contact in initial * REGISTER and INVITE requests as well as the c field in the SDP. * @param iSipContactPort - port to use in the SIP Contact headers. * @param iNewContactId - contactId to use to specify this contact should * be used (see @sipxLineAdd, @sipxCallCreate, @sipxCallConnect). */ SIPXTAPI_API SIPX_RESULT sipxConfigAddContact(const SIPX_INST hInst, const char* szSipContactAddress, const int iSipContactPort, SIPX_CONTACT_ID& iNewContactId); /** * Get the local TCP port for SIP signaling. The port is supplied in the * call to sipXinitialize; however, the port may be allocated dynamically. * This method will return SIPX_RESULT_SUCCESS if able to return the port * value. SIPX_RESULT_FAILURE is returned if the protocol is not enabled. * * @param hInst Instance pointer obtained by sipxInitialize * @param pPort Pointer to a port number. This value must not be NULL. * */ SIPXTAPI_API SIPX_RESULT sipxConfigGetLocalSipTcpPort(SIPX_INST hInst, int* pPort) ; /** * Get the local TLS port for SIP signaling. The port is supplied in the * call to sipXinitialize; however, the port may be allocated dynamically. * This method will return SIPX_RESULT_SUCCESS if able to return the port * value. SIPX_RESULT_FAILURE is returned if the protocol is not enabled. * * @param hInst Instance pointer obtained by sipxInitialize * @param pPort Pointer to a port number. This value must not be NULL. * */ SIPXTAPI_API SIPX_RESULT sipxConfigGetLocalSipTlsPort(SIPX_INST hInst, int* pPort) ; /** * Set the preferred bandwidth requirement for codec selection. Whenever * possible a codec matching that requirement will be selected for a call. * This method will return SIPX_RESULT_SUCCESS if able to set the audio codec * preferences. SIPX_RESULT_FAILURE is returned if the preference is not set. * * @param hInst Instance pointer obtained by sipxInitialize * @param bandWidth Valid bandwidth requirements are AUDIO_CODEC_BW_LOW, * AUDIO_CODEC_BW_NORMAL, and AUDIO_CODEC_BW_HIGH. * */ SIPXTAPI_API SIPX_RESULT sipxConfigSetAudioCodecPreferences(const SIPX_INST hInst, SIPX_AUDIO_BANDWIDTH_ID bandWidth) ; /** * Set the codec preference order by name. The codec name(s) must match one of * the supported codecs otherwise this function will fail. * This method will return SIPX_RESULT_SUCCESS if able to set the audio codec. * SIPX_RESULT_FAILURE is returned if the codec is not set. * * @param hInst Instance pointer obtained by sipxInitialize * @param szCodecName space delimited list of codec names. * Note: TELEPHONE-EVENT is implicitly included * */ SIPXTAPI_API SIPX_RESULT sipxConfigSetAudioCodecByName(const SIPX_INST hInst, const char* szCodecName) ; /** * Get the current codec preference. * * @param hInst Instance pointer obtained by sipxInitialize * @param pBandWidth pointer to an integer that will contain AUDIO_CODEC_BW_LOW, * AUDIO_CODEC_BW_NORMAL, or AUDIO_CODEC_BW_HIGH. AUDIO_CODEC_BW_CUSTOM * will be returned if a specific codec was et using the * sipxConfigSetAudioCodecByName function. */ SIPXTAPI_API SIPX_RESULT sipxConfigGetAudioCodecPreferences(const SIPX_INST hInst, SIPX_AUDIO_BANDWIDTH_ID *pBandWidth); /** * Get the number of audio codecs. * This method will return SIPX_RESULT_SUCCESS if able to set the audio codec * preferences. SIPX_RESULT_FAILURE is returned if the number of codecs can * no be retrieved. * * @param hInst Instance pointer obtained by sipxInitialize * @param pNumCodecs Pointer to the number of codecs. This value must not be NULL. * */ SIPXTAPI_API SIPX_RESULT sipxConfigGetNumAudioCodecs(const SIPX_INST hInst, int* pNumCodecs) ; /** * Get the audio codec at a certain index in the list of codecs. Use this * function in conjunction with sipxConfigGetNumAudioCodecs to enumerate * the list of audio codecs. * This method will return SIPX_RESULT_SUCCESS if able to set the audio codec * preferences. SIPX_RESULT_FAILURE is returned if the audio codec can not * be retrieved. * * @param hInst Instance pointer obtained by sipxInitialize * @param index Index in the list of codecs * @param pCodec SIPX_AUDIO_CODEC structure that holds information * (name, bandwidth requirement) about the codec. * */ SIPXTAPI_API SIPX_RESULT sipxConfigGetAudioCodec(const SIPX_INST hInst, const int index, SIPX_AUDIO_CODEC* pCodec) ; /** * Set the bandwidth parameters for video codecs.Depending on the bandwidth * parameter that is passed in the settings will be set to: * * VIDEO_CODEC_BW_LOW bitrate 5 kbps, framerate 10 fps * VIDEO_CODEC_BW_NORMAL bitrate 70 kbps, framerate is what it was set to * with sipxConfigSetVideoParameters or 30 if not set. * VIDEO_CODEC_BW_HIGH bitrate 400 kbps, framerate is what it was set to * with sipxConfigSetVideoParameters or 30 if not set. * * This method will return SIPX_RESULT_SUCCESS if able to set the video codec * preferences. SIPX_RESULT_FAILURE is returned if the preference is not set. * * @param hInst Instance pointer obtained by sipxInitialize * @param bandWidth Valid bandwidth requirements are VIDEO_CODEC_BW_LOW, * VIDEO_CODEC_BW_NORMAL, and VIDEO_CODEC_BW_HIGH. * * @see sipxConfigSetVideoParameters */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoBandwidth(const SIPX_INST hInst, SIPX_VIDEO_BANDWIDTH_ID bandWidth); /** * Gets the list of video capture devices. * * @param hInst Instance pointer obtained by sipxInitialize * @param arrSzCaptureDevices Array of character arrays to be populated * by this function call. * @param nDeviceStringLength Length of buffer in arrSzCaptureDevice array. * @param nArrayLength Number of strings (of length nDeviceStringLength) in * the arrSzCaptureDevice array. */ SIPXTAPI_API SIPX_RESULT sipxConfigGetVideoCaptureDevices(const SIPX_INST hInst, char **arrSzCaptureDevices, int nDeviceStringLength, int nArrayLength); /** * Gets the current video capture device. * * @param hInst Instance pointer obtained by sipxInitialize * @param szCaptureDevice Character array to be populated by this function * call. * @param nLength Max length of szCaptureDevice buffer. * */ SIPXTAPI_API SIPX_RESULT sipxConfigGetVideoCaptureDevice(const SIPX_INST hInst, char* szCaptureDevice, int nLength); /** * Sets the video capture device. * * @param hInst Instance pointer obtained by sipxInitialize * @param szCaptureDevice Pointer to a character array containing the * name of the desired video capture device. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoCaptureDevice(const SIPX_INST hInst, const char* szCaptureDevice); /** * Set the codec by name. The name must match one of the supported codecs * otherwise this function will fail. * This method will return SIPX_RESULT_SUCCESS if able to set the video codec. * SIPX_RESULT_FAILURE is returned if the codec is not set. * * @param hInst Instance pointer obtained by sipxInitialize * @param szCodecName codec name * */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoCodecByName(const SIPX_INST hInst, const char* szCodecName) ; /** * Reset the codec list if it was modified by sipxConfigSetVideoCodecByName. This * resets the selection to a full codec list. * This method will return SIPX_RESULT_SUCCESS if able to set the audio codec. * SIPX_RESULT_FAILURE is returned if the codec is not set. * * @param hInst Instance pointer obtained by sipxInitialize * */ SIPXTAPI_API SIPX_RESULT sipxConfigResetVideoCodecs(const SIPX_INST hInst); /** * Get the current codec preference. * * @param hInst Instance pointer obtained by sipxInitialize * @param pBandWidth pointer to an integer that will contain AUDIO_CODEC_BW_LOW, * AUDIO_CODEC_BW_NORMAL, or AUDIO_CODEC_BW_HIGH. AUDIO_CODEC_BW_CUSTOM * will be returned if a specific codec was set using the * sipxConfigSetVideoCodecByName function. */ SIPXTAPI_API SIPX_RESULT sipxConfigGetVideoCodecPreferences(const SIPX_INST hInst, SIPX_VIDEO_BANDWIDTH_ID *pBandWidth); /** * Get the number of video codecs. * This method will return SIPX_RESULT_SUCCESS if able to set the audio codec * preferences. SIPX_RESULT_FAILURE is returned if the number of codecs can * no be retrieved. * * @param hInst Instance pointer obtained by sipxInitialize * @param pNumCodecs Pointer to the number of codecs. This value must not be NULL. * */ SIPXTAPI_API SIPX_RESULT sipxConfigGetNumVideoCodecs(const SIPX_INST hInst, int* pNumCodecs) ; /** * Set the supported video format * This method will limit the supported video format to either * VIDEO_FORMAT_CIF (352x288), VIDEO_FORMAT_QCIF (176x144), * VIDEO_FORMAT_SQCIF (128x92), or VIDEO_FORMAT_QVGA (320x240). * The method will return SIPX_RESULT_SUCCESS if it is able to set the video * format, SIPX_RESULT_FAILURE is returned if the video format can not be set. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoFormat(const SIPX_INST hInst, SIPX_VIDEO_FORMAT videoFormat); /** * Get the video codec at a certain index in the list of codecs. Use this * function in conjunction with sipxConfigGetNumVideoCodecs to enumerate * the list of video codecs. * This method will return SIPX_RESULT_SUCCESS if able to set the video codec * preferences. SIPX_RESULT_FAILURE is returned if the video codec can not * be retrieved. * * @param hInst Instance pointer obtained by sipxInitialize * @param index Index in the list of codecs * @param pCodec SIPX_VIDEO_CODEC structure that holds information * (name, bandwidth requirement) about the codec. * */ SIPXTAPI_API SIPX_RESULT sipxConfigGetVideoCodec(const SIPX_INST hInst, const int index, SIPX_VIDEO_CODEC* pCodec) ; /** * Get the local contact address available for outbound/inbound signaling and * audio. The local contact addresses will always include the local IP * addresses. The local contact addresses may also include external NAT- * derived addresses (e.g. STUN). See the definition of SIPX_CONTACT_ADDRESS * for more details on the structure. * * Determining which contact address to use depends on your network topology. * If you have a proxy/edge proxy within the same firewall/NAT space, you can * use the LOCAL UDP, TCP, or TLS contact type for your calls. If your * proxy resides outside of the firewall/NAT space, you should use the * NAT_MAPPED or RELAY contact type (UDP only). Both NAT_MAPPED and RELAY * use your STUN-derived IP address, however RELAY requests TURN for media * paths. * * @param hInst Instance pointer obtained by sipxInitialize * @param addresses A pre-allocated list of SIPX_CONTACT_ADDRESS * structures. This data will be filled in by the API call. * @param nMaxAddresses The maximum number of addresses supplied by the * addresses parameter. * @param nActualAddresses The actual number of addresses populated in * the addresses parameter. */ SIPXTAPI_API SIPX_RESULT sipxConfigGetLocalContacts(const SIPX_INST hInst, SIPX_CONTACT_ADDRESS addresses[], size_t nMaxAddresses, size_t& nActualAddresses) ; /** * Get our local ip/port combination for the designated remote ip/port. This * API will look at all of the stun and/or SIP message results to see if a * NAT binding exists for this particular host. If using a proxy server, * this is generally never needed, however, in peer-to-peer modes this can * sometimes help you get through NATs when using out-of-band registrars / * signaling helpers (not recommended -- use a proxy instead). * * For this API to be useful, you need to add a keepalive to the remote host * prior to calling this API. This may optionally block if a keep-alive request * has been started, but we are waiting for a response. * * @param hInst Instance pointer obtained by sipxInitialize * @param szRemoteIp IP of remote party * @param iRemotePort port or remote party * @param szContactIp Buffer to place local contact IP if successful * @param nContactIpLength Length of szContactIp buffer * @param iContactPort Int to place contact port * @param iTimeoutMs Timeout in MS. Values of 0 (or less) signal not to * block. Any other value is rounded up to multiple of 50ms. For * VoIP, a value of 500ms seems plenty (latency longer than 300ms * will result in a fairly bad audio experience). */ SIPXTAPI_API SIPX_RESULT sipxConfigGetLocalFeedbackAddress(const SIPX_INST hInst, const char* szRemoteIp, const int iRemotePort, char* szContactIp, size_t nContactIpLength, int& iContactPort, int iTimeoutMs) ; /** * Populates an array of IP Addresses in char* form. The array must be preallocated to * contain MAX_IP_ADDRESSES elements. * * WARNING: THIS API IS DEPRECATED AND WILL CHANGE IN FUTURE REVISIONS * * @param arrAddresses Pre-allocated array to be popluated with ip addresses. * @param arrAddressAdapter For each record in arrAddresses, there is a corresponding record, * with the same index, in arrAddressAdpater which represents the * "sipx adapter name" for that address * @param numAddresses Input: Size of the preallocated arrays. * Output: Number of IPs found by the system. */ SIPXTAPI_API SIPX_RESULT sipxConfigGetAllLocalNetworkIps(const char* arrAddresses[], const char* arrAddressAdapter[], int &numAddresses); /** * Set security parameters for an instance of sipXtapi. * @deprecated These should be set using sipxInitialize. * * @param hInst Instance pointer obtained by sipxInitialize * @param szDbLocation The directory in which the certificate database resides. * @param szMyCertNickname The local user's certificate nickname, for database lookup. * @param szDbPassword The password for the certificated database. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetSecurityParameters(const SIPX_INST hInst, const char* szDbLocation, const char* szMyCertNickname, const char* szDbPassword); /** * Enables/Disables use of short field names in sip messages. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnabled True if short names, false if long names */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableSipShortNames(const SIPX_INST hInst, const bool bEnabled); /** * Enables/Disables use of date header in sip messages. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnabled True if date header, false if no date header */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableSipDateHeader(const SIPX_INST hInst, const bool bEnabled); /** * Enables/Disables use of allow header in sip messages. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnabled True if allow header, false if no allow header */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableSipAllowHeader(const SIPX_INST hInst, const bool bEnabled); /** * Sets the Accept Language used in sip messages. e.g. - "EN" * * @param hInst Instance pointer obtained by sipxInitialize * @param szLanguage - Accept Language string */ SIPXTAPI_API SIPX_RESULT sipxConfigSetSipAcceptLanguage(const SIPX_INST hInst, const char* szLanguage); /** * Sets the location header for SIP messages. The location header will be * included in SIP requests and responses. You can disable the location * header on a call-by-call basis in the by changing the bEnableLocationHeader * flag on sipxCallAccept, sipxCallConnect, and sipxConferenceAdd methods. * * @param hInst Instance pointer obtained by sipxInitialize * @param szHeader - Location header * * @see sipxCallAccept * @see sipxCallConnect * @see sipxConferenceAdd */ SIPXTAPI_API SIPX_RESULT sipxConfigSetLocationHeader(const SIPX_INST hInst, const char* szHeader); /** * Set the connection idle timeout. If a media connection is idle for this * threshold, a SILENCE event will be fired to the application layer. * * Applications may decide to tear down the call after receiving this event * under the assumption that the remote party is gone away. Be careful when * using codecs that support silence suppression -- Some implementations * continue to send RTP heartbeats, however, others will not send any data * and may appear to be dead. * * @param hInst Instance pointer obtained by sipxInitialize * @param idleTimeout The time in seconds that a socket is idle before a * MEDIA_REMOTE_SILENT event is fired. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetConnectionIdleTimeout(const SIPX_INST hInst, const int idleTimeout); /** * Call this function to prepare a sipXtapi instance for a * system hibernation. This function is not thread-safe. * * @param hInst Instance pointer obtained by sipxInitialize */ SIPXTAPI_API SIPX_RESULT sipxConfigPrepareToHibernate(const SIPX_INST hInst); /** * Call this function upon returning from a system hibernation. * This function is not thread-safe. * @param hInst Instance pointer obtained by sipxInitialize */ SIPXTAPI_API SIPX_RESULT sipxConfigUnHibernate(const SIPX_INST hInst); /** * Enables RTP streaming over TCP. Enabling this feature * allows the application to use RTP streaming over TCP or UDP. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnable True allows RTP-over-TCP, false disallows it. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableRtpOverTcp(const SIPX_INST hInst, bool bEnable); /** * Sets the display object for the "video preview". * * @param hInst Instance pointer obtained by sipxInitialize * @param pDisplay Pointer to a video preview display object. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoPreviewDisplay(const SIPX_INST hInst, SIPX_VIDEO_DISPLAY* const pDisplay); /** * Updates the Preview window with a new frame buffer. Should be called * when the window receives a PAINT message. * * @param hInst Instance pointer obtained by sipxInitialize * @param hWnd Window handle of the video preview window. */ SIPXTAPI_API SIPX_RESULT sipxConfigUpdatePreviewWindow(const SIPX_INST hInst, const SIPX_WINDOW_HANDLE hWnd); /** * Sets the video quality. * * @param hInst Instance pointer obtained by sipxInitialize * @param quality Id setting the video quality. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoQuality(const SIPX_INST hInst, const SIPX_VIDEO_QUALITY_ID quality); /** * Sets the bit rate and frame rate parameters for video. * * @param hInst Instance pointer obtained by sipxInitialize * @param bitRate Bit rate parameter in kbps * @param frameRate Frame rate parameter frames per second */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoParameters(const SIPX_INST hInst, const int bitRate, const int frameRate); /** * Sets the video bitrate * * @param hInst Instance pointer obtained by sipxInitialize * @param bitRate Bit rate parameter */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoBitrate(const SIPX_INST hInst, const int bitRate); /** * Sets the video framerate * * @param hInst Instance pointer obtained by sipxInitialize * @param frameRate Frame rate parameter */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoFramerate(const SIPX_INST hInst, const int frameRate); /** * Set the cpu usage * * @param hInst Instance pointer obtained by sipxInitialize * @param cpuUsage CPU usage in percent */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoCpuUsage(const SIPX_INST hInst, const int cpuUsage); /** * Subscribe for NOTIFY events which may be published by another end-point or * server. * * sipXtapi will automatically refresh subscriptions until * sipxConfigUnsubscribe is called. Please make sure you call * sipxCallUnsubscribe before tearing down your instance of sipXtapi. * * @param hInst Instance pointer obtained by sipxInitialize * @param hLine Line Identity for the outbound call. The line identity * helps defines the "From" caller-id. * @param szTargetUrl The Url of the publishing end-point. * @param szEventType A string representing the type of event that can be * published. This string is used to populate the "Event" header in * the SIP SUBSCRIBE request. For example, if checking voicemail * status, your would use "message-summary". * @param szAcceptType A string representing the types of NOTIFY events that * this client will accept. This string is used to populate the * "Accept" header in the SIP SUBSCRIBE request. For example, if * checking voicemail status, you would use * "application/simple-message-summary" * @param contactId Id of the desired contact record to use for this call. * The id refers to a Contact Record obtained by a call to * sipxConfigGetLocalContacts. The application can choose a * contact record of type LOCAL, NAT_MAPPED, CONFIG, or RELAY. * The Contact Type allows you to control whether the * user agent and media processing advertises the local address * (e.g. LOCAL contact of 10.1.1.x or * 192.168.x.x), the NAT-derived address to the target party, * or, local contact addresses of other types. * @param phSub Pointer to a subscription handle whose value is set by this * funtion. This handle allows you to cancel the subscription and * differeniate between NOTIFY events. */ SIPXTAPI_API SIPX_RESULT sipxConfigSubscribe(const SIPX_INST hInst, const SIPX_LINE hLine, const char* szTargetUrl, const char* szEventType, const char* szAcceptType, const SIPX_CONTACT_ID contactId, SIPX_SUB* phSub); /** * Unsubscribe from previously subscribed NOTIFY events. This method will * send another subscription request with an expires time of 0 (zero) to end * your subscription. * * @param hSub The subscription handle obtained from the call to * sipxConfigSubscribe. */ SIPXTAPI_API SIPX_RESULT sipxConfigUnsubscribe(const SIPX_SUB hSub); /** * Associates an external transport mechanism for SIP signaling with * the given instance. * * @param hInst An instance handle obtained from sipxInitialize. * @param hTransport Reference to a SIPX_TRANSPORT handle. This function will * assign a value to the referenced handle. * @param bIsReliable If false, indicates that SIPxua should retry external transport * writes in case of response timeouts. If true, SIPxua will not attempt retries * in case of a response timeouts. For connection oriented transport (like TCP), * bIsReliable should be true, for packet oriented transport (like UDP), * bIsReliable should be false. * @param szTransport Transport type string to be used in SIP URIs. * For example, passing in a szTransport of "flibble" will cause the * transport tag to be added to the URI like so: * "sip:mickey\@example.com;transport=flibble" * @param szLocalIP IP address which is the source address for the write. * @param iLocalPort Port value from which the data will be sent. * @param writeProc Function pointer to the callback for writing data * using the transport mechanism. * @param szLocalRoutingId A local routing id pass back to the write proc callback. * @param pUserData User data passed back to the write proc. */ SIPXTAPI_API SIPX_RESULT sipxConfigExternalTransportAdd(SIPX_INST const hInst, SIPX_TRANSPORT& hTransport, const bool bIsReliable, const char* szTransport, const char* szLocalIP, const int iLocalPort, SIPX_TRANSPORT_WRITE_PROC writeProc, const char* szLocalRoutingId, const void* pUserData = NULL) ; /** * Removes an external transport mechanism from the given instance. * Will fail if transport in use. * * @param hTransport Handle to the external transport object. Obtained via * a call to sipxConfigExternalTransportAdd */ SIPXTAPI_API SIPX_RESULT sipxConfigExternalTransportRemove(const SIPX_TRANSPORT hTransport); /** * The external transport mechanism can be configured to route by user or by * destination ip/port. User is the default. * * @param hTransport Handle to the external transport object. Obtained via a * call to sipxConfigExternalTransportAdd * @param bRouteByUser true to route by user (default), false to route by * destination ip/port. */ SIPXTAPI_API SIPX_RESULT sipxConfigExternalTransportRouteByUser(const SIPX_TRANSPORT hTransport, bool bRouteByUser) ; /** * Called by the application when it receives a complete SIP message via * it's external transport mechanism and want to pass it along to sipXtapi. * The application is responsible for * preparing the Data so that it is composed of a single and complete * SIP message. * * @param hTransport Handle to the external transport object. Obtained via * a call to sipxConfigExternalTransportAdd * @param szSourceIP IP address which was the source of the data which was read. * @param iSourcePort Port value from which the data was sent. * @param szLocalIP Local IP address on which the data was received. * @param iLocalPort Local port value on which the data was received. * @param pData Pointer to the data which was received, which should point to * a single and complete SIP message. * @param nData Size of the data which was received. */ SIPXTAPI_API SIPX_RESULT sipxConfigExternalTransportHandleMessage(const SIPX_TRANSPORT hTransport, const char* szSourceIP, const int iSourcePort, const char* szLocalIP, const int iLocalPort, const void* pData, const size_t nData); /** * Sets the SIP target URL for voice quality reports. Voice Quality reports * are sent at the completion of each call and give details on the voice * quality (latency, noise, MOS scores, etc). Presently, this is not * implemented in the open source version. * * This must be enabled prior to creating a call or receiving a new call * indiciation. Likewise, changes will not take effect for existing calls. * * @param hInst An instance handle obtained from sipxInitialize. * @param szServer Target SIP URL for the voice quality reports. A * value of NULL will disable voice quality reports. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVoiceQualityServer(const SIPX_INST hInst, const char* szServer) ; //@} /** @name Utility Functions */ //@{ /** * Simple utility function to parse the username, host, and port from * a URL. All url, field, and header parameters are ignored. You may also * specify NULL for any parameters (except szUrl) which are not needed. * Lastly, the caller must allocate enough storage space for each url * component -- if in doubt use the length of the supplied szUrl. */ SIPXTAPI_API SIPX_RESULT sipxUtilUrlParse(const char* szUrl, char* szUsername, char* szHostname, int* iPort) ; /** * Simple utility function to parse the display name from a SIP URL. */ SIPXTAPI_API SIPX_RESULT sipxUtilUrlGetDisplayName(const char* szUrl, char* szDisplayName, size_t nDisplayName) ; /** * Simple utility function to update a URL. If the szUrl isn't large enough, * or is NULL, this function will fail, however, the nUrl will contained the * required size in bytes. * * To leave an existing component unchanged, use NULL for strings and -1 for * ports. */ SIPXTAPI_API SIPX_RESULT sipxUtilUrlUpdate(char* szUrl, size_t & nUrl, const char* szNewUsername, const char* szNewHostname, const int iNewPort) ; /** * Get the Nth named url parameter from the designated url. * * @param szUrl The url to parse * @param szParamName Name of the url parameter * @param nParamIndex Index of the url parameter (zero-based). This is used * if you have multiple url parameters with the same name -- otherwise, * you should use 0. * @param szParamValue Buffer to place parameter value * @param nParamValue size of parameter value buffer (szParamValue) */ SIPXTAPI_API SIPX_RESULT sipxUtilUrlGetUrlParam(const char* szUrl, const char* szParamName, size_t nParamIndex, char* szParamValue, size_t nParamValue) ; //@} #endif // _sipXtapi_h_ sipxtapi-3.3.0~test17/sipXtackLib/include/tapi/sipXtapiEvents.h0000644000175000017500000017415012205613256025344 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 Robert J. Andreasen, Jr. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// /** * @file sipXtapiEvents.h * sipXtapi event declarations * * The sipXtapiEvents.h header file defines all of the events fired as part of * sipXtapi. Event categories include call state events, line state events, * SIP info events, SIP subscription events, configuration events, security * events, media events, and keepalive events. * * Each event notification is comprised of a event type and a cause code. * The event type identifies a state transition (e.g. from call connected to * call disconnected. The cause identifies the reason for the change (e.g. * someone hung up). * * @see sipxEventListenerAdd * @see sipxEventListenerRemove * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ #ifndef _SIPXTAPIEVENT_H #define _SIPXTAPIEVENT_H // SYSTEM INCLUDES // APPLICATION INCLUDES #include "sipXtapi.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // FORWARD DECLARATIONS /** * Enum with all of the possible event types. */ typedef enum SIPX_EVENT_CATEGORY { EVENT_CATEGORY_CALLSTATE, /**< CALLSTATE events signify a change in state of a call. States range from the notification of a new call to ringing to connection established to changes in audio state (starting sending, stop sending) to termination of a call. */ EVENT_CATEGORY_LINESTATE, /**< LINESTATE events indicate changes in the status of a line appearance. Lines identify inbound and outbound identities and can be either provisioned (hardcoded) or configured to automatically register with a registrar. Lines also encapsulate the authentication criteria needed for dynamic registrations. */ EVENT_CATEGORY_INFO_STATUS, /**< INFO_STATUS events are sent when the application requests sipXtapi to send an INFO message to another user agent. The status event includes the response for the INFO method. Application developers should look at this event to determine the outcome of the INFO message. */ EVENT_CATEGORY_INFO, /**< INFO events are sent to the application whenever an INFO message is received by the sipXtapi user agent. INFO messages are sent to a specific call. sipXtapi will automatically acknowledges the INFO message at the protocol layer. */ EVENT_CATEGORY_SUB_STATUS, /**< SUB_STATUS events are sent to the application layer for information on the subscription state (e.g. OK, Expired). */ EVENT_CATEGORY_NOTIFY, /**< NOTIFY evens are send to the application layer after a remote publisher has sent data to the application. The application layer can retrieve the data from this event. */ EVENT_CATEGORY_CONFIG, /**< CONFIG events signify changes in configuration. For example, when requesting STUN support, a notification is sent with the STUN outcome (either SUCCESS or FAILURE) */ EVENT_CATEGORY_SECURITY, /**< SECURITY events signify occurences in call security processing. These events are only sent when using S/MIME or TLS. */ EVENT_CATEGORY_MEDIA, /**< MEDIA events signify changes in the audio state for sipXtapi or a particular call. */ EVENT_CATEGORY_KEEPALIVE /**< KEEPALIVE events signal when a keepalive is started/stopped/fails. A feedback event will report back your NAT-mapped IP address in some cases. @see SIPX_KEEPALIVE_TYPE for more information.*/ } SIPX_EVENT_CATEGORY; /** * VALID_SIPX_EVENT_CATEGORY utility macro to validate if an event category * is valid (within expected range). */ #define VALID_SIPX_EVENT_CATEGORY(x) (((x) >= EVENT_CATEGORY_CALLSTATE) && ((x) <= EVENT_CATEGORY_KEEPALIVE)) /** * Signature for event callback/observer. Application developers should * not block this event callback thread -- You should re-post these events * to your own thread context for handling if you require blocking and/or * heavy prorcessing. The sipxDuplicateEvent and sipxFreeDuplicatedEvent * methods are available to copy the event callback data (The data is only * available for the duration of the callback). For example, upon receiving * the callback, copy the data using sipxDuplicateEvent(...), post the * copied data to your event callback, process it, and lastly free the event * data using sipxFreeDuplicatedEvent(...). * * The application developer must look at the SIPX_EVENT_CATEGORY and then * cast the pInfo method to the appropriate structure: * *
 * EVENT_CATEGORY_CALLSTATE:   pCallInfo = (SIPX_CALLSTATE_INFO*) pInfo ;
 * EVENT_CATEGORY_LINESTATE:   pLineInfo = (SIPX_LINESTATE_INFO*) pInfo ;
 * EVENT_CATEGORY_INFO_STATUS: pInfoStatus = (SIPX_INFOSTATUS_INFO*) pInfo ;
 * EVENT_CATEGORY_INFO:        pInfoInfo = (SIPX_INFO_INFO*) pInfo ;
 * EVENT_CATEGORY_SUB_STATUS:  pSubInfo = (SIPX_SUBSTATUS_INFO*) pInfo ;
 * EVENT_CATEGORY_NOTIFY:      pNotifyInfo = (SIPX_NOTIFY_INFO*) pInfo ;
 * EVENT_CATEGORY_CONFIG:      pConfigInfo - (SIPX_CONFIG_INFO*) pInfo ;
 * EVENT_CATEGORY_SECURITY:    pSecInfo = (SIPX_SECURITY_INFO*) pInfo ;
 * EVENT_CATEGORY_MEDIA:       pMediaInfo = (SIPX_MEDIA_INFO*) pInfo ;
 * 
* * Please see the SIPX_EVENT_CATEGORY and structure definitions for details. * * @param category The category of the event (call, line, subscription, notify, etc.). * @param pInfo Pointer to the event info structure. Depending on the event * type, the application layer needs to cast this parameter to the * appropriate structure. * @param pUserData User data provided when listener was added */ typedef bool (SIPX_CALLING_CONVENTION *SIPX_EVENT_CALLBACK_PROC)(SIPX_EVENT_CATEGORY category, void* pInfo, void* pUserData); /** * Major call state events identify significant changes in the state of a * call. * * Below you will find state diagrams that show the typical event transitions * for both outbound and inbound calls. * * @image html callevents_inbound.gif * * Figure 1: Event flows for an inbound call (received call) * * @image html callevents_outbound.gif * * Figure 2: Event flows for an outbound call (placed call) */ typedef enum SIPX_CALLSTATE_EVENT { CALLSTATE_UNKNOWN = 0, /**< An UNKNOWN event is generated when the state for a call is no longer known. This is generally an error condition; see the minor event for specific causes. */ CALLSTATE_NEWCALL = 1000, /**< The NEWCALL event indicates that a new call has been created automatically by the sipXtapi. This event is most frequently generated in response to an inbound call request. */ CALLSTATE_DIALTONE = 2000, /**< The DIALTONE event indicates that a new call has been created for the purpose of placing an outbound call. The application layer should determine if it needs to simulate dial tone for the end user. */ CALLSTATE_REMOTE_OFFERING = 2500, /**< The REMOTE_OFFERING event indicates that a call setup invitation has been sent to the remote party. The invitation may or may not every receive a response. If a response is not received in a timely manor, sipXtapi will move the call into a disconnected state. If calling another sipXtapi user agent, the reciprocal state is OFFER. */ CALLSTATE_REMOTE_ALERTING = 3000, /**< The REMOTE_ALERTING event indicates that a call setup invitation has been accepted and the end user is in the alerting state (ringing). Depending on the SIP configuration, end points, and proxy servers involved, this event should only last for 3 minutes. Afterwards, the state will automatically move to DISCONNECTED. If calling another sipXtapi user agent, the reciprocate state is ALERTING. Pay attention to the cause code for this event. If the cause code is "CALLSTATE_CAUSE_EARLY_MEDIA", the remote the party is sending early media (e.g. gateway is producing ringback or audio feedback). In this case, the user agent should not produce local ringback. */ CALLSTATE_CONNECTED = 4000, /**< The CONNECTED state indicates that call has been setup between the local and remote party. Network audio should be flowing provided and the microphone and speakers should be engaged. */ CALLSTATE_BRIDGED = 5000, /** The BRIDGED state indicates that a call is active, however, the local microphone/speaker are not engaged. If this call is part of a conference, the party will be able to talk with other BRIDGED conference parties. Application developers can still play and record media. */ CALLSTATE_HELD = 6000, /** The HELD state indicates that a call is both locally and remotely held. No network audio is flowing and the local microphone and speaker are not engaged. */ CALLSTATE_REMOTE_HELD = 7000, /** The REMOTE_HELD state indicates that the remote party is on hold. Locally, the microphone and speaker are still engaged, however, no network audio is flowing. */ CALLSTATE_DISCONNECTED = 8000, /**< The DISCONNECTED state indicates that a call was disconnected or failed to connect. A call may move into the DISCONNECTED states from almost every other state. Please review the DISCONNECTED minor events to understand the cause. */ CALLSTATE_OFFERING = 9000, /**< An OFFERING state indicates that a new call invitation has been extended this user agent. Application developers should invoke sipxCallAccept(), sipxCallReject() or sipxCallRedirect() in response. Not responding will result in an implicit call sipXcallReject(). */ CALLSTATE_ALERTING = 10000, /**< An ALERTING state indicates that an inbound call has been accepted and the application layer should alert the end user. The alerting state is limited to 3 minutes in most configurations; afterwards the call will be canceled. Applications will generally play some sort of ringing tone in response to this event. */ CALLSTATE_DESTROYED = 11000, /**< The DESTORYED event indicates the underlying resources have been removed for a call. This is the last event that the application will receive for any call. The call handle is invalid after this event is received. */ CALLSTATE_TRANSFER_EVENT = 12000, /**< The transfer state indicates a state change in a transfer attempt. Please see the CALLSTATE_TRANSFER_EVENT cause codes for details on each state transition */ } SIPX_CALLSTATE_EVENT; /** * Callstate cause events identify the reason for a Callstate event or * provide more detail. */ typedef enum SIPX_CALLSTATE_CAUSE { CALLSTATE_CAUSE_UNKNOWN, /**< Unknown cause */ CALLSTATE_CAUSE_NORMAL, /**< The stage changed due to normal operation */ CALLSTATE_CAUSE_TRANSFERRED, /**< A call is being transferred to this user agent from another user agent.*/ CALLSTATE_CAUSE_TRANSFER, /**< A call on this user agent is being transferred to another user agent. */ CALLSTATE_CAUSE_CONFERENCE, /**< A conference operation caused a stage change */ CALLSTATE_CAUSE_EARLY_MEDIA, /**< The remote party is alerting and providing ringback audio (early media) */ CALLSTATE_CAUSE_REQUEST_NOT_ACCEPTED, /**< The callee rejected a request (e.g. hold) */ CALLSTATE_CAUSE_BAD_ADDRESS, /**< The state changed due to a bad address. This can be caused by a malformed URL or network problems with your DNS server */ CALLSTATE_CAUSE_BUSY, /**< The state changed because the remote party is busy */ CALLSTATE_CAUSE_RESOURCE_LIMIT, /**< Not enough resources are available to complete the desired operation */ CALLSTATE_CAUSE_NETWORK, /**< A network error caused the desired operation to fail */ CALLSTATE_CAUSE_REDIRECTED, /**< The stage changed due to a redirection of a call. */ CALLSTATE_CAUSE_NO_RESPONSE, /**< No response was received from the remote party or network node. */ CALLSTATE_CAUSE_AUTH, /**< Unable to authenticate due to either bad or missing credentials */ CALLSTATE_CAUSE_TRANSFER_INITIATED, /**< A transfer attempt has been initiated. This event is sent when a user agent attempts either a blind or consultative transfer. */ CALLSTATE_CAUSE_TRANSFER_ACCEPTED, /**< A transfer attempt has been accepted by the remote transferee. This event indicates that the transferee supports transfers (REFER method). The event is fired upon a 2xx class response to the SIP REFER request. */ CALLSTATE_CAUSE_TRANSFER_TRYING, /**< The transfer target is attempting the transfer. This event is sent when transfer target (or proxy / B2BUA) receives the call invitation, but before the the tranfer target accepts is. */ CALLSTATE_CAUSE_TRANSFER_RINGING, /**< The transfer target is ringing. This event is generally only sent during blind transfer. Consultative transfer should proceed directly to TRANSFER_SUCCESS or TRANSFER_FAILURE. */ CALLSTATE_CAUSE_TRANSFER_SUCCESS, /**< The transfer was completed successfully. The original call to transfer target will automatically disconnect.*/ CALLSTATE_CAUSE_TRANSFER_FAILURE, /**< The transfer failed. After a transfer fails, the application layer is responsible for recovering original call to the transferee. That call is left on hold. */ CALLSTATE_CAUSE_REMOTE_SMIME_UNSUPPORTED, /**< Fired if the remote party's user-agent does not support S/MIME. */ CALLSTATE_CAUSE_SMIME_FAILURE, /**< Fired if a local S/MIME operation failed. For more information, applications should process the SECURITY event. */ CALLSTATE_CAUSE_SHUTDOWN, /**< The even was fired as part of sipXtapi shutdown. */ CALLSTATE_CAUSE_BAD_REFER, /**< An unusable refer was sent to this user-agent. */ CALLSTATE_CAUSE_NO_KNOWN_INVITE, /**< This user-agent received a request or response, but there is no known matching invite. */ CALLSTATE_CAUSE_BYE_DURING_IDLE, /**< A BYE message was received, however, the call is in in an idle state. */ CALLSTATE_CAUSE_UNKNOWN_STATUS_CODE, /**< A response was received with an unknown status code. */ CALLSTATE_CAUSE_BAD_REDIRECT, /**< Receive a redirect with NO contact or a RANDOM redirect. */ CALLSTATE_CAUSE_TRANSACTION_DOES_NOT_EXIST, /**< No such transaction; Accepting or Rejecting a call that is part of a transfer. */ CALLSTATE_CAUSE_CANCEL, /**< The event was fired in response to a cancel attempt from the remote party */ CALLSTATE_CAUSE_NO_CODECS, /**< An attempt to send INVITE with no codecs in SDP.*/ CALLSTATE_CAUSE_SERVER_ERROR /**< Server or client at far end had major (500 class) error */ } SIPX_CALLSTATE_CAUSE ; /** * Enumeration of possible linestate Events. * * @image html lineevents.gif */ typedef enum SIPX_LINESTATE_EVENT { LINESTATE_UNKNOWN = 0, /**< This is the initial Line event state. */ LINESTATE_REGISTERING = 20000, /**< The REGISTERING event is fired when sipXtapi has successfully sent a REGISTER message, but has not yet received a success response from the registrar server */ LINESTATE_REGISTERED = 21000, /**< The REGISTERED event is fired after sipXtapi has received a response from the registrar server, indicating a successful registration. */ LINESTATE_UNREGISTERING = 22000, /**< The UNREGISTERING event is fired when sipXtapi has successfully sent a REGISTER message with an expires=0 parameter, but has not yet received a success response from the registrar server */ LINESTATE_UNREGISTERED = 23000, /**< The UNREGISTERED event is fired after sipXtapi has received a response from the registrar server, indicating a successful un-registration. */ LINESTATE_REGISTER_FAILED = 24000, /**< The REGISTER_FAILED event is fired to indicate a failure of REGISTRATION. It is fired in the following cases: The client could not connect to the registrar server. The registrar server challenged the client for authentication credentials, and the client failed to supply valid credentials. The registrar server did not generate a success response (status code == 200) within a timeout period. */ LINESTATE_UNREGISTER_FAILED = 25000, /**< The UNREGISTER_FAILED event is fired to indicate a failure of un-REGISTRATION. It is fired in the following cases: The client could not connect to the registrar server. The registrar server challenged the client for authentication credentials, and the client failed to supply valid credentials. The registrar server did not generate a success response (status code == 200) within a timeout period. */ LINESTATE_PROVISIONED = 26000, /**< The PROVISIONED event is fired when a sipXtapi Line is added, and Registration is not requested (i.e. - sipxLineAdd is called with a bRegister parameter of false. */ } SIPX_LINESTATE_EVENT; /** * Enumeration of possible linestate Event causes. */ typedef enum SIPX_LINESTATE_CAUSE { LINESTATE_CAUSE_UNKNOWN = 0, /**< No cause specified. */ LINESTATE_REGISTERING_NORMAL = LINESTATE_REGISTERING + 1, /**< See LINESTATE_REGISTERING event. */ LINESTATE_REGISTERED_NORMAL = LINESTATE_REGISTERED + 1, /**< See LINESTATE_REGISTERED event. */ LINESTATE_UNREGISTERING_NORMAL = LINESTATE_UNREGISTERING + 1, /**< See LINESTATE_UNREGISTERING event. */ LINESTATE_UNREGISTERED_NORMAL = LINESTATE_UNREGISTERED + 1, /**< See LINESTATE_UNREGISTERED event. */ LINESTATE_REGISTER_FAILED_COULD_NOT_CONNECT = LINESTATE_REGISTER_FAILED + 1, /**< Failed to register because of a connectivity problem. */ LINESTATE_REGISTER_FAILED_NOT_AUTHORIZED = LINESTATE_REGISTER_FAILED + 2, /**< Failed to register because of an authorization / authentication failure. */ LINESTATE_REGISTER_FAILED_TIMEOUT = LINESTATE_REGISTER_FAILED + 3, /**< Failed to register because of a timeout. */ LINESTATE_UNREGISTER_FAILED_COULD_NOT_CONNECT = LINESTATE_UNREGISTER_FAILED + 1, /**< Failed to unregister because of a connectivity problem. */ LINESTATE_UNREGISTER_FAILED_NOT_AUTHORIZED = LINESTATE_UNREGISTER_FAILED + 2, /**< Failed to unregister because of of an authorization / authentication failure. */ LINESTATE_UNREGISTER_FAILED_TIMEOUT = LINESTATE_UNREGISTER_FAILED + 3, /**< Failed to register because of a timeout. */ LINESTATE_PROVISIONED_NORMAL = LINESTATE_PROVISIONED + 1 /**< See LINESTATE_PROVISIONED event. */ } SIPX_LINESTATE_CAUSE; /** * Enumeration of possible INFO status events */ enum SIPX_INFOSTATUS_EVENT { INFOSTATUS_UNKNOWN = 0 , /**< This is the initial value for an INFOSTATUS event. */ INFOSTATUS_RESPONSE = 30000, /**< This event is fired if a response is received after an INFO message has been sent */ INFOSTATUS_NETWORK_ERROR = 31000 /**< This event is fired in case a network error was encountered while trying to send an INFO event. */ }; /** * Enumeration of possible configuration events */ enum SIPX_CONFIG_EVENT { CONFIG_UNKNOWN = 0, /**< Unknown configuration event */ CONFIG_STUN_SUCCESS = 40000, /**< A STUN binding has been obtained for signaling purposes. For a SIPX_CONFIG_EVENT type of CONFIG_STUN_SUCCESS, the pData pointer of the info structure will point to a SIPX_CONTACT_ADDRESS structure. */ CONFIG_STUN_FAILURE = 41000, /**< Unable to obtain a STUN binding for signaling purposes. */ } ; /** * Enumeration of possible security events */ typedef enum SIPX_SECURITY_EVENT { SECURITY_UNKNOWN = 0,/**< An UNKNOWN event is generated when the state for a call is no longer known. This is generally an error condition; see the minor event for specific causes. */ SECURITY_ENCRYPT = 1000, /**< The ENCRYPT event indicates that an SMIME encryption has been attempted. See the cause code for the encryption outcome, and the info structure for more information. */ SECURITY_DECRYPT = 2000, /**< The DECRYPT event indicates that an SMIME decryption has been attempted. See the cause code for the encryption outcome, and the info structure for more information. */ SECURITY_TLS = 4000, /**< TLS related security event. */ } SIPX_SECURITY_EVENT; /** * Enumeration of possible security causes */ typedef enum SIPX_SECURITY_CAUSE { SECURITY_CAUSE_UNKNOWN = 0, /**< An UNKNOWN cause code is generated when the state for the security operation is no longer known. This is generally an error condition; see the info structure for details. */ SECURITY_CAUSE_NORMAL, /**< Event was fired as part of the normal encryption / decryption process. */ SECURITY_CAUSE_ENCRYPT_SUCCESS, /**< An S/MIME encryption succeeded. */ SECURITY_CAUSE_ENCRYPT_FAILURE_LIB_INIT, /**< An S/MIME encryption failed because the security library could not start. */ SECURITY_CAUSE_ENCRYPT_FAILURE_BAD_PUBLIC_KEY, /**< An S/MIME encryption failed because of a bad certificate / public key. */ SECURITY_CAUSE_ENCRYPT_FAILURE_INVALID_PARAMETER,/**< An S/MIME encryption failed because of an invalid parameter. */ SECURITY_CAUSE_DECRYPT_SUCCESS, /**< An S/MIME decryption succeeded. */ SECURITY_CAUSE_DECRYPT_FAILURE_DB_INIT, /**< An S/MIME decryption failed due to a failure to initialize the certificate database. */ SECURITY_CAUSE_DECRYPT_FAILURE_BAD_DB_PASSWORD, /**< An S/MIME decryption failed due to an invalid certificate database password. */ SECURITY_CAUSE_DECRYPT_FAILURE_INVALID_PARAMETER,/**< An S/MIME decryption failed due to an invalid parameter. */ SECURITY_CAUSE_DECRYPT_BAD_SIGNATURE, /**< An S/MIME decryption operation aborted due to a bad signature. */ SECURITY_CAUSE_DECRYPT_MISSING_SIGNATURE, /**< An S/MIME decryption operation aborted due to a missing signature. */ SECURITY_CAUSE_DECRYPT_SIGNATURE_REJECTED, /**< An S/MIME decryption operation aborted because the signature was rejected. */ SECURITY_CAUSE_TLS_SERVER_CERTIFICATE, /**< A TLS server certificate is being presented to the application for possible rejection. The application must respond to this message. If the application returns false, the certificate is rejected and the call will not complete. If the application returns true, the certificate is accepted. */ SECURITY_CAUSE_TLS_BAD_PASSWORD, /**< A TLS operation failed due to a bad password. */ SECURITY_CAUSE_TLS_LIBRARY_FAILURE, /**< A TLS operation failed. */ SECURITY_CAUSE_REMOTE_HOST_UNREACHABLE, /**< The remote host is not reachable. */ SECURITY_CAUSE_TLS_CONNECTION_FAILURE, /**< A TLS connection to the remote party failed. */ SECURITY_CAUSE_TLS_HANDSHAKE_FAILURE, /**< A failure occured during the TLS handshake. */ SECURITY_CAUSE_SIGNATURE_NOTIFY, /**< The SIGNATURE_NOTIFY event is fired when the user-agent receives a SIP message with signed SMIME as its content. The signer's certificate will be located in the info structure associated with this event. The application can choose to accept the signature, by returning 'true' in response to this message or can choose to reject the signature by returning 'false' in response to this message. */ SECURITY_CAUSE_TLS_CERTIFICATE_REJECTED /** < The application has rejected the server's TLS certificate. */ } SIPX_SECURITY_CAUSE; /** * Enumeration of possible media events */ typedef enum SIPX_MEDIA_EVENT { MEDIA_UNKNOWN = 0, /**< Unknown or undefined media event, this is generally the sign of an internal error in sipXtapi */ MEDIA_LOCAL_START = 50000, /**< Local media (audio or video) is being sent to the remote party */ MEDIA_LOCAL_STOP, /**< Local media (audio or video) is no longer being sent to the remote party. This may be caused by a local/remote hold operation, call tear down, or error. See the SIPX_MEDIA_CAUSE enumeration for more information. */ MEDIA_REMOTE_START, /**< Remote media (audio or video) is ready to be received. If no audio/video is received for longer then the idle period, a MEDIA_REMOTE_SILENT event will be fired. See sipxConfigSetConnectionIdleTimeout. */ MEDIA_REMOTE_STOP, /**< Remote media (audio or video) has been stopped due to a hold or call tear down.*/ MEDIA_REMOTE_SILENT, /**< Remote media has not been received for some configured period. This generally indicates a network problem and/or a problem with the remote party. See sipxConfigSetConnectionIdleTimeout for more information. */ MEDIA_PLAYFILE_START, /**< A file is being played to local and/or remote parties. This event will be followed by a MEDIA_PLAYFILE_STOP when the file is manually stopped or finished playing. */ MEDIA_PLAYFILE_FINISH, /**< A file has completed playing. You need to call sipxCallAudioPlayFileStop() or sipxConferencePlayAudioFileStop() to prepare for the next file playback. */ MEDIA_PLAYFILE_STOP, /**< A file playback has been stopped.*/ MEDIA_PLAYBUFFER_START, /**< A buffer is being played to local and/or remote parties. This event will be followed by a MEDIA_PLAYBUFFER_STOP when the file is manually stopped or finished playing. */ MEDIA_PLAYBUFFER_FINISH, /**< A buffer has completed playing. You need to call sipxCallPlayBufferStop() to prepare for the next buffer playback. */ MEDIA_PLAYBUFFER_STOP, /**< A buffer playback has been stopped.*/ MEDIA_RECORDFILE_START, /**< Recording to a file has started. This event will be followed by a MEDIA_RECORDFILE_STOP when the recording is manually stopped or or finished after specified amount of time. */ MEDIA_RECORDFILE_STOP, /**< A recording has been manually stopped, automatically finished or aborted because of an error.*/ MEDIA_RECORDBUFFER_START, /**< Recording to a buffer has started. This event will be followed by a MEDIA_RECORDBUFFER_STOP when the recording is manually stopped or or finished after specified amount of time. */ MEDIA_RECORDBUFFER_STOP, /**< A recording has been manually stopped, automatically finished or aborted because of an error.*/ MEDIA_REMOTE_DTMF, /**< A dtmf tone was started/stopped, see the cause codes for exact status */ MEDIA_DEVICE_FAILURE, /**< Fired if the media device is not present or already in use. */ MEDIA_REMOTE_ACTIVE, /**< Media has been received */ MEDIA_MIC_ENERGY_LEVEL, /**< Mic energy level - value in idleTime */ MEDIA_H264_SPS, /**< H.264 SPS parameter set recieved */ MEDIA_H264_PPS /**< H.264 PPS parameter set recieved */ } SIPX_MEDIA_EVENT ; /** * Enumeration of possible KEEPALIVE events (EVENT_CATEGORY_KEEPALIVE) */ typedef enum SIPX_KEEPALIVE_EVENT { KEEPALIVE_START, /**< A keepalive attempt has been started. The developer is responsible for stopping all keepalives. In some cases, keepalives will be automatically stopped -- however do not rely on that.*/ KEEPALIVE_FEEDBACK, /**< The keepalive process has obtained information regarding your NAT mapped address (or local address). Feedback events are sent with the mapped address from a STUN transaction or the rport results from a SIP transaction. */ KEEPALIVE_FAILURE, /**< FAILURE events are only fired when the physical send fails. The application developer should stop the keepalive or can monitor the keepalive until the condition changes (lack of failure or feedback event). */ KEEPALIVE_STOP /**< A keepalive process has been stopped. */ } SIPX_KEEPALIVE_EVENT ; /** * Enumeration of possible KEEPALIVE cause codes (EVENT_CATEGORY_KEEPALIVE) */ typedef enum SIPX_KEEPALIVE_CAUSE { KEEPALIVE_CAUSE_NORMAL } SIPX_KEEPALIVE_CAUSE ; /** * Keepalive event information structure. This information is passed as * part of the sipXtapi callback mechanism. Based on the * SIPX_KEEPALIVE_CATEGORY, the application developer should cast the pInfo * member of your callback to the appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_KEEPALIVE_INFO { size_t nSize ; /**< Size of the structure */ SIPX_KEEPALIVE_EVENT event ; /**< Keepalive event identifier. */ SIPX_KEEPALIVE_CAUSE cause ; /**< Keepalive cause */ SIPX_KEEPALIVE_TYPE type ; /**< Keepalive type */ const char* szRemoteAddress ; /**< Target IP/host where you are sending the keepalives */ int remotePort ; /**< Target port where you are sending the keepalives */ int keepAliveSecs ; /**< How often keepalives are being sent */ const char* szFeedbackAddress; /**< This UA's IP address as seen by the remote side (only valid in FEEDBACK events) */ int feedbackPort ; /**< This UA's port as seen by the remote side (only valid in FEEDBACK events) */ } SIPX_KEEPALIVE_INFO ; /** * Enumeration of possible media event causes. */ typedef enum SIPX_MEDIA_CAUSE { MEDIA_CAUSE_NORMAL, /**< Normal cause; the call was likely torn down.*/ MEDIA_CAUSE_HOLD, /**< Media state changed due to a local or remote hold operation */ MEDIA_CAUSE_UNHOLD, /**< Media state changed due to a local or remote unhold operation */ MEDIA_CAUSE_FAILED, /**< Media state changed due to an error condition. */ MEDIA_CAUSE_DEVICE_UNAVAILABLE, /**< Media state changed due to an error condition, (device was removed, already in use, etc). */ MEDIA_CAUSE_INCOMPATIBLE, /**< Incompatible destination -- We were unable to negotiate a codec */ MEDIA_CAUSE_DTMF_START, /**< A DTMF tone has started */ MEDIA_CAUSE_DTMF_STOP /**< A DTMF tone has stopped */ } SIPX_MEDIA_CAUSE ; /** * Enumeration of possible media event types. Today, MEDIA_TYPE_AUDIO and * MEDIA_TYPE_VIDEO are supported. */ typedef enum SIPX_MEDIA_TYPE { MEDIA_TYPE_AUDIO, /**< Audio media event type */ MEDIA_TYPE_VIDEO, /**< Video media event type */ } SIPX_MEDIA_TYPE ; /** * Media event information structure. This information is passed as part of * the sipXtapi callback mechanism. Based on the SIPX_EVENT_CATEGORY, the * application developer should cast the pInfo member of your callback to the * appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_MEDIA_INFO { size_t nSize ; /**< Size of the structure. */ SIPX_MEDIA_EVENT event ; /**< Media event identifier. See SIPX_MEDIA_EVENT for more information. */ SIPX_MEDIA_CAUSE cause ; /**< Media cause identifier. See SIPX_MEDIA_CAUSE for more information. */ SIPX_MEDIA_TYPE mediaType ; /**< Media type: Either MEDIA_TYPE_AUDIO or MEDIA_TYPE_VIDEO. */ SIPX_CALL hCall ; /**< Associate call (or SIPX_CALL_NULL if not associated with a call). */ SIPX_CODEC_INFO codec ; /**< Negotiated codec; only supplied on MEDIA_LOCAL_START and MEDIA_REMOTE_START events. */ int idleTime; /**< For MEDIA_REMOTE_SILENT events contains idle time (ms). For MEDIA_RECORDFILE_STOP and MEDIA_RECORDBUFFER_STOP events contains number of recorded samples. For other events this value should be ignored. For MEDIA_MIC_ENERGY_LEVEL contains energy level*/ SIPX_TONE_ID toneId; /**< DTMF tone received from remote party; only supplied on MEDIA_REMOTE_DTMF event). Note: Only RFC 2833 DTMF detection is supported (not in-band DTMF or dialtone detection, etc.)*/ } SIPX_MEDIA_INFO ; /** * Callstate event information structure. This information is passed as part of * the sipXtapi callback mechanism. Based on the SIPX_EVENT_CATEGORY, the * application developer should cast the pInfo member of your callback to the * appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_CALLSTATE_INFO { // TODO: Add a bitmask that identified which structure items are valid. For // example, codec and hAssociatedCall are only valid for certain event // sequences. size_t nSize; /**< The size of this structure. */ SIPX_CALL hCall; /**< Call handle associated with the callstate event. */ SIPX_LINE hLine; /**< Line handle associated with the callstate event. */ SIPX_CALLSTATE_EVENT event; /**< Callstate event enum code. Identifies the callstate event. */ SIPX_CALLSTATE_CAUSE cause; /**< Callstate cause enum code. Identifies the cause of the callstate event. */ SIPX_CALL hAssociatedCall ; /**< Call associated with this event. For example, when a new call is created as part of a consultative transfer, this handle contains the handle of the original call. */ } SIPX_CALLSTATE_INFO; /** * Linestate event information structure. This information is passed as part of * the sipXtapi callback mechanism. Based on the SIPX_EVENT_CATEGORY, the * application developer should cast the pInfo member of your callback to the * appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct { size_t nSize ; /**< The size of this structure. */ SIPX_LINE hLine; /**< Line handle associated with the linestate event. */ SIPX_LINESTATE_EVENT event ; /**< Callstate event enum code. Identifies the linestate event. */ SIPX_LINESTATE_CAUSE cause ; /**< Callstate cause enum code. Identifies the cause of the linestate event. */ } SIPX_LINESTATE_INFO ; /** * Major classifications of response statuses for a SIP message. */ typedef enum SIPX_MESSAGE_STATUS { SIPX_MESSAGE_OK, /**< The message was successfully processed (200) */ SIPX_MESSAGE_FAILURE, /**< The server received the message, but could or would not process it. */ SIPX_MESSAGE_SERVER_FAILURE, /**< The server encountered an error while trying to process the message. */ SIPX_MESSAGE_GLOBAL_FAILURE, /**< Fatal error encountered. */ } SIPX_MESSAGE_STATUS ; /** * An INFOSTATUS event informs that application layer of the status * of an outbound INFO requests. This information is passed as part of * the sipXtapi callback mechanism. Based on the SIPX_EVENT_CATEGORY, the * application developer should cast the pInfo member of your callback to the * appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_INFOSTATUS_INFO { size_t nSize ; /**< the size of this structure in bytes */ SIPX_INFO hInfo ; /**< the handle used to make the outbound info request. */ SIPX_MESSAGE_STATUS status ; /**< Emumerated status for this request acknowledgement. */ int responseCode ; /**< Numerical status code for this request acknowledgement. */ const char* szResponseText ; /**< The text of the request acknowledgement. */ SIPX_INFOSTATUS_EVENT event; /**< Event code for this INFO STATUS message */ } SIPX_INFOSTATUS_INFO ; /** * An INFO event signals the application layer that an INFO message * was sent to this user agent. If the INFO message was sent to a * call context (session) hCall will desiginate the call session. * * This information is passed as part of the sipXtapi callback mechanism. * Based on the SIPX_EVENT_CATEGORY, the application developer should cast the * pInfo member of your callback to the appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_INFO_INFO { size_t nSize ; /**< Size of structure */ SIPX_CALL hCall ; /**< Call handle if available */ SIPX_LINE hLine ; /**< Line handle if available */ const char* szFromURL ; /**< the URL of the host that originated the INFO message */ const char* szUserAgent; /**< the User Agent string of the source agent */ const char* szContentType ; /**< string indicating the info content type */ const char* pContent ; /**< pointer to the INFO message content */ size_t nContentLength ; /**< length of the INFO message content */ } SIPX_INFO_INFO ; /** * Enumeration of the possible subscription states visible to the client. */ typedef enum SIPX_SUBSCRIPTION_STATE { SIPX_SUBSCRIPTION_PENDING, /**< THe subscription is being set up, but not yet active. */ SIPX_SUBSCRIPTION_ACTIVE , /**< The subscription is currently active. */ SIPX_SUBSCRIPTION_FAILED , /**< The subscription is not active due to a failure.*/ SIPX_SUBSCRIPTION_EXPIRED , /**< The subscription's lifetime has expired. */ // TBD } SIPX_SUBSCRIPTION_STATE; /** * Enumeration of cause codes for state subscription state changes. */ typedef enum SIPX_SUBSCRIPTION_CAUSE { SUBSCRIPTION_CAUSE_UNKNOWN = -1, /**< No cause specified. */ SUBSCRIPTION_CAUSE_NORMAL /**< Normal cause for state change. */ } SIPX_SUBSCRIPTION_CAUSE; /** * An SUBSTATUS event informs that application layer of the status * of an outbound SUBSCRIPTION requests; * * This information is passed as part of the sipXtapi callback mechanism. * Based on the SIPX_EVENT_CATEGORY, the application developer should cast the * pInfo member of your callback to the appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_SUBSTATUS_INFO { size_t nSize ; /**< The size of this structure in bytes */ SIPX_SUB hSub ; /**< A handle to the subscription to which this state change occurred. */ SIPX_SUBSCRIPTION_STATE state ; /**< Enum state value indicating the current state of the subscription. */ SIPX_SUBSCRIPTION_CAUSE cause; /**< Enum cause for the state change in this event. */ const char* szSubServerUserAgent; /**< The User Agent header field value from the SIP SUBSCRIBE response (may be NULL) */ } SIPX_SUBSTATUS_INFO ; /** * A NOTIFY_INFO event signifies that a NOTIFY message was received for * an active subscription. * * This information is passed as part of the sipXtapi callback mechanism. * Based on the SIPX_EVENT_CATEGORY, the application developer should cast the * pInfo member of your callback to the appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_NOTIFY_INFO { size_t nSize ; /**< The size of this structure in bytes */ SIPX_SUB hSub ; /**< A handle to the subscrption which caused this NOTIFY event to be received. */ const char* szNotiferUserAgent; /**< The User-Agent header field value from the SIP NOTIFY response (may be NULL) */ const char* szContentType ; /**< String indicating the info content type */ const void* pContent ; /**< Pointer to the NOTIFY message content */ size_t nContentLength ; /**< Length of the NOTIFY message content in bytes */ } SIPX_NOTIFY_INFO ; /** * SIPX_CONFIG_INFO events signifies that a change in configuration was * observed. * * NOTE: This structure is subject to change. * * This information is passed as part of the sipXtapi callback mechanism. * Based on the SIPX_EVENT_CATEGORY, the application developer should cast the * pInfo member of your callback to the appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_CONFIG_INFO { size_t nSize ; /**< The size of this structure in bytes */ SIPX_CONFIG_EVENT event ; /**< Event code -- see SIPX_CONFIG_EVENT for details. */ void* pData; /**< Pointer to event data -- SEE SIPX_CONFIG_EVENT for details. */ } SIPX_CONFIG_INFO ; /** * An SIPX_SECURITY_INFO event informs that application layer of the status * of a security operation. * * This information is passed as part of the sipXtapi callback mechanism. * Based on the SIPX_EVENT_CATEGORY, the application developer should cast the * pInfo member of your callback to the appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_SECURITY_INFO { size_t nSize ; /**< the size of this structure in bytes */ char* szSRTPkey; /**< the negotiated SRTP key, if any. */ void* pCertificate; /**< pointer to the certificate blob that was used to encrypt and/or sign. */ int nCertificateSize; /**< size of the certificate blob */ SIPX_SECURITY_EVENT event; /**< Event code for this SECURITY_INFO message */ SIPX_SECURITY_CAUSE cause; /**< Cause code for this SECURITY_INFO message*/ char* szSubjAltName; /**< Populated for SECURITY_CAUSE_SIGNATURE_NOTIFY.*/ char* callId; /**< Points to a call-id string associated with the event. Can be NULL. */ SIPX_CALL hCall; /**< A call handle associated with the event. Can be 0, to signify that the event is not associated with a call. */ char* remoteAddress; /**< A remote address associated with the event. Can be NULL. */ } SIPX_SECURITY_INFO ; /* ============================ FUNCTIONS ================================= */ /** * Duplicate the event information for a sipXtapi event. This method is only * needed if you wish to post the event information to another thread context. * Once the event has been handled, you must call sipxFreeDuplicatedEvent on * the copy to avoid memory leaks. * * @param category Category type supplied by the sipXtapi event callback. * @param pEventSource Source of event data supplied by the sipXtapi event * callback. * @param pEventCopy New copy of the event data. This data must be freed * by calling sipxFreeDuplicatedEvent. */ SIPXTAPI_API SIPX_RESULT sipxDuplicateEvent(SIPX_EVENT_CATEGORY category, const void* pEventSource, void** pEventCopy) ; /** * Frees up memory allocated as part of sipxDuplicateEvent. Do not call this * API on pointers received as part of the sipXtapi call back. * * @param category Category type supplied by the sipXtapi event callback. * @param pEventCopy Copy of event data supplied by sipxDuplicateEvent. */ SIPXTAPI_API SIPX_RESULT sipxFreeDuplicatedEvent(SIPX_EVENT_CATEGORY category, void* pEventCopy) ; /** * Add a callback/observer for the purpose of receiving sipXtapi events * * @param hInst Instance pointer obtained by sipxInitialize. * @param pCallbackProc Function to receive sipx events * @param pUserData user data passed along with event data */ SIPXTAPI_API SIPX_RESULT sipxEventListenerAdd(const SIPX_INST hInst, SIPX_EVENT_CALLBACK_PROC pCallbackProc, void *pUserData); /** * Remove a sipXtapi event callback/observer. Supply the same * pCallbackProc and pUserData values as sipxEventListenerAdd. * * @param hInst Instance pointer obtained by sipxInitialize. * @param pCallbackProc Function used to receive sipx events * @param pUserData user data specified as part of sipxListenerAdd */ SIPXTAPI_API SIPX_RESULT sipxEventListenerRemove(const SIPX_INST hInst, SIPX_EVENT_CALLBACK_PROC pCallbackProc, void* pUserData) ; /* ============================ FUNCTIONS ================================= */ /** * Create a printable string version of the designated call state event ids. * This is generally used for debugging. * * @param event sipxtapi event code * @param cause sipxtapi cause event code * @param szBuffer buffer to store event string * @param nBuffer length of string buffer szBuffer */ SIPXTAPI_API char* sipxCallEventToString(SIPX_CALLSTATE_EVENT event, SIPX_CALLSTATE_CAUSE cause, char* szBuffer, size_t nBuffer) ; /** * Create a printable string version of the designated event. * This is generally used for debugging. * * @param category Event category code * @param pEvent Pointer to the Event. * @param szBuffer buffer to store event string * @param nBuffer length of string buffer szBuffer */ SIPXTAPI_API char* sipxEventToString(const SIPX_EVENT_CATEGORY category, const void* pEvent, char* szBuffer, size_t nBuffer); /** * Create a printable string version of the designated line event ids. * This is generally used for debugging. * * @deprecated Use sipxEventToString instead. * @param event major event type id * @param cause event type id * @param szBuffer buffer to store event string * @param nBuffer length of string buffer szBuffer */ SIPXTAPI_API char* sipxLineEventToString(SIPX_LINESTATE_EVENT event, SIPX_LINESTATE_CAUSE cause, char* szBuffer, size_t nBuffer); /** * Create a printable string version of the designated config event. * This is generally used for debugging. * * @param event Configuration event id * @param szBuffer Buffer to store event string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxConfigEventToString(SIPX_CONFIG_EVENT event, char* szBuffer, size_t nBuffer) ; /** * Create a printable string version of the designated subscription status state. * This is generally used for debugging. * * @param state Subscription state id * @param szBuffer Buffer to store event string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxSubStatusStateToString(SIPX_SUBSCRIPTION_STATE state, char* szBuffer, size_t nBuffer) ; /** * Create a printable string version of the designated subscription status cause. * This is generally used for debugging. * * @param cause Subscription cause id * @param szBuffer Buffer to store event string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxSubStatusCauseToString(SIPX_SUBSCRIPTION_CAUSE cause, char* szBuffer, size_t nBuffer) ; /** * Create a printable string version of the designated security event. * This is generally used for debugging. * * @param event Security event id * @param szBuffer Buffer to store event string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxSecurityEventToString(SIPX_SECURITY_EVENT event, char* szBuffer, size_t nBuffer); /** * Create a printable string version of the designated security cause. * This is generally used for debugging. * * @param cause Security cause id * @param szBuffer Buffer to store cause string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxSecurityCauseToString(SIPX_SECURITY_CAUSE cause, char* szBuffer, size_t nBuffer); /** * Create a printable string version of the designated media event. * This is generally used for debugging. * * @param event Media event id * @param szBuffer Buffer to store event string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxMediaEventToString(SIPX_MEDIA_EVENT event, char* szBuffer, size_t nBuffer); /** * Create a printable string version of the designated media cause. * This is generally used for debugging. * * @param cause Media cause id * @param szBuffer Buffer to store cause string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxMediaCauseToString(SIPX_MEDIA_CAUSE cause, char* szBuffer, size_t nBuffer); /** * Create a printable string version of the designated keepalive event. * This is generally used for debugging. * * @param event Keepalive event id * @param szBuffer Buffer to store event string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxKeepaliveEventToString(SIPX_KEEPALIVE_EVENT event, char* szBuffer, size_t nBuffer); /** * Create a printable string version of the designated keepalive cause. * This is generally used for debugging. * * @param cause Keepalive cause id * @param szBuffer Buffer to store cause string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxKeepaliveCauseToString(SIPX_KEEPALIVE_CAUSE cause, char* szBuffer, size_t nBuffer); #endif /* ifndef _sipXtapiEvents_h_ */ sipxtapi-3.3.0~test17/sipXtackLib/include/tapi/sipXtapiInternal.h0000644000175000017500000010101412205613256025641 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _SIPXTAPIINTERNAL_H /* [ */ #define _SIPXTAPIINTERNAL_H // SYSTEM INCLUDES // APPLICATION INCLUDES #include "tapi/sipXtapi.h" #include "tapi/SipXMessageObserver.h" #ifdef VOICE_ENGINE # include "tapi/GipsDefs.h" #endif #include "net/SipSession.h" #include "net/SipUserAgent.h" #include "net/SipSubscribeClient.h" #include "utl/UtlDefs.h" #include "utl/UtlContainable.h" #include "os/OsRWMutex.h" #include "os/OsReadLock.h" #include "os/OsWriteLock.h" #include "os/OsSysLog.h" #include "os/OsMutex.h" #include "os/OsMsgQ.h" #include "os/OsNatKeepaliveListener.h" // DEFINES /** sipXtapi can be configured to expire after a certain date */ //#define SIPXTAPI_EVAL_EXPIRATION #ifdef SIPXTAPI_EVAL_EXPIRATION # define EVAL_EXPIRE_MONTH 0 // zero based # define EVAL_EXPIRE_DAY 31 # define EVAL_EXPIRE_YEAR 2006 #endif // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // FORWARD DECLARATIONS class SipSubscribeServer; class SipSubscribeClient; class CallManager ; class SipUserAgent ; class SipRefreshMgr ; class KeepaliveEventDispatcher; class SipXEventDispatcher; class CpMediaInterface; // STRUCTS // TYPEDEFS typedef struct MIC_SETTING { bool bInitialized ; /**< Is the data valid */ bool bMuted ; /**< Muted state (regain gain) */ int iGain ; /**< Gain setting (GAIN_MIN-GAIN_MAX) */ char device[MAX_VIDEO_DEVICE_LENGTH]; /**< Desired auto device */ } MIC_SETTING ; typedef struct SPEAKER_SETTING { bool bInitialized ; /**< Is the data valid */ int iVol ; /**< Gain setting (VOLUME_MIN-VOLUME_MAX) */ char device[MAX_VIDEO_DEVICE_LENGTH]; /**< Desired auto device */ } SPEAKER_SETTING ; typedef struct AEC_SETTING { bool bInitialized ; /**< Is the data valid */ SIPX_AEC_MODE mode ; /**< Is AEC enabled? */ } AEC_SETTING ; typedef struct AGC_SETTING { bool bInitialized ; /**< Is the data valid */ bool bEnabled; /**< Is AGC enabled? */ } AGC_SETTING ; typedef struct NOISE_REDUCTION_SETTING { bool bInitialized ; /**< Is the data valid */ SIPX_NOISE_REDUCTION_MODE mode ; /**< Is NR enabled? */ } NOISE_REDUCTION_SETTING ; typedef struct AUDIO_CODEC_PREFERENCES { bool bInitialized; /**< Is the data valid */ int numCodecs; /**< Number of codecs */ SIPX_AUDIO_BANDWIDTH_ID codecPref; /**< Numeric Id of codec preference */ SIPX_AUDIO_BANDWIDTH_ID fallBack; /**< Fallback id if codec setting fails */ UtlString* pPreferences; /**< List of preferred codecs */ SdpCodec** sdpCodecArray; /**< Pointer to an array of codecs */ } AUDIO_CODEC_PREFERENCES; typedef struct VIDEO_CODEC_PREFERENCES { bool bInitialized; /**< Is the data valid */ int numCodecs; /**< Number of codecs */ SIPX_VIDEO_BANDWIDTH_ID codecPref; /**< Numeric Id of codec preference */ SIPX_VIDEO_BANDWIDTH_ID fallBack; /**< Fallback id if codec setting fails */ UtlString* pPreferences; /**< List of preferred codecs */ SdpCodec** sdpCodecArray; /**< Pointer to an array of codecs */ } VIDEO_CODEC_PREFERENCES; typedef struct TONE_STATES { bool bInitialized; // bool tonePlaying; } TONE_STATES; typedef struct SIPX_INSTANCE_DATA { SipUserAgent* pSipUserAgent ; SdpCodecList* pCodecFactory ; CallManager* pCallManager ; SipLineMgr* pLineManager ; SipRefreshMgr* pRefreshManager ; SipSubscribeServer* pSubscribeServer; SipSubscribeClient* pSubscribeClient; SipRefreshManager* pSipRefreshManager ; SipDialogMgr* pDialogManager ; MIC_SETTING micSetting ; SPEAKER_SETTING speakerSettings[2] ; AEC_SETTING aecSetting ; AGC_SETTING agcSetting ; NOISE_REDUCTION_SETTING nrSetting ; SPEAKER_TYPE enabledSpeaker ; AUDIO_CODEC_PREFERENCES audioCodecSetting; VIDEO_CODEC_PREFERENCES videoCodecSetting; TONE_STATES toneStates; SipXEventDispatcher* pEventDispatcher; char* inputAudioDevices[MAX_AUDIO_DEVICES] ; char* outputAudioDevices[MAX_AUDIO_DEVICES] ; SipXMessageObserver* pMessageObserver; OsNotification *pStunNotification ; /**< Signals the initial stun success/failure when calling sipXconfigEnableStun */ OsMutex* pLock ; int nCalls ; /**< Counter for inprocess calls */ int nConferences ; /**< Counter for inprocess conferences */ int nLines ; /**< Counter for inprocess lines */ void* pVoiceEngine; /**< Cache VoiceEngine pointer */ char dbLocation[256]; /**< Cache cert db location > */ char myCertNickname[32]; /**< Cache certificate nickname > */ char dbPassword[32]; /**< Cache cert db password > */ bool bShortNames; /**< short names in sip messages >*/ bool bAllowHeader; /**< use allow header in sip messages>*/ bool bDateHeader; /**< use Date header in sip messages>*/ char szAcceptLanguage[16]; /**< accept language to use in sip messages>*/ char szLocationHeader[256]; /**< location header */ bool bRtpOverTcp; /**< allow RTP over TCP */ int nEnergyLevelNotificationPeriodMs; /**< period of time between each stream energy level notification>*/ KeepaliveEventDispatcher* pKeepaliveDispatcher ; } SIPX_INSTANCE_DATA ; typedef enum SIPX_INTERNAL_CALLSTATE { SIPX_INTERNAL_CALLSTATE_UNKNOWN = 0, /** Unknown call state */ SIPX_INTERNAL_CALLSTATE_OUTBOUND_ATTEMPT, /** Early dialog: outbound */ SIPX_INTERNAL_CALLSTATE_INBOUND_ATEMPT, /** Early dialog: inbound */ SIPX_INTERNAL_CALLSTATE_CONNECTED, /** Active call - remote audio */ SIPX_INTERNAL_CALLSTATE_HELD, /** both on hold due to a local hold */ SIPX_INTERNAL_CALLSTATE_REMOTE_HELD, /** Remotely held call */ SIPX_INTERNAL_CALLSTATE_BRIDGED, /** Locally held call, bridging */ SIPX_INTERNAL_CALLSTATE_DISCONNECTED, /** Disconnected or failed */ SIPX_INTERNAL_CALLSTATE_DESTROYING, /** In the process of being destroyed */ } SIPX_INTERNAL_CALLSTATE ; typedef struct SIPX_CALL_DATA { UtlString* callId; UtlString* sessionCallId; UtlString* ghostCallId; UtlString* remoteAddress ; UtlString* lineURI ; UtlString* contactAddress ; SIPX_LINE hLine ; SIPX_INSTANCE_DATA* pInst ; OsRWMutex* pMutex ; SIPX_CONF hConf ; SIPX_SECURITY_ATTRIBUTES security; SIPX_VIDEO_DISPLAY display; UtlBoolean bRemoveInsteadOfDrop ; /** Remove the call instead of dropping it -- this is used as part of consultative transfer when we are the transfer target and need to replace a call leg within the same CpPeerCall. */ SIPX_CALLSTATE_EVENT lastCallstateEvent ; SIPX_CALLSTATE_CAUSE lastCallstateCause ; SIPX_MEDIA_EVENT lastLocalMediaAudioEvent ; SIPX_MEDIA_EVENT lastLocalMediaVideoEvent ; SIPX_MEDIA_EVENT lastRemoteMediaAudioEvent ; SIPX_MEDIA_EVENT lastRemoteMediaVideoEvent ; SIPX_INTERNAL_CALLSTATE state ; UtlBoolean bInFocus ; int connectionId; /** Cache the connection id */ SIPX_TRANSPORT hTransport; bool bHoldAfterConnect; /** Used if we are the transfer target, and the replaced call is HELD or REMOTE_HELD, then this flag is set, and indicates that the call should be placed on hold after the connection is established. */ bool bCallHoldInvoked; /** Set to true if sipxCallHold has been invoked. Set to fales if sipxCallUnhold has been invoked. */ bool bTonePlaying; int nFilesPlaying; } SIPX_CALL_DATA ; typedef enum CONF_HOLD_STATE { CONF_STATE_UNHELD = 0, CONF_STATE_BRIDGING_HOLD, CONF_STATE_NON_BRIDGING_HOLD } CONF_HOLD_STATE; typedef struct { UtlString strCallId ; SIPX_INSTANCE_DATA* pInst ; size_t nCalls ; SIPX_CALL hCalls[CONF_MAX_CONNECTIONS] ; CONF_HOLD_STATE confHoldState; SIPX_TRANSPORT hTransport; int nNumFilesPlaying; OsRWMutex* pMutex ; } SIPX_CONF_DATA ; typedef struct { Url* lineURI ; SIPX_INSTANCE_DATA* pInst ; OsRWMutex* pMutex ; SIPX_CONTACT_TYPE contactType ; UtlSList* pLineAliases ; SIPX_CONTACT_ID contactId ; } SIPX_LINE_DATA ; typedef struct { SIPX_INFO_INFO infoData; SIPX_INSTANCE_DATA* pInst; SipSession* pSession; OsRWMutex* pMutex; } SIPX_INFO_DATA; typedef struct { SIPX_INSTANCE_DATA* pInst; UtlString* pResourceId; UtlString* pEventType; HttpBody* pContent; OsRWMutex* pMutex; } SIPX_PUBLISH_DATA; typedef struct { SIPX_INSTANCE_DATA* pInst; UtlString* pDialogHandle; OsRWMutex* pMutex; } SIPX_SUBSCRIPTION_DATA; #define MAX_TRANSPORT_NAME 32 class SIPX_TRANSPORT_DATA { public: SIPX_TRANSPORT_DATA() { pInst = NULL; bIsReliable = false; iLocalPort = -1; pFnWriteProc = NULL; pMutex = NULL; hTransport = 0; pUserData = NULL; bRouteByUser = true; memset(szLocalIp, 0, sizeof(szLocalIp)); memset(szTransport, 0, sizeof(szTransport)); memset(cRoutingId, 0, sizeof(cRoutingId)) ; } /** Copy constructor. */ SIPX_TRANSPORT_DATA(const SIPX_TRANSPORT_DATA& ref) { copy(ref); } /** Assignment operator. */ SIPX_TRANSPORT_DATA& operator=(const SIPX_TRANSPORT_DATA& ref) { // check for assignment to self if (this == &ref) return *this; return copy(ref); } SIPX_TRANSPORT_DATA& copy(const SIPX_TRANSPORT_DATA& ref) { hTransport = ref.hTransport; pInst = ref.pInst; bIsReliable = ref.bIsReliable; memset(szTransport, 0, sizeof(szTransport)) ; strncpy(szTransport, ref.szTransport, MAX_TRANSPORT_NAME - 1); memset(szLocalIp, 0, sizeof(szLocalIp)) ; strncpy(szLocalIp, ref.szLocalIp, sizeof(szLocalIp)-1); memset(cRoutingId, 0, sizeof(cRoutingId)) ; strncpy(cRoutingId, ref.cRoutingId, sizeof(cRoutingId)-1); iLocalPort = ref.iLocalPort; pFnWriteProc = ref.pFnWriteProc; pUserData = ref.pUserData ; bRouteByUser = ref.bRouteByUser; return *this; } static const bool isCustomTransport(const SIPX_TRANSPORT_DATA* const pTransport) { bool bRet = false; if (pTransport) { if (strlen(pTransport->szTransport) > 0) { bRet = true; } } return bRet; } SIPX_TRANSPORT hTransport; SIPX_INSTANCE_DATA* pInst; bool bIsReliable; char szTransport[MAX_TRANSPORT_NAME]; char szLocalIp[32]; int iLocalPort; SIPX_TRANSPORT_WRITE_PROC pFnWriteProc; OsRWMutex* pMutex; const void* pUserData; char cRoutingId[64] ; bool bRouteByUser; } ; /** * internal sipXtapi structure that binds a * an event callback proc * with an instance pointer and user data */ typedef struct { SIPX_EVENT_CALLBACK_PROC pCallbackProc; void* pUserData; SIPX_INSTANCE_DATA* pInst; } EVENT_LISTENER_DATA; typedef enum SIPX_LOCK_TYPE { SIPX_LOCK_NONE, SIPX_LOCK_READ, SIPX_LOCK_WRITE } SIPX_LOCK_TYPE ; /* ============================ FUNCTION POINTER DEFINITIONS =============== */ typedef void (*sipxCallEventCallbackFn)(const void* pSrc, const char* szCallId, SipSession* pSession, const char* szRemoteAddress, SIPX_CALLSTATE_EVENT event, SIPX_CALLSTATE_CAUSE cause, void* pEventData, const char* assertedIdentity); typedef void (*sipxMediaCallbackFn)(const void* pSrc, const char* szCallId, const char* szRemoteAddress, SIPX_MEDIA_EVENT event, SIPX_MEDIA_CAUSE cause, SIPX_MEDIA_TYPE type, void* pEventData); typedef void (*sipxLineEventCallbackFn)(const void* pSrc, const char* szLineIdentifier, SIPX_LINESTATE_EVENT event, SIPX_LINESTATE_CAUSE cause, const char *bodyBytes); typedef bool (*sipxEventCallbackFn)(const void* pSrc, SIPX_EVENT_CATEGORY category, void* pInfo); /* ============================ FUNCTIONS ================================= */ /** * Disable all listener callbacks -- events will be dropped */ void sipxDisableListeners() ; /** * Enable all listener callbacks (default setting) */ void sipxEnableListeners() ; /** * Destroy all calls and send simulated DESTROY events */ void sipxCallDestroyAll(const SIPX_INST hInst) ; /** * Remove/Destroy all Conferences */ void sipxConferenceDestroyAll(const SIPX_INST hInst) ; /** * Remove/Destroy all Lines */ void sipxLineRemoveAll(const SIPX_INST hInst) ; /** * Remove/Destroy all Publishers */ void sipxPublisherDestroyAll(const SIPX_INST hInst) ; /** * Remove/Destroy all subscriptions */ void sipxSubscribeDestroyAll(const SIPX_INST hInst) ; /** * Fire events to interested listeners (call events only). */ void sipxFireCallEvent(const void* pSrc, const char* szCallId, SipSession* pSession, const char* szRemoteAddress, SIPX_CALLSTATE_EVENT event, SIPX_CALLSTATE_CAUSE cause, void* pEventData=NULL, const char* szRemoteAssertedIdentity = NULL) ; /** * Fires events to interested listener (media events only) */ void sipxFireMediaEvent(const void* pSrc, const char* szCallId, const char* szRemoteAddress, SIPX_MEDIA_EVENT event, SIPX_MEDIA_CAUSE cause, SIPX_MEDIA_TYPE type, void* pEventData = NULL) ; /** * Fires events to interested listener (keepalive events only) */ void sipxFireKeepaliveEvent(const void* pSrc, SIPX_KEEPALIVE_EVENT event, SIPX_KEEPALIVE_CAUSE cause, SIPX_KEEPALIVE_TYPE type, const char* szRemoteAddress, int remotePort, int keepAliveSecs, const char* szMappedAddress, int mappedPort) ; /** * Fires a Line Event to the listeners. */ void sipxFireLineEvent(const void* pSrc, const char* szLineIdentifier, SIPX_LINESTATE_EVENT event, SIPX_LINESTATE_CAUSE cause, const char *bodyBytes = NULL); /** * Bubbles up all non-line and non-call events to the application layer */ bool sipxFireEvent(const void* pSrc, SIPX_EVENT_CATEGORY category, void* pInfo); SIPX_INSTANCE_DATA* findSessionByCallManager(const void* pCallManager) ; SIPX_CALL_DATA* sipxCallLookup(const SIPX_CALL hCall, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); void sipxCallReleaseLock(SIPX_CALL_DATA*, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); void sipxCallObjectFree(const SIPX_CALL hCall, const OsStackTraceLogger& oneBackInStack); SIPX_CALL sipxCallLookupHandle(const UtlString& callID, const void* pSrc); void destroyCallData(SIPX_CALL_DATA* pData); UtlBoolean validCallData(SIPX_CALL_DATA* pData); UtlBoolean sipxCallGetCommonData(SIPX_CALL hCall, SIPX_INSTANCE_DATA** pInst, UtlString* pStrCallId, UtlString* pStrRemoteAddress, UtlString* pLineId, UtlString* pGhostCallId = NULL, UtlString* pContactAddress = NULL) ; SIPX_CONF sipxCallGetConf(SIPX_CALL hCall) ; SIPXTAPI_API UtlBoolean sipxCallGetState(SIPX_CALL hCall, SIPX_CALLSTATE_EVENT& lastEvent, SIPX_CALLSTATE_CAUSE& lastCause, SIPX_INTERNAL_CALLSTATE& state) ; UtlBoolean sipxCallGetMediaState(SIPX_CALL hCall, SIPX_MEDIA_EVENT& lastLocalMediaAudioEvent, SIPX_MEDIA_EVENT& lastLocalMediaVideoEvent, SIPX_MEDIA_EVENT& lastRemoteMediaAudioEvent, SIPX_MEDIA_EVENT& lastRemoteMediaVideoEvent) ; UtlBoolean sipxCallSetMediaState(SIPX_CALL hCall, SIPX_MEDIA_EVENT event, SIPX_MEDIA_TYPE type) ; UtlBoolean sipxCallSetState(SIPX_CALL hCall, SIPX_CALLSTATE_EVENT event, SIPX_CALLSTATE_CAUSE cause) ; SIPX_CONTACT_TYPE sipxCallGetLineContactType(SIPX_CALL hCall) ; SIPX_LINE_DATA* sipxLineLookup(const SIPX_LINE hLine, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); void sipxLineReleaseLock(SIPX_LINE_DATA* pData, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); void sipxLineObjectFree(const SIPX_LINE hLine) ; SIPX_LINE sipxLineLookupHandle(const char* szLineURI, const char* requestUri); SIPX_LINE sipxLineLookupHandleByURI(const char* szURI); UtlBoolean validLineData(const SIPX_LINE_DATA*) ; UtlBoolean sipxAddCallHandleToConf(const SIPX_CALL hCall, const SIPX_CONF hConf) ; UtlBoolean sipxRemoveCallHandleFromConf(const SIPX_CONF hConf, const SIPX_CALL hCall) ; SIPX_CONF_DATA* sipxConfLookup(const SIPX_CONF hConf, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); void sipxConfReleaseLock(SIPX_CONF_DATA* pData, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); void sipxConfFree(const SIPX_CONF hConf) ; UtlBoolean validConfData(const SIPX_CONF_DATA* pData) ; void sipxIncSessionCount(); void sipxDecSessionCount(); int sipxGetSessionCount(); UtlBoolean sipxIsCallInFocus() ; SIPXTAPI_API SIPX_RESULT sipxStructureIntegrityCheck(); const char* sipxContactTypeToString(SIPX_CONTACT_TYPE type) ; const char* sipxTransportTypeToString(SIPX_TRANSPORT_TYPE type) ; /** * Frees the INFO structure allocated by a call to sipxCallSendInfo * * @param pData Pointer to SIPX_INFO_DATA structure */ void sipxInfoFree(SIPX_INFO_DATA* pData); /** * Releases the INFO handle created by a call to sipxCallSendInfo. * Also cals sipxInfoFree. * * @param hInfo Handle to the Info object */ void sipxInfoObjectFree(SIPX_INFO hInfo); /** * Frees the TRANSPORT structure allocated by a call to sipxConfigExternalTransportAdd * * @param pData Pointer to SIPX_TRANSPORT_DATA structure */ void sipxTransportFree(SIPX_TRANSPORT_DATA* pData); /** * Releases the TRANSPORT handle created sipxConfigExternalTransportAdd * Also cals sipxTransportFree. * * @param hInfo Handle to the Transport object */ void sipxTransportObjectFree(SIPX_TRANSPORT hTransport); void sipxGetContactHostPort(SIPX_INSTANCE_DATA* pData, SIPX_CONTACT_TYPE contactType, Url& uri, SIPX_TRANSPORT_TYPE protocol) ; //: Get the external host and port given the contact preference /** * Looks up the SIPX_INFO_DATA structure pointer, given the SIPX_INFO handle. * @param hInfo Info Handle * @param type Lock type to use during lookup. */ SIPX_INFO_DATA* sipxInfoLookup(const SIPX_INFO hInfo, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); /** * Unlocks the mutex associated with the INFO DATA * * @param pData pointer to the SIPX_INFO structure * @param type Type of lock (read or write) */ void sipxInfoReleaseLock(SIPX_INFO_DATA* pData, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); SIPX_PUBLISH_DATA* sipxPublishLookup(const SIPX_PUB hPub, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); void sipxPublishReleaseLock(SIPX_PUBLISH_DATA* pData, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); SIPX_SUBSCRIPTION_DATA* sipxSubscribeLookup(const SIPX_SUB hSub, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); void sipxSubscribeReleaseLock(SIPX_SUBSCRIPTION_DATA* pData, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); /** * Looks up the SIPX_TRANSPORT_DATA structure pointer, given the SIPX_TRANSPORT handle. * @param hTransport Transport Handle * @param type Lock type to use during lookup. */ SIPX_TRANSPORT_DATA* sipxTransportLookup(const SIPX_TRANSPORT hTransport, SIPX_LOCK_TYPE type); /** * Unlocks the mutex associated with the TRANSPORT DATA * * @param pData pointer to the SIPX_TRANSPORT structure * @param type Type of lock (read or write) */ void sipxTransportReleaseLock(SIPX_TRANSPORT_DATA* pData, SIPX_LOCK_TYPE type); /** * Destroy all external transports for a given instance */ void sipxTransportDestroyAll(const SIPX_INST hInst) ; /** * Adds a log entry to the system log - made necessary to add logging * capability on the API level. * * @param logLevel priority of the log entry * @param format a format string for the following variable argument list */ SIPXTAPI_API void sipxLogEntryAdd(OsSysLogPriority logLevel, const char *format, ...); /** * Utility function for setting allowed methods on a * instance's user-agent. */ SIPXTAPI_API SIPX_RESULT sipxConfigAllowMethod(const SIPX_INST hInst, const char* method, const bool bAllow = true); /** * Get the list of active calls for the specified call manager instance */ SIPXTAPI_API SIPX_RESULT sipxGetActiveCallIds(SIPX_INST hInst, int maxCalls, int& actualCalls, UtlString callIds[]) ; /** * Callback for subscription client state */ void sipxSubscribeClientSubCallback(enum SipSubscribeClient::SubscriptionState newState, const char* earlyDialogHandle, const char* dialogHandle, void* applicationData, int responseCode, const char* responseText, long expiration, const SipMessage* subscribeResponse); /** * Callback for subscription client NOTIFY content */ void sipxSubscribeClientNotifyCallback(const char* earlyDialogHandle, const char* dialogHandle, void* applicationData, const SipMessage* notifyRequest); /** * Look for leaks in internal handles */ SIPXTAPI_API SIPX_RESULT sipxCheckForHandleLeaks() ; /** * Flush handles to remove peaks between test cases -- this *WILL* leak * memory. */ SIPXTAPI_API SIPX_RESULT sipxFlushHandles() ; /** * Translate tone ids to implementation specific codes * * @param toneId sipx-internal tone id * @param xlateId implementation-specific tone id */ SIPXTAPI_API SIPX_RESULT sipxTranslateToneId(const SIPX_TONE_ID toneId, SIPX_TONE_ID& xlateId) ; /** * Gets an CpMediaInterface pointer, associated with the call connection. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param ppInstData pointer to a memory address that is set to the media interface * pointer. */ SIPXTAPI_API SIPX_RESULT sipxCallGetConnectionMediaInterface(const SIPX_CALL hCall, void** ppInstData); /** * Returns the 'local' connection id * * @param hInst Instance pointer obtained by sipxInitialize */ SIPXTAPI_API SIPX_RESULT sipxConfigGetLocalAudioConnectionId(const SIPX_INST hInst, int& connectionId); #ifdef VOICE_ENGINE /** * For Gips VoiceEngine versions of sipXtapi, this method will * return the GipsVoiceEngineLib pointer associated with the * call. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. */ SIPXTAPI_API GipsVoiceEngineLib* sipxCallGetVoiceEnginePtr(const SIPX_CALL hCall); /** * For Gips VoiceEngine versions of sipXtapi, this method will * return the GipsVoiceEngineLib pointer associated with the * factory implementation. * * @param hInst Instance pointer obtained by sipxInitialize */ SIPXTAPI_API GipsVoiceEngineLib* sipxConfigGetVoiceEnginePtr(const SIPX_INST hInst); #ifdef _WIN32 /** * For Gips VoiceEngine versions of sipXtapi, this method will * return a Audio Tuning Wizard pointer associated with the * factory implementation. * * @param hInst Instance pointer obtained by sipxInitialize */ SIPXTAPI_API GIPSAECTuningWizard* sipxConfigGetVoiceEngineAudioWizard(); #endif #ifdef VIDEO /** * For Gips VideoEngine versions of sipXtapi, this method will * return the GipsVideoEngine[Windows|Mac] pointer associated with * the factory implementation. * * @param hInst Instance pointer obtained by sipxInitialize */ SIPXTAPI_API GipsVideoEnginePlatform* sipxConfigGetVideoEnginePtr(const SIPX_INST hInst); #endif VIDEO /** * For Gips VoiceEngine versions of sipXtapi, this method will * creates a Local Audio connection, which can be used to play * media files. * * @param hInst Instance pointer obtained by sipxInitialize */ SIPXTAPI_API SIPX_RESULT sipxCreateLocalAudioConnection(const SIPX_INST hInst); /** * For Gips VoiceEngine versions of sipXtapi, this method will * destroys the Local Audio connection, which was created by a * call to sipxCreateLocalAudioConnection. * * @param hInst Instance pointer obtained by sipxInitialize */ SIPXTAPI_API SIPX_RESULT sipxDestroyLocalAudioConnection(const SIPX_INST hInst); /** * For Gips VoiceEngine versions of sipXtapi, this method will * enable or disable insertion of VoiceEngine trace output into the * sipXtapi log. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnable Enable or disable VoceEngine trace output */ SIPXTAPI_API SIPX_RESULT sipxEnableAudioLogging(const SIPX_INST hInst, bool bEnable); #else /* not VoiceEngine */ /** * Get pointer to Sipx media interface for call. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. */ SIPXTAPI_API CpMediaInterface* sipxCallGetCpMediaInterface(const SIPX_CALL hCall); /** * Get pointer to Sipx media control message queue for call. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. */ SIPXTAPI_API OsMsgQ* sipxCallGetMediaConrolQueue(const SIPX_CALL hCall); #endif UtlBoolean sipxCallSetRemoveInsteadofDrop(SIPX_CALL hCall) ; UtlBoolean sipxCallIsRemoveInsteadOfDropSet(SIPX_CALL hCall) ; SIPX_RESULT __sipxEventListenerAdd(const SIPX_INST hInst, SIPX_EVENT_CALLBACK_PROC pCallbackProc, void *pUserData) ; SIPX_RESULT __sipxEventListenerRemove(const SIPX_INST hInst, SIPX_EVENT_CALLBACK_PROC pCallbackProc, void* pUserData) ; void sipxUpdateListeners(SIPX_INST hOldInst, SIPX_INST hNewInst) ; /** * Dynamically loads the following NSS runtime libraries, if they can be found: * smime3.dll;nss3.dll;nspr4.dll;plc4.dll * * @returns SIPX_RESULT_SUCCESS if all NSS libraries were loaded. Otherwise, * SIPX_RESULT_MISSING_RUNTIME_FILES is returned. * */ SIPXTAPI_API SIPX_RESULT sipxConfigLoadSecurityRuntime(); /** * Called from sipxConfigExternalTransportAdd, this function creates * LOCAL, STUN, and RELAY contact records for the newly added * transport mechanism. */ void sipxCreateExternalTransportContacts(const SIPX_TRANSPORT_DATA* pData); class SecurityHelper { public: void generateSrtpKey(SIPX_SECURITY_ATTRIBUTES& securityAttrib); void setDbLocation(SIPX_SECURITY_ATTRIBUTES& securityAttrib, const char* dbLocation); void setMyCertNickname(SIPX_SECURITY_ATTRIBUTES& securityAttrib, const char* myCertNickname); void setDbPassword(SIPX_SECURITY_ATTRIBUTES& securityAttrib, const char* dbPassword); }; class KeepaliveEventDispatcher : public OsNatKeepaliveListener { public: KeepaliveEventDispatcher(void* pSrc) : OsNatKeepaliveListener() { m_pSrc = pSrc ; } ; virtual ~KeepaliveEventDispatcher() {} ; virtual void OnKeepaliveStart(const OsNatKeepaliveEvent& event) { sipxFireKeepaliveEvent(m_pSrc, KEEPALIVE_START, KEEPALIVE_CAUSE_NORMAL, (SIPX_KEEPALIVE_TYPE) event.type, event.remoteAddress, event.remotePort, event.keepAliveSecs, event.mappedAddress, event.mappedPort) ; } virtual void OnKeepaliveStop(const OsNatKeepaliveEvent& event) { sipxFireKeepaliveEvent(m_pSrc, KEEPALIVE_STOP, KEEPALIVE_CAUSE_NORMAL, (SIPX_KEEPALIVE_TYPE) event.type, event.remoteAddress, event.remotePort, event.keepAliveSecs, event.mappedAddress, event.mappedPort) ; } virtual void OnKeepaliveFeedback(const OsNatKeepaliveEvent& event) { sipxFireKeepaliveEvent(m_pSrc, KEEPALIVE_FEEDBACK, KEEPALIVE_CAUSE_NORMAL, (SIPX_KEEPALIVE_TYPE) event.type, event.remoteAddress, event.remotePort, event.keepAliveSecs, event.mappedAddress, event.mappedPort) ; } virtual void OnKeepaliveFailure(const OsNatKeepaliveEvent& event) { sipxFireKeepaliveEvent(m_pSrc, KEEPALIVE_FAILURE, KEEPALIVE_CAUSE_NORMAL, (SIPX_KEEPALIVE_TYPE) event.type, event.remoteAddress, event.remotePort, event.keepAliveSecs, event.mappedAddress, event.mappedPort) ; } protected: void* m_pSrc ; } ; #endif /* ] _SIPXTAPIINTERNAL_H */ sipxtapi-3.3.0~test17/sipXtackLib/include/Makefile.am0000644000175000017500000000700512205613305023271 0ustar00danieldaniel00000000000000# preserve header timestamps to preserve incremental builds across # projects nobase_pkgincludeHEADERS_INSTALL = $(INSTALL) -D -p -c -m 644 ## If we use windows, make these conditional includes EXTRA_DIST = \ resparse/wnt/arpa/inet.h \ resparse/wnt/arpa/nameser.h \ resparse/wnt/crypt.h \ resparse/wnt/inet_aton.h \ resparse/wnt/netinet/in.h \ resparse/wnt/nterrno.h \ resparse/wnt/resolv/resolv.h \ resparse/wnt/res_signal.h \ resparse/wnt/sys/param.h \ resparse/wnt/sys/uio.h \ resparse/wnt/sysdep.h \ resparse/wnt/utilNT.h nobase_pkginclude_HEADERS = \ net/HttpBody.h \ net/HttpMessage.h \ net/HttpRequestContext.h \ net/HttpServer.h \ net/HttpService.h \ net/MailAttachment.h \ net/MailMessage.h \ net/MimeBodyPart.h \ net/NameValuePair.h \ net/NameValuePairInsensitive.h \ net/NetAttributeTokenizer.h \ net/NetBase64Codec.h \ net/NetMd5Codec.h \ net/ProvisioningAgent.h \ net/ProvisioningAgentXmlRpcAdapter.h \ net/ProvisioningAttrList.h \ net/ProvisioningClass.h \ net/QoS.h \ net/SdpBody.h \ net/SdpHelper.h \ net/SipClient.h \ net/SipContactDb.h \ net/SipDialog.h \ net/SipDialogEvent.h \ net/SipDialogMgr.h \ net/SipDialogMonitor.h \ net/SipConfigServerAgent.h \ net/SipLineCredentials.h \ net/SipLineEvent.h \ net/SipLine.h \ net/SipLineList.h \ net/SipLineMgr.h \ net/SipMessageEvent.h \ net/SipMessage.h \ net/SipMessageList.h \ net/SipNonceDb.h \ net/SipNotifyStateTask.h \ net/SipObserverCriteria.h \ net/SipPimClient.h \ net/SipPresenceEvent.h \ net/SipProtocolServerBase.h \ net/SipPublishContentMgr.h \ net/SipPublishServer.h \ net/SipPublishServerEventStateCompositor.h \ net/SipPublishServerEventStateMgr.h \ net/SipRefreshMgr.h \ net/SipRefreshManager.h \ net/SipRequestContext.h \ net/SipResourceList.h \ net/SipServerBase.h \ net/SipServerBroker.h \ net/SipSession.h \ net/SipSrvLookup.h \ net/SipSubscribeClient.h \ net/SipSubscribeServer.h \ net/SipSubscribeServerEventHandler.h \ net/SipSubscriptionMgr.h \ net/SipTcpServer.h \ net/SipTlsServer.h \ net/SipTransaction.h \ net/SipTransactionList.h \ net/SipUdpServer.h \ net/SipUserAgentBase.h \ net/SipUserAgent.h \ net/SipUserAgentStateless.h \ net/SmimeBody.h \ net/StateChangeNotifier.h \ net/TapiMgr.h \ net/Url.h \ net/version.h \ net/XmlRpcBody.h \ net/XmlRpcDispatch.h \ net/XmlRpcMethod.h \ net/XmlRpcRequest.h \ net/XmlRpcResponse.h \ net/HttpConnection.h \ net/HttpConnectionMap.h \ net/PidfBody.h \ resparse/bzero.h \ resparse/ns_name.h \ resparse/poll.h \ resparse/res_config.h \ resparse/res_info.h \ resparse/rr.h \ resparse/types.h \ tapi/SipXHandleMap.h \ tapi/SipXMessageObserver.h \ tapi/SipXEventDispatcher.h \ tapi/doxyfile \ tapi/sipXtapi.h \ tapi/sipXtapiEvents.h \ tapi/sipXtapiInternal.h net/version.h: .FORCE @test -d net || mkdir net @echo '#ifndef SIP_STACK_VERSION' > net/version_new.h @echo '#define SIP_STACK_VERSION "@VERSION@"' >> net/version_new.h @echo '#endif' >> net/version_new.h @if test ! -r net/version.h || ! diff net/version.h net/version_new.h > /dev/null \ ;then \ echo sipXtack version is @VERSION@ \ ; mv net/version_new.h net/version.h \ ;else \ rm -f net/version_new.h \ ;fi .FORCE: sipxtapi-3.3.0~test17/sipXtackLib/include/Makefile.in0000644000175000017500000005221112321445002023275 0ustar00danieldaniel00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = sipXtackLib/include DIST_COMMON = $(nobase_pkginclude_HEADERS) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/general.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/sipXlib.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(pkgincludedir)" HEADERS = $(nobase_pkginclude_HEADERS) ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMRNB_INCLUDE = @AMRNB_INCLUDE@ AMRNB_LIB_ROOT = @AMRNB_LIB_ROOT@ AMRWB_INCLUDE = @AMRWB_INCLUDE@ AMRWB_LIB_ROOT = @AMRWB_LIB_ROOT@ AMRWB_TARGET = @AMRWB_TARGET@ AMR_TARGET = @AMR_TARGET@ AMTAR = @AMTAR@ ANT = @ANT@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CARBON_LIBS = @CARBON_LIBS@ CA_LIBS = @CA_LIBS@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPUNIT_CFLAGS = @CPPUNIT_CFLAGS@ CPPUNIT_CONFIG = @CPPUNIT_CONFIG@ CPPUNIT_LIBS = @CPPUNIT_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPS_PCRE_CFLAGS = @DEPS_PCRE_CFLAGS@ DEPS_PCRE_LIBS = @DEPS_PCRE_LIBS@ DLLTOOL = @DLLTOOL@ DOT = @DOT@ DOXYGEN = @DOXYGEN@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DYNEXT = @DYNEXT@ EAGC_LDFLAGS = @EAGC_LDFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EJBE_LDFLAGS = @EJBE_LDFLAGS@ EPLC_LDFLAGS = @EPLC_LDFLAGS@ EVAD_LDFLAGS = @EVAD_LDFLAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ G722_TARGET = @G722_TARGET@ G726_TARGET = @G726_TARGET@ GIPSINC = @GIPSINC@ GIPS_CE_OBJS = @GIPS_CE_OBJS@ GIPS_CPPFLAGS = @GIPS_CPPFLAGS@ GIPS_NEQ_OBJS = @GIPS_NEQ_OBJS@ GIPS_VE_OBJS = @GIPS_VE_OBJS@ GREP = @GREP@ GSM_CFLAGS = @GSM_CFLAGS@ GSM_CXXFLAGS = @GSM_CXXFLAGS@ GSM_LDFLAGS = @GSM_LDFLAGS@ GSM_LIBS = @GSM_LIBS@ GSM_TARGET = @GSM_TARGET@ ILBC_INCLUDE = @ILBC_INCLUDE@ ILBC_LIB_ROOT = @ILBC_LIB_ROOT@ ILBC_LIB_TARGET = @ILBC_LIB_TARGET@ ILBC_TARGET = @ILBC_TARGET@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTERFACE_FLAGS = @INTERFACE_FLAGS@ JAVA = @JAVA@ JAVAC_DEBUG = @JAVAC_DEBUG@ JAVAC_OPTIMIZED = @JAVAC_OPTIMIZED@ JAVA_HOME = @JAVA_HOME@ L16_TARGET = @L16_TARGET@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NAMED_PROGRAM = @NAMED_PROGRAM@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPUS_CFLAGS = @OPUS_CFLAGS@ OPUS_LIBS = @OPUS_LIBS@ OPUS_TARGET = @OPUS_TARGET@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PCMAPCMU_TARGET = @PCMAPCMU_TARGET@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ RTL_CXXFLAGS = @RTL_CXXFLAGS@ RTL_LDFLAGS = @RTL_LDFLAGS@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SIPXMEDIA_CE_LIBS = @SIPXMEDIA_CE_LIBS@ SIPXMEDIA_VE_LIBS = @SIPXMEDIA_VE_LIBS@ SIPXMEDIA_VE_STATIC_LIBS = @SIPXMEDIA_VE_STATIC_LIBS@ SIPXPBXUSER = @SIPXPBXUSER@ SIPXPHONECONF = @SIPXPHONECONF@ SIPXPHONEDATA = @SIPXPHONEDATA@ SIPXPHONELIB = @SIPXPHONELIB@ SIPX_BACKUPDIR = @SIPX_BACKUPDIR@ SIPX_BINDIR = @SIPX_BINDIR@ SIPX_CONFDIR = @SIPX_CONFDIR@ SIPX_CONFIGPHONEDIR = @SIPX_CONFIGPHONEDIR@ SIPX_DATADIR = @SIPX_DATADIR@ SIPX_DBDIR = @SIPX_DBDIR@ SIPX_DOCDIR = @SIPX_DOCDIR@ SIPX_INCDIR = @SIPX_INCDIR@ SIPX_LIBDIR = @SIPX_LIBDIR@ SIPX_LOGDIR = @SIPX_LOGDIR@ SIPX_PARKMUSICDIR = @SIPX_PARKMUSICDIR@ SIPX_RUNDIR = @SIPX_RUNDIR@ SIPX_SCHEMADIR = @SIPX_SCHEMADIR@ SIPX_TMPDIR = @SIPX_TMPDIR@ SIPX_UNIT_TARGET = @SIPX_UNIT_TARGET@ SIPX_VXMLDATADIR = @SIPX_VXMLDATADIR@ SPANDSP_CFLAGS = @SPANDSP_CFLAGS@ SPANDSP_CXXFLAGS = @SPANDSP_CXXFLAGS@ SPANDSP_LDFLAGS = @SPANDSP_LDFLAGS@ SPANDSP_LIBS = @SPANDSP_LIBS@ SPEEXDSP_CFLAGS = @SPEEXDSP_CFLAGS@ SPEEXDSP_LIBS = @SPEEXDSP_LIBS@ SPEEXDSP_STATIC_LIB = @SPEEXDSP_STATIC_LIB@ SPEEX_CFLAGS = @SPEEX_CFLAGS@ SPEEX_LIBS = @SPEEX_LIBS@ SPEEX_ROOT = @SPEEX_ROOT@ SPEEX_STATIC_LIB = @SPEEX_STATIC_LIB@ SPEEX_TARGET = @SPEEX_TARGET@ SS_LDFLAGS = @SS_LDFLAGS@ STATIC_CODEC_LIBS = @STATIC_CODEC_LIBS@ STRIP = @STRIP@ TONES_TARGET = @TONES_TARGET@ VERSION = @VERSION@ VIDEO_DEFINE = @VIDEO_DEFINE@ WXWIDGETS_CFLAGS = @WXWIDGETS_CFLAGS@ WXWIDGETS_CONFIG = @WXWIDGETS_CONFIG@ WXWIDGETS_CXXFLAGS = @WXWIDGETS_CXXFLAGS@ WXWIDGETS_LIBS = @WXWIDGETS_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ codeclibdir = @codeclibdir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ enable_dot = @enable_dot@ enable_html_docs = @enable_html_docs@ enable_latex_docs = @enable_latex_docs@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ jar = @jar@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ sipx_abs_srcdir = @sipx_abs_srcdir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ wwwdir = @wwwdir@ # preserve header timestamps to preserve incremental builds across # projects nobase_pkgincludeHEADERS_INSTALL = $(INSTALL) -D -p -c -m 644 EXTRA_DIST = \ resparse/wnt/arpa/inet.h \ resparse/wnt/arpa/nameser.h \ resparse/wnt/crypt.h \ resparse/wnt/inet_aton.h \ resparse/wnt/netinet/in.h \ resparse/wnt/nterrno.h \ resparse/wnt/resolv/resolv.h \ resparse/wnt/res_signal.h \ resparse/wnt/sys/param.h \ resparse/wnt/sys/uio.h \ resparse/wnt/sysdep.h \ resparse/wnt/utilNT.h nobase_pkginclude_HEADERS = \ net/HttpBody.h \ net/HttpMessage.h \ net/HttpRequestContext.h \ net/HttpServer.h \ net/HttpService.h \ net/MailAttachment.h \ net/MailMessage.h \ net/MimeBodyPart.h \ net/NameValuePair.h \ net/NameValuePairInsensitive.h \ net/NetAttributeTokenizer.h \ net/NetBase64Codec.h \ net/NetMd5Codec.h \ net/ProvisioningAgent.h \ net/ProvisioningAgentXmlRpcAdapter.h \ net/ProvisioningAttrList.h \ net/ProvisioningClass.h \ net/QoS.h \ net/SdpBody.h \ net/SdpHelper.h \ net/SipClient.h \ net/SipContactDb.h \ net/SipDialog.h \ net/SipDialogEvent.h \ net/SipDialogMgr.h \ net/SipDialogMonitor.h \ net/SipConfigServerAgent.h \ net/SipLineCredentials.h \ net/SipLineEvent.h \ net/SipLine.h \ net/SipLineList.h \ net/SipLineMgr.h \ net/SipMessageEvent.h \ net/SipMessage.h \ net/SipMessageList.h \ net/SipNonceDb.h \ net/SipNotifyStateTask.h \ net/SipObserverCriteria.h \ net/SipPimClient.h \ net/SipPresenceEvent.h \ net/SipProtocolServerBase.h \ net/SipPublishContentMgr.h \ net/SipPublishServer.h \ net/SipPublishServerEventStateCompositor.h \ net/SipPublishServerEventStateMgr.h \ net/SipRefreshMgr.h \ net/SipRefreshManager.h \ net/SipRequestContext.h \ net/SipResourceList.h \ net/SipServerBase.h \ net/SipServerBroker.h \ net/SipSession.h \ net/SipSrvLookup.h \ net/SipSubscribeClient.h \ net/SipSubscribeServer.h \ net/SipSubscribeServerEventHandler.h \ net/SipSubscriptionMgr.h \ net/SipTcpServer.h \ net/SipTlsServer.h \ net/SipTransaction.h \ net/SipTransactionList.h \ net/SipUdpServer.h \ net/SipUserAgentBase.h \ net/SipUserAgent.h \ net/SipUserAgentStateless.h \ net/SmimeBody.h \ net/StateChangeNotifier.h \ net/TapiMgr.h \ net/Url.h \ net/version.h \ net/XmlRpcBody.h \ net/XmlRpcDispatch.h \ net/XmlRpcMethod.h \ net/XmlRpcRequest.h \ net/XmlRpcResponse.h \ net/HttpConnection.h \ net/HttpConnectionMap.h \ net/PidfBody.h \ resparse/bzero.h \ resparse/ns_name.h \ resparse/poll.h \ resparse/res_config.h \ resparse/res_info.h \ resparse/rr.h \ resparse/types.h \ tapi/SipXHandleMap.h \ tapi/SipXMessageObserver.h \ tapi/SipXEventDispatcher.h \ tapi/doxyfile \ tapi/sipXtapi.h \ tapi/sipXtapiEvents.h \ tapi/sipXtapiInternal.h all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu sipXtackLib/include/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu sipXtackLib/include/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-nobase_pkgincludeHEADERS: $(nobase_pkginclude_HEADERS) @$(NORMAL_INSTALL) @list='$(nobase_pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(pkgincludedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(pkgincludedir)" || exit 1; \ fi; \ $(am__nobase_list) | while read dir files; do \ xfiles=; for file in $$files; do \ if test -f "$$file"; then xfiles="$$xfiles $$file"; \ else xfiles="$$xfiles $(srcdir)/$$file"; fi; done; \ test -z "$$xfiles" || { \ test "x$$dir" = x. || { \ echo " $(MKDIR_P) '$(DESTDIR)$(pkgincludedir)/$$dir'"; \ $(MKDIR_P) "$(DESTDIR)$(pkgincludedir)/$$dir"; }; \ echo " $(INSTALL_HEADER) $$xfiles '$(DESTDIR)$(pkgincludedir)/$$dir'"; \ $(INSTALL_HEADER) $$xfiles "$(DESTDIR)$(pkgincludedir)/$$dir" || exit $$?; }; \ done uninstall-nobase_pkgincludeHEADERS: @$(NORMAL_UNINSTALL) @list='$(nobase_pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \ $(am__nobase_strip_setup); files=`$(am__nobase_strip)`; \ dir='$(DESTDIR)$(pkgincludedir)'; $(am__uninstall_files_from_dir) ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(HEADERS) installdirs: for dir in "$(DESTDIR)$(pkgincludedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-nobase_pkgincludeHEADERS install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-nobase_pkgincludeHEADERS .MAKE: install-am install-strip .PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ clean-libtool ctags distclean distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-nobase_pkgincludeHEADERS \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags uninstall uninstall-am uninstall-nobase_pkgincludeHEADERS net/version.h: .FORCE @test -d net || mkdir net @echo '#ifndef SIP_STACK_VERSION' > net/version_new.h @echo '#define SIP_STACK_VERSION "@VERSION@"' >> net/version_new.h @echo '#endif' >> net/version_new.h @if test ! -r net/version.h || ! diff net/version.h net/version_new.h > /dev/null \ ;then \ echo sipXtack version is @VERSION@ \ ; mv net/version_new.h net/version.h \ ;else \ rm -f net/version_new.h \ ;fi .FORCE: # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: sipxtapi-3.3.0~test17/sipXtackLib/src/0000755000175000017500000000000012321445027020402 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXtackLib/src/net/0000755000175000017500000000000012321445027021170 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXtackLib/src/net/HttpBody.cpp0000644000175000017500000004316012205613256023437 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2008 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie (dpetrie AT SIPez DOT com) // SYSTEM INCLUDES #include #include // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // The number of hex chars to use for boundary strings. #define BOUNDARY_STRING_LENGTH 8 // Mask to extract the low (BOUNDARY_STRING_LENGTH*4) bits of an unsigned int. #define BOUNDARY_COUNTER_MASK 0xFFFFFFFF // STATIC VARIABLE INITIALIZATIONS unsigned HttpBody::boundaryCounter = 0; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor HttpBody::HttpBody(const char* bytes, int length, const char* contentType) : bodyLength(0) { mClassType = HTTP_BODY_CLASS; for(int partIndex = 0; partIndex < MAX_HTTP_BODY_PARTS; partIndex++) { mpBodyParts[partIndex] = NULL; } mBodyPartCount = 0; if (contentType) { append(contentType); strip(UtlString::both); #ifdef TEST_PRINT osPrintf("Content type: \"%s\"\n", contentType); #endif int boundaryIndex = index(MULTIPART_BOUNDARY_PARAMETER, 0, UtlString::ignoreCase); if(boundaryIndex >=0 && index(CONTENT_TYPE_MULTIPART, 0, UtlString::ignoreCase) == 0) { boundaryIndex += strlen(MULTIPART_BOUNDARY_PARAMETER); // Allow white space before = int fieldLength = this->length(); while(boundaryIndex < fieldLength && (data()[boundaryIndex] == ' ' || data()[boundaryIndex] == '\t')) boundaryIndex++; if(data()[boundaryIndex] == '=') { mMultipartBoundary.append(&data()[boundaryIndex + 1]); mMultipartBoundary.strip(UtlString::leading); int whiteSpaceIndex = mMultipartBoundary.first(' '); if(whiteSpaceIndex > 0) mMultipartBoundary.remove(whiteSpaceIndex); whiteSpaceIndex = mMultipartBoundary.first('\t'); if(whiteSpaceIndex > 0) mMultipartBoundary.remove(whiteSpaceIndex); whiteSpaceIndex = mMultipartBoundary.first('\"'); if(whiteSpaceIndex == 0) mMultipartBoundary.remove(whiteSpaceIndex,1); whiteSpaceIndex = mMultipartBoundary.last('\"'); if(whiteSpaceIndex > 0) mMultipartBoundary.remove(whiteSpaceIndex); #ifdef TEST_PRINT osPrintf("HttpBody: boundary=%s\n", mMultipartBoundary.data()); #endif } } } if(bytes && length < 0) length = strlen(bytes); if(bytes && length > 0) { if (mBody.append(bytes, length).length() > 0) //append was successful { bodyLength = length; if(isMultipart()) { for(int partIndex = 0; partIndex < MAX_HTTP_BODY_PARTS; partIndex++) { const char* partBytes; const char* parentBodyBytes; int partLength; int partStart; int parentBodyLength; getBytes(&parentBodyBytes, &parentBodyLength); getMultipartBytes(partIndex, &partBytes, &partLength, &partStart); if(partLength <= 0) break; if (partLength > 0) { #ifdef TEST_PRINT osPrintf("HttpBody constructor - MimeBodyPart %d added - partStart=%d - partLength=%d\n", partIndex, partStart, partLength ); #endif mpBodyParts[partIndex] = new MimeBodyPart(this, partStart, partLength); // Save the number of body parts. mBodyPartCount = partIndex + 1; } else mpBodyParts[partIndex] = NULL; } } // Append failed else { bodyLength = mBody.length(); } } // No content else { bodyLength = 0; } } } // Construct a multipart HttpBody with zero parts. HttpBodyMultipart::HttpBodyMultipart(const char* contentType) : HttpBody(NULL, -1, contentType) { for (int partIndex = 0; partIndex < MAX_HTTP_BODY_PARTS; partIndex++) { mpBodyParts[partIndex] = NULL; } // Create the boundary. nextBoundary(mMultipartBoundary); // Write it into the body. mBody = "--"; mBody.append(mMultipartBoundary); mBody.append("--\r\n"); // Add the boundary parameter to the type. append(";" MULTIPART_BOUNDARY_PARAMETER "=\""); append(mMultipartBoundary); append("\""); // No need to check validity of the boundary string, as there is no // body content for it to appear in. // Update bodyLength. bodyLength = mBody.length(); } // Copy constructor HttpBody::HttpBody(const HttpBody& rHttpBody) : UtlString(rHttpBody), bodyLength(rHttpBody.bodyLength), mBody(rHttpBody.mBody), mMultipartBoundary(rHttpBody.mMultipartBoundary), mBodyPartCount(rHttpBody.mBodyPartCount), mClassType(rHttpBody.mClassType) { for (int partIndex = 0; partIndex < MAX_HTTP_BODY_PARTS; partIndex++) { mpBodyParts[partIndex] = rHttpBody.mpBodyParts[partIndex] ? new MimeBodyPart(this, rHttpBody.mpBodyParts[partIndex]->getRawStart(), rHttpBody.mpBodyParts[partIndex]->getRawLength() ) : NULL; } } // Destructor HttpBody::~HttpBody() { for(int partIndex = 0; partIndex < MAX_HTTP_BODY_PARTS; partIndex++) { if(mpBodyParts[partIndex]) { delete mpBodyParts[partIndex]; mpBodyParts[partIndex] = NULL; } } } /* ============================ MANIPULATORS ============================== */ // Assignment operator HttpBody& HttpBody::operator=(const HttpBody& rhs) { if (this == &rhs) // handle the assignment to self case return *this; mBody = rhs.mBody; bodyLength = rhs.bodyLength; // Set the content type remove(0); append(rhs); mMultipartBoundary = rhs.mMultipartBoundary; mBodyPartCount = rhs.mBodyPartCount; for(int partIndex = 0; partIndex < MAX_HTTP_BODY_PARTS; partIndex++) { if(mpBodyParts[partIndex]) delete mpBodyParts[partIndex]; if (rhs.mpBodyParts[partIndex]) mpBodyParts[partIndex] = new MimeBodyPart(this, rhs.mpBodyParts[partIndex]->getRawStart(), rhs.mpBodyParts[partIndex]->getRawLength() ); else mpBodyParts[partIndex] = NULL; } return *this; } // Pseudo factory body copier HttpBody* HttpBody::copyBody(const HttpBody& sourceBody) { // TODO: There should be a type member. This is dangerous // as the class type may not line up with the content type HttpBody* body = NULL; BodyClassTypes classType = sourceBody.getClassType(); switch(classType) { case SDP_BODY_CLASS: body = new SdpBody(((const SdpBody&)sourceBody)); break; case SMIME_BODY_CLASS: body = new SmimeBody(((const SmimeBody&)(sourceBody))); break; case PIDF_BODY_CLASS: body = new PidfBody(((const PidfBody&)(sourceBody))); break; case DIALOG_EVENT_BODY_CLASS: body = new SipDialogEvent(sourceBody); break; case HTTP_BODY_CLASS: body = new HttpBody(sourceBody); #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpMessage::HttpMessage HttpBody copy content-type: %s\n", bodyType ? bodyType : ""); #endif break; default: OsSysLog::add(FAC_SIP, PRI_ERR, "HttpBody::copyBody unhandled body type: %d", classType); body = new HttpBody(sourceBody); break; } return(body); } // Pseudo factory HttpBody* HttpBody::createBody(const char* bodyBytes, int bodyLength, const char* contentTypeField, const char* contentEncoding) { HttpBody* body = NULL; UtlString contentTypeString; if(contentTypeField) { contentTypeString.append(contentTypeField); contentTypeString.toLower(); // Find parameter seporator if there is one int paramIndex = contentTypeString.index(';'); if (paramIndex > 0) { contentTypeString.remove(paramIndex); } contentTypeString.strip(UtlString::both); } if(contentTypeField && strcmp(contentTypeString.data(), SDP_CONTENT_TYPE) == 0) { body = new SdpBody(bodyBytes, bodyLength); } else if(contentTypeField && strcmp(contentTypeString.data(), CONTENT_SMIME_PKCS7) == 0) { body = new SmimeBody(bodyBytes, bodyLength, contentEncoding); } else if(contentTypeField && strcmp(contentTypeString.data(), CONTENT_TYPE_PIDF) == 0) { body = new PidfBody(bodyBytes, bodyLength, contentEncoding); } //else if(contentTypeField && // strcmp(contentTypeString.data(), DIALOG_EVENT_CONTENT_TYPE) == 0) //{ // body = new SipDialogEvent(bodyBytes, bodyLength, contentEncoding); //} else if ((bodyLength > 1) || (bodyBytes[0] != '\n')) { body = new HttpBody(bodyBytes, bodyLength, contentTypeField); } return(body); } // Append a multipart body part to an existing multiparty body. void HttpBody::appendBodyPart(const HttpBody& body, const UtlDList& parameters) { assert(isMultipart()); // Construct a new MimeBodyPart for the new body part. MimeBodyPart* part = new MimeBodyPart(body, parameters); // Insert it as the last body part. int index; for (index = 0; index < MAX_HTTP_BODY_PARTS; index++) { if (!mpBodyParts[index]) { mpBodyParts[index] = part; break; } } assert(index < MAX_HTTP_BODY_PARTS); // Turn the final boundary into an intermediate boundary. mBody.remove(mBody.length() - 4); mBody.append("\r\n"); // Insert the headers. int rawPartStart = mBody.length(); UtlDListIterator iterator(*part->getParameters()); NameValuePair* nvp; while ((nvp = (NameValuePair*) iterator())) { mBody.append(nvp->data()); mBody.append(": "); mBody.append(nvp->getValue()); mBody.append("\r\n"); } mBody.append("\r\n"); // Insert the body. int partStart = mBody.length(); const char* bytes; int length; body.getBytes(&bytes, &length); mBody.append(bytes, length); int partEnd = mBody.length(); // Update bodyLength. bodyLength = mBody.length(); // Determine if we have to change the boundary string. bool change_boundary_string = mBody.index(mMultipartBoundary, partStart) != UTL_NOT_FOUND; // Add the final boundary. mBody.append("\r\n--"); mBody.append(mMultipartBoundary); mBody.append("--\r\n"); // Update the MimeBodyPart to know where it is contained in the HttpBody. part->attach(this, rawPartStart, partEnd - rawPartStart, partStart, partEnd - partStart); // If we have to change the boundary string. if (change_boundary_string) { // Find a new boundary string that isn't in the body. do { nextBoundary(mMultipartBoundary); } while (mBody.index(mMultipartBoundary) != UTL_NOT_FOUND); // Replace the old boundary string. for (int partIndex = 0; partIndex < MAX_HTTP_BODY_PARTS; partIndex++) { MimeBodyPart* part = mpBodyParts[partIndex]; if (part) { // Replace the boundary string just before this part. mBody.replace(part->getRawStart() - (2 + BOUNDARY_STRING_LENGTH), BOUNDARY_STRING_LENGTH, mMultipartBoundary.data(), BOUNDARY_STRING_LENGTH); } } // Replace the boundary string in the final boundary. mBody.replace(mBody.length() - (4 + BOUNDARY_STRING_LENGTH), BOUNDARY_STRING_LENGTH, mMultipartBoundary.data(), BOUNDARY_STRING_LENGTH); // Replace the boundary string in the Content-Type. size_t loc = this->index(";" MULTIPART_BOUNDARY_PARAMETER "=\""); this->replace(loc + sizeof (";" MULTIPART_BOUNDARY_PARAMETER "=\"") - 1, BOUNDARY_STRING_LENGTH, mMultipartBoundary.data(), BOUNDARY_STRING_LENGTH); } } /* ============================ ACCESSORS ================================= */ int HttpBody::getLength() const { return bodyLength; } void HttpBody::getBytes(const char** bytes, int* length) const { *bytes = mBody.data(); *length = mBody.length(); } void HttpBody::getBytes(UtlString* bytes, int* length) const { bytes->remove(0); const char* bytePtr; getBytes(&bytePtr, length); if (*length > 0) { //hint to the string to change the capacity to the new length. //if this fails, we may not have enough ram to complete this operation unsigned int newLength = (*length); if (bytes->capacity(newLength) >= newLength) { bytes->append(bytePtr, *length); } else { OsSysLog::add(FAC_SIP, PRI_ERR, "HttpBody::getBytes allocation failure to reserve %d bytes", newLength); } } } const char* HttpBody::getBytes() const { return mBody.data(); } HttpBody::BodyClassTypes HttpBody::getClassType() const { return(mClassType); } const char* HttpBody::getMultipartBoundary() const { return mMultipartBoundary.data(); } const char* HttpBody::getContentType() const { return data(); } UtlBoolean HttpBody::getMultipartBytes(int partIndex, const char** bytes, int* length, int* start) const { #ifdef TEST_PRINT osPrintf("GetMultipartBytes: PartIndex = %d\n", partIndex); #endif UtlBoolean partFound = FALSE; if(!mMultipartBoundary.isNull()) { #ifdef TEST_PRINT osPrintf("Multipart Boundary: %s\n", mMultipartBoundary.data() ); // JMJ #endif int byteIndex = -1; int partNum = -1; int partStartIndex = -1; int partEndIndex = -1; do { byteIndex = mBody.index(mMultipartBoundary.data(), byteIndex + 1); #ifdef TEST_PRINT osPrintf("ByteIndex: %d\n", byteIndex); #endif if(byteIndex >= 0) { partNum++; if(partNum == partIndex) { #ifdef TEST_PRINT osPrintf("Part Num: %d\n", partNum); #endif partStartIndex = byteIndex + mMultipartBoundary.length(); if((mBody.data())[partStartIndex] == '\r') partStartIndex++; if((mBody.data())[partStartIndex] == '\n') partStartIndex++; #ifdef TEST_PRINT osPrintf("Part Start Index: %d\n", partStartIndex); #endif } else if(partNum == partIndex + 1) { partEndIndex = byteIndex - 3; if(((mBody.data())[partEndIndex]) == '\n') partEndIndex--; if(((mBody.data())[partEndIndex]) == '\r') partEndIndex--; #ifdef TEST_PRINT osPrintf("Part End Index: %d\n", partEndIndex); #endif } } } while(partNum <= partIndex && byteIndex >= 0); if(partStartIndex >= 0 && partEndIndex > 0) { *bytes = &(mBody.data()[partStartIndex]); *length = partEndIndex - partStartIndex + 1; *start = partStartIndex; partFound = TRUE; } else { *bytes = NULL; *length = 0; *start = -1; } } return(partFound); } const MimeBodyPart* HttpBody::getMultipart(int index) const { const MimeBodyPart* bodyPart = NULL; if(index >= 0 && index < MAX_HTTP_BODY_PARTS && isMultipart()) { bodyPart = mpBodyParts[index]; } return(bodyPart); } int HttpBody::getMultipartCount() const { return mBodyPartCount; } /* ============================ INQUIRY =================================== */ UtlBoolean HttpBody::isMultipart() const { return(!mMultipartBoundary.isNull()); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ void HttpBody::nextBoundary(UtlString& boundary) { boundaryCounter += 0x54637281; // This constant is arbitrary, but it must // be odd. char buffer[BOUNDARY_STRING_LENGTH + 1]; // Need to trim boundary counter to the needed length, as // "unsigned" may be longer. sprintf(buffer, "%0*x", BOUNDARY_STRING_LENGTH, boundaryCounter & BOUNDARY_COUNTER_MASK); boundary = buffer; } sipxtapi-3.3.0~test17/sipXtackLib/src/net/HttpMessage.cpp0000644000175000017500000033005212205617431024124 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie (dpetrie AT SIPez DOT com) // SYSTEM INCLUDES #include #include #ifdef __pingtel_on_posix__ //needed by linux #include #endif #include #include #include "utl/UtlDListIterator.h" // APPLICATION INCLUDES #include #include // Needed for SIP_SHORT_CONTENT_LENGTH_FIELD. #include #include #include #include #include #include #include #ifdef HAVE_SSL #include #endif /* HAVE_SSL */ #include #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define HTTP_READ_TIMEOUT_MSECS 30000 #define MAX_UDP_MESSAGE 65536 // :TODO: need this to be cleaned up - there are at least three controls here #undef MSG_DEBUG #undef TEST_PRINT #undef TEST // STATIC VARIABLE INITIALIZATIONS OsAtomicInt HttpMessage::smHttpMessageCount(0); // LOCAL MACROS #ifdef _VXWORKS #define iswspace(a) ((((a) >= 0x09) && ((a) <= 0x0D)) || ((a) == 0x20)) #endif /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor HttpMessage::HttpMessage(const char* messageBytes, int byteCount) { smHttpMessageCount++; mHeaderCacheClean = FALSE; //nameValues = new UtlHashBag(100); body = NULL; transportTimeStamp = 0; lastResendDuration = 0; timesSent = 0; transportProtocol = OsSocket::UNKNOWN; mFirstSent = FALSE; mSendPort = PORT_NONE; mpResponseListenerQueue = NULL; mResponseListenerData = NULL; #ifdef HTTP_TIMELOG mTimeLog.addEvent("CREATED"); #endif parseMessage(messageBytes, byteCount); } HttpMessage::HttpMessage(OsSocket* inSocket, int bufferSize) { smHttpMessageCount++; mHeaderCacheClean = FALSE; //mNameValues = new UtlHashBag(100); body = NULL; transportTimeStamp = 0; lastResendDuration = 0; timesSent = 0; transportProtocol = OsSocket::UNKNOWN; mFirstSent = FALSE; mSendPort = PORT_NONE; mpResponseListenerQueue = NULL; mResponseListenerData = NULL; #ifdef HTTP_TIMELOG mTimeLog.addEvent("READ FROM SOCKET"); #endif read(inSocket, bufferSize); } // Copy constructor HttpMessage::HttpMessage(const HttpMessage& rHttpMessage) { smHttpMessageCount++; //UtlString messageBytes; //int len; mHeaderCacheClean = rHttpMessage.mHeaderCacheClean; mFirstHeaderLine = rHttpMessage.mFirstHeaderLine; body = NULL; if(rHttpMessage.body) { body = HttpBody::copyBody(*(rHttpMessage.body)); } //nameValues = new UtlHashBag(100); transportTimeStamp = rHttpMessage.transportTimeStamp; lastResendDuration = rHttpMessage.lastResendDuration; transportProtocol = rHttpMessage.transportProtocol; timesSent = rHttpMessage.timesSent; mFirstSent = rHttpMessage.mFirstSent; mSendPort = rHttpMessage.mSendPort; mpResponseListenerQueue = rHttpMessage.mpResponseListenerQueue; mResponseListenerData = rHttpMessage.mResponseListenerData; // Hugely inefficient, but it was easy to code //rHttpMessage.getBytes(&messageBytes, &len); //parseMessage(messageBytes.data(), len); NameValuePair* headerField; NameValuePair* copiedHeader = NULL; UtlDListIterator iterator((UtlDList&)rHttpMessage.mNameValues); while((headerField = (NameValuePair*) iterator())) { copiedHeader = new NameValuePair(*headerField); mNameValues.append(copiedHeader); } #ifdef HTTP_TIMELOG mTimeLog = rHttpMessage.mTimeLog; #endif mSendAddress = rHttpMessage.mSendAddress; mSendPort = rHttpMessage.mSendPort; //messageBytes = OsUtil::NULL_OS_STRING; } // Destructor HttpMessage::~HttpMessage() { smHttpMessageCount--; //mFirstHeaderLine = OsUtil::NULL_OS_STRING; //UtlDListIterator iterator((UtlDList&)nameValues); NameValuePair* headerField = NULL; mHeaderCacheClean = FALSE; // For each name value: while((headerField = (NameValuePair*) mNameValues.get())) { //iterator.remove(); delete headerField; headerField = NULL; } // This appears to be very slow //nameValues.destroyAll(); if(body) { delete body; body = 0; } } /* ============================ MANIPULATORS ============================== */ // Assignment operator HttpMessage& HttpMessage::operator=(const HttpMessage& rHttpMessage) { // handle the assignment to self case if (this == &rHttpMessage) return *this; smHttpMessageCount--; mHeaderCacheClean = rHttpMessage.mHeaderCacheClean; mFirstHeaderLine = rHttpMessage.mFirstHeaderLine; //nameValues.destroyAll(); // Get rid of any headers which exist in this message NameValuePair* headerField = NULL; while((headerField = (NameValuePair*) mNameValues.get())) { delete headerField; headerField = NULL; } if(body) { delete body; body = NULL; } if(rHttpMessage.body) { body = HttpBody::copyBody(*(rHttpMessage.body)); } //use copy constructor to copy values smHttpMessageCount++; //UtlString messageBytes; //int len; transportTimeStamp = rHttpMessage.transportTimeStamp; lastResendDuration = rHttpMessage.lastResendDuration; transportProtocol = rHttpMessage.transportProtocol; timesSent = rHttpMessage.timesSent; mFirstSent = rHttpMessage.mFirstSent; mSendPort = rHttpMessage.mSendPort; mpResponseListenerQueue = rHttpMessage.mpResponseListenerQueue; mResponseListenerData = rHttpMessage.mResponseListenerData; // Hugely inefficient //rHttpMessage.getBytes(&messageBytes, &len); //parseMessage(messageBytes.data(), len); NameValuePair* copiedHeader = NULL; UtlDListIterator iterator((UtlDList&)rHttpMessage.mNameValues); while((headerField = (NameValuePair*) iterator())) { copiedHeader = new NameValuePair(*headerField); mNameValues.append(copiedHeader); } #ifdef HTTP_TIMELOG mTimeLog = rHttpMessage.mTimeLog; #endif mSendAddress = rHttpMessage.mSendAddress; mSendPort = rHttpMessage.mSendPort; //messageBytes = OsUtil::NULL_OS_STRING; return *this; } /* void HttpMessage::convertToPlatformPath(const char* uri, UtlString& platformFilePath) { UtlString uriString(uri); #ifdef _WIN32 int pathSeparatorIndex; while((pathSeparatorIndex = uriString.first('/')) >= 0) { uriString.replace(pathSeparatorIndex, 1, "\\"); } #endif platformFilePath = uriString; }*/ int HttpMessage::parseFirstLine(const char* messageBytesPtr, int byteCount) { mHeaderCacheClean = FALSE; mFirstHeaderLine = OsUtil::NULL_OS_STRING; int bytesConsumed = 0; // Read the first header line int nextLineOffset; int headerLineLength = UtlNameValueTokenizer::findNextLineTerminator(messageBytesPtr, byteCount, &nextLineOffset); if(headerLineLength < 0) { headerLineLength = byteCount; } if(headerLineLength > 0) { mFirstHeaderLine.append(messageBytesPtr, headerLineLength); if(nextLineOffset > 0) { bytesConsumed += nextLineOffset; } else { bytesConsumed = byteCount; } } return(bytesConsumed); } // Parse message out of byte bucket // Note: this should be broken up into smaller methods as // the need arrises for it atomic functionality void HttpMessage::parseMessage(const char* messageBytes, int byteCount) { mHeaderCacheClean = FALSE; if(byteCount <= 0) { if(messageBytes) { byteCount = strlen(messageBytes); } else { byteCount = 0; mFirstHeaderLine = OsUtil::NULL_OS_STRING; if(body) delete body; body = NULL; } } if(byteCount > 0) { int bytesConsumed = 0; const char* messageBytesPtr = messageBytes; // Read the first header line bytesConsumed = parseFirstLine(messageBytes, byteCount); // Parse the headers out and add them to the list bytesConsumed += parseHeaders(messageBytes + bytesConsumed, byteCount - bytesConsumed, mNameValues); // Create the body if there is stuff left if(byteCount > bytesConsumed) { messageBytesPtr = messageBytes + bytesConsumed; if(body) { delete body; } // Construct the body from the remaining bytes parseBody(messageBytesPtr, byteCount - bytesConsumed); } } } void HttpMessage::parseBody(const char* messageBytesPtr, int bodyLength) { if (bodyLength <= 1 && messageBytesPtr && (messageBytesPtr[0] == '\n' || messageBytesPtr[0] == '\r')) { // do nothing } // Need to use a body factory const char* contentType = getHeaderValue(0, HTTP_CONTENT_TYPE_FIELD); if (NULL == contentType) { // "C" => SIP_SHORT_CONTENT_TYPE_FIELD); cannot use sipMessage.h // // Could not find full header field name, so check for // short header field names. // contentType = getHeaderValue(0, "C"); } // HTTP_CONTENT_TRANSFER_ENCODING_FIELD does not have a short form. const char* contentEncodingString = getHeaderValue(0, HTTP_CONTENT_TRANSFER_ENCODING_FIELD); if (contentEncodingString == NULL) { contentEncodingString = getHeaderValue(0, "E"); } body = HttpBody::createBody(messageBytesPtr, bodyLength, contentType, contentEncodingString); } int HttpMessage::findHeaderEnd(const char* headerBytes, int messageLength) { int lineLength = 0; int nextLineIndex = 0; int bytesConsumed = 0; while(messageLength - bytesConsumed > 0 && (lineLength = UtlNameValueTokenizer::findNextLineTerminator(&headerBytes[bytesConsumed], messageLength - bytesConsumed, &nextLineIndex))) { if(nextLineIndex > 0) { bytesConsumed += nextLineIndex; } else { if(lineLength < 0) { bytesConsumed += messageLength - bytesConsumed; } else { bytesConsumed += lineLength; } } } // If we found a blank line: if(nextLineIndex == 1 && (headerBytes[bytesConsumed] == NEWLINE || headerBytes[bytesConsumed] == CARRIAGE_RETURN)) { bytesConsumed++; } else if(nextLineIndex == 2 && (headerBytes[bytesConsumed] == NEWLINE || headerBytes[bytesConsumed] == CARRIAGE_RETURN) && ((headerBytes[bytesConsumed + 1] == NEWLINE || headerBytes[bytesConsumed + 1] == CARRIAGE_RETURN))) { bytesConsumed += 2; } else { // If we did not find a terminator, there is no explicit end to the // headers bytesConsumed = -1; } return(bytesConsumed); } int HttpMessage::parseHeaders(const char* headerBytes, int messageLength, UtlDList& headerNameValues) { UtlString name; UtlString value; char nameFirstChar; NameValuePair* headerField = NULL; NameValuePair* previousHeaderField = NULL; UtlNameValueTokenizer parser(headerBytes, messageLength); int nameFound; // If this is a zero length line the rest is the body do { nameFound = parser.getNextPair(HTTP_NAME_VALUE_DELIMITER, &name, & value); if(nameFound) { // If this is a line continuation nameFirstChar = name(0); if(previousHeaderField != NULL && (nameFirstChar == ' ' || nameFirstChar == '\t')) { // Re-join the name and value if there is anything // in value if(!value.isNull()) { name.append(HTTP_NAME_VALUE_DELIMITER); name.append(value.data()); } // Append this to the previous headers's value name.insert(0, previousHeaderField->getValue()); previousHeaderField->setValue(name.data()); } // Create a new name value pair for the header line else { name.toUpper(); // Remove trailing white space name.strip(UtlString::leading); headerField = new NameValuePair(name.data(), value.data()); headerNameValues.append(headerField); previousHeaderField = headerField; } } //name = OsUtil::NULL_OS_STRING; //value = OsUtil::NULL_OS_STRING; } while(nameFound); //name = OsUtil::NULL_OS_STRING; //value= OsUtil::NULL_OS_STRING; return(parser.getProcessedIndex()); } int HttpMessage::get(Url& httpUrl, int maxWaitMilliSeconds, bool bPersistent) { OsSysLog::add(FAC_HTTP, PRI_DEBUG, "HttpMessage::get(2) httpUrl = '%s'", httpUrl.toString().data()); HttpMessage request; UtlString uriString; httpUrl.getPath(uriString, TRUE); request.setRequestFirstHeaderLine(HTTP_GET_METHOD, uriString, HTTP_PROTOCOL_VERSION); return(get(httpUrl, request, maxWaitMilliSeconds, bPersistent)); } OsStatus HttpMessage::get(Url& httpUrl, int iMaxWaitMilliSeconds, GetDataCallbackProc pCallbackProc, void* pOptionalData, OsConnectionSocket** socket) { OsSysLog::add(FAC_HTTP, PRI_DEBUG, "HttpMessage::get(5) httpUrl = '%s'", httpUrl.toString().data()); OsStatus rc = OS_SUCCESS ; UtlString uriString; httpUrl.getPath(uriString, TRUE); // Put CGI variable in PATH as this is GET // Construct a request HttpMessage request; request.setRequestFirstHeaderLine(HTTP_GET_METHOD, uriString, HTTP_PROTOCOL_VERSION); // Construct the socket to send request and get response int httpPort; UtlString httpHost; httpUrl.getHostAddress(httpHost); UtlString hostPort(httpHost); httpPort = httpUrl.getHostPort(); UtlString urlType; httpUrl.getUrlType(urlType); if (!portIsValid(httpPort)) { if (httpUrl.getScheme() == Url::HttpsUrlScheme) httpPort = 443; else httpPort = 80; hostPort.append(":"); char tmpportbuf[10]; sprintf(tmpportbuf,"%d",httpPort); hostPort += tmpportbuf; } request.addHeaderField("Host", hostPort.data()); request.addHeaderField("Accept", "*/*"); OsConnectionSocket *httpSocket = NULL; int tries = 0; int connected = 0; int exp = 1; while (tries++ < HttpMessageRetries) { if (httpUrl.getScheme() == Url::HttpsUrlScheme) { #ifdef HAVE_SSL httpSocket = (OsConnectionSocket *)new OsSSLConnectionSocket(httpPort, httpHost, iMaxWaitMilliSeconds/1000); #else /* ! HAVE_SSL */ // SSL is not configured in, so we cannot do https: gets. OsSysLog::add(FAC_SIP, PRI_CRIT, "HttpMessage::get(Url&,int,...) SSL not configured; " "cannot get URL '%s'", httpUrl.toString().data()); httpSocket = NULL; #endif /* HAVE_SSL */ } else { httpSocket = new OsConnectionSocket(httpPort, httpHost); } if (httpSocket) { connected = httpSocket->isConnected(); if (!connected) { OsSysLog::add(FAC_SIP, PRI_ERR, "HttpMessage::get socket connection to %s:%d failed, try again %d ...", httpHost.data(), httpPort, tries); delete httpSocket; httpSocket = 0; OsTask::delay(20*exp); exp = exp*2; } else { break; } } } if (!connected) { OsSysLog::add(FAC_SIP, PRI_ERR, "HttpMessage::get socket connection to %s:%d failed, give up...", httpHost.data(), httpPort); return OS_FAILED; } if (socket != NULL) { *socket = httpSocket ; } // Send the request int bytesSent = 0; if (httpSocket->isReadyToWrite(iMaxWaitMilliSeconds)) bytesSent = request.write(httpSocket); // Handle the response if(bytesSent > 0 && httpSocket->isReadyToRead(iMaxWaitMilliSeconds)) { UtlString buffer ; int iRead = readHeader(httpSocket, buffer) ; if (iRead > 0) { mHeaderCacheClean = FALSE; int iHeaderLength = parseFirstLine(buffer.data(), iRead) ; parseHeaders(&buffer.data()[iHeaderLength], iRead-iHeaderLength, mNameValues) ; int iContentLength = getContentLength() ; if (iContentLength > 0) iRead = readBody(httpSocket, iContentLength, pCallbackProc, pOptionalData) ; } } else rc = OS_NO_MORE_DATA ; if (socket == NULL) { delete httpSocket ; } return rc ; } int HttpMessage::get(Url& httpUrl, HttpMessage& request, int maxWaitMilliSeconds, bool bPersistent) { OsSysLog::add(FAC_HTTP, PRI_DEBUG, "HttpMessage::get(3) httpUrl = '%s'", httpUrl.toString().data()); HttpConnectionMap *pConnectionMap = NULL; HttpConnectionMapEntry* pConnectionMapEntry = NULL; UtlString uriString; httpUrl.getPath(uriString, TRUE); // Put CGI variable in PATH as this is GET // Construct the socket to send request and get response int httpPort; httpPort = httpUrl.getHostPort(); UtlString httpHost; httpUrl.getHostAddress(httpHost); UtlString urlType; httpUrl.getUrlType(urlType); // Construct the key for the persistent connection mapping UtlString key; if (bPersistent) { } // preserve these fields if they are already set if ( request.getHeaderValue(0, HTTP_HOST_FIELD) == NULL) { UtlString hostPort(httpHost); httpPort = httpUrl.getHostPort(); if (httpPort == PORT_NONE) { if (httpUrl.getScheme() == Url::HttpUrlScheme) httpPort = 80; else httpPort = 443; hostPort.append(":"); char tmpportbuf[10]; sprintf(tmpportbuf,"%d",httpPort); hostPort += tmpportbuf; } request.addHeaderField(HTTP_HOST_FIELD, hostPort.data()); } if ( request.getHeaderValue(0, HTTP_ACCEPT_FIELD) == NULL) { request.addHeaderField(HTTP_ACCEPT_FIELD, "*/*"); } OsConnectionSocket *httpSocket = NULL; int connected = 0; int httpStatus = -1; int bytesRead = 0; int bytesSent = 0; int sendTries = 0; // Set connection header to keep-alive, get a map entry for the URI with the asscoiated socket. // If there is no existing map entry, one will be created with the httpSocket set to NULL. if (bPersistent) { pConnectionMap = HttpConnectionMap::getHttpConnectionMap(); request.setHeaderValue(HTTP_CONNECTION_FIELD, "Keep-Alive"); pConnectionMapEntry = pConnectionMap->getPersistentConnection(httpUrl, httpSocket); } // Try to send request at least once, on persistent connections retry once if it fails. // Retry on persistent connections because the getPersistentConnection call may return // a non-NULL socket, assuming the connection is persistent when the other side is not. while (sendTries < HttpMessageRetries && bytesRead == 0) { if (httpSocket == NULL) { int tries = 0; int exp = 1; while (tries++ < HttpMessageRetries) { if (urlType == "https") { #ifdef HAVE_SSL httpSocket = (OsConnectionSocket *)new OsSSLConnectionSocket(httpPort, httpHost, maxWaitMilliSeconds/1000); #else /* ! HAVE_SSL */ // SSL is not configured in, so we cannot do https: gets. OsSysLog::add(FAC_SIP, PRI_CRIT, "HttpMessage::get(Url&,HttpMessage&,int) SSL not configured; " "cannot get URL '%s'", httpUrl.toString().data()); httpSocket = NULL; #endif /* HAVE_SSL */ } else { httpSocket = new OsConnectionSocket(httpPort, httpHost); } if (httpSocket) { connected = httpSocket->isConnected(); if (!connected) { OsSysLog::add(FAC_SIP, PRI_ERR, "HttpMessage::get socket connection to %s:%d failed, try again %d ...\n", httpHost.data(), httpPort, tries); delete httpSocket; httpSocket = 0; OsTask::delay(20*exp); exp = exp*2; } else { break; } } } // If we created a new connection and are persistent then remember the socket in the map // and mark connection as being used if (pConnectionMapEntry) { pConnectionMapEntry->mpSocket = httpSocket; pConnectionMapEntry->mbInUse = true; } } else { connected = httpSocket->isConnected(); } if (!connected) { OsSysLog::add(FAC_SIP, PRI_ERR, "HttpMessage::get socket connection to %s:%d failed, give up...\n", httpHost.data(), httpPort); if (pConnectionMap) { // Release lock on persistent connection pConnectionMapEntry->mLock.release(); } return httpStatus; } // Send the request - most of the time returns 1 for some reason, 0 indicates problem if (httpSocket->isReadyToWrite(maxWaitMilliSeconds)) { bytesSent = request.write(httpSocket); } if (bytesSent == 0) { if (pConnectionMap) { // No bytes were sent .. if this is a persistent connection and it failed on retry // mark it unused in the connection map. Set socket to NULL if (sendTries == HttpMessageRetries-1) { pConnectionMapEntry->mbInUse = false; } // Close socket to avoid timeouts in subsequent calls httpSocket->close(); delete httpSocket; pConnectionMapEntry->mpSocket = NULL; httpSocket = NULL; OsSysLog::add(FAC_HTTP, PRI_DEBUG, "HttpMessage::get Sending failed sending on persistent connection on try %d", sendTries); } } else if( bytesSent > 0 && httpSocket->isReadyToRead(maxWaitMilliSeconds)) { bytesRead = read(httpSocket); // Close a non-persistent connection if (pConnectionMap == NULL) { httpSocket->close(); } else { if (bytesRead == 0) { // No bytes were read .. if this is a persistent connection // and it failed on retry mark it unused // in the connection map. Set socket to NULL if (sendTries == HttpMessageRetries-1) { pConnectionMapEntry->mbInUse = false; } httpSocket->close(); delete httpSocket; pConnectionMapEntry->mpSocket = NULL; httpSocket = NULL; OsSysLog::add(FAC_HTTP, PRI_DEBUG, "HttpMessage::get Receiving failed on persistent connection on try %d", sendTries); } else { // On success don't retry for persistent connection, set sendTries // to mamximum to break out of loop sendTries = HttpMessageRetries; } } } ++sendTries; } if (pConnectionMapEntry) { // Release lock on persistent connection pConnectionMapEntry->mLock.release(); } if(bytesRead > 0) { httpStatus = getResponseStatusCode(); int authEntity = SERVER; if(httpStatus == HTTP_UNAUTHORIZED_CODE) { authEntity = SERVER; } else if(httpStatus == HTTP_PROXY_UNAUTHORIZED_CODE) { authEntity = PROXY; } UtlString authScheme; getAuthenticationScheme(&authScheme, authEntity); if(authScheme.compareTo(HTTP_BASIC_AUTHENTICATION, UtlString::ignoreCase) == 0) { // if we have a password add the credentials to the // request UtlString user; UtlString password; httpUrl.getUserId(user); httpUrl.getPassword(password); if(! user.isNull()) { request.setBasicAuthorization(user, password, authEntity); // Construct a new socket OsConnectionSocket *httpAuthSocket = NULL; int httpStatus = -1; int tries = 0; int connected = 0; int exp = 1; while (tries++ < 6) { if (urlType == "https") { #ifdef HAVE_SSL httpAuthSocket = (OsConnectionSocket *)new OsSSLConnectionSocket(httpPort, httpHost, maxWaitMilliSeconds/1000); #else /* ! HAVE_SSL */ // SSL is not configured in, so we cannot do https: gets. OsSysLog::add(FAC_SIP, PRI_CRIT, "HttpMessage::get(Url&,HttpMessage&,int) SSL not configured; " "cannot get URL '%s'", httpUrl.toString().data()); httpAuthSocket = NULL; #endif /* HAVE_SSL */ } else httpAuthSocket = new OsConnectionSocket(httpPort, httpHost); if (httpAuthSocket) { connected = httpAuthSocket->isConnected(); if (!connected) { OsSysLog::add(FAC_SIP, PRI_ERR, "HttpMessage::get socket connection to %s:%d failed, try again %d ...\n", httpHost.data(), httpPort, tries); delete httpAuthSocket; httpAuthSocket = 0; OsTask::delay(20*exp); exp = exp*2; } else { break; } } } if (!connected) { OsSysLog::add(FAC_SIP, PRI_ERR, "HttpMessage::get socket connection to %s:%d failed, give up...\n", httpHost.data(), httpPort); return httpStatus; } // Sent the request again if (httpAuthSocket->isReadyToWrite(maxWaitMilliSeconds)) bytesSent = request.write(httpAuthSocket); bytesRead = 0; // Clear out the data in the previous response mHeaderCacheClean = FALSE; mNameValues.destroyAll(); if(body) { delete body; body = 0; } // Wait for the response if(bytesSent > 0 && httpAuthSocket->isReadyToRead(maxWaitMilliSeconds)) { bytesRead = read(httpAuthSocket); httpAuthSocket->close(); } // Get the response if(bytesRead > 0) { httpStatus = getResponseStatusCode(); } if (httpAuthSocket) delete httpAuthSocket; } // end if auth. retry } // End if Basic Auth. } // End if first response was returned if (httpSocket && !bPersistent) { delete httpSocket; httpSocket = 0; } return(httpStatus); } int HttpMessage::readHeader(OsSocket* inSocket, UtlString& buffer) { char ch ; int iBytesRead = 0 ; int iRead; OsSocket::IpProtocolSocketType socketType = inSocket->getIpProtocol(); UtlString remoteHost; int remotePort; UtlBoolean bLastWasCr = FALSE; UtlBoolean bIsCrLfFormat = FALSE ; setSendProtocol(socketType); // If there are no residual bytes in the buffer if (inSocket->isOk() && ((socketType != OsSocket::TCP && socketType != OsSocket::SSL_SOCKET) || inSocket->isReadyToRead(HTTP_READ_TIMEOUT_MSECS))) { while (inSocket->isOk() && inSocket->isReadyToRead(HTTP_READ_TIMEOUT_MSECS)) { iRead = inSocket->read(&ch, 1, &remoteHost, &remotePort); if (iRead == 1) { buffer.append(ch) ; iBytesRead++ ; if ((bLastWasCr) && (ch == CARRIAGE_RETURN)) { // Read Lf is we are in crlf format if (bIsCrLfFormat) { iRead = inSocket->read(&ch, 1, &remoteHost, &remotePort); } // Time to quit, we have hit the end of the header break ; } else if ((bLastWasCr) && (ch == NEWLINE)) { bIsCrLfFormat = TRUE ; } else { if (ch == CARRIAGE_RETURN) bLastWasCr = TRUE ; if (!iswspace(ch)) bLastWasCr = FALSE ; } } else break ; } } return(iBytesRead); } int HttpMessage::readBody(OsSocket* inSocket, int iLength, GetDataCallbackProc pCallbackProc, void* pOptionalData) { char buffer[4096] ; int iBytesRead = 0 ; unsigned int iRead; OsSocket::IpProtocolSocketType socketType = inSocket->getIpProtocol(); UtlString remoteHost; int remotePort; // If there are no residual bytes in the buffer if (inSocket->isOk() && ((socketType != OsSocket::TCP && socketType != OsSocket::SSL_SOCKET ) || inSocket->isReadyToRead(HTTP_READ_TIMEOUT_MSECS))) { while (inSocket->isOk() && inSocket->isReadyToRead(HTTP_READ_TIMEOUT_MSECS) && (iBytesRead < iLength)) { int iMaxRead = sipx_min(sizeof(buffer), (unsigned int) (iLength - iBytesRead)) ; iRead = inSocket->read(buffer, iMaxRead, &remoteHost, &remotePort); if (iRead > 0) { iBytesRead += iRead ; UtlBoolean bRC = (*pCallbackProc)(buffer, (unsigned long) iRead, pOptionalData, this) ; if (bRC == FALSE) { break ; } } else break ; } } // Signal callback proc that data transfer is complete (*pCallbackProc)(NULL, -1, pOptionalData, this) ; return(iBytesRead); } int HttpMessage::read(OsSocket* inSocket, int bufferSize, UtlString* externalBuffer, int maxContentLength) { // // Initialize state variables that keep track of what we have seen // of the incoming HTTP message. // mHeaderCacheClean = FALSE; // Remember to empty the list of parsed header values, as we will use it // to parse the headers on the HTTP response we are going to read. mNameValues.destroyAll(); //the following code if enabled will test the effect of messages coming in a //fragmented way. This should NOT be enabled in a released build as //performance will be severely affected. #ifdef FRAGMENTATION_TEST #ifdef _WIN32 #pragma message("!!!!!!!!!! WARNING: Buffer size set to 1. DO NOT build release builds this way. Very SLOW! Please change this in: " __FILE__) #else #warning !!!!!!!!!!! Buffer size set to 1. DO NOT build release builds this way. Very SLOW !!!!!!!!!!!!!!!!!! #endif bufferSize = 1; #endif // allBytes is the buffer we will be using to assemble the message. // If externalBuffer is supplied, use that, otherwise use localBuffer. UtlString localBuffer; UtlString* allBytes = externalBuffer != NULL ? externalBuffer : &localBuffer; int returnMessageLength = 0; // Attempt to minimize the number of times that the string gets // re-allocated and copied by setting the initial capacity to the // requested approximate message size, bufferSize. int byteCapacity = allBytes->capacity(bufferSize); if (byteCapacity >= bufferSize) { // Reallocating allBytes was successful. // Get information about the socket. UtlString remoteHost; int remotePort; inSocket->getRemoteHostIp(&remoteHost, &remotePort); OsSocket::IpProtocolSocketType socketType = inSocket->getIpProtocol(); setSendProtocol(socketType); #ifdef TEST OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpMessage::read socket: %p " "getIpProtocol: %d remoteHost: %s remotePort: %d\n", inSocket, socketType, remoteHost.data(), remotePort); #endif // Initialize control variables. char* buffer = new char[bufferSize]; int bytesTotal = allBytes->length(); int bytesRead = 0; // The byte offset of the end of the header. -1 means the end // has not yet been seen. int headerEnd = -1; // The length of the content. -1 means the end is not yet known. int contentLength = -1; UtlBoolean contentLengthSet = FALSE; // Assume content-type is set until we read all of the headers. UtlBoolean contentTypeSet = TRUE; UtlString contentType; // // Read the HTTP message. // // If there are no residual bytes in the buffer, read from the socket. // :TODO: This is probably not quite right. I suspect that its // main effect is to have the first read from the socket use 4 // arguments (to get the remote host/port), whereas the read at // the bottom of the do-while uses 2 arguments (because it // usually does later reads, and don't need to get the remote // ost/port again). But this scheme doesn't work so well, as // there is a third fetch of remote host/port inside the body of // the do-while. if (bytesTotal <= 0 && inSocket->isOk() && (OsSocket::isFramed(socketType) || inSocket->isReadyToRead(HTTP_READ_TIMEOUT_MSECS))) { bytesRead = inSocket->read(buffer, bufferSize, &remoteHost, &remotePort); setSendAddress(remoteHost.data(), remotePort); if (bytesRead <= 0) { delete[] buffer; return bytesRead; } } do { if (bytesRead > 0) { if (allBytes->append(buffer, bytesRead).length() > 0) { bytesTotal += bytesRead; } else { osPrintf("ERROR: Error appending data. possible out of memory error.\n"); bytesRead = 0; break; } } //osPrintf("HttpMessage::read buffer capacity: %d buff addr: %X\n", allBytes.capacity(), allBytes.data()); // If we have not yet found the end of the headers if (headerEnd < 0) { headerEnd = findHeaderEnd(allBytes->data(), bytesTotal); // UDP and Multicast UDP you can only do one read // The fragmentation is handled at the socket layer // If we did not get it all we are not going to get any more if (OsSocket::isFramed(socketType) && headerEnd <= 0) { headerEnd = bytesTotal; } // We found the end of all the headers. Parse them. if (headerEnd > 0) { // Parse the first line int endOfFirstLine = parseFirstLine(allBytes->data(), headerEnd); // Parse all of the headers parseHeaders(&(allBytes->data()[endOfFirstLine]), headerEnd - endOfFirstLine, mNameValues); #ifdef TEST // Print out the header values as we have extracted them. if (OsSysLog::getLoggingPriority() <= PRI_DEBUG) { UtlDListIterator iterator((UtlDList&) mNameValues); NameValuePair* headerField; # ifdef MSG_DEBUG // :TODO: Commented out for the time being to reduce // the volume of debug messages. We really need // finer-grained control over debugging messages // than we have now. while ((headerField = (NameValuePair*) iterator()) != NULL) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpMessage::read Found header '%s': '%s'", headerField->data(), headerField->getValue()); } # endif /* MSG_DEBUG */ } #endif // Get the content length { const char* value; if ((value = getHeaderValue(0, HTTP_CONTENT_LENGTH_FIELD)) != NULL) { contentLengthSet = TRUE; contentLength = atoi(value); } else if ((value = getHeaderValue(0, SIP_SHORT_CONTENT_LENGTH_FIELD)) != NULL) { contentLengthSet = TRUE; contentLength = atoi(value); } } // Get the content type contentTypeSet = getContentType(&contentType); #ifdef TEST OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpMessage::read contentLengthSet %d, " "contentLength %d, contentTypeSet %d, " "contentType '%s'", contentLengthSet, contentLength, contentTypeSet, contentType.data()); #endif // If this is UDP we know that the message has // a maximum size of 64K if (socketType == OsSocket::UDP && contentLength > MAX_UDP_MESSAGE) { OsSysLog::add(FAC_SIP, PRI_WARNING, "HttpMessage::read Content-Length too big for " "UDP: %d, from %s:%d assuming: %d", contentLength, remoteHost.data(), remotePort, MAX_UDP_MESSAGE); contentLength = MAX_UDP_MESSAGE; } // Make sure we do not try to allocate something // outrageously large. if (contentLength > maxContentLength) { contentLengthSet = FALSE; OsSysLog::add(FAC_SIP, PRI_WARNING, "HttpMessage::read Content-Length too big: %d," "closing socket type: %d to %s:%d", contentLength, socketType, remoteHost.data(), remotePort); // Shut it all down, because it may be an abusive sender. inSocket->close(); allBytes->remove(0); break; } // If a content length is set adjust the capacity // to minimize the number of resizing and memory // shuffling operations else if (contentLength > 0) { byteCapacity = headerEnd + contentLength + 100; allBytes->capacity(headerEnd + contentLength + 100); } } } // If we know we have all of the message, exit this loop. // To know we have all of the message, we need to have seen the end of the headers. // If there was a Content-Length, we need to have read that many more bytes. // If there was no Content-Length, this socket must have a framed protocol. if (headerEnd > 0 && (contentLengthSet ? contentLength + headerEnd <= ((int) allBytes->length()) : OsSocket::isFramed(socketType))) { break; } // Check to see if this is a non-framed protocol, we have seen the end of the headers, // but we haven't seen a Content-Length header. That is an error condition. if (!OsSocket::isFramed(socketType) && headerEnd > 0 && !contentLengthSet) { OsSysLog::add(FAC_SIP, PRI_ERR, "HttpMessage::read Message has no Content-Length " "on unframed socket type: %d\n", socketType); // Exit the loop with the defective message, because we have no way to find its end. break; } // Check to see if this is a framed protocol, because to get here, the first read // of the message did not get to its end. That is an error condition. if (OsSocket::isFramed(socketType)) { OsSysLog::add(FAC_SIP, PRI_ERR, "HttpMessage::read Attempt to do second read for a message " "on framed socket type: %d\n", socketType); // Exit the loop with the defective message, because we have no way to find its end. break; } // Make sure we set the source of the bytes if (remoteHost.isNull()) { inSocket->getRemoteHostIp(&remoteHost); remotePort = inSocket->getRemoteHostPort(); setSendAddress(remoteHost.data(), remotePort); } // Read more of the message and continue processing it. } while (inSocket->isOk() && (OsSocket::isFramed(socketType) || inSocket->isReadyToRead(HTTP_READ_TIMEOUT_MSECS)) && (bytesRead = inSocket->read(buffer, bufferSize)) > 0); // // We have reached one of the conditions that indicates to stop // reading the HTTP message. Decide whether we have finished // reading successfully. // // Calculate the end of the message & body length unsigned int bodyLength = 0; unsigned int messageLength = 0; if (headerEnd > 0 && (!contentLengthSet || OsSocket::isFramed(socketType))) { messageLength = allBytes->length(); bodyLength = messageLength - headerEnd; } else if (headerEnd > 0 && contentLengthSet) { // We have found a Content-Length header. //only if the total bytes read is as expected //ie equal or greater than (contentLength + headerEnd) if (bytesTotal - headerEnd >= contentLength) { // We have the entire expected length of the message. bodyLength = contentLength; messageLength = headerEnd + contentLength; // There is residual bytes for the next message if (messageLength < allBytes->length()) { #ifdef TEST_PRINT int residual = allBytes->length() - messageLength; OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpMessage::read bytes left over: %d\n", residual); #endif // Get ride of initial white space as the residual is // suppose to be the begining of the next message int endOfWhiteSpace = FALSE; while(messageLength < allBytes->length() && !endOfWhiteSpace) { switch((allBytes->data())[messageLength]) { case ' ': case '\n': case '\r': case '\t': messageLength++; break; default: endOfWhiteSpace = TRUE; break; } } #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpMessage::read trimming whitespace from " "residual: %d\n", residual + messageLength - allBytes->length()); #endif } } else { // We do not have the entire expected length of the message. bodyLength = bytesTotal - headerEnd; # ifdef MSG_DEBUG // At this point, the entire message should have been read // (in multiple reads if necessary). OsSysLog::add(FAC_SIP, PRI_WARNING, "HttpMessage::read Not all content data " "successfully read: received %d body bytes but " "Content-Length was %d", bodyLength, contentLength); # endif /* MSG_DEBUG */ #ifdef TEST OsSysLog::add(FAC_SIP, PRI_WARNING, "HttpMessage::read protocol %d, remoteHost %s, " "remotePort %d", socketType, remoteHost.data(), remotePort); OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpMessage::read Content:\n>>>%.*s<<<\n", allBytes->length(), allBytes->data()); #endif } } else if (allBytes->length() > 0) { // We have not found the end of headers, or we have not found // a Content-Length header. # ifdef MSG_DEBUG // This should not happen because the message will have been // fetched with multiple reads if necessary. OsSysLog::add(FAC_SIP, PRI_ERR, "HttpMessage::read End of headers not found. " "%d bytes read. Content:\n>>>%.*s<<<\n", allBytes->length(), allBytes->length(), allBytes->data()); # endif /* MSG_DEBUG */ } // If there is a body. if (headerEnd > 0 && bodyLength) { // All that is left is the body to deal with parseBody(&(allBytes->data()[headerEnd]), bodyLength); } delete[] buffer; returnMessageLength = messageLength; } else { // Attempt to resize the input buffer to the requested // approximate size (allBytes->capacity(bufferSize)) failed, so // return an error. OsSysLog::add(FAC_SIP, PRI_ERR, "HttpMessage::read allBytes->capacity(%d) failed, " "returning %d", bufferSize, byteCapacity); returnMessageLength = 0; } return(returnMessageLength); } UtlBoolean HttpMessage::write(OsSocket* outSocket) const { UtlString buffer; int bufferLen; int bytesWritten; getBytes(&buffer, &bufferLen); bytesWritten = outSocket->write(buffer.data(), bufferLen); return(bytesWritten == bufferLen); } void HttpMessage::unescape(UtlString& escapedText) { //UtlString unescapedText; int numUnescapedChars = 0; const char* unescapedTextPtr = escapedText; // The number of unescaped characters is always less than // or equal to the number of escaped characters. Therefore // we will cheat a little and used the escapedText as // the destiniation to directly write characters in place // as the append method is very expensive char* resultPtr = new char[escapedText.length() + 1]; int escapedChar = -1; while(*unescapedTextPtr) { // Substitute escaped space if(*unescapedTextPtr == '+') { //unescapedText.append(' '); resultPtr[numUnescapedChars] = ' '; numUnescapedChars++; } // Substitute escaped hex char else if(*unescapedTextPtr == '%') { unescapedTextPtr++; if(*unescapedTextPtr) { if(*unescapedTextPtr >= '0' && *unescapedTextPtr <= '9') { escapedChar = (*unescapedTextPtr - '0') * 16; } else if(*unescapedTextPtr >= 'a' && *unescapedTextPtr <= 'f') { escapedChar = (*unescapedTextPtr - 'W') * 16; } else if(*unescapedTextPtr >= 'A' && *unescapedTextPtr <= 'F') { escapedChar = (*unescapedTextPtr - '7') * 16; } unescapedTextPtr++; if(*unescapedTextPtr) { if(*unescapedTextPtr >= '0' && *unescapedTextPtr <= '9') { escapedChar += (*unescapedTextPtr - '0'); } else if(*unescapedTextPtr >= 'a' && *unescapedTextPtr <= 'f') { escapedChar += (*unescapedTextPtr - 'W'); } else if(*unescapedTextPtr >= 'A' && *unescapedTextPtr <= 'F') { escapedChar += (*unescapedTextPtr - '7'); } #ifdef TEST_PRINT osPrintf("HttpMessage::unescape char: %d\n", escapedChar); #endif //unescapedText.append((char) escapedChar); resultPtr[numUnescapedChars] = (char) escapedChar; numUnescapedChars++; } else { #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "Bogus dude: escaped char wo/ 2 hex digits: %s\n", escapedText.data()); #endif break; } } else { #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "Bogus dude: escaped char wo/ 2 hex digits: %s\n", escapedText.data()); #endif break; } } // Char is face value else { //unescapedText.append(unescapedTextPtr, 1); resultPtr[numUnescapedChars] = *unescapedTextPtr; numUnescapedChars++; } // Go to the next character unescapedTextPtr++; } //escapedText = unescapedText; resultPtr[numUnescapedChars] = '\0'; escapedText.replace(0, numUnescapedChars, resultPtr); escapedText.remove(numUnescapedChars); delete[] resultPtr; } void HttpMessage::escape(UtlString& unEscapedText) { UtlString escapedText; escapedText.capacity((size_t) unEscapedText.length()); const char* unescapedTextPtr = unEscapedText.data(); char unEscapedChar; char escapedChar[4]; while(*unescapedTextPtr) { unEscapedChar = *unescapedTextPtr; if((unEscapedChar >= 'a' && unEscapedChar <= 'z') || (unEscapedChar >= 'A' && unEscapedChar <= 'Z') || (unEscapedChar >= '0' && unEscapedChar <= '9') || unEscapedChar == '-' || //dash unEscapedChar == '_' || //underscore unEscapedChar == '.' ) { escapedText.append(&unEscapedChar, 1); } else if(unEscapedChar == ' ') { escapedText.append("+", 1); } else { sprintf(escapedChar, "%%%02X", (int)(unEscapedChar & 0xff)); #ifdef TEST_PRINT osPrintf("%d escaped: %s\n", (int) unEscapedChar, escapedChar); #endif escapedText.append(escapedChar); } unescapedTextPtr++; } unEscapedText = escapedText; } void HttpMessage::escapeOneChar(UtlString& unEscapedText, char tobeEscapedChar) { UtlString escapedText; escapedText.capacity((size_t) unEscapedText.length()); const char* unescapedTextPtr = unEscapedText.data(); char unEscapedChar; char escapedChar[4]; while(*unescapedTextPtr) { unEscapedChar = *unescapedTextPtr; if(unEscapedChar == tobeEscapedChar ) { if (' ' == unEscapedChar) { strcpy(escapedChar, "+"); } else { sprintf(escapedChar, "%%%02X", (int) (unEscapedChar & 0xff)); } #ifdef TEST_PRINT osPrintf("%d escaped: %s\n", (int) unEscapedChar, escapedChar); #endif escapedText.append(escapedChar); } else escapedText.append(&unEscapedChar, 1); unescapedTextPtr++; } unEscapedText = escapedText; } void HttpMessage::escapeChars(UtlString& unEscapedText, UtlString& tobeEscapedChars) { const char* tobeEscapedcharsPtr = tobeEscapedChars.data(); char unEscapedChar; while (*tobeEscapedcharsPtr) { unEscapedChar = *tobeEscapedcharsPtr; escapeOneChar(unEscapedText, unEscapedChar); tobeEscapedcharsPtr++; } } void HttpMessage::cannonizeToken(UtlString& token) { int len = token.length(); UtlBoolean capNextChar = TRUE; const char* tokenPtr = token.data(); char thisChar; // If len == 1 we assume short names are being used - don't cannonize them if (len > 1) { for(int capCharIndex = 0; capCharIndex < len; capCharIndex++) { thisChar = tokenPtr[capCharIndex]; if(capNextChar) { if(thisChar >= 'a' && thisChar <= 'z') { token.replaceAt(capCharIndex, toupper(thisChar)); } capNextChar = FALSE; } else if(thisChar >= 'A' && thisChar <= 'Z') { token.replaceAt(capCharIndex, tolower(thisChar)); } if(thisChar == '-') { capNextChar = TRUE; } } // Special case CSeq and try to minimize impact of check for CSeq if(len == 4 && tokenPtr[0] == 'C' && tokenPtr[1] == 's' && tokenPtr[2] == 'e' && tokenPtr[3] == 'q') { token.replaceAt(1, 'S'); } } #ifdef TEST_PRINT //osPrintf("HttpMessage::cannonizeToken \"%s\"\n", // token.data()); #endif } void HttpMessage::logTimeEvent(const char* eventName) { #ifdef HTTP_TIMELOG mTimeLog.addEvent(eventName); #endif } void HttpMessage::dumpTimeLog() const { #ifdef HTTP_TIMELOG mTimeLog.dumpLog(); #endif } /* ============================ ACCESSORS ================================= */ int HttpMessage::getHttpMessageCount() { return(smHttpMessageCount); } const char* HttpMessage::getFirstHeaderLine() const { return(mFirstHeaderLine.data()); } void HttpMessage::setFirstHeaderLine(const char* newHeaderLine) { mHeaderCacheClean = FALSE; if(newHeaderLine) { mFirstHeaderLine.remove(0); mFirstHeaderLine.append(newHeaderLine); } else { mFirstHeaderLine.remove(0); } } void HttpMessage::setFirstHeaderLine(const char* subfield0, const char* subfield1, const char* subfield2) { UtlString headerValue; headerValue.append(subfield0); headerValue.append(HEADER_LINE_PART_DELIMITER); headerValue.append(subfield1); headerValue.append(HEADER_LINE_PART_DELIMITER); headerValue.append(subfield2); setFirstHeaderLine(headerValue.data()); } void HttpMessage::setTransportTime(long timeStamp) { transportTimeStamp = timeStamp; } void HttpMessage::touchTransportTime() { //long now = OsDateTime::getSecsSinceEpoch(); OsTime time; OsDateTime::getCurTimeSinceBoot(time); setTransportTime(time.seconds()); } long HttpMessage::getTransportTime() const { return(transportTimeStamp); } void HttpMessage::setResendDuration(int resendMSec) { lastResendDuration = resendMSec; } int HttpMessage::getResendDuration() const { return(lastResendDuration); } int HttpMessage::getTimesSent() const { return(timesSent); } void HttpMessage::incrementTimesSent() { timesSent++; } void HttpMessage::setTimesSent(int times) { timesSent = times; } void HttpMessage::setSendProtocol(OsSocket::IpProtocolSocketType protocol) { transportProtocol = protocol; } OsSocket::IpProtocolSocketType HttpMessage::getSendProtocol() const { return(transportProtocol); } void HttpMessage::setFirstSent() { mFirstSent = TRUE; } void HttpMessage::setSendAddress(const char* address, int port) { mSendAddress.remove(0); if(address) mSendAddress.append(address); mSendPort = port; } void HttpMessage::getSendAddress(UtlString* address, int* port) const { *address = mSendAddress; *port = mSendPort; } void HttpMessage::resetTransport() { transportTimeStamp = 0; lastResendDuration = 0; timesSent = 0; transportProtocol = OsSocket::UNKNOWN; mFirstSent = FALSE; mSendAddress = ""; mSendPort = PORT_NONE; } OsMsgQ* HttpMessage::getResponseListenerQueue() const { return(mpResponseListenerQueue); } void HttpMessage::setResponseListenerQueue(OsMsgQ* responseListenerQueue) { mpResponseListenerQueue = responseListenerQueue; } void* HttpMessage::getResponseListenerData() const { return(mResponseListenerData); } void HttpMessage::setResponseListenerData(void* responseListenerData) { mResponseListenerData = responseListenerData; } int HttpMessage::getCountHeaderFields(const char* name) const { int fieldCount; if(name) { UtlString nameString(name); nameString.toUpper(); UtlString nameCollectable(nameString); fieldCount = mNameValues.occurrencesOf(&nameCollectable); } else { fieldCount = mNameValues.entries(); } return(fieldCount); } NameValuePair* HttpMessage::getHeaderField(int index, const char* name) const { UtlDListIterator iterator((UtlDList&)mNameValues); //NameValuePair* headerFieldName = NULL; NameValuePair* headerField = NULL; int fieldIndex = 0; //iterator.reset(); //if(name) //{ //UtlString upperCaseName(name); //upperCaseName.toUpper(); //UtlString headerFieldName(name ? name : ""); //headerFieldName.toUpper(); //} //int nameLength = 0; //if(name) //{ // nameLength = strlen(name); //} // For each name value: while(fieldIndex <= index) { // Go to the next header field if(name) { // Too slow and too much overhead (i.e. needs UtlContainable string // to be constructed and destroyed) // headerField = (NameValuePair*) iterator.findNext(&headerFieldName); // Find a header with a matching name do { headerField = (NameValuePair*) iterator(); } while(headerField && strcasecmp(name, headerField->data()) != 0); } else { headerField = (NameValuePair*) iterator(); } if(!headerField) { break; } fieldIndex++; } //if(headerFieldName) //{ // delete headerFieldName; // headerFieldName = NULL; //} return(headerField); } const char* HttpMessage::getHeaderValue(int index, const char* name) const { const char* value = NULL; NameValuePair* headerField = getHeaderField(index, name); if(headerField) { value = headerField->getValue(); } return(value); } void HttpMessage::setHeaderValue(const char* name, const char* newValue, int index) { mHeaderCacheClean = FALSE; NameValuePair* headerField = getHeaderField(index, name); if(headerField) { headerField->setValue(newValue); } else { addHeaderField(name, newValue); } } UtlBoolean HttpMessage::removeHeader(const char* name, int index) { mHeaderCacheClean = FALSE; UtlBoolean foundHeader = FALSE; UtlDListIterator iterator((UtlDList&)mNameValues); NameValuePair* headerFieldName = NULL; NameValuePair* headerField = NULL; int fieldIndex = 0; if(name) { headerFieldName = new NameValuePair(name); headerFieldName->toUpper(); } // For each name value: while(fieldIndex <= index) { // Go to the next header field if(name) { headerField = (NameValuePair*) iterator.findNext(headerFieldName); } else { headerField = (NameValuePair*) iterator(); } if(!headerField) { break; } fieldIndex++; } if(headerFieldName) { delete headerFieldName; headerFieldName = NULL; } if(headerField) { mNameValues.removeReference(headerField); delete headerField; foundHeader = TRUE; } return(foundHeader); } void HttpMessage::addHeaderField(const char* name, const char* value) { mHeaderCacheClean = FALSE; NameValuePair* headerField = new NameValuePair(name ? name : "", value); headerField->toUpper(); mNameValues.insert(headerField); } void HttpMessage::insertHeaderField(const char* name, const char* value, int index) { mHeaderCacheClean = FALSE; NameValuePair* headerField = new NameValuePair(name ? name : "", value); headerField->toUpper(); mNameValues.insertAt(index, headerField); } const HttpBody* HttpMessage::getBody() const { return(body); } void HttpMessage::setBody(HttpBody* newBody) { if(body) { delete body; } body = newBody; } UtlBoolean HttpMessage::getContentType(UtlString* contentTypeString, UtlHashMap* parameters) const { const char* contentType = getHeaderValue(0, HTTP_CONTENT_TYPE_FIELD); contentTypeString->remove(0); if(contentType) { UtlNameValueTokenizer::getSubField(contentType, 0, ";", contentTypeString); contentTypeString->strip(UtlString::both); if(parameters) { // Might consider using this instead of the following code // HttpRequestContext::parseCgiVariables(mRawFieldParameters, // *mpFieldParameters, ";", "=", // TRUE, &Url::gen_value_unescape); // The following is a bit inefficient in that it reparses looking for the ; param separator each time UtlString contentTypeParam; for (int param_idx = 1; UtlNameValueTokenizer::getSubField(contentType, param_idx, ";", &contentTypeParam); param_idx++ ) { UtlString name; UtlString value; UtlNameValueTokenizer paramPair(contentTypeParam); UtlString* nameString = NULL; UtlString* valueString = NULL; if (paramPair.getNextPair('=',&name,&value)) { nameString = new UtlString(name); nameString->toLower(); // Cannonize as lower case nameString->strip(UtlString::both); valueString = new UtlString(value); Url::gen_value_unescape(*valueString); parameters->insertKeyAndValue(nameString, valueString); nameString = NULL; } else { // No text between semicolins OsSysLog::add(FAC_SIP,PRI_WARNING,"invalid content-type parameter '%s'", contentTypeParam.data()); } } } } return(contentType != NULL); } void HttpMessage::setContentType(const char* contentTypeString, const char* accessType, const char* expirationDate, const char* url, int size, const char* hash) { UtlString contentHeaderValue(contentTypeString); UtlString escapedValue; if(accessType) { escapedValue = accessType; Url::gen_value_escape(escapedValue); const char* quoteFound = strchr(escapedValue, '"'); contentHeaderValue.append(';'); contentHeaderValue.append(HTTP_CONTENT_TYPE_PARAM_ACCESS_TYPE); contentHeaderValue.append('='); if(!quoteFound) { contentHeaderValue.append('"'); } contentHeaderValue.append(escapedValue); if(!quoteFound) { contentHeaderValue.append('"'); } } if(expirationDate) { contentHeaderValue.append(';'); contentHeaderValue.append(HTTP_CONTENT_TYPE_PARAM_EXPIRATION); contentHeaderValue.append('='); escapedValue = expirationDate; Url::gen_value_escape(escapedValue); contentHeaderValue.append(escapedValue); } if(url) { contentHeaderValue.append(';'); // Looks like Motorola might be case sensative //contentHeaderValue.append(HTTP_CONTENT_TYPE_PARAM_URL); contentHeaderValue.append("URL"); contentHeaderValue.append('='); escapedValue = url; Url::gen_value_escape(escapedValue); contentHeaderValue.append(escapedValue); } if(size > 0) { UtlString sizeString; UtlInt::toString(sizeString, size); contentHeaderValue.append(';'); contentHeaderValue.append(HTTP_CONTENT_TYPE_PARAM_SIZE); contentHeaderValue.append('='); escapedValue = sizeString; Url::gen_value_escape(escapedValue); contentHeaderValue.append(escapedValue); } if(hash) { contentHeaderValue.append(';'); contentHeaderValue.append(HTTP_CONTENT_TYPE_PARAM_HASH); contentHeaderValue.append('='); escapedValue = hash; Url::gen_value_escape(escapedValue); contentHeaderValue.append(escapedValue); } setHeaderValue(HTTP_CONTENT_TYPE_FIELD, contentHeaderValue); } void HttpMessage::setDateField() { OsDateTime now; OsDateTime::getCurTime(now); UtlString nowString; now.getHttpTimeString(nowString); setHeaderValue(HTTP_DATE_FIELD, nowString.data()); } int HttpMessage::getContentLength() const { const char* contentLength = getHeaderValue(0, HTTP_CONTENT_LENGTH_FIELD); int length = 0; if (contentLength) length = atoi(contentLength); return(length); } void HttpMessage::setContentLength(int contentLength) { char contentLengthString[HTTP_LONG_INT_CHARS]; sprintf(contentLengthString, "%d", contentLength); setHeaderValue(HTTP_CONTENT_LENGTH_FIELD, contentLengthString); } void HttpMessage::getUserAgentField(UtlString* userAgentField) const { const char* userAgent = getHeaderValue(0, HTTP_USER_AGENT_FIELD); userAgentField->remove(0); if(userAgent) { userAgentField->append(userAgent); } } void HttpMessage::setUserAgentField(const char* userAgentField) { setHeaderValue(HTTP_USER_AGENT_FIELD, userAgentField); } void HttpMessage::setRefresh(int seconds, const char* refreshUrl) { char refreshLenString[HTTP_LONG_INT_CHARS]; sprintf(refreshLenString, "%d", seconds); UtlString refreshField(refreshLenString); refreshField.append(" "); if(refreshUrl && refreshUrl[0]) { refreshField.append("URL="); refreshField.append(refreshUrl); } setHeaderValue(HTTP_REFRESH_FIELD, refreshField.data()); } UtlBoolean HttpMessage::getDateField(long* epochDate) const { const char* dateField = getHeaderValue(0, HTTP_DATE_FIELD); if(dateField) { *epochDate = OsDateTime::convertHttpDateToEpoch(dateField); // returns zero if the format is not understood if(! *epochDate) { #ifdef TEST_PRINT osPrintf("WARNING: unsupported date format\n"); osPrintf("Date field: \"%s\"\n", dateField); osPrintf("epoch date: %d\n", *epochDate); #endif } } return(dateField != NULL && *epochDate); } UtlBoolean HttpMessage::getAcceptField(UtlString& acceptValue) const { const char* value = getHeaderValue(0, HTTP_ACCEPT_FIELD); acceptValue.remove(0); if(value) { acceptValue = value; } return(value != NULL); } void HttpMessage::getAcceptLanguageField(UtlString* acceptLanaguageFieldValue) const { const char* language = getHeaderValue(0, HTTP_ACCEPT_LANGUAGE_FIELD); acceptLanaguageFieldValue->remove(0); if(language) { acceptLanaguageFieldValue->append(language); } } void HttpMessage::setAcceptLanguageField(const char* acceptLanaguageFieldValue) { setHeaderValue(HTTP_ACCEPT_LANGUAGE_FIELD, acceptLanaguageFieldValue); } void HttpMessage::setLocationField(const char* locationField) { setHeaderValue(HTTP_LOCATION_FIELD, locationField); } void HttpMessage::getBytes(UtlString* bufferString, int* length) const { *length = 0; UtlString name; const char* value; *bufferString = mFirstHeaderLine; bufferString->append(END_OF_LINE_DELIMITOR); UtlDListIterator iterator((UtlDList&)mNameValues); NameValuePair* headerField; UtlBoolean foundContentLengthHeader = FALSE; int bodyLen = 0; UtlString bodyBytes; if(body) { body->getBytes(&bodyBytes, &bodyLen); } int oldLen = 0 ; if(mHeaderCacheClean && bodyLen == (oldLen = getContentLength())) { // We have a clean serialized cache of the first header line // and headers, use it instead of serializing it // Check if the content length is explicitly set //if(oldLen > 0 || // avoid getHeaderField call if content length set // getHeaderField(0, HTTP_CONTENT_LENGTH_FIELD)) //{ // foundContentLengthHeader = TRUE; //} // dummy code to allow instrumentation and setting of break points oldLen = 0; } else { // we have to serialize the headers and cache the result // This cast is a bit of hack for this instrumention so that // the const signature does not have to change ((HttpMessage*)this)->mHeaderCacheClean = TRUE; // dummy code to allow instrumentation and setting of break points oldLen = 0; } // For each name value: while((headerField = (NameValuePair*) iterator())) { // Do not free up name and data as this are contained // in the NameValuePair name = *headerField; cannonizeToken(name); value = headerField->getValue(); // Keep track while we are looping through if we see a // content-length header or not - also test for a SIP short name // content length header so we don't add one if there is a short // name header. if((name.compareTo(HTTP_CONTENT_LENGTH_FIELD, UtlString::ignoreCase) == 0) || (name.compareTo("l", UtlString::ignoreCase) == 0)) { foundContentLengthHeader = TRUE; int fieldBodyLengthValue = atoi(value ? value : ""); if(fieldBodyLengthValue != bodyLen) { char bodyLengthString[40]; sprintf(bodyLengthString, "%d", bodyLen); OsSysLog::add(FAC_SIP, PRI_WARNING, "HttpMessage::getBytes content-length: %s wrong setting to: %s", value ? value : "", bodyLengthString); headerField->setValue(bodyLengthString); value = headerField->getValue(); } } bufferString->append(name); bufferString->append(HTTP_NAME_VALUE_DELIMITER); bufferString->append(" "); if(value) { bufferString->append(value); } bufferString->append(END_OF_LINE_DELIMITOR); } // Make sure the content length is set if(!foundContentLengthHeader) { HttpBody* pBody = (HttpBody*)getBody(); UtlString ContentLen(HTTP_CONTENT_LENGTH_FIELD); cannonizeToken(ContentLen); bufferString->append(ContentLen); bufferString->append(HTTP_NAME_VALUE_DELIMITER); char bodyLengthString[40]; if (pBody) sprintf(bodyLengthString, " %d", pBody->getLength()); else sprintf(bodyLengthString, " %d", bodyLen); bufferString->append(bodyLengthString); bufferString->append(END_OF_LINE_DELIMITOR); } bufferString->append(END_OF_LINE_DELIMITOR); if(body) { bufferString->append(bodyBytes.data(), body->getLength()); } *length = bufferString->length(); } void HttpMessage::getFirstHeaderLinePart(int partIndex, UtlString* part, char separator) const { const char* partStart = mFirstHeaderLine.data(); // Tolerate separators in the begining while(*partStart == separator) partStart++; const char* partEnd; int index = 0; part->remove(0); // Find the begining while(partStart && index < partIndex) { partStart = strchr(partStart, separator); if(partStart == NULL) break; partStart++; // Tolerate multiple consecutive separators while(*partStart == separator) partStart++; index++; } // If there is a begining find the end if(partStart) { if(partIndex < 2) { partEnd = strchr(partStart, separator); if(partEnd == NULL) { partEnd = partStart + strlen(partStart); } int len = partEnd - partStart; part->append(partStart, len); //part->append("",1); } // This is the third part take the whole thing else { part->append(partStart); } } } // Response access methods void HttpMessage::setResponseFirstHeaderLine(const char* protocol, int statusCode, const char* statusText) { char codeBuffer[HTTP_LONG_INT_CHARS]; sprintf(codeBuffer, "%d", statusCode); setFirstHeaderLine(protocol, codeBuffer, statusText); } void HttpMessage::getResponseProtocol(UtlString* protocol) const { getFirstHeaderLinePart(0, protocol); } int HttpMessage::getResponseStatusCode() const { UtlString codeString; getFirstHeaderLinePart(1, &codeString); int ret = atoi(codeString.data()); return ret; } void HttpMessage::getResponseStatusText(UtlString* text) const { getFirstHeaderLinePart(2, text); *text = text->strip(UtlString::both); } // Request access methods void HttpMessage::setRequestFirstHeaderLine(const char* method, const char* uri, const char* protocol) { if (uri[0] == '<') { OsSysLog::add(FAC_SIP, PRI_ERR, "HttpMessage::setRequestFirstHeaderLine(3) request URI has <>: '%s'", uri); } setFirstHeaderLine(method, uri, protocol); } void HttpMessage::getRequestMethod(UtlString* method) const { getFirstHeaderLinePart(0, method); *method =method->strip(UtlString::both); } void HttpMessage::getRequestUri(UtlString* uri) const { getFirstHeaderLinePart(1, uri); } void HttpMessage::getRequestProtocol(UtlString* protocol) const { getFirstHeaderLinePart(2, protocol); *protocol = protocol->strip(UtlString::both); } void HttpMessage::changeRequestUri(const char* newUri) { UtlString method; UtlString protocol; getFirstHeaderLinePart(0, &method); getFirstHeaderLinePart(2, &protocol); setRequestFirstHeaderLine(method.data(), newUri, protocol.data()); } UtlBoolean HttpMessage::getAuthenticationScheme(UtlString* scheme, int authorizationEntity) const { const char* fieldValue = NULL; if(authorizationEntity == SERVER) { fieldValue = getHeaderValue(0, HTTP_WWW_AUTHENTICATE_FIELD); } else if(authorizationEntity == PROXY) { fieldValue = getHeaderValue(0, HTTP_PROXY_AUTHENTICATE_FIELD); } if(fieldValue) { NetAttributeTokenizer tokenizer(fieldValue); UtlString dummy; tokenizer.getNextAttribute(*scheme, dummy); cannonizeToken(*scheme); } return(fieldValue != NULL); } void HttpMessage::setAuthenticationData(const char* scheme, const char* realm, const char* nonce, const char* opaque, const char* domain, enum HttpEndpointEnum authEntity) { UtlString schemeString; UtlString authField; if(scheme) { schemeString.append(scheme); authField.append(scheme); cannonizeToken(authField); } else { authField.append(HTTP_BASIC_AUTHENTICATION); // :TBD: should be Digest } authField.append(' '); authField.append(HTTP_AUTHENTICATION_REALM_TOKEN); authField.append('='); if(realm) { authField.append('\"'); authField.append(realm); authField.append('\"'); } else { OsSysLog::add( FAC_SIP, PRI_ERR, "HttpMessage::setAuthenticationData: no realm specified" ); } if( 0 == schemeString.compareTo(HTTP_DIGEST_AUTHENTICATION, UtlString::ignoreCase ) ) { if(domain && *domain) { authField.append(", "); authField.append(HTTP_AUTHENTICATION_DOMAIN_TOKEN); authField.append("=\""); authField.append(domain); authField.append('\"'); } if(nonce && *nonce) { authField.append(", "); authField.append(HTTP_AUTHENTICATION_NONCE_TOKEN); authField.append("=\""); authField.append(nonce); authField.append('\"'); } if(opaque && *opaque) { authField.append(", "); authField.append(HTTP_AUTHENTICATION_OPAQUE_TOKEN); authField.append("=\""); authField.append(opaque); authField.append('\"'); } // :TBD: should add qop } //setHeaderValue(HTTP_WWW_AUTHENTICATE_FIELD, authField.data(), 0); addAuthenticationField(authField.data(), authEntity); } UtlBoolean HttpMessage::getAuthenticationData(UtlString* scheme, UtlString* realm, UtlString* nonce, UtlString* opaque, UtlString* algorithm, // MD5 or MD5-sess UtlString* qop, // may be multiple values int authorizationEntity) const { const char* fieldValue = NULL; if(authorizationEntity == SERVER) { fieldValue = getHeaderValue(0, HTTP_WWW_AUTHENTICATE_FIELD); } else if(authorizationEntity == PROXY) { fieldValue = getHeaderValue(0, HTTP_PROXY_AUTHENTICATE_FIELD); } if(fieldValue) { NetAttributeTokenizer tokenizer(fieldValue); UtlString name; UtlString value; if(realm) realm->remove(0); if(nonce) nonce->remove(0); if(opaque) opaque->remove(0); if(algorithm) algorithm->remove(0); if(qop) qop->remove(0); tokenizer.getNextAttribute(*scheme, value); cannonizeToken(*scheme); // Search for tokens independent of order while(tokenizer.getNextAttribute(name, value)) { name.toLower(); if( realm && name.compareTo(HTTP_AUTHENTICATION_REALM_TOKEN, UtlString::ignoreCase) == 0 ) { realm->append(value.data()); } else if(nonce && name.compareTo(HTTP_AUTHENTICATION_NONCE_TOKEN, UtlString::ignoreCase) == 0) { nonce->append(value.data()); } else if(opaque && name.compareTo(HTTP_AUTHENTICATION_OPAQUE_TOKEN, UtlString::ignoreCase) == 0) { opaque->append(value.data()); } else if(algorithm && name.compareTo(HTTP_AUTHENTICATION_ALGORITHM_TOKEN, UtlString::ignoreCase) == 0) { algorithm->append(value.data()); } else if(qop && name.compareTo(HTTP_AUTHENTICATION_QOP_TOKEN, UtlString::ignoreCase) == 0) { qop->append(value.data()); } } } return(fieldValue != NULL); } UtlBoolean HttpMessage::getAuthorizationUser(UtlString* userId) const { UtlBoolean foundUserId = FALSE; UtlString scheme; UtlString dummy; getAuthorizationScheme(&scheme); #ifdef TEST osPrintf("HttpMessage::getAuthorizationUser authorization scheme: \"%s\"\n", scheme.data()); #endif // Basic if(scheme.compareTo(HTTP_BASIC_AUTHENTICATION, UtlString::ignoreCase) == 0) { foundUserId = getBasicAuthorizationData(userId, &dummy); #ifdef TEST_PRINT if(foundUserId) { osPrintf("HttpMessage::getAuthorizationUser userId: \"%s\" from message\n", userId->data()); } else { osPrintf("HttpMessage::getAuthorizationUser failed to get userId from message\n"); } #endif } // Digest else if(scheme.compareTo(HTTP_DIGEST_AUTHENTICATION, UtlString::ignoreCase) == 0) { getDigestAuthorizationData(userId); } // scheme not supported else { userId->remove(0); } return(foundUserId); } UtlBoolean HttpMessage::getAuthorizationField(UtlString* authenticationField, int authorizationEntity) const { const char* fieldValue = NULL; if(authorizationEntity == SERVER) { fieldValue = getHeaderValue(0, HTTP_AUTHORIZATION_FIELD); } else if(authorizationEntity == PROXY) { fieldValue = getHeaderValue(0, HTTP_PROXY_AUTHORIZATION_FIELD); } authenticationField->remove(0); if(fieldValue) { authenticationField->append(fieldValue); } return(fieldValue != NULL); } UtlBoolean HttpMessage::getDigestAuthorizationData(UtlString* user, UtlString* realm, UtlString* nonce, UtlString* opaque, UtlString* response, UtlString* uri, int authorizationEntity, int index) const { const char* value = NULL; value = getHeaderValue(index, HTTP_PROXY_AUTHORIZATION_FIELD); if(!value) { value = getHeaderValue(index, HTTP_AUTHORIZATION_FIELD); } if(value) { NetAttributeTokenizer tokenizer(value); UtlString name; UtlString value; UtlString scheme; if(realm) realm->remove(0); if(nonce) nonce->remove(0); if(opaque) opaque->remove(0); if(user) user->remove(0); if(uri) uri->remove(0); if(response) response->remove(0); // If this is a digest response tokenizer.getNextAttribute(scheme, value); if( 0 == scheme.compareTo(HTTP_DIGEST_AUTHENTICATION, UtlString::ignoreCase ) ) { // Search for tokens independent of order while(tokenizer.getNextAttribute(name, value)) { name.toUpper(); if(realm && name.compareTo(HTTP_AUTHENTICATION_REALM_TOKEN, UtlString::ignoreCase) == 0) { realm->append(value.data()); } else if(nonce && name.compareTo(HTTP_AUTHENTICATION_NONCE_TOKEN, UtlString::ignoreCase) == 0) { nonce->append(value.data()); } else if(opaque && name.compareTo(HTTP_AUTHENTICATION_OPAQUE_TOKEN, UtlString::ignoreCase) == 0) { opaque->append(value.data()); } else if(user && name.compareTo(HTTP_AUTHENTICATION_USERNAME_TOKEN, UtlString::ignoreCase) == 0) { user->append(value.data()); } else if(response && name.compareTo(HTTP_AUTHENTICATION_RESPONSE_TOKEN, UtlString::ignoreCase) == 0) { response->append(value.data()); } else if(uri && name.compareTo(HTTP_AUTHENTICATION_URI_TOKEN, UtlString::ignoreCase) == 0) { uri->append(value.data()); } } } } return(value != NULL); } void HttpMessage::addAuthenticationField(const char* authenticationField, enum HttpEndpointEnum authEntity) { const char* fieldName = "bad-auth-entity"; if(authEntity == PROXY) { fieldName = HTTP_PROXY_AUTHENTICATE_FIELD; } else if(authEntity == SERVER) { fieldName = HTTP_WWW_AUTHENTICATE_FIELD; } addHeaderField(fieldName, authenticationField); } UtlBoolean HttpMessage::getAuthenticationField(int index, enum HttpEndpointEnum authEntity, const char* authenticationField) const { const char* fieldName = "bad-auth-entity"; if(authEntity == SERVER) { fieldName = HTTP_PROXY_AUTHENTICATE_FIELD; } else if(authEntity == PROXY) { fieldName = HTTP_WWW_AUTHENTICATE_FIELD; } const char* value = getHeaderValue(index, fieldName); authenticationField = value ? value : ""; return(value != NULL); } void HttpMessage::addAuthenticationField(const char * AuthorizeField, const char * AuthorizeValue, UtlBoolean otherAuthentications) { /* NameValuePair* nv = new NameValuePair(AuthorizeField, AuthorizeValue); // Look for other via fields int fieldIndex = nameValues.index(nv); if(fieldIndex == UTL_NOT_FOUND || !afterOtherVias) { nameValues.insert(nv); } else { nameValues.insertAt(fieldIndex, nv); }*/ } void HttpMessage::setDigestAuthorizationData(const char* user, const char* realm, const char* nonce, const char* uri, const char* response, const char* algorithm, const char* cnonce, const char* opaque, const char* qop, int nonceCount, int authorizationEntity) { UtlString schemeString; UtlString authField; authField.append(HTTP_DIGEST_AUTHENTICATION); if(user && strlen(user)) { authField.append(' '); authField.append(HTTP_AUTHENTICATION_USERNAME_TOKEN); authField.append("=\""); authField.append(user); authField.append('\"'); } if(realm) { authField.append(", "); authField.append(HTTP_AUTHENTICATION_REALM_TOKEN); authField.append("=\""); authField.append(realm); authField.append('\"'); } if(nonce && strlen(nonce)) { authField.append(", "); authField.append(HTTP_AUTHENTICATION_NONCE_TOKEN); authField.append("=\""); authField.append(nonce); authField.append('\"'); } if(uri && strlen(uri)) { authField.append(", "); authField.append(HTTP_AUTHENTICATION_URI_TOKEN); authField.append("=\""); authField.append(uri); authField.append('\"'); } if(response && strlen(response)) { authField.append(", "); authField.append(HTTP_AUTHENTICATION_RESPONSE_TOKEN); authField.append("=\""); authField.append(response); authField.append('\"'); } if(algorithm && strlen(algorithm)) { authField.append(", "); authField.append(HTTP_AUTHENTICATION_ALGORITHM_TOKEN); authField.append("="); authField.append(algorithm); } UtlString alg(algorithm ? algorithm : ""); if(cnonce && strlen(cnonce) && ((qop && strlen(qop)) || (algorithm && alg.compareTo(HTTP_MD5_SESSION_ALGORITHM, UtlString::ignoreCase) == 0))) { authField.append(", "); authField.append(HTTP_AUTHENTICATION_CNONCE_TOKEN); authField.append("=\""); authField.append(cnonce); authField.append('\"'); } if(opaque && strlen(opaque)) { authField.append(", "); authField.append(HTTP_AUTHENTICATION_OPAQUE_TOKEN); authField.append("=\""); authField.append(opaque); authField.append('\"'); } if(qop && strlen(qop)) { UtlString qopString(qop); authField.append(", "); authField.append(HTTP_AUTHENTICATION_QOP_TOKEN); authField.append("="); int qopIntIndex = qopString.index(HTTP_QOP_AUTH_INTEGRITY, 0, UtlString::ignoreCase); int qopIndex = qopString.index(HTTP_QOP_AUTH, 0, UtlString::ignoreCase); if(qopIntIndex >= 0) { authField.append(HTTP_QOP_AUTH_INTEGRITY); } else if(qopIndex >= 0) { authField.append(HTTP_QOP_AUTH); } } if(nonceCount > 0 && qop && strlen(qop)) { char nonceCountBuffer[20]; sprintf(nonceCountBuffer, "%.8x", nonceCount); UtlString nonceCountString(nonceCountBuffer); nonceCountString.toLower(); authField.append(", "); authField.append(HTTP_AUTHENTICATION_NONCE_COUNT_TOKEN); authField.append('='); authField.append(nonceCountString); } if(authorizationEntity == SERVER) { addHeaderField(HTTP_AUTHORIZATION_FIELD, authField.data()); } else if(authorizationEntity == PROXY) { addHeaderField(HTTP_PROXY_AUTHORIZATION_FIELD, authField.data()); } } void HttpMessage::buildMd5UserPasswordDigest(const char* user, const char* realm, const char* password, UtlString& userPasswordDigest) { // Construct A1 UtlString a1Buffer; if(user) a1Buffer.append(user); a1Buffer.append(':'); if(realm) a1Buffer.append(realm); a1Buffer.append(':'); if(password) a1Buffer.append(password); // Encode A1 NetMd5Codec::encode(a1Buffer.data(), userPasswordDigest); } /*void HttpMessage::buildMd5Digest(const char* user, const char* password, const char* realm, const char* nonce, const char* uri, const char* method, UtlString* responseToken) { UtlString encodedA1; buildMd5UserPasswordDigest(user, realm, password, encodedA1); buildMd5Digest(encodedA1.data(), NULL, //algorithm nonce, NULL, // cnonce 0, // nonceCount NULL, // qop method, uri, NULL, // bodyDigest responseToken); }*/ void HttpMessage::buildMd5Digest(const char* userPasswordDigest, const char* algorithm, const char* nonce, const char* cnonce, int nonceCount, const char* qop, const char* method, const char* uri, const char* bodyDigest, UtlString* responseToken) { // Construct A1 UtlString encodedA1; UtlString alg(algorithm ? algorithm : ""); if(alg.compareTo(HTTP_MD5_SESSION_ALGORITHM, UtlString::ignoreCase) == 0) { UtlString a1Buffer(userPasswordDigest); a1Buffer.append(':'); if(nonce) a1Buffer.append(nonce); a1Buffer.append(':'); if(cnonce) a1Buffer.append(cnonce); NetMd5Codec::encode(a1Buffer.data(), encodedA1); } else { encodedA1 = userPasswordDigest; } // Construct A2 UtlString a2Buffer; UtlString encodedA2; if(method) a2Buffer.append(method); a2Buffer.append(':'); if(uri) a2Buffer.append(uri); UtlString qopString(qop ? qop : ""); UtlBoolean qopInt = FALSE; int qopIndex = qopString.index(HTTP_QOP_AUTH_INTEGRITY, 0, UtlString::ignoreCase); if(qopIndex >= 0) { qopInt = TRUE; a2Buffer.append(':'); if(bodyDigest) a2Buffer.append(bodyDigest); } // Encode A2 NetMd5Codec::encode(a2Buffer.data(), encodedA2); // Construct buffer UtlString buffer(encodedA1); buffer.append(':'); if(nonce) buffer.append(nonce); qopIndex = qopString.index(HTTP_QOP_AUTH, 0, UtlString::ignoreCase); if(qopIndex >= 0) { char nonceCountBuffer[20]; sprintf(nonceCountBuffer, "%.8x", nonceCount); UtlString nonceCountString(nonceCountBuffer); nonceCountString.toLower(); buffer.append(':'); buffer.append(nonceCountString); buffer.append(':'); if(cnonce) buffer.append(cnonce); buffer.append(':'); if(qopInt) { buffer.append(HTTP_QOP_AUTH_INTEGRITY); } else { buffer.append(HTTP_QOP_AUTH); } } buffer.append(':'); buffer.append(encodedA2); // Encode buffer NetMd5Codec::encode(buffer.data(), *responseToken); #ifdef TEST_PRINT osPrintf("HttpMessage::buildMd5Digest expecting authorization:\n\tuserPasswordDigest: '%s'\n\tnonce: '%s'\n\tmethod: '%s'\n\turi: '%s'\n\tresponse: '%s'\n", userPasswordDigest, nonce, method, uri, responseToken->data()); #endif } UtlBoolean HttpMessage::verifyMd5Authorization(const char* userId, const char* password, const char* nonce, const char* realm, const char* thisMessageMethod, const char* thisMessageUri, enum HttpEndpointEnum authEntity) const { UtlBoolean allowed = FALSE; UtlString uri; UtlString method; UtlString referenceHash; UtlString msgUser; UtlString msgRealm; UtlString msgNonce; UtlString msgOpaque; UtlString msgDigestHash; UtlString msgUri; if(thisMessageUri && *thisMessageUri) { uri.append(thisMessageUri); } else { getRequestUri(&uri); } if(thisMessageMethod && *thisMessageMethod) { method.append(thisMessageMethod); } else { getRequestMethod(&method); } // Build a digest hash for the reference buildMd5Digest(password, NULL, // algorithm nonce, NULL, // cnonce 0, // nonceCount NULL, // qop method.data(), uri.data(), NULL, // body digest &referenceHash); // Build a digest hash for the reference /* buildMd5Digest(password,"",nonce,"", uri.data(), method.data(), &referenceHash);*/ // Get the digest hash given in the message int authIndex = 0; while(getDigestAuthorizationData(&msgUser, &msgRealm, &msgNonce, &msgOpaque, &msgDigestHash, &msgUri, authEntity, authIndex)) { if((referenceHash.compareTo(msgDigestHash) == 0)) { allowed = TRUE; break; } authIndex++; } #ifdef TEST OsSysLog::add(FAC_SIP,PRI_DEBUG,"HttpMessage::verifyMd5Authorization got digest response: \"%s\"\n", msgDigestHash.data()); OsSysLog::add(FAC_SIP,PRI_DEBUG,"HttpMessage::verifyMd5Authorization wanted response: \"%s\"\n", referenceHash.data()); #endif return(allowed); } UtlBoolean HttpMessage::verifyMd5Authorization(const char* userPasswordDigest, const char* nonce, const char* thisMessageMethod, const char* thisMessageUri) const { UtlBoolean allowed; UtlString uri; UtlString method; UtlString referenceHash; UtlString msgUser; UtlString msgRealm; UtlString msgNonce; UtlString msgOpaque; UtlString msgDigestHash; UtlString msgUri; if(thisMessageUri && *thisMessageUri) { uri.append(thisMessageUri); } else { getRequestUri(&uri); } if(thisMessageMethod && *thisMessageMethod) { method.append(thisMessageMethod); } else { getRequestMethod(&method); } // Build a digest hash for the reference buildMd5Digest(userPasswordDigest, NULL, // algorithm nonce, NULL, // cnonce 0, // nonceCount NULL, // qop method.data(), uri.data(), NULL, // body digest &referenceHash); // Get the digest hash given in the message allowed = getDigestAuthorizationData(&msgUser, &msgRealm, &msgNonce, &msgOpaque, &msgDigestHash, &msgUri); if(allowed) { allowed = (referenceHash.compareTo(msgDigestHash) == 0); } #ifdef TEST OsSysLog::add(FAC_SIP,PRI_DEBUG,"HttpMessage::verifyMd5Authorization got digest response: \"%s\"\n", msgDigestHash.data()); OsSysLog::add(FAC_SIP,PRI_DEBUG,"HttpMessage::verifyMd5Authorization wanted response: \"%s\"\n", referenceHash.data()); #endif return(allowed); } void HttpMessage::buildBasicAuthorizationCookie(const char* user, const char* password, UtlString* cookie) { UtlString clearToken; // Create the base64 encoded user:password cookie if(user) { clearToken.append(user); } clearToken.append(':'); if(password) { clearToken.append(password); } NetBase64Codec::encode(clearToken.length(), clearToken.data(), *cookie); } void HttpMessage::setRequestUnauthorized(const HttpMessage* request, const char* authenticationScheme, const char* authenticationRealm, const char* authenticationNonce, const char* authenticationOpaque, const char* authenticationDomain) { setResponseFirstHeaderLine("HTTP/1.1", HTTP_UNAUTHORIZED_CODE, HTTP_UNAUTHORIZED_TEXT); setAuthenticationData(authenticationScheme, authenticationRealm, authenticationNonce, authenticationOpaque, authenticationDomain); } void HttpMessage::setBasicAuthorization(const char* user, const char* password, int authorizationEntity) { UtlString fieldValue(HTTP_BASIC_AUTHENTICATION); UtlString encodedToken; // Create the encoded user:password cookie buildBasicAuthorizationCookie(user, password, &encodedToken); // Add the cookie to the field fieldValue.append(' '); fieldValue.append(encodedToken.data()); // Set the header field if(authorizationEntity == SERVER) { setHeaderValue(HTTP_AUTHORIZATION_FIELD, fieldValue.data(), 0); } else if(authorizationEntity == PROXY) { setHeaderValue(HTTP_PROXY_AUTHORIZATION_FIELD, fieldValue.data(), 0); } } UtlBoolean HttpMessage::getAuthorizationScheme(UtlString* scheme) const { UtlString fieldValue; UtlBoolean fieldSet = getAuthorizationField(&fieldValue, SERVER); UtlNameValueTokenizer::getSubField(fieldValue.data(), 0, " \t", scheme); scheme->toUpper(); return(fieldSet); } UtlBoolean HttpMessage::getBasicAuthorizationData(UtlString* encodedCookie) const { UtlString fieldValue; UtlBoolean fieldSet = getAuthorizationField(&fieldValue, SERVER); UtlString scheme; UtlNameValueTokenizer::getSubField(fieldValue.data(), 0, " \t", &scheme); scheme.toUpper(); // If the scheme is not basic, then the second token is probably not a cookie if(scheme.compareTo(HTTP_BASIC_AUTHENTICATION, UtlString::ignoreCase) == 0) { UtlNameValueTokenizer::getSubField(fieldValue.data(), 1, " \t", encodedCookie); } else { encodedCookie->remove(0); } return(fieldSet); } UtlBoolean HttpMessage::getBasicAuthorizationData(UtlString* userId, UtlString* password) const { UtlString cookie; UtlBoolean cookieFound = getBasicAuthorizationData(&cookie); userId->remove(0); password->remove(0); if(cookieFound) { #ifdef TEST osPrintf("HttpMessage::getBasicAuthorizationData cookie: \"%s\"\n", cookie.data()); #endif int decodedLength = NetBase64Codec::decodedSize(cookie.length(), cookie.data()); char* decodedCookie = new char[decodedLength + 1]; NetBase64Codec::decode(cookie.length(), cookie.data(), decodedLength, decodedCookie); #ifdef TEST_PRINT decodedCookie[decodedLength] = 0; osPrintf("HttpMessage::getBasicAuthorizationData decoded cookie: \"%s\"\n", decodedCookie); #endif // Parse out the userId and password intptr_t userPasswordSeparatorIndex = (intptr_t) strchr(decodedCookie, ':'); if(userPasswordSeparatorIndex) { userPasswordSeparatorIndex -= (intptr_t) decodedCookie; userId->append(decodedCookie, userPasswordSeparatorIndex); password->append(&decodedCookie[userPasswordSeparatorIndex + 1], decodedLength - (userPasswordSeparatorIndex + 1)); #ifdef TEST osPrintf("HttpMessage::getBasicAuthorizationData user/password separator index: %d\n", userPasswordSeparatorIndex); osPrintf("HttpMessage::getBasicAuthorizationData user: \"%s\" password: \"%s\"\n", userId->data(), password->data()); #endif } // No separator, assume the whole thing is a user Id else { #ifdef TEST_PRINT osPrintf("HttpMessage::getBasicAuthorizationData no user/password separator found\n"); #endif userId->append(decodedCookie, decodedLength); } delete[] decodedCookie; decodedCookie = NULL; } #ifdef TEST else { osPrintf("HttpMessage::getBasicAuthorizationData cookie not found in message\n"); } #endif return(cookieFound); } UtlBoolean HttpMessage::verifyBasicAuthorization(const char* user, const char* password) const { UtlString referenceCookie; UtlString givenCookie; UtlBoolean userAllowed = TRUE; if(user == NULL || strcmp(user, "") == 0) { #ifdef TEST osPrintf("HttpMessage::verifyBasicAuthorization no db user id given\n"); #endif userAllowed = FALSE; } #ifdef TEST else { osPrintf("HttpMessage::verifyBasicAuthorization user: \"%s\" password: \"%s\"\n", user, password); } #endif if(userAllowed) { // Create the reference encoded user:password cookie buildBasicAuthorizationCookie(user, password, &referenceCookie); // Get the user:password cookie provided in this message userAllowed = getBasicAuthorizationData(&givenCookie); #ifdef TEST osPrintf("HttpMessage::verifyBasicAuthorization user: \"%s\" password: \"%s\"\n", user, password); osPrintf("HttpMessage::verifyBasicAuthorization ref. cookie: \"%s\"\n", referenceCookie.data()); osPrintf("HttpMessage::verifyBasicAuthorization msg. cookie: \"%s\"\n", givenCookie.data()); #endif } if(userAllowed) { // If the cookies match, allow this message userAllowed = (referenceCookie.compareTo(givenCookie.data()) == 0); } #ifdef TEST else { osPrintf("HttpMessage::verifyBasicAuthorization no cookie in authorization field\n"); } #endif return(userAllowed); } /* ============================ INQUIRY =================================== */ UtlBoolean HttpMessage::isWholeMessage(const char* messageBuffer, int bufferLength, int& numberBytesChecked, int& contentLength) { return(FALSE); } UtlBoolean HttpMessage::isFirstSend() const { return(!mFirstSent); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/HttpRequestContext.cpp0000644000175000017500000004041312205613256025535 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2010 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS //#define TEST_DEBUG #ifdef TEST_DEBUG # include #endif // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor HttpRequestContext::HttpRequestContext(const char* requestMethod, const char* rawUrl, const char* mappedFile, const char* serverName, const char* userId, const OsConnectionSocket* connection ) : mUsingInsensitive(false), mConnectionEncrypted(false), mPeerCertTrusted(false) { if(requestMethod) { mEnvironmentVars[HTTP_ENV_REQUEST_METHOD].append(requestMethod); mEnvironmentVars[HTTP_ENV_REQUEST_METHOD].toUpper(); } if(rawUrl) { mEnvironmentVars[HTTP_ENV_RAW_URL].append(rawUrl); mEnvironmentVars[HTTP_ENV_UNMAPPED_FILE].append(rawUrl); int fileEndIndex = mEnvironmentVars[HTTP_ENV_RAW_URL].index('?'); if(fileEndIndex > 0) { mEnvironmentVars[HTTP_ENV_UNMAPPED_FILE].remove(fileEndIndex); mEnvironmentVars[HTTP_ENV_QUERY_STRING].append((&(mEnvironmentVars[HTTP_ENV_RAW_URL].data())[fileEndIndex + 1])); parseCgiVariables(mEnvironmentVars[HTTP_ENV_QUERY_STRING].data()); } } if(mappedFile) { mEnvironmentVars[HTTP_ENV_MAPPED_FILE].append(mappedFile); } if(serverName) { mEnvironmentVars[HTTP_ENV_SERVER_NAME].append(serverName); } if(userId) { mEnvironmentVars[HTTP_ENV_USER].append(userId); } if (connection) { mConnectionEncrypted = connection->isEncrypted(); mPeerCertTrusted = connection->peerIdentity(&mPeerIdentities); OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpRequestContext::_( connection=%p ) %s", connection, mPeerCertTrusted ? "Cert Trusted" : "Cert Not Trusted" ); } } // Copy constructor HttpRequestContext::HttpRequestContext(const HttpRequestContext& rHttpRequestContext) { //copy mEnvironmentVars[HTTP_ENV_LAST] int count = 0; for (count = HttpRequestContext::HTTP_ENV_RAW_URL; count < HttpRequestContext::HTTP_ENV_LAST ; count ++) { if(!rHttpRequestContext.mEnvironmentVars[count].isNull()) { mEnvironmentVars[count].remove(0); mEnvironmentVars[count].append(rHttpRequestContext.mEnvironmentVars[count]); } } // delete the old values in the UtlSList if(!mCgiVariableList.isEmpty()) { mCgiVariableList.destroyAll(); } //copy mCgiVariableList memebers individually mUsingInsensitive = rHttpRequestContext.mUsingInsensitive; UtlSListIterator iterator((UtlSList&)rHttpRequestContext.mCgiVariableList); NameValuePair* nameValuePair = NULL; UtlString value; UtlString name; int index = 0; do { nameValuePair = (NameValuePair*)iterator(); if(nameValuePair) { name = *nameValuePair; value = nameValuePair->getValue(); NameValuePair* newNvPair = ( mUsingInsensitive ? new NameValuePair(name, value) : new NameValuePairInsensitive(name, value) ); mCgiVariableList.insertAt(index, newNvPair); index ++; } } while (nameValuePair != NULL); mConnectionEncrypted = rHttpRequestContext.mConnectionEncrypted; mPeerCertTrusted = rHttpRequestContext.mPeerCertTrusted; if ( mPeerCertTrusted ) { UtlSListIterator rPeerNames(rHttpRequestContext.mPeerIdentities); UtlString* peerName; while ( (peerName = static_cast(rPeerNames())) ) { mPeerIdentities.append(new UtlString(*peerName)); } } } // Destructor HttpRequestContext::~HttpRequestContext() { mCgiVariableList.destroyAll(); mPeerIdentities.destroyAll(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator HttpRequestContext& HttpRequestContext::operator=(const HttpRequestContext& rhs) { if (this == &rhs) // handle the assignment to self case return *this; else { //copy mEnvironmentVars[HTTP_ENV_LAST] int count = 0; for (count = HttpRequestContext::HTTP_ENV_RAW_URL; count < HttpRequestContext::HTTP_ENV_LAST ; count ++) { if(!rhs.mEnvironmentVars[count].isNull()) { mEnvironmentVars[count].remove(0); mEnvironmentVars[count].append(rhs.mEnvironmentVars[count]); } } // delete the old values in the UtlSList if(!mCgiVariableList.isEmpty()) { mCgiVariableList.destroyAll(); } //copy mCgiVariableList memebers individually mUsingInsensitive = rhs.mUsingInsensitive; UtlSListIterator iterator((UtlSList&)rhs.mCgiVariableList); NameValuePair* nameValuePair = NULL; UtlString value; UtlString name; int index = 0; do { nameValuePair = (NameValuePair*)iterator(); if(nameValuePair) { name.append(*nameValuePair); value.append(nameValuePair->getValue()); NameValuePair* newNvPair = ( mUsingInsensitive ? new NameValuePair(name, value) : new NameValuePairInsensitive(name, value) ); mCgiVariableList.insertAt(index, newNvPair); index ++; value.remove(0); name.remove(0); } } while (nameValuePair != NULL); } mConnectionEncrypted = rhs.mConnectionEncrypted; mPeerCertTrusted = rhs.mPeerCertTrusted; if ( mPeerCertTrusted ) { UtlSListIterator rPeerNames(rhs.mPeerIdentities); UtlString* peerName; while ( (peerName = static_cast(rPeerNames())) ) { mPeerIdentities.append(new UtlString(*peerName)); } } return *this; } void HttpRequestContext::extractPostCgiVariables(const HttpBody& body) { int length; UtlString bodyBytes; body.getBytes(&bodyBytes, &length); parseCgiVariables(bodyBytes.data()); bodyBytes.remove(0); } /* ============================ ACCESSORS ================================= */ void HttpRequestContext::getEnvironmentVariable(enum RequestEnvironmentVariables envVariable, UtlString& value) const { if(envVariable >= 0 && envVariable < HTTP_ENV_LAST) { value = mEnvironmentVars[envVariable]; } else { value.remove(0); } } UtlBoolean HttpRequestContext::getCgiVariable(const char* name, UtlString& value, int occurance) const { UtlSListIterator iterator((UtlSList&)mCgiVariableList); NameValuePair* nameValuePair = NULL; int fieldIndex = 0; UtlString upperCaseName; UtlBoolean foundName = FALSE; value.remove(0); # ifdef TEST_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpRequestContext::getCgiVariable %p (\"%s\",,%d)", &mCgiVariableList, name, occurance ); # endif if(name) { upperCaseName.append(name); upperCaseName.toUpper(); } NameValuePair *matchName = ( mUsingInsensitive ? new NameValuePair(upperCaseName) : new NameValuePairInsensitive(upperCaseName) ); // For each name value: for (fieldIndex = 0, nameValuePair = (NameValuePair*) iterator.findNext(matchName); fieldIndex < occurance; fieldIndex++ ) { nameValuePair = (NameValuePair*) iterator.findNext(matchName); # ifdef TEST_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpRequestContext::getCgiVariable(name,val,occ) %p skipping %d '%s' -> '%s'", &mCgiVariableList, fieldIndex, nameValuePair ? nameValuePair->data() : "UNFOUND", nameValuePair ? nameValuePair->getValue() : "UNFOUND" ); # endif } delete matchName; # ifdef TEST_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpRequestContext::getCgiVariable(name,val,occ) %p stopped at %d '%s' -> '%s'", &mCgiVariableList, fieldIndex, nameValuePair ? nameValuePair->data() : "UNFOUND", nameValuePair ? nameValuePair->getValue() : "UNFOUND" ); # endif if(fieldIndex == occurance && nameValuePair) { value.append(nameValuePair->getValue()); foundName = TRUE; } return(foundName); } UtlBoolean HttpRequestContext::getCgiVariable(int index, UtlString& name, UtlString& value) const { NameValuePair* nameValuePair = NULL; name.remove(0); value.remove(0); if((int)(mCgiVariableList.entries()) > index && index >= 0) { nameValuePair = (NameValuePair*)mCgiVariableList.at(index); if(nameValuePair) { name = *nameValuePair; value.append(nameValuePair->getValue()); } } return(nameValuePair != NULL); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ void HttpRequestContext::parseCgiVariables(const char* queryString) { parseCgiVariables(queryString, mCgiVariableList, "&", "="); } void HttpRequestContext::parseCgiVariables(const char* queryString, UtlList& cgiVariableList, const char* pairSeparator, const char* nameValueSeparator, UtlBoolean nameIsCaseInsensitive, UnEscapeFunction unescape) { #if 0 printf("HttpRequestContext::parseCgiVariables queryString = '%s', pairSeparator = '%s', nameValueSeparator = '%s', nameIsCaseInsensitive = %d\n", queryString, pairSeparator, nameValueSeparator, nameIsCaseInsensitive); #endif //UtlString nameAndValue; const char* nameAndValuePtr; int nameAndValueLength; //UtlString name; const char* namePtr; int nameLength; int nameValueIndex = 0; UtlString value; int lastCharIndex = 0; int relativeIndex; int nameValueRelativeIndex; int queryStringLength = strlen(queryString); do { // Pull out a name value pair //osPrintf("HttpRequestContext::parseCgiVariables parseCgiVariables: \"%s\" lastCharIndex: %d", // &(queryString[lastCharIndex]), lastCharIndex); UtlNameValueTokenizer::getSubField(&(queryString[lastCharIndex]), queryStringLength - lastCharIndex, 0, pairSeparator, nameAndValuePtr, nameAndValueLength, &relativeIndex); lastCharIndex += relativeIndex; if(nameAndValuePtr && nameAndValueLength > 0) { // Separate the name and value UtlNameValueTokenizer::getSubField(nameAndValuePtr, nameAndValueLength, 0, nameValueSeparator, namePtr, nameLength, &nameValueRelativeIndex); // Get rid of leading white space in the name while(nameLength > 0 && (*namePtr == ' ' || *namePtr == '\t')) { nameLength--; namePtr++; } if(nameLength > 0) { // Ignore any subsequent name value separators should they exist //int nvSeparatorIndex = nameAndValue.index(nameValueSeparator); int valueSeparatorOffset = strspn(&(namePtr[nameLength]), nameValueSeparator); const char* valuePtr = &(namePtr[nameLength]) + valueSeparatorOffset; int valueLength = nameAndValueLength - (valuePtr - nameAndValuePtr); // If there is a value if(valueSeparatorOffset <= 0 || *valuePtr == '\0' || valueLength <= 0) { valuePtr = NULL; valueLength = 0; } // Construct the new pair of the right subclass of NameValuePair // to have the compareTo method we want. NameValuePair* newNvPair = nameIsCaseInsensitive ? new NameValuePairInsensitive("") : new NameValuePair(""); newNvPair->append(namePtr, nameLength); if(valuePtr) { value.remove(0); value.append(valuePtr, valueLength); value.strip(UtlString::both); unescape(value); newNvPair->setValue(value); } else { newNvPair->setValue(""); } // Unescape the name. unescape(*newNvPair); newNvPair->strip(UtlString::both); # ifdef TEST_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpRequestContext::parseCgiVariables adding %p '%s' -> '%s'", &cgiVariableList, newNvPair->data(), newNvPair->getValue() ); # endif // Add the name, value pair to the list cgiVariableList.insert(newNvPair); nameValueIndex++; } } } while(nameAndValuePtr && nameAndValueLength > 0 && queryString[lastCharIndex] != '\0'); } /// Test whether or not the client connection is encrypted. bool HttpRequestContext::isEncrypted() const { return mConnectionEncrypted; } /// Test whether or not the given name is the SSL client that sent this request. bool HttpRequestContext::isTrustedPeer( const UtlString& peername ) const { /* * This tests the host identity provided by the SSL handshake; it does not * test the HTTP user identity. * @returns * - true if the connection is SSL and the peername matches a name in the peer certificate. * - false if not. */ # ifdef TEST_DEBUG UtlSListIterator peers(mPeerIdentities); UtlString peerNames("Peers: "); UtlString* peer; while((peer = static_cast(peers()))) { peerNames.append(" '"); peerNames.append(*peer); peerNames.append("'"); } OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpRequestContext::isTrustedPeer('%s')\n %s %s", peername.data(), mPeerCertTrusted ? "Cert Trusted" : "Cert Not Trusted", peerNames.data() ); # endif return mPeerCertTrusted && mPeerIdentities.contains(&peername); } sipxtapi-3.3.0~test17/sipXtackLib/src/net/HttpServer.cpp0000644000175000017500000017341612205613256024020 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #if defined(_WIN32) # ifndef WINCE # include # endif #elif defined(_VXWORKS) # include # include #elif defined(__pingtel_on_posix__) # include # include # define O_BINARY 0 // There is no notion of a "not binary" file under POSIX, // so we just set O_BINARY used below to no bits in the mask. #else # error Unsupported target platform. #endif #ifdef WINCE # include #else # include # include # include #endif #include "os/OsDefs.h" #include "os/OsSysLog.h" // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #ifdef _VXWORKS # define O_BINARY 0 # define S_IREAD 0 # define S_IWRITE 0 #endif // STATIC VARIABLE INITIALIZATIONS #ifdef TEST_UPLOAD_FILE_DEBUG void incrementalCheckSum(unsigned int* checkSum, const char* buffer, int bufferLength) { int integerIndex = 0; while(integerIndex < bufferLength) { (*checkSum) += (*buffer); buffer++; integerIndex++; } } #endif /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor HttpServer::HttpServer(OsServerSocket *pSocket, OsConfigDb* userPasswordDb, const char* realm, OsConfigDb* validIpAddressDB, bool bPersistentConnection) : OsTask("HttpServer-%d"), httpStatus(OS_TASK_NOT_STARTED), mpServerSocket(pSocket), mpUserPasswordDigestDb(NULL), mpUserPasswordBasicDb(userPasswordDb), mpValidIpAddressDB(validIpAddressDB), mpNonceDb(new OsConfigDb), mRealm(realm), mAllowMappedFiles(true), // :TODO: should be false, but allow now for backward compatibility mbPersistentConnection(bPersistentConnection), mHttpConnections(0), mpHttpConnectionList(new UtlSList) { if(mpValidIpAddressDB) { loadValidIpAddrList(); } if (!mpNonceDb) { OsSysLog::add( FAC_SIP, PRI_ERR, "HttpServer failed to allocate mpNonceDb"); } if (!mpHttpConnectionList) { mbPersistentConnection = false; OsSysLog::add( FAC_SIP, PRI_ERR, "HttpServer failed to allocate mpHttpConnectionList"); } } void HttpServer::loadValidIpAddrList() { //maybe there should be no reference to OsConfig DB here and the hashTable should be passed // as paramenter to HtppServer. If time permits I will make the change. - SDUA UtlString strKey; int i = 1; while(true) { char szTempBuf[32] ; sprintf(szTempBuf, "%d", i) ; UtlString ipAddress; if( mpValidIpAddressDB->get(szTempBuf, ipAddress) && !ipAddress.isNull()) { UtlString *pMatchIpAddress = new UtlString(ipAddress); mValidIpAddrList.insert(pMatchIpAddress); i++; continue; } else { //no more ip addresses break; } } } // Copy constructor HttpServer::HttpServer(const HttpServer& rHttpServer) { } // Destructor HttpServer::~HttpServer() { if(mpServerSocket) { // Close the server socket to unblock the listener mpServerSocket->close(); } // Wait until run exits before clobbering members waitUntilShutDown(); if(mpServerSocket) { delete mpServerSocket; mpServerSocket = NULL; } if(mpUserPasswordDigestDb) { delete mpUserPasswordDigestDb; mpUserPasswordDigestDb = NULL; } if(mpUserPasswordBasicDb) { delete mpUserPasswordBasicDb; mpUserPasswordBasicDb = NULL; } if(mpValidIpAddressDB) { delete mpValidIpAddressDB; mpValidIpAddressDB = NULL; mValidIpAddrList.destroyAll(); } if(mpNonceDb) { delete mpNonceDb; mpNonceDb = NULL; } // Delete all of the processor mappings mRequestProcessorMethods.destroyAll(); // Delete remaining HttpConnections if (mpHttpConnectionList) { mpHttpConnectionList->destroyAll(); delete mpHttpConnectionList; } // Delete the hash of services mHttpServices.destroyAll(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator HttpServer& HttpServer::operator=(const HttpServer& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } OsStatus HttpServer::getStatus() { return httpStatus; } int HttpServer::run(void* runArg) { OsConnectionSocket* requestSocket = NULL; if (!mpServerSocket->isOk()) { OsSysLog::add( FAC_SIP, PRI_ERR, "HttpServer: port not ok" ); httpStatus = OS_PORT_IN_USE; } while(! isShuttingDown() && mpServerSocket->isOk()) { requestSocket = mpServerSocket->accept(); if(requestSocket) { if (mbPersistentConnection) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpServer: Using persistent connection" ); // Check for any old HttpConnections that can be deleted int items = mpHttpConnectionList->entries(); if (items != 0) { int deleted = 0; UtlSListIterator iterator(*mpHttpConnectionList); HttpConnection* connection; while ((connection = static_cast(iterator()))) { if (connection->toBeDeleted()) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "Destroying connection %p", connection); mpHttpConnectionList->destroy(connection); ++deleted; if (mHttpConnections > 0) { --mHttpConnections; } } } items = mpHttpConnectionList->entries(); OsSysLog::add(FAC_SIP, PRI_DEBUG, "Destroyed %d inactive HttpConnections, %d remaining", deleted, items); } // Create new persistent connection if (mHttpConnections < MAX_PERSISTENT_HTTP_CONNECTIONS) { ++mHttpConnections; HttpConnection* newConnection = new HttpConnection(requestSocket, this); mpHttpConnectionList->append(newConnection); OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpServer: starting persistent connection %d (%p)", mHttpConnections, newConnection); newConnection->start(); } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "HttpServer::run out of persistent connections - sending 503"); HttpMessage request; HttpMessage response; // Read the http request from the socket request.read(requestSocket); // Send out of resources message response.setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION, HTTP_OUT_OF_RESOURCES_CODE, HTTP_OUT_OF_RESOURCES_TEXT); response.write(requestSocket); requestSocket->close(); delete requestSocket; requestSocket = NULL; } } else { HttpMessage request; // Read a http request from the socket request.read(requestSocket); UtlString remoteIp; requestSocket->getRemoteHostIp(&remoteIp); HttpMessage* response = NULL; // If request from Valid IP Address if( processRequestIpAddr(remoteIp, request, response)) { // If the request is authorized processRequest(request, response, requestSocket); } if(response) { response->write(requestSocket); delete response; response = NULL; } requestSocket->close(); delete requestSocket; requestSocket = NULL; } } else { httpStatus = OS_PORT_IN_USE; } } // while (! isShuttingDown && mpServerSocket->isOk()) if ( !isShuttingDown() ) { OsSysLog::add( FAC_SIP, PRI_ERR, "HttpServer: exit due to port failure" ); } httpStatus = OS_TASK_NOT_STARTED; return(TRUE); } UtlBoolean HttpServer::isRequestAuthorized(const HttpMessage& request, HttpMessage*& response, UtlString& userId) { UtlBoolean allowRequest = FALSE; if( mpUserPasswordDigestDb == NULL && mpUserPasswordBasicDb == NULL) { allowRequest = TRUE; return allowRequest; } // If digest authentication is enabled else if(mpUserPasswordDigestDb && !mpUserPasswordDigestDb->isEmpty()) { #ifdef TEST_PRINT osPrintf("HttpServer::isRequestAuthorized\n") ; UtlString requestBytes; int requestLen; request.getBytes(&requestBytes, & requestLen); osPrintf("HTTP digest request:\n%s\n_______________________\n", requestBytes.data()); requestBytes.remove(0); #endif UtlString user; UtlString nonce; UtlString nonceKey; char nonceSecret[20]; request.getDigestAuthorizationData(&user, NULL, NULL, &nonceKey); UtlString userPasswordDigest; mpUserPasswordDigestDb->get(user.data(), userPasswordDigest); #ifdef TEST_PRINT osPrintf("HttpServer::isRequestAuthorized got db User \"%s\" db userPasswordDigest: \"%s\"\n", user.data(), userPasswordDigest.data()); #endif // Get the nonce for the user/URI pair if(!user.isNull()) { mpNonceDb->get(nonceKey.data(), nonce); #ifdef TEST_PRINT osPrintf("HttpServer::isRequestAuthorized got nonceKey \"%s\" nonce: \"%s\"\n", nonceKey.data(), nonce.data()); #endif // Remove the nonce from the database, so that it cannot be re-used mpNonceDb->remove(nonceKey.data()); } // If the user is setup for a password if(!userPasswordDigest.isNull() && request.verifyMd5Authorization(userPasswordDigest.data(), nonce)) { allowRequest = TRUE; userId = user; } // Generate the authorization error response if(!allowRequest) { // Create the nonce request.getRequestUri(&nonceKey); nonceKey.insert(0, ':'); sprintf(nonceSecret, "%d", rand()); nonceKey.insert(0, nonceSecret); UtlString nonceSeed; sprintf(nonceSecret, "%d",rand()); nonceSeed = nonceKey; nonceSeed.append(nonceSecret); NetMd5Codec::encode(nonceSeed.data(), nonce); // Add it to the database for when the authorized request comes in mpNonceDb->set(nonceKey.data(), nonce.data()); #ifdef TEST_PRINT osPrintf("HttpServer::isRequestAuthorized set nonceKey \"%s\" nonce: \"%s\"\n", nonceKey.data(), nonce.data()); #endif // Create the response UtlString hostIp; OsSocket::getHostIp(&hostIp); response = new HttpMessage(); response->setRequestUnauthorized(&request, HTTP_DIGEST_AUTHENTICATION, mRealm.data(), nonce.data(), nonceKey.data(), // authenticationOpaque hostIp.data()); // domain const char* text = "Unauthorized request"; HttpBody* body = new HttpBody(text, -1, CONTENT_TYPE_TEXT_PLAIN); response->setBody(body); response->setContentType(CONTENT_TYPE_TEXT_PLAIN); response->setContentLength(strlen(text)); nonceSeed.remove(0); hostIp.remove(0); } user.remove(0); nonce.remove(0); nonceKey.remove(0); userPasswordDigest.remove(0); } else if(mpUserPasswordBasicDb && !mpUserPasswordBasicDb->isEmpty()) { #ifdef TEST_PRINT UtlString requestBytes; int requestLen; request.getBytes(&requestBytes, & requestLen); osPrintf("HTTP basic request:\n%s\n_______________________\n", requestBytes.data()); requestBytes.remove(0); #endif UtlString user; UtlString msgPassword; UtlString dbPassword; request.getBasicAuthorizationData(&user, &msgPassword); OsStatus userFound = mpUserPasswordBasicDb->get(user.data(), dbPassword); #ifdef TEST_PRINT osPrintf("HttpServer::isRequestAuthorized user: %s, password: %s\n",user.data(), dbPassword.data()) ; if(userFound == OS_NOT_FOUND) { osPrintf("HttpServer::isRequestAuthorized user: %s not in database\n", user.data()); } #endif // Passwords stored as digest in user-config. // Must convert passwords to encrypted ones also UtlString digestPassword ; UtlString realm(mRealm) ; HttpMessage::buildMd5UserPasswordDigest((const char*) user.data(), (const char*) realm.data(), (const char*) msgPassword.data(), digestPassword) ; // The user does not exist or passwords do not match if(userFound != OS_SUCCESS || user.isNull() || dbPassword.compareTo(digestPassword) != 0) { #ifdef TEST_PRINT if(userFound == OS_SUCCESS) { osPrintf("HttpServer::isRequestAuthorized user:%s, realm:%s, msgPassword:%s, digestPassword:%s\n", user.data(), realm.data(), msgPassword.data(), digestPassword.data()) ; osPrintf("HttpServer::isRequestAuthorized password: %s, generated digest: %s\n", dbPassword.data(), digestPassword.data()) ; osPrintf("HttpServer::isRequestAuthorized user: %s password does not match\n", user.data()); } #endif allowRequest = FALSE; // Generate a unauthorized response UtlString hostIp; OsSocket::getHostIp(&hostIp); response = new HttpMessage(); response->setRequestUnauthorized(&request, HTTP_BASIC_AUTHENTICATION, mRealm.data(), NULL, // nonce NULL, // authenticationOpaque hostIp.data()); // domain const char *text = "Unauthorized request"; HttpBody* body = new HttpBody(text, -1, CONTENT_TYPE_TEXT_PLAIN); response->setBody(body); response->setContentType(CONTENT_TYPE_TEXT_PLAIN); response->setContentLength(strlen(text)); hostIp.remove(0); } // The password matches else { allowRequest = TRUE; userId = user; } user.remove(0); msgPassword.remove(0); dbPassword.remove(0); digestPassword.remove(0); realm.remove(0); } else { // AJS - Disabled unauthorized access for 0.8.0 allowRequest = FALSE; #ifdef TEST_PRINT osPrintf("HttpServer::requestAuthorized authentication enabled\n"); #endif } return(allowRequest); } UtlBoolean HttpServer::processRequestIpAddr(const UtlString& remoteIp, const HttpMessage& request, HttpMessage*& response) { UtlBoolean isValidIp = FALSE; UtlString remoteAddress(remoteIp); UtlString matchIp(remoteAddress); if(mValidIpAddrList.isEmpty() || mValidIpAddrList.find(&matchIp)) { isValidIp = TRUE; } else { response = new HttpMessage(); response->setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION, HTTP_FORBIDDEN_CODE, HTTP_FORBIDDEN_TEXT); OsSysLog::add(FAC_SIP, PRI_INFO, "HTTP Request from IP address: %s disallowed", remoteAddress.data()); } return isValidIp ; } void HttpServer::processRequest(const HttpMessage& request, HttpMessage*& response, const OsConnectionSocket* connection ) { UtlString method; response = NULL; UtlString userId; if(isRequestAuthorized(request, response, userId)) { request.getRequestMethod(&method); method.toUpper(); UtlString uri; request.getRequestUri(&uri); UtlString uriFileName(uri); int fileNameEnd = -1; if(method.compareTo(HTTP_GET_METHOD) == 0) { fileNameEnd = uriFileName.first('?'); if(fileNameEnd > 0) { uriFileName.remove(fileNameEnd); } } UtlString mappedUriFileName; int badCharsIndex = uriFileName.index(".."); if(badCharsIndex < 0) { badCharsIndex = uriFileName.index("//"); } if(badCharsIndex >= 0) { OsSysLog::add(FAC_SIP, PRI_ERR, "Disallowing URI: \"%s\"", uriFileName.data()); // Disallow relative path names going up for security reasons mappedUriFileName.append("/"); } else { // Map the file name mapUri(mUriMaps, uriFileName.data(), mappedUriFileName); } OsSysLog::add(FAC_SIP, PRI_DEBUG, "HTTP '%s' '%s' mapped to: '%s'", method.data(), uriFileName.data(), mappedUriFileName.data()); // Build the request context HttpRequestContext requestContext(method.data(), uri.data(), mappedUriFileName.data(), NULL, !userId.isNull() ? userId.data() : NULL, connection ); if(method.compareTo(HTTP_POST_METHOD) == 0) { //Need to get the CGI/form variables from the body. const HttpBody* body = request.getBody(); if(body && !body->isMultipart()) { requestContext.extractPostCgiVariables(*body); } } if( method.compareTo(HTTP_GET_METHOD) == 0 || method.compareTo(HTTP_POST_METHOD) == 0 ) { // If there is a request processor for this URI RequestProcessor* requestProcessorPtr; if(findRequestProcessor(uriFileName.data(), requestProcessorPtr)) { requestProcessorPtr(requestContext, request, response); } else { // Check to see whether there is a service for this URI HttpService* pService = NULL; if (findHttpService(uriFileName.data(), pService)) { pService->processRequest(requestContext, request, response); } else if (mAllowMappedFiles) { // Use the default request processor processFileRequest(requestContext, request, response); } else { // This is not allowed, but there is no reason to tell them that processFileNotFound(requestContext, request, response); } } } else if(method.compareTo(HTTP_PUT_METHOD) == 0) { processPutRequest(requestContext, request, response); } else { processNotSupportedRequest(requestContext, request, response); } } } /// set permission for access to mapped file names void HttpServer::allowFileAccess(bool fileAccess ///< true => allow access, false => disallow access ) { mAllowMappedFiles = fileAccess; } void HttpServer::processFileRequest(const HttpRequestContext& requestContext, const HttpMessage& request, HttpMessage*& response) { UtlString uri; request.getRequestUri(&uri); UtlString uriFileName; UtlString method; requestContext.getEnvironmentVariable(HttpRequestContext::HTTP_ENV_MAPPED_FILE, uriFileName); request.getRequestMethod(&method); if(!uriFileName.isNull()) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpServer: Trying to open: \"%s\"\n", uriFileName.data()); int fileDesc = open(uriFileName.data(), O_BINARY | O_RDONLY, 0); if(fileDesc < 0) { OsSysLog::add(FAC_SIP, PRI_ERR, "HttpServer::processFileRequest" " failed to open '%s' Errno: %d", uriFileName.data(), errno); } struct stat fileStatInfo; if(fileDesc >= 0 && !fstat(fileDesc, &fileStatInfo)) { int fileDescToGet = -1; const char* contentType = CONTENT_TYPE_TEXT_PLAIN; // If the URI is directory if(fileStatInfo.st_mode & S_IFDIR) { contentType = CONTENT_TYPE_TEXT_HTML; // check for index files UtlString indexFileName(uriFileName.data()); if(indexFileName.data()[indexFileName.length() - 1] != '/') indexFileName.append('/'); indexFileName.append("index.html"); //HttpMessage::convertToPlatformPath(indexFileName.data(), // indexFileName); #ifdef TEST_PRINT osPrintf("HttpServer: Trying to open: \"%s\"\n", indexFileName.data()); OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpServer: Trying to open: \"%s\"", indexFileName.data()); #endif fileDescToGet = open(indexFileName.data(), O_RDONLY, 0); if(fileDescToGet < 0) { // Try index.htm indexFileName.remove(indexFileName.length() - 1); #ifdef TEST_PRINT osPrintf("HttpServer: Trying to open: \"%s\"\n", indexFileName.data()); OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpServer: Trying to open: \"%s\"", indexFileName.data()); #endif fileDescToGet = open(indexFileName.data(), O_RDONLY | O_BINARY, 0); } // No index files, construct an html list of files if(fileDescToGet < 0) { UtlString indexText ; constructFileList(indexText, uri, uriFileName) ; HttpBody* body = new HttpBody(indexText.data(), indexText.length(), contentType); response = new HttpMessage(); response->setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION, HTTP_OK_CODE, HTTP_OK_TEXT); response->setBody(body); response->setContentType(contentType); response->setContentLength(indexText.length()); indexText.remove(0); } indexFileName.remove(0); } else if(fileStatInfo.st_mode & S_IFREG) { fileDescToGet = fileDesc; // This stuff really ought to be configurable and // contained in a list const char* fileNamePtr = uriFileName.data(); int extensionIndex = uriFileName.last('.'); if(extensionIndex >= 0) { fileNamePtr += extensionIndex + 1; if(strcmp(fileNamePtr, "htm") == 0 || strcmp(fileNamePtr, "html") == 0) { contentType = CONTENT_TYPE_TEXT_HTML; } else if(strcmp(fileNamePtr, "aif") == 0) { contentType = "application/pingtel"; } else if(strcmp(fileNamePtr, "raw") == 0) { contentType = "audio/raw"; } else if(strcmp(fileNamePtr, "gif") == 0) { contentType = "image/gif"; } else if(strcmp(fileNamePtr, "jar") == 0) { contentType = "application/octet-stream"; } else if(strcmp(fileNamePtr, "jpg") == 0 || strcmp(fileNamePtr, "jpeg") == 0) { contentType = "image/jpeg"; } else if(strcmp(fileNamePtr, "wav") == 0) { contentType = "image/wav"; } else if(strcmp(fileNamePtr, "js") == 0) { contentType = "application/x-javascript" ; } } } // If the URI is a file get it if(fileDescToGet >= 0) { char* buffer = new char[HTTP_DEFAULT_SOCKET_BUFFER_SIZE + 1]; int numBytesRead; UtlString fileContents; while((numBytesRead = read(fileDescToGet, buffer, HTTP_DEFAULT_SOCKET_BUFFER_SIZE)) > 0) { fileContents.append(buffer, numBytesRead); } HttpBody* body = new HttpBody(fileContents.data(), fileContents.length(), contentType); response = new HttpMessage(); response->setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION, HTTP_OK_CODE, HTTP_OK_TEXT); response->setBody(body); response->setContentType(contentType); response->setContentLength(fileContents.length()); if(fileDescToGet != fileDesc) close(fileDescToGet); if(buffer) delete buffer; buffer = NULL; fileContents.remove(0); } close(fileDesc); } // File not found else { processFileNotFound(requestContext, request, response); } } } void HttpServer::constructFileList(UtlString & indexText, UtlString uri, UtlString uriFileName) { #ifdef _VXWORKS /* [ */ char tmpDateBuf[80]; #endif /* _VXWORKS ] */ #ifdef TEST_PRINT osPrintf("HttpServer::constructFileList entered, uri = %s, uriFileName = %s", uri.data(), uriFileName.data()) ; #endif indexText.append("\n"); indexText.append("

Contents of "); // Use the public uri not the mapped one indexText.append(uri.data()); indexText.append("

\n\n\n"); #ifdef _VXWORKS /* [ */ char sizeBuffer[80]; DIR* uriDir = opendir((char*) uriFileName.data()); struct dirent* uriDirEntry = NULL; struct tm* timeStruct = NULL; if(uriFileName.data()[uriFileName.length() - 1] != '/') uriFileName.append('/'); while((uriDirEntry = readdir(uriDir)) != NULL) { indexText.append("\n"); dirEntryFileName.remove(0); } closedir(uriDir); #endif /* _VXWORKS ] */ #ifdef _WIN32 /* [ */ char sizeBuffer[80]; BOOL bFoundFile = FALSE; WIN32_FIND_DATA fileInfo; SYSTEMTIME sysTime; UtlString searchString = uriFileName; searchString.append("\\*.*"); HANDLE hFile = FindFirstFile( (char*) searchString.data(), // file name &fileInfo); // data buffer if (hFile != INVALID_HANDLE_VALUE) bFoundFile = TRUE; if(uriFileName.data()[uriFileName.length() - 1] != '/') uriFileName.append('/'); while(bFoundFile) { indexText.append("\n"); dirEntryFileName.remove(0); bFoundFile = FindNextFile(hFile,&fileInfo); } #endif /* _WIN32 ] */ indexText.append("
\nName\nSize (Bytes)\nDate\n
\nd_name); indexText.append("\">"); indexText.append(uriDirEntry->d_name); indexText.append("\n\n"); UtlString dirEntryFileName(uriFileName); dirEntryFileName.append(uriDirEntry->d_name); struct stat dirEntryStat; stat((char*)dirEntryFileName.data(), &dirEntryStat); if(dirEntryStat.st_mode & S_IFDIR) { indexText.append("directory"); } else { sprintf(sizeBuffer, "%d", dirEntryStat.st_size); indexText.append(sizeBuffer); } indexText.append("\n\n"); timeStruct = localtime(&dirEntryStat.st_ctime); sprintf(tmpDateBuf, " %02d/%02d/%d %02d:%02d", timeStruct->tm_mon+1,timeStruct->tm_mday,1900+timeStruct->tm_year, timeStruct->tm_hour,timeStruct->tm_min); indexText.append(tmpDateBuf); indexText.append("\n
\n"); indexText.append(fileInfo.cFileName); indexText.append("\n\n"); UtlString dirEntryFileName(uriFileName); dirEntryFileName.append(fileInfo.cFileName); DWORD fileAttrs = GetFileAttributes((char *)dirEntryFileName.data()); if(fileAttrs & FILE_ATTRIBUTE_DIRECTORY) { indexText.append("directory"); } else { sprintf(sizeBuffer, "%lu", fileInfo.nFileSizeLow); indexText.append(sizeBuffer); } FILETIME ft = fileInfo.ftCreationTime ; indexText.append("\n\n"); FileTimeToSystemTime(&ft,&sysTime); char tmpDateBuf[80]; sprintf(tmpDateBuf, " %02d/%02d/%d %02d:%02d", sysTime.wMonth,sysTime.wDay,sysTime.wYear, sysTime.wHour,sysTime.wMinute); strcat(sizeBuffer,tmpDateBuf); indexText.append(tmpDateBuf); indexText.append("\n
\n\n"); } void HttpServer::processPutRequest(const HttpRequestContext& requestContext, const HttpMessage& request, HttpMessage*& response) { processNotSupportedRequest(requestContext, request, response); } void HttpServer::processPostFile(const HttpRequestContext& requestContext, const HttpMessage& request, HttpMessage*& response) { UtlString status; doPostFile(requestContext, request, response, status); } int HttpServer::doPostFile(const HttpRequestContext& requestContext, const HttpMessage& request, HttpMessage*& response, UtlString& status) { int ret = 0; // ret == 1: success, ret == 0: failed status.remove(0); response = NULL; const HttpBody* body = request.getBody(); UtlString htmlMessage("\n\n"); #ifdef TEST_UPLOAD_FILE_DEBUG const char* saveBytes; int saveLen; body->getBytes(&saveBytes, &saveLen); int bodyDumpFileDesc = open("/flash0/postbodyDump.aif", O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, S_IREAD | S_IWRITE); ::write(bodyDumpFileDesc, saveBytes, saveLen); close(bodyDumpFileDesc); #endif if(body) { if(body->isMultipart()) { const MimeBodyPart* firstPartFileBody = //firstPartMessage.getBody(); body->getMultipart(0); const char* fileData; int fileDataLength; if(firstPartFileBody) { #ifdef TEST_UPLOAD_FILE_DEBUG unsigned int bufferCheckSum = 0; unsigned int fileCheckSum = 0; #endif firstPartFileBody->getBytes(&fileData, &fileDataLength); if (fileDataLength > 0) { while (fileDataLength && (*fileData == ' ' || *fileData == '\r' || *fileData == '\n')) { #ifdef TEST_PRINT osPrintf("HttpServer::doPostFile - Trimming kernal char %02X from front of kernel.\n",*fileData); #endif fileData++; fileDataLength--; } } if (fileDataLength > 0) { #ifdef TEST_UPLOAD_FILE_DEBUG incrementalCheckSum(&bufferCheckSum, fileData, fileDataLength); #endif UtlString fieldValue; firstPartFileBody->getPartHeaderValue(HTTP_CONTENT_DISPOSITION_FIELD, fieldValue); if(!fieldValue.isNull()) { NetAttributeTokenizer tokenizer(fieldValue.data()); UtlString tokenName; UtlString tokenValue; while(tokenizer.getNextAttribute(tokenName, tokenValue)) { tokenName.toUpper(); #ifdef TEST_PRINT //osPrintf("Token name: \"%s\" value: \"%s\"\n", // tokenName.data(), tokenValue.data()); #endif if(tokenName.compareTo("NAME") == 0) { // The value is the file name use to save the body as if(fileDataLength > 0) { int fileDesc = open(tokenValue.data(), O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, S_IREAD | S_IWRITE); if(fileDesc >= 0) { int bytesWritten = write(fileDesc, (char*)fileData, fileDataLength); #ifdef TEST_UPLOAD_FILE_DEBUG unsigned int postWriteCheckSum = 0; incrementalCheckSum(&postWriteCheckSum, fileData, fileDataLength); osPrintf("Post write check sum: %d\n", postWriteCheckSum); #endif close(fileDesc); if(bytesWritten == fileDataLength) { #ifdef TEST_UPLOAD_FILE_DEBUG // Open the file again to do the checksum unsigned int checkSumFileDesc = open(tokenValue.data(), O_BINARY | O_RDONLY, 0); char checkSumBuffer[2001]; int checkSumBytesRead; int totalBytesRead = 0; do { checkSumBytesRead = read(checkSumFileDesc, checkSumBuffer, 2000); totalBytesRead += checkSumBytesRead; if(checkSumBytesRead > 0) incrementalCheckSum(&fileCheckSum, checkSumBuffer, checkSumBytesRead); } while(checkSumBytesRead > 0); close(checkSumFileDesc); unsigned int postReadCheckSum = 0; incrementalCheckSum(&postReadCheckSum, fileData, fileDataLength); osPrintf("Post read check sum: %d\n", postReadCheckSum); osPrintf("HttpServer::processPostFile bufferCheckSum: %d fileCheckSum: %d, buffer size: %d, file size: %d\n", bufferCheckSum, fileCheckSum, fileDataLength, totalBytesRead); #endif htmlMessage.append("

Upload Successful

\n"); char buffer[20]; sprintf(buffer, "%d", bytesWritten); status = UtlString(buffer); status.append(" bytes saved as file: "); status.append(tokenValue.data()); htmlMessage.append(status); ret = 1; } // Something happened, it did not write the whole file else { htmlMessage.append("

Upload Failed

\n"); htmlMessage.append("Insufficient file space\n"); char buffer[100]; sprintf(buffer, "
Bytes available: %d\n
Bytes needed: %d for file: ", bytesWritten, fileDataLength); htmlMessage.append(buffer); htmlMessage.append(tokenValue.data()); #ifdef _VXWORKS ::remove(tokenValue.data()); htmlMessage.append("\n
File not saved\n"); #endif htmlMessage.append("\

Troubleshooting\

Before you call Pingtel for customer support, please print this page. \ You can also follow these troubleshooting suggestions:\

    \
  • \ Check the size of each file stored on your phone. Click here \ to see a list; please print this list.
  • \ \
    If the size of any of these files is greater than 5K, a file may have \ been loaded incorrectly.\
  • \ Verify that your device and user configuration files contain configuration \ parameters:\
  • \ \ \ \
  • \ If one of these files incorrectly contains some other type of data:
  • \ \
      \
    • \ Reload your pinger-config file here.
    • \ \
    • \ Reload your user-config file here.
    • \
    \ \
  • \ If you have loaded audio files onto your phone, check the file size.
  • \ \
      \
    • \ An audio file should be no greater than 100K.
    • \ \
    • \ If the file is larger, replace it with a smaller file here.\
    • \
    \
\ If you need further assistance, please contact Pingtel at custsupp@pingtel.com."); } } else { htmlMessage.append("

Upload Failed

\n"); htmlMessage.append("Unable to open file \""); htmlMessage.append(tokenValue); htmlMessage.append("\" for write\n"); #ifdef TEST_PRINT osPrintf("Unable to open file \"%s\" for write\n", tokenValue.data()); #endif } } else { htmlMessage.append("

Upload Failed

\n"); htmlMessage.append("Zero length file"); #ifdef TEST_PRINT osPrintf("Zero length file"); #endif } break; } } if(tokenName.isNull()) { htmlMessage.append("

Upload Failed

\n"); htmlMessage.append("No file name given to save content\n"); #ifdef TEST_PRINT osPrintf("No file name given to save content\n"); #endif } tokenName.remove(0); tokenValue.remove(0); } else { htmlMessage.append("

Upload Failed

\n"); htmlMessage.append("Content-Disposition field not found\n"); #ifdef TEST_PRINT osPrintf("Content-Disposition field not found\n"); #endif } fieldValue.remove(0); } else { htmlMessage.append("

Upload Failed

\n"); htmlMessage.append("First part file body contains zero byte data. Please check the filename and try again.\n"); #ifdef TEST_PRINT osPrintf("First part file body contains zero byte data. Please check the filename and try again.\n"); #endif } } else { UtlString strMessage = "Possible out of memory condition. Restart and try again.\n"; htmlMessage.append("

Upload Failed

\n"); htmlMessage.append("First part has NO file body.\n"); htmlMessage.append(strMessage.data()); #ifdef TEST_PRINT osPrintf("%s",strMessage.data()); #endif } } else { htmlMessage.append("

Upload Failed

\n"); htmlMessage.append("Single part body\n"); #ifdef TEST_PRINT osPrintf("Single part body\n"); #endif } } else { UtlString strMessage = "NO file body. Possible out of memory condition. Restart and try again.\n"; htmlMessage.append("

Upload Failed

\n"); htmlMessage.append("NO file body.\n"); htmlMessage.append(strMessage.data()); #ifdef TEST_PRINT osPrintf("%s",strMessage.data()); #endif } htmlMessage.append("\n

\nHome\n\n\n"); createHtmlResponse(HTTP_OK_CODE, HTTP_OK_TEXT, htmlMessage.data(), response); htmlMessage.remove(0); return ret; } void HttpServer::processNotSupportedRequest(const HttpRequestContext& requestContext, const HttpMessage& request, HttpMessage*& response) { // Method not supported response = new HttpMessage(); response->setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION, HTTP_UNSUPPORTED_METHOD_CODE, HTTP_UNSUPPORTED_METHOD_TEXT); const char* text = "Not Implemented\n"; HttpBody* body = new HttpBody(text, -1, CONTENT_TYPE_TEXT_HTML); response->setBody(body); response->setContentType(CONTENT_TYPE_TEXT_HTML); response->setContentLength(strlen(text)); } void HttpServer::processFileNotFound(const HttpRequestContext& requestContext, const HttpMessage& request, HttpMessage*& response) { response = new HttpMessage(); response->setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION, HTTP_FILE_NOT_FOUND_CODE, HTTP_FILE_NOT_FOUND_TEXT); const char* text = "File Not Found\n"; HttpBody* body = new HttpBody(text, -1 , CONTENT_TYPE_TEXT_HTML); response->setBody(body); response->setContentType(CONTENT_TYPE_TEXT_HTML); response->setContentLength(strlen(text)); } void HttpServer::processUserNotAuthorized(const HttpRequestContext& requestContext, const HttpMessage& request, HttpMessage*& response, const char* text) { #ifdef TEST_PRINT osPrintf("HttpServer::processUserNotAuthorized reached\n") ; #endif UtlString hostIp; OsSocket::getHostIp(&hostIp); response = new HttpMessage(); response->setRequestUnauthorized(&request, HTTP_BASIC_AUTHENTICATION, NULL, // realm NULL, // nonce NULL, // authenticationOpaque hostIp.data()); // domain //char* text = "User Not Authorized\n"; if (text == 0) { text = "User Not Authorized\n"; } HttpBody* body = new HttpBody(text, -1 , CONTENT_TYPE_TEXT_HTML); response->setBody(body); response->setContentType(CONTENT_TYPE_TEXT_HTML); response->setContentLength(strlen(text)); hostIp.remove(0); } void HttpServer::testCgiRequest(const HttpRequestContext& requestContext, const HttpMessage& request, HttpMessage*& response) { UtlString url; UtlString value; requestContext.getEnvironmentVariable(HttpRequestContext::HTTP_ENV_RAW_URL, url); UtlString cgiDump("\n\n"); cgiDump.append(url); cgiDump.append(" dump\n\n\n

Environment Variables\n

\n"); cgiDump.append("\n\n\n\n\n"); requestContext.getEnvironmentVariable(HttpRequestContext::HTTP_ENV_RAW_URL, value); cgiDump.append("\n\n\n\n"); requestContext.getEnvironmentVariable(HttpRequestContext::HTTP_ENV_UNMAPPED_FILE, value); cgiDump.append("\n\n\n\n"); requestContext.getEnvironmentVariable(HttpRequestContext::HTTP_ENV_MAPPED_FILE, value); cgiDump.append("\n\n\n\n"); requestContext.getEnvironmentVariable(HttpRequestContext::HTTP_ENV_QUERY_STRING, value); cgiDump.append("\n\n\n\n"); requestContext.getEnvironmentVariable(HttpRequestContext::HTTP_ENV_SERVER_NAME, value); cgiDump.append("\n\n\n\n"); requestContext.getEnvironmentVariable(HttpRequestContext::HTTP_ENV_REQUEST_METHOD, value); cgiDump.append("\n\n\n\n"); requestContext.getEnvironmentVariable(HttpRequestContext::HTTP_ENV_USER, value); cgiDump.append("\n\n\n\n
NameValue
HTTP_ENV_RAW_URL"); cgiDump.append(value); cgiDump.append("
HTTP_ENV_UNMAPPED_FILE"); cgiDump.append(value); cgiDump.append("
HTTP_ENV_MAPPED_FILE"); cgiDump.append(value); cgiDump.append("
HTTP_ENV_QUERY_STRING"); cgiDump.append(value); cgiDump.append("
HTTP_ENV_SERVER_NAME"); cgiDump.append(value); cgiDump.append("
HTTP_ENV_REQUEST_METHOD"); cgiDump.append(value); cgiDump.append("
HTTP_ENV_USER"); cgiDump.append(value); cgiDump.append("
\n"); cgiDump.append("

CGI/Form Variables\n

\n"); cgiDump.append("\n\n\n\n\n"); int index = 0; UtlString name; while(requestContext.getCgiVariable(index, name, value)) { #ifdef TEST_PRINT osPrintf("getCgiVariable: %s = %s\n", name.data(), value.data()); #endif cgiDump.append("\n\n\n\n"); index++; } cgiDump.append("
NameValue
"); cgiDump.append(name); cgiDump.append(""); cgiDump.append(value); cgiDump.append("
\n"); createHtmlResponse(HTTP_OK_CODE, HTTP_OK_TEXT, cgiDump.data(), response); url.remove(0); value.remove(0); cgiDump.remove(0); name.remove(0); } void HttpServer::createHtmlResponse(int responseCode, const char* responseCodeText, const char* htmlBodyText, HttpMessage*& response) { response = new HttpMessage(); response->setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION, responseCode, responseCodeText); HttpBody* body = new HttpBody(htmlBodyText, -1, CONTENT_TYPE_TEXT_HTML); response->setBody(body); response->setContentType(CONTENT_TYPE_TEXT_HTML); response->setContentLength(strlen(htmlBodyText)); } void HttpServer::addUriMap(const char* fromUri, const char* toUri) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpServer::addUriMap '%s' to '%s'", fromUri, toUri); mUriMaps.set(fromUri, toUri); } void HttpServer::addRequestProcessor(const char* fileUrl, RequestProcessor* requestProcessor ) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpServer::addRequestProcessor '%s' to %p", fileUrl, requestProcessor); addUriMap( fileUrl, fileUrl ); UtlString* name = new UtlString(fileUrl); UtlVoidPtr* value = new UtlVoidPtr((void*)requestProcessor); mRequestProcessorMethods.insertKeyAndValue(name, value); } void HttpServer::addHttpService(const char* fileUrl, HttpService* service) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpServer::addHttpService '%s' to %p", fileUrl, service); UtlString* name = new UtlString(fileUrl); UtlVoidPtr* value = new UtlVoidPtr(service); mHttpServices.insertKeyAndValue(name, value); } /* ============================ ACCESSORS ================================= */ void HttpServer::setPasswordDigest(const char* user, const char* password, UtlString& userPasswordDigest) { userPasswordDigest.remove(0); if(user && *user && mpUserPasswordDigestDb) { HttpMessage::buildMd5UserPasswordDigest(user, mRealm, password, userPasswordDigest); mpUserPasswordDigestDb->set(user, userPasswordDigest.data()); } else if(user && *user && password && mpUserPasswordBasicDb) { // Basic Digest uses encrypted password in user-config HttpMessage::buildMd5UserPasswordDigest(user, mRealm, password, userPasswordDigest); mpUserPasswordBasicDb->set(user, userPasswordDigest.data()); userPasswordDigest = password; } } /** * added by Pradeep: * This takes an already encrypted password and sets it as the new encrypted password. */ void HttpServer::setPasswordDigest(const char* user, const char* passwordDigest) { if(user && *user && mpUserPasswordDigestDb) { mpUserPasswordDigestDb->set(user, passwordDigest); } else if(user && *user && passwordDigest && mpUserPasswordBasicDb) { mpUserPasswordBasicDb->set(user, passwordDigest); } } void HttpServer::getDigest(const char* user, const char* password, UtlString& userPasswordDigest) { HttpMessage::buildMd5UserPasswordDigest(user, mRealm, password, userPasswordDigest); #ifdef TEST_PRINT osPrintf("HttpServer::getDigest user = %s password = %s realm = %s digestpassword = %s", user, password, mRealm.data(), userPasswordDigest.data()) ; #endif } void HttpServer::removeUser(const char* user, const char* password) { UtlString strUser(user) ; if(user && *user && mpUserPasswordDigestDb) { mpUserPasswordDigestDb->remove(strUser); } else if(user && *user && password && mpUserPasswordBasicDb) { mpUserPasswordBasicDb->remove(strUser); } strUser.remove(0); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ UtlBoolean HttpServer::findRequestProcessor(const char* fileUri, RequestProcessor* &requestProcessor ) { UtlString uriCollectable(fileUri); UtlVoidPtr* processorCollectable; requestProcessor = NULL; processorCollectable = (UtlVoidPtr*) mRequestProcessorMethods.findValue(&uriCollectable); if(processorCollectable) { requestProcessor = (RequestProcessor*)processorCollectable->getValue(); } return(requestProcessor != NULL); } UtlBoolean HttpServer::findHttpService(const char* fileUri, HttpService*& pService) { UtlString uriCollectable(fileUri); UtlVoidPtr* processorCollectable; processorCollectable = (UtlVoidPtr*) mHttpServices.findValue(&uriCollectable); if(processorCollectable) { pService = (HttpService *) processorCollectable->getValue(); } return(pService != NULL); } UtlBoolean HttpServer::mapUri(OsConfigDb& uriMaps, const char* uri, UtlString& mappedUri) { UtlBoolean mapFound = FALSE; if(uri) { UtlString originalUri(uri); UtlString mapFromUri(uri); UtlString mapToUri; int dirSeparatorIndex; OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpServer::mapUri looking for \"%s\"", mapFromUri.data()); do { uriMaps.get(mapFromUri, mapToUri); if(!mapToUri.isNull()) { mappedUri.remove(0); mappedUri.append(mapToUri.data()); if(mappedUri.data()[mappedUri.length() - 1] != '/' && uri[mapFromUri.length()] != '/' && mapFromUri.length() < originalUri.length()) { // Need a directory seporator mappedUri.append('/'); } mappedUri.append(&(originalUri.data()[mapFromUri.length()])); mapFound = TRUE; break; } dirSeparatorIndex = mapFromUri.last('/'); if(dirSeparatorIndex == 0 && mapFromUri.length() > 1) { mapFromUri.remove(1); } else if(dirSeparatorIndex >= 0) { mapFromUri.remove(dirSeparatorIndex); } else { break; } } while(!mapFound && !mapFromUri.isNull() != 0); } OsSysLog::add(FAC_SIP, PRI_DEBUG, "Map to uri: \"%s\"", mappedUri.data()); return(mapFound); } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/HttpService.cpp0000644000175000017500000000227512205613256024144 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor HttpService::HttpService() { } // Destructor HttpService::~HttpService() { } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/MailAttachment.cpp0000644000175000017500000001703512205613256024577 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // MailAttachment class definition for Mailer #include "net/NetBase64Codec.h" #include "net/MailAttachment.h" MailAttachment::MailAttachment(const MailAttachment &original) { // Copy Constructor: m_Filename = original.m_Filename; m_MIMEtype = original.m_MIMEtype; int base64Len = strlen(original.m_Base64)+1; m_Base64 = new char[base64Len]; if (m_Base64) { memcpy(m_Base64, original.m_Base64, base64Len); } else { m_Base64 = NULL; } } bool MailAttachment::Load(const UtlString &filename) { bool successful = false; // Save the filename (sans-path) and generate a MIME content type based on // the extension. (Note that this code only supports a few major MIME // types and is intended for demonstration only.) m_Filename = filename; UtlString ext = m_Filename(m_Filename.length()-3, 3); ext.toLower(); if (ext == "gif") m_MIMEtype = "image/gif"; else if (ext == "jpg") m_MIMEtype = "image/jpeg"; else if (ext == "zip") m_MIMEtype = "application/zip"; else if (ext == "wav") m_MIMEtype = "audio/x-wav"; else if (ext == "htm") m_MIMEtype = "text/html"; else if (ext == "txt") m_MIMEtype = "text/plain"; else m_MIMEtype = "application/octet-stream"; // Open the file for reading OsFile file(filename.data()); if (file.open() == OS_SUCCESS) { // Save the file size unsigned long fileSize; file.getLength(fileSize); // Create a buffer for the file contents unsigned char *buffer = new unsigned char[fileSize]; if (buffer != NULL) { // Allocate a buffer for the base64 encoding of the file contents unsigned long nBytesForEncoding = (fileSize/3+1)*4; unsigned long nBytesForCRLF = (nBytesForEncoding/76+1)*2; unsigned long nBytesForTerminatingNull = 1; m_Base64 = new char[nBytesForEncoding+nBytesForCRLF+nBytesForTerminatingNull]; if (m_Base64 != NULL) { // Read the file contents into the buffer unsigned long bytesRead; if ( file.read(buffer, fileSize,bytesRead) == OS_SUCCESS ) { if (bytesRead == fileSize) { // Perform Base64 encoding on the buffer Base64Encode(buffer, fileSize); successful = true; } } // Deallocate the base64 buffer if not successful delete [] m_Base64; m_Base64 = NULL; } delete [] buffer; buffer = NULL; } file.close(); } return successful; } bool MailAttachment::Load( const unsigned char *data, const size_t& rDatalength, const UtlString &rFilename ) { bool successful = false; // Save the filename (sans-path) and generate a MIME content type based on // the extension. (Note that this code only supports a few major MIME // types and is intended for demonstration only.) m_Filename = rFilename; UtlString ext = m_Filename(m_Filename.length()-3, 3); ext.toLower(); if (ext == "gif") m_MIMEtype = "image/gif"; else if (ext == "jpg") m_MIMEtype = "image/jpeg"; else if (ext == "zip") m_MIMEtype = "application/zip"; else if (ext == "wav") m_MIMEtype = "audio/x-wav"; else if (ext == "htm") m_MIMEtype = "text/html"; else if (ext == "txt") m_MIMEtype = "text/plain"; else m_MIMEtype = "application/octet-stream"; if (data != NULL) { // Allocate a buffer for the base64 encoding of the file contents unsigned long nBytesForEncoding = (rDatalength/3+1)*4; unsigned long nBytesForCRLF = (nBytesForEncoding/76+1)*2; unsigned long nBytesForTerminatingNull = 1; m_Base64 = new char[nBytesForEncoding+nBytesForCRLF+nBytesForTerminatingNull]; if (m_Base64 != NULL) { // Perform Base64 encoding on the buffer Base64Encode(data, rDatalength); successful = true; } } return successful; } MailAttachment::~MailAttachment() { // Deallocate the base64 buffer if it exists if (m_Base64) { delete [] m_Base64; m_Base64 = NULL; } } void MailAttachment::Base64Encode(const unsigned char *buffer, unsigned long buflen) { m_Base64[0] = '\0'; // Three bytes (24 bits) from the file unsigned char rawByte[3]; // The 4-byte encoding of these 24 bits unsigned char encodedByte[4]; // Number of bytes currently in the base64 encoding unsigned int nBytes = 0; // Byte index of start of line in the base64 encoding unsigned int iLineStart = 0; // The base64 character set unsigned char base64CharSet[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; // Read 24 bits (3 bytes) at a time from the buffer for (unsigned long i = 0; i < buflen; i += 3) { // Read a 24 bit quantum into rawByte as three bytes rawByte[0] = buffer[i]; if (i+1 < buflen) rawByte[1] = buffer[i+1]; else rawByte[1] = '\0'; if (i+2 < buflen) rawByte[2] = buffer[i+2]; else rawByte[2] = '\0'; // Splice the quantum into four groups of 6 bits, // left-padding these with zeros to make them 8 bits wide encodedByte[0] = (rawByte[0] & 0xFC) >> 2; encodedByte[1] = ((rawByte[0] & 0x03) << 4) | (rawByte[1] >> 4); encodedByte[2] = ((rawByte[1] & 0x0F) << 2) | (rawByte[2] >> 6); encodedByte[3] = (rawByte[2] & 0x3F); // These values are indices into the base64 character set, so // replace them with their respective characters encodedByte[0] = base64CharSet[encodedByte[0]]; encodedByte[1] = base64CharSet[encodedByte[1]]; encodedByte[2] = base64CharSet[encodedByte[2]]; encodedByte[3] = base64CharSet[encodedByte[3]]; // If the quantum was only 1 byte: replace last 2 bytes of encoding with == if (i+1 >= buflen) { encodedByte[2] = '='; encodedByte[3] = '='; } // If the quantum was only 2 bytes: replace last byte of encoding with = if (i+2 >= buflen) encodedByte[3] = '='; // Save these to the base64 buffer m_Base64[nBytes++] = encodedByte[0]; m_Base64[nBytes++] = encodedByte[1]; m_Base64[nBytes++] = encodedByte[2]; m_Base64[nBytes++] = encodedByte[3]; // Lines can be a maximum of 76 characters long if ((nBytes-iLineStart) % 76 == 0) { m_Base64[nBytes++] = '\r'; m_Base64[nBytes++] = '\n'; iLineStart = nBytes; } } m_Base64[nBytes++] = '\0'; // DWW Found out eudora and other mail programs require \r\n at 76 chars // something our NetBase64encode does not do! // UtlString encodedData; // NetBase64Codec::encode(buflen, buffer, encodedData); // memcpy(m_Base64, encodedData.data(), encodedData.length()); } sipxtapi-3.3.0~test17/sipXtackLib/src/net/MailMessage.cpp0000644000175000017500000002167712205613256024102 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // MailMessage class definition for Mailer //Example: /* MailMessage message("XXX", "XXX@pingtel.com", "XXX.pingtel.com"); message.Body("this is a test message"); message.Subject("Hello World!"); message.To("XXX","XXXr@pingtel.com"); message.Send(); */ // NOTE: String concatenation is expensive; this code is written for // clarity, not speed. #include "net/MailMessage.h" #include "os/OsConnectionSocket.h" UtlString CRLF = "\r\n"; UtlString CRLFCRLF = "\r\n\r\n"; void MailMessage::Body(const UtlString &rText) { UtlString text = rText.data(); m_ContentType = "text/plain; charset=\"us-ascii\"; format=flowed"; m_Body = text; } void MailMessage::Body(const UtlString &rText, const UtlString &rHtml) { UtlString text = rText.data(); UtlString html = rHtml.data(); UtlString boundary = "---=_Next_Part_of_Text_HTML_Alternatives_13579820350782"; m_ContentType = "multipart/alternative; boundary=\"" + boundary + "\""; m_Body = CRLF + "--" + boundary + CRLF; // m_Body += "Content-Type: text/plain; charset=\"us-ascii\"; format=flowed" m_Body += "Content-Type: text/plain; charset=\"us-ascii\"" + /* format=flowed" */ CRLF; // m_Body += "Content-Transfer-Encoding: quoted-printable" + CRLF; m_Body += CRLF; m_Body += text; m_Body += CRLF + "--" + boundary + CRLF; // m_Body += "Content-Type: text/html; charset=\"us-ascii\"; format=flowed" m_Body += "Content-Type: text/html; charset=\"us-ascii\"" + /* format=flowed" */ CRLF; // m_Body += "Content-Transfer-Encoding: quoted-printable" + CRLF; m_Body += CRLF; m_Body += html; m_Body += CRLF + "--" + boundary + "--"; } bool MailMessage::Attach(const UtlString &rFilename) { UtlString filename = rFilename.data(); MailAttachment att; if (att.Load(filename.data())) { m_vecAttachment.push_back(att); return true; } else return false; } bool MailMessage::Attach( const unsigned char *data, const int& rDatalength, const UtlString &rFilename ) { MailAttachment att; if ( att.Load( data, rDatalength, rFilename ) ) { m_vecAttachment.push_back(att); return true; } else return false; } #define MAILBUFLEN 4096 UtlString MailMessage::Send() { char receiveBuf[MAILBUFLEN]; UtlString r; UtlString str; // Connect to the SMTP server OsConnectionSocket s(25,m_Server.data()); if (!s.isConnected()) return "Could not connect to server"; // Receive the banner s.read(receiveBuf,MAILBUFLEN); // Send the HELO command str = "HELO localhost"; str += CRLF.data(); s.write(str.data(),str.length()); // Receive a 250 response s.read(receiveBuf,MAILBUFLEN); if (memcmp(receiveBuf,"250",3) != 0) return "Unacceptable response to HELO: " + r; // Send the MAIL FROM command str = "MAIL FROM:"; str += m_From.Address.data(); str += CRLF.data(); s.write(str.data(),str.length()); // Receive a 250 response s.read(receiveBuf,MAILBUFLEN); if (memcmp(receiveBuf,"250",3) != 0) return "Unacceptable response to MAIL FROM: " + r; // Send an RCPT TO for all recipients (To, Cc, and Bcc) unsigned int i; for (i = 0; i < m_vecTo.size(); i++) { // Send an RCPT TO command str = "RCPT TO:"; str += m_vecTo[i].Address.data(); str += CRLF.data(); s.write(str.data(),str.length()); // Receive a 250 response s.read(receiveBuf,MAILBUFLEN); if (memcmp(receiveBuf,"250",3) != 0) return "Unacceptable response to RCPT TO: " + r; } for (i = 0; i < m_vecCc.size(); i++) { // Send an RCPT TO command str = "RCPT TO:"; str += m_vecCc[i].Address.data(); str += CRLF.data(); s.write(str.data(),str.length()); // Receive a 250 response s.read(receiveBuf,MAILBUFLEN); if (memcmp(receiveBuf,"250",3) != 0) return "Unacceptable response to RCPT TO: " + r; } for (i = 0; i < m_vecBcc.size(); i++) { // Send an RCPT TO command str = "RCPT TO:"; str += m_vecBcc[i].Address.data(); str += CRLF.data(); s.write(str.data(),str.length()); // Receive a 250 response s.read(receiveBuf,MAILBUFLEN); if (memcmp(receiveBuf,"250",3) != 0) return "Unacceptable response to RCPT TO: " + r; } // Send the DATA command str = "DATA"; str += CRLF.data(); s.write(str.data(),str.length()); // Receive a 354 response s.read(receiveBuf,MAILBUFLEN); if (memcmp(receiveBuf,"354",3) != 0) return "Unacceptable response to DATA: " + r; // Format the data UtlString data = FormatForSending(); // Send the message, terminated with \r\n.\r\n str = data.data(); str += CRLF.data(); s.write(str.data(),str.length()); // Receive a 250 response s.read(receiveBuf,MAILBUFLEN); if (memcmp(receiveBuf,"250",3) != 0) return "Unacceptable response to body: " + r; return ""; } UtlString MailMessage::FormatForSending() { unsigned int i; int lineLength = 4; // From: "Name"
UtlString data = "From: " + m_From.toString() + CRLF; // To: "Name"
, "Name"
data += "To: "; for (i = 0; i < m_vecTo.size(); i++) { if (lineLength + m_vecTo[i].toString().length() > 998) { data += "\r\n "; lineLength = 1; } data += m_vecTo[i].toString(); lineLength += m_vecTo[i].toString().length(); if (i < m_vecTo.size()-1) { data += ", "; lineLength += 2; } } data += CRLF; // Cc: "Name"
, "Name"
data += "Cc: "; for (i = 0; i < m_vecCc.size(); i++) { if (lineLength + m_vecCc[i].toString().length() > 998) { data += "\r\n "; lineLength = 1; } data += m_vecCc[i].toString(); lineLength += m_vecCc[i].toString().length(); if (i < m_vecCc.size()-1) { data += ", "; lineLength += 2; } } data += CRLF; // Subject: Subject text data += "Subject: " + m_Subject + CRLF; // Date: Mon, 25 Sep 2001 11:11:11 -0600\r\n UtlString dateString; OsDateTime now; OsDateTime::getCurTime(now); now.getHttpTimeString(dateString); /* SYSTEMTIME now; GetLocalTime(&now); TIME_ZONE_INFORMATION tzinfo; GetTimeZoneInformation(&tzinfo); char *day[] = { "Sun","Mon","Tue","Wed","Thu","Fri","Sat" }; char *month[] = { "Jan","Feb","Mar","Apr","May","Jun","Jul", "Aug","Sep","Oct","Nov","Dec" }; char buf[128]; wsprintf(buf, "Date: %s, %u %s %u %02u:%02u:%02u %c%02u%02u", day[now.wDayOfWeek], now.wDay, month[now.wMonth], now.wYear, now.wHour, now.wMinute, now.wSecond, tzinfo.Bias > 0 ? '-' : '+', abs(tzinfo.Bias/60), abs(tzinfo.Bias%60)); */ char buf[128]; sprintf(buf, "Date: %s",dateString.data()); data += buf + CRLF; // MIME version header data += "Mime-Version: 1.0" + CRLF; // If attachments... if (m_vecAttachment.size() > 0) { UtlString boundary = "---=_Next_Part_of_Message_987456321147852369"; // MIME content type header and separator line data += "Content-Type: multipart/mixed; boundary=\"" + boundary + "\"" + CRLFCRLF; // Message body data += "--" + boundary + CRLF; data += "Content-Type: " + m_ContentType + CRLF; data += "Content-Transfer-Encoding: quoted-printable" + CRLFCRLF; data += m_Body + CRLF; // Attachments for (int i = 0; i < ((int)(m_vecAttachment.size())); i++) { data += "--" + boundary + CRLF; data += "Content-Type: " + m_vecAttachment[i].MIMEtype() + "; name=\"" + m_vecAttachment[i].Filename() + "\"" + CRLF; data += "Content-Transfer-Encoding: base64" + CRLF; data += "Content-Disposition: attachment; filename=\"" + m_vecAttachment[i].Filename() + "\"" + CRLFCRLF; data += m_vecAttachment[i].Base64Data() + CRLF; } data += "--" + boundary + "--"; } // No attachments else { // MIME content type header data += "Content-Type: " + m_ContentType + CRLF; // Separator line, body data += CRLF + m_Body; } data += CRLF + "."; data += CRLF; return data; } sipxtapi-3.3.0~test17/sipXtackLib/src/net/MimeBodyPart.cpp0000644000175000017500000001452612205613256024242 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor MimeBodyPart::MimeBodyPart(const HttpBody* parent, int parentBodyStartIndex, int rawBodyLength) { mpParentBody = parent; mParentBodyRawStartIndex = parentBodyStartIndex; mRawBodyLength = rawBodyLength; mParentBodyStartIndex = parentBodyStartIndex; mBodyLength = 0; if(rawBodyLength > 0 && parent) { const char* parentBodyBytes; const char* bodyBytes; int parentBodyLength; parent->getBytes(&parentBodyBytes, &parentBodyLength); bodyBytes = parentBodyBytes + parentBodyStartIndex; if(parentBodyLength >= parentBodyStartIndex + rawBodyLength) { int parsedBytes = HttpMessage::parseHeaders(bodyBytes, rawBodyLength, mNameValues); // search the part headers for a Content-Type NameValuePair* partType; UtlDListIterator partHeaders(mNameValues); for( partType = static_cast(partHeaders()); partType && partType->compareTo(HTTP_CONTENT_TYPE_FIELD, UtlString::ignoreCase); partType = static_cast(partHeaders()) ) { } if (partType) { // the content-type of the part is stored in the parent UtlString append(partType->getValue()); } mParentBodyStartIndex = parentBodyStartIndex + parsedBytes; mBodyLength = mRawBodyLength - parsedBytes; } } } // Construct a MimeBodyPart from an HttpBody and a list of parameters. MimeBodyPart::MimeBodyPart(const HttpBody& httpBody, //< Provides the bytes of the body. const UtlDList& parameters //< Provides the parameters. ) : HttpBody(httpBody), mpParentBody(NULL), mParentBodyRawStartIndex(-1), mRawBodyLength(-1), mParentBodyStartIndex(-1), mBodyLength(-1) { // Copy the parameters to mNameValues. UtlDListIterator iterator(parameters); NameValuePair* nvp; while((nvp = (NameValuePair*) iterator())) { mNameValues.append(new NameValuePair(nvp->data(), nvp->getValue())); } // Add the Content-Type parameter, taken from the HttpBody. mNameValues.append(new NameValuePair(HTTP_CONTENT_TYPE_FIELD, httpBody.getContentType())); // Add the Content-Transfer-Encoding parameter. mNameValues.append(new NameValuePair(HTTP_CONTENT_TRANSFER_ENCODING_FIELD, HTTP_CONTENT_TRANSFER_ENCODING_BINARY)); // Members that reference the parent will be corrected later. } // Copy constructor MimeBodyPart::MimeBodyPart(const MimeBodyPart& rMimeBodyPart) : HttpBody(rMimeBodyPart) { UtlDListIterator iterator((UtlDList&)rMimeBodyPart.mNameValues); NameValuePair* nvp; while((nvp = (NameValuePair*)iterator())) { mNameValues.append(new NameValuePair(nvp->data(), nvp->getValue())); } mpParentBody = rMimeBodyPart.mpParentBody; mParentBodyRawStartIndex = rMimeBodyPart.mParentBodyRawStartIndex; mRawBodyLength = rMimeBodyPart.mRawBodyLength; mParentBodyStartIndex = rMimeBodyPart.mParentBodyStartIndex; mBodyLength = rMimeBodyPart.mBodyLength; } // Destructor MimeBodyPart::~MimeBodyPart() { mNameValues.destroyAll(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator MimeBodyPart& MimeBodyPart::operator=(const MimeBodyPart& rhs) { if (this == &rhs) // handle the assignment to self case return *this; mNameValues.destroyAll(); UtlDListIterator iterator((UtlDList&)rhs.mNameValues); NameValuePair* nvp; while((nvp = (NameValuePair*)iterator())) { mNameValues.append(new NameValuePair(nvp->data(), nvp->getValue())); } mpParentBody = rhs.mpParentBody; mParentBodyRawStartIndex = rhs.mParentBodyRawStartIndex; mRawBodyLength = rhs.mRawBodyLength; mParentBodyStartIndex = rhs.mParentBodyStartIndex; mBodyLength = rhs.mBodyLength; return *this; } /** Update the members that locate this MimeBodyPart within its parent * HttpBody. */ void MimeBodyPart::attach(HttpBody* parent, int rawPartStart, int rawPartLength, int partStart, int partLength) { mpParentBody = parent; mParentBodyRawStartIndex = rawPartStart; mRawBodyLength = rawPartLength; mParentBodyStartIndex = partStart; mBodyLength = partLength; } /* ============================ ACCESSORS ================================= */ void MimeBodyPart::getBytes(const char** bytes, int* length) const { *bytes = NULL; if(mpParentBody) { const char* parentBodyBytes; int parentBodyLength; mpParentBody->getBytes(&parentBodyBytes, &parentBodyLength); if(mParentBodyStartIndex + mBodyLength <= parentBodyLength) { *bytes = parentBodyBytes + mParentBodyStartIndex; } } *length = mBodyLength; } UtlBoolean MimeBodyPart::getPartHeaderValue(const char* headerName, UtlString& headerValue) const { headerValue.remove(0); NameValuePair matchName(headerName); NameValuePair* nvp = (NameValuePair*) mNameValues.find(&matchName); if(nvp) { headerValue.append(nvp->getValue()); } return(nvp != NULL); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/NameValuePair.cpp0000644000175000017500000000664012205613256024375 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #include // APPLICATION INCLUDES #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS int NameValuePair::count = 0; OsMutex NameValuePair::mCountLock(OsMutex::Q_PRIORITY); int getNVCount() { return NameValuePair::count; } /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor NameValuePair::NameValuePair(const char* name, const char* value) : UtlString(name) { valueString = NULL; setValue(value); #ifdef TEST_ACCOUNT mCountLock.acquire(); count++; mCountLock.release(); #endif } // Copy constructor NameValuePair::NameValuePair(const NameValuePair& rNameValuePair) : UtlString(rNameValuePair) { // Slow copy does implicit const./dest of UtlString //((UtlString) *this) = rNameValuePair; // Use parent copy constructor this->UtlString::operator=(rNameValuePair); valueString = NULL; setValue(rNameValuePair.valueString); } // Destructor NameValuePair::~NameValuePair() { if(valueString) { delete[] valueString; valueString = 0; } #ifdef TEST_ACCOUNT mCountLock.acquire(); count--; mCountLock.release(); #endif } /* ============================ MANIPULATORS ============================== */ // Assignment operator NameValuePair& NameValuePair::operator=(const NameValuePair& rhs) { if (this == &rhs) // handle the assignment to self case return *this; ((UtlString&) *this) = rhs.data(); setValue(rhs.valueString); return *this; } /* ============================ ACCESSORS ================================= */ const char* NameValuePair::getValue() { return(valueString); } void NameValuePair::setValue(const char* newValue) { if(newValue) { int len = strlen(newValue); if(valueString && len > (int) strlen(valueString)) { delete[] valueString; valueString = new char[len + 1]; } else if (!valueString) valueString = new char[len + 1]; strcpy(valueString, newValue); } else if(valueString) { delete[] valueString; valueString = 0; } } /* ============================ INQUIRY =================================== */ UtlBoolean NameValuePair::isInstanceOf(const UtlContainableType type) const { // Check if it is my type and the defer parent type comparisons to parent return(areSameTypes(type, NameValuePair::TYPE) || UtlString::isInstanceOf(type)); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/NameValuePairInsensitive.cpp0000644000175000017500000000744112205613256026616 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #include // APPLICATION INCLUDES #include "net/NameValuePairInsensitive.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS const UtlContainableType NameValuePairInsensitive::TYPE = "NameValuePairInsensitive"; // Most methods are carried over from NameValuePair. // Constructor NameValuePairInsensitive::NameValuePairInsensitive(const char* name, const char* value) : NameValuePair(name, value) { // All the work is done by the NameValuePair constructor. } // Copy constructor NameValuePairInsensitive::NameValuePairInsensitive( const NameValuePairInsensitive& rNameValuePairInsensitive) : NameValuePair(rNameValuePairInsensitive) { // All the work is done by the NameValuePair constructor. } // Destructor NameValuePairInsensitive::~NameValuePairInsensitive() { // All the work is done by the NameValuePair destructor. } /* ============================ MANIPULATORS ============================== */ // Assignment operator NameValuePairInsensitive& NameValuePairInsensitive::operator=(const NameValuePairInsensitive& rhs) { ((NameValuePair&) *this) = (const NameValuePair) rhs; return *this; } /* ============================ ACCESSORS ================================= */ const char* NameValuePairInsensitive::getValue() { return ((NameValuePair*) this)->getValue(); } void NameValuePairInsensitive::setValue(const char* newValue) { ((NameValuePair*) this)->setValue(newValue); } /* ============================ INQUIRY =================================== */ // Returns a hash value. the algorithm is according to // g_string_hash() in glib. unsigned NameValuePairInsensitive::hash() const { // Need to use data() in case mpData is null const char* pHashData = data(); size_t hashSize = length(); unsigned hashValue = 0; while (hashSize > 0) { // Put each character through toupper before hashing it. hashValue = (hashValue << 5) - hashValue + toupper(*pHashData); pHashData++; hashSize--; } return hashValue; } // Get the ContainableType for a UtlContainable derived class. UtlContainableType NameValuePairInsensitive::getContainableType() const { return NameValuePairInsensitive::TYPE; } // Compare this object to another like-objects. int NameValuePairInsensitive::compareTo( UtlContainable const * compareContainable) const { int compareFlag = -1; if (compareContainable) { compareFlag = ((UtlString*) this)-> compareTo(((UtlString*) compareContainable)->data(), UtlString::ignoreCase); } return compareFlag; } // Test this object to another like-object for equality. UtlBoolean NameValuePairInsensitive::isEqual( UtlContainable const * compareContainable) const { return (compareTo(compareContainable) == 0); } UtlBoolean NameValuePairInsensitive::isInstanceOf(const UtlContainableType type) const { // Check if it is my type and the defer parent type comparisons to parent return(areSameTypes(type, NameValuePairInsensitive::TYPE) || NameValuePair::isInstanceOf(type)); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/NetAttributeTokenizer.cpp0000644000175000017500000001440612205613256026210 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor NetAttributeTokenizer::NetAttributeTokenizer(const char* parseString) { if(parseString) { attributeParseString.append(parseString); } parseIndex = 0; } // Copy constructor NetAttributeTokenizer::NetAttributeTokenizer(const NetAttributeTokenizer& rNetAttributeTokenizer) { } // Destructor NetAttributeTokenizer::~NetAttributeTokenizer() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator NetAttributeTokenizer& NetAttributeTokenizer::operator=(const NetAttributeTokenizer& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } UtlBoolean NetAttributeTokenizer::getNextAttribute(UtlString& attributeName, UtlString& attributeValue) { UtlBoolean foundNextAttribute = FALSE; const char* attributeSeparators = ", \t\n\r"; const char* quoteCharacters = "\'\""; const char nameValueSeparator = '='; const char escapeChar = '\\'; int stringLen = attributeParseString.length(); int attributeNameStart = -1; int attributeNameEnd = -1; int attributeValueStart = -1; int attributeValueEnd = -1; UtlBoolean valuePresent = FALSE; attributeName.remove(0); attributeValue.remove(0); if(parseIndex < stringLen) { const char* parseString = attributeParseString.data(); // Skip attribute separator stuff before the attribute name while(strchr(attributeSeparators, parseString[parseIndex]) && parseIndex < stringLen) { parseIndex++; } // If a begining of a attribute name exists if(parseIndex < stringLen) { attributeNameStart = parseIndex; } // Find the end of the attribute name while(!strchr(attributeSeparators, parseString[parseIndex]) && parseString[parseIndex] != nameValueSeparator && parseIndex < stringLen) { parseIndex++; attributeNameEnd = parseIndex; } // Set the attribute name if(attributeNameStart >= 0 && attributeNameEnd >= 0) { attributeName.append(&parseString[attributeNameStart], attributeNameEnd - attributeNameStart); foundNextAttribute = TRUE; } // Skip name value separator stuff before the attribute value while((strchr(attributeSeparators, parseString[parseIndex]) || parseString[parseIndex] == nameValueSeparator) && parseIndex < stringLen) { if(parseString[parseIndex] == nameValueSeparator) { valuePresent = TRUE; } parseIndex++; } // If there was an equal sign, there is a value if(valuePresent) { // See of the value is quoted if(strchr(quoteCharacters, parseString[parseIndex])) { parseIndex++; attributeValueStart = parseIndex; // Need to check for escape character // even number contiguous means the quote is not escaped // Find the end quote int escapeCount = 0; while((!strchr(quoteCharacters, parseString[parseIndex]) || escapeCount % 2) && // an odd number of escape chars means the // quoteCharacter is escaped parseIndex < stringLen) { if(parseString[parseIndex] == escapeChar) { escapeCount++; } else { escapeCount = 0; } parseIndex++; attributeValueEnd = parseIndex; } // Index past the last quote for the next token if(parseIndex < stringLen) { parseIndex++; } } // Not quoted find the first white space as separator else { attributeValueStart = parseIndex; while(!strchr(attributeSeparators, parseString[parseIndex]) && parseIndex < stringLen) { parseIndex++; attributeValueEnd = parseIndex; } } // Set the attribute value if(attributeValueStart >= 0 && attributeValueEnd >= 0) { attributeValue.append(&parseString[attributeValueStart], attributeValueEnd - attributeValueStart); } } } return(foundNextAttribute); } UtlBoolean NetAttributeTokenizer::getAttributes(UtlList& attributeList) { UtlBoolean attributesFound = FALSE; UtlString name; UtlString value; while(getNextAttribute(name, value)) { attributeList.insert(new NameValuePair(name.data(), value.data())); attributesFound = TRUE; } name.remove(0); value.remove(0); return(attributesFound); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/NetBase64Codec.cpp0000644000175000017500000001567112205613256024341 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2007 SIPfoundry Inc. // License by SIPfoundry under the LGPL license. // // Copyright (C) 2004 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPez, LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ //////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include // APPLICATION INCLUDES #include "os/OsDefs.h" #include "utl/UtlRegex.h" #include "net/NetBase64Codec.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const char* NetBase64Codec::Base64Codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; const RegEx ValidBase64("^([A-Za-z0-9+/]+)(={0,2})$"); // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor NetBase64Codec::NetBase64Codec() { } // Copy constructor NetBase64Codec::NetBase64Codec(const NetBase64Codec& rNetBase64Codec) { } // Destructor NetBase64Codec::~NetBase64Codec() { } /* ============================ MANIPULATORS ============================== */ void NetBase64Codec::encode(int dataSize, const char data[], int& encodedDataSize, char encodedData[]) { int i; int j = 0; encodedDataSize = encodedSize(dataSize); for (i = 0; i < (dataSize - (dataSize % 3)); i+=3) // Encode 3 bytes at a time. { encodedData[j] = Base64Codes[ (data[i] & 0xfc) >> 2 ]; encodedData[j+1] = Base64Codes[ ((data[i] & 0x03) << 4) | ((data[i+1] & 0xf0) >> 4) ]; encodedData[j+2] = Base64Codes[ ((data[i+1] & 0x0f) << 2) | ((data[i+2] & 0xc0) >> 6) ]; encodedData[j+3] = Base64Codes[ (data[i+2] & 0x3f) ]; j += 4; } i = dataSize - (dataSize % 3); // Where we left off before. switch (dataSize % 3) { case 2: // One character padding needed. { encodedData[j] = Base64Codes[ (data[i] & 0xfc) >> 2 ]; encodedData[j+1] = Base64Codes[ ((data[i] & 0x03) << 4) | ((data[i+1] & 0xf0) >> 4) ]; encodedData[j+2] = Base64Codes[ (data[i+1] & 0x0f) << 2 ]; encodedData[j+3] = Base64Codes[64]; // Pad break; } case 1: // Two character padding needed. { encodedData[j] = Base64Codes[ (data[i] & 0xfc) >> 2 ]; encodedData[j+1] = Base64Codes[ (data[i] & 0x03) << 4 ]; encodedData[j+2] = Base64Codes[64]; // Pad encodedData[j+3] = Base64Codes[64]; // Pad break; } } // encodedData[j+4] = NULL; } void NetBase64Codec::encode(int dataSize, const char data[], UtlString& encodedData) { int numEncodeBytes = encodedSize(dataSize); char* encodeBuffer = new char[numEncodeBytes]; encode(dataSize, data, numEncodeBytes, encodeBuffer); encodedData.remove(0); encodedData.append(encodeBuffer, numEncodeBytes); delete[] encodeBuffer; encodeBuffer = NULL; } int NetBase64Codec::encodedSize(int dataSize) { int size = dataSize / 3; if(dataSize % 3) size++; size *= 4; return(size); } /// @returns > 0 iff the encoded data is syntactically valid, 0 if not. size_t NetBase64Codec::validEncodingBytes(int encodedDataSize, ///< number of encoded octets const char encodedData[] ///< the encoded data ) { bool syntaxIsValid = false; int encodingBytes = 0; RegEx validBase64(ValidBase64); if (validBase64.Search(encodedData,encodedDataSize)) { /* * The pattern of the string matched, now check to see if the number of padding * bytes is correct for the number of encoding bytes. */ int ignoreOffset; int paddingBytes; validBase64.Match(1,ignoreOffset,encodingBytes); // the actual encoded value characters validBase64.Match(2,ignoreOffset,paddingBytes); // the padding - trailing '=' characters switch (paddingBytes) { case 0: syntaxIsValid = (0 == encodingBytes % 4); break; case 1: syntaxIsValid = (3 == encodingBytes % 4); break; case 2: syntaxIsValid = (2 == encodingBytes % 4); break; default: // for any other value, the syntax is not valid break; } } else { // encodedData contained invalid characters } return syntaxIsValid ? encodingBytes : 0; } char NetBase64Codec::decodeChar(const char encoded) { // This does not check for invalid characters, so call isValid before you call this!!! return(encoded == '=' ? 0 : strchr(Base64Codes, encoded) - Base64Codes ); } bool NetBase64Codec::decode(int encodedDataSize, const char encodedData[], int& dataSize, char data[]) { bool valid = isValid(encodedDataSize, encodedData); if (valid) { int i; int j = 0; dataSize = decodedSize(encodedDataSize, encodedData); for (i = 0; i < encodedDataSize; i+=4) // Work on 4 bytes at a time. { // Twiddle bits. data[j] = (decodeChar(encodedData[i]) << 2) | ((decodeChar(encodedData[i+1]) & 0x30) >> 4); if(j + 1 < dataSize) { data[j+1] = ((decodeChar(encodedData[i+1]) & 0x0f) << 4) | ((decodeChar(encodedData[i+2]) & 0x3c) >> 2); if(j + 2 < dataSize) { data[j+2] = ((decodeChar(encodedData[i+2]) & 0x03) << 6) | (decodeChar(encodedData[i+3]) & 0x3f); } } j += 3; } } return valid; } // Decode from one UtlString into another bool NetBase64Codec::decode(const UtlString& encodedData, /* size is encodedData.length(), * not null terminated */ UtlString& data // output: the decoded data ) { bool valid = isValid(encodedData); if (valid) { size_t sizeNeeded = decodedSize(encodedData.length(), encodedData.data()); int size; // Resize output string to get space for decoded data. data.resize(sizeNeeded); // Do decode decode(encodedData.length(), encodedData.data(), size, (char*)data.data()); // Resize output string to value, returned by decode(). data.resize(size); } return valid; } int NetBase64Codec::decodedSize(int encodedDataSize, const char encodedData[]) { size_t nonPadBytes = validEncodingBytes(encodedDataSize, encodedData); return nonPadBytes ? (nonPadBytes * 3) / 4 : 0; } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/NetMd5Codec.cpp0000644000175000017500000003015612205613256023735 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include // APPLICATION INCLUDES #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // FORWARD DECLARATIONS typedef uint16_t UINT2; typedef uint32_t UINT4; /* MD5 context. */ typedef struct { UINT4 state[4]; /* state (ABCD) */ UINT4 count[2]; /* number of bits, modulo 2^64 (lsb first) */ unsigned char buffer[64]; /* input buffer */ } MD5_CTX_PT; static void MD5Init(MD5_CTX_PT *); static void MD5Update(MD5_CTX_PT *, unsigned char *, unsigned int); static void MD5Final(unsigned char [16], MD5_CTX_PT *); /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor NetMd5Codec::NetMd5Codec() { } // Destructor NetMd5Codec::~NetMd5Codec() { } /* ============================ MANIPULATORS ============================== */ void NetMd5Codec::encode(const char* text, UtlString& encodedText) { // This stuff should be packaged into a real class where the // init and update happens in the constructor, and the final is a method MD5_CTX_PT context; unsigned char digest[16]; unsigned int len = strlen (text); unsigned int i; char szTmp[MD5_SIZE]; memset(digest,0,sizeof(digest)); MD5Init (&context); MD5Update (&context, (unsigned char *)text, len); MD5Final (digest, &context); for (i = 0; i < 16; i++) { sprintf(szTmp, "%02x", digest[i]); encodedText.append(szTmp); } } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ /* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved. License to copy and use this software is granted provided that it is identified as the "RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing this software or this function. License is also granted to make and use derivative works provided that such works are identified as "derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing the derived work. RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided "as is" without express or implied warranty of any kind. These notices must be retained in any copies of any part of this documentation and/or software. */ #include #include typedef unsigned char *POINTER; /* Constants for MD5Transform routine. */ #define S11 7 #define S12 12 #define S13 17 #define S14 22 #define S21 5 #define S22 9 #define S23 14 #define S24 20 #define S31 4 #define S32 11 #define S33 16 #define S34 23 #define S41 6 #define S42 10 #define S43 15 #define S44 21 static void MD5Transform(UINT4 [4], unsigned char [64]); static void Encode(unsigned char *, UINT4 *, unsigned int); static void Decode(UINT4 *, unsigned char *, unsigned int); static void MD5_memcpy(POINTER, POINTER, unsigned int); static void MD5_memset(POINTER, int, unsigned int); static unsigned char PADDING[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* F, G, H and I are basic MD5 functions. */ #define F(x, y, z) (((x) & (y)) | ((~x) & (z))) #define G(x, y, z) (((x) & (z)) | ((y) & (~z))) #define H(x, y, z) ((x) ^ (y) ^ (z)) #define I(x, y, z) ((y) ^ ((x) | (~z))) /* ROTATE_LEFT rotates x left n bits. */ #define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) /* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. Rotation is separate from addition to prevent recomputation. */ #define FF(a, b, c, d, x, s, ac) { \ (a) += F ((b), (c), (d)) + (x) + (UINT4)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define GG(a, b, c, d, x, s, ac) { \ (a) += G ((b), (c), (d)) + (x) + (UINT4)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define HH(a, b, c, d, x, s, ac) { \ (a) += H ((b), (c), (d)) + (x) + (UINT4)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define II(a, b, c, d, x, s, ac) { \ (a) += I ((b), (c), (d)) + (x) + (UINT4)(ac); \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } /* MD5 initialization. Begins an MD5 operation, writing a new context. */ void MD5Init (MD5_CTX_PT *context) /* context */ { context->count[0] = context->count[1] = 0; /* Load magic initialization constants.*/ context->state[0] = 0x67452301; context->state[1] = 0xefcdab89; context->state[2] = 0x98badcfe; context->state[3] = 0x10325476; } /* MD5 block update operation. Continues an MD5 message-digest operation, processing another message block, and updating the context. */ void MD5Update (MD5_CTX_PT *context, /* context */ unsigned char *input, /* input block */ unsigned int inputLen) /* length of input block */ { unsigned int i, index, partLen; /* Compute number of bytes mod 64 */ index = (unsigned int)((context->count[0] >> 3) & 0x3F); /* Update number of bits */ if ((context->count[0] += ((UINT4)inputLen << 3)) < ((UINT4)inputLen << 3)) context->count[1]++; context->count[1] += ((UINT4)inputLen >> 29); partLen = 64 - index; /* Transform as many times as possible. */ if (inputLen >= partLen) { MD5_memcpy((POINTER)&context->buffer[index], (POINTER)input, partLen); MD5Transform(context->state, context->buffer); for (i = partLen; i + 63 < inputLen; i += 64) MD5Transform(context->state, &input[i]); index = 0; } else i = 0; /* Buffer remaining input */ MD5_memcpy((POINTER)&context->buffer[index], (POINTER)&input[i], inputLen-i); } /* MD5 finalization. Ends an MD5 message-digest operation, writing the the message digest and zeroizing the context. */ void MD5Final (unsigned char *digest, /* message digest */ MD5_CTX_PT *context) /* context */ { unsigned char bits[8]; unsigned int index, padLen; /* Save number of bits */ Encode (bits, context->count, 8); /* Pad out to 56 mod 64.*/ index = (unsigned int)((context->count[0] >> 3) & 0x3f); padLen = (index < 56) ? (56 - index) : (120 - index); MD5Update (context, PADDING, padLen); /* Append length (before padding) */ MD5Update (context, bits, 8); /* Store state in digest */ Encode (digest, context->state, 16); /* Zeroize sensitive information.*/ MD5_memset ((POINTER)context, 0, sizeof (*context)); } /* MD5 basic transformation. Transforms state based on block. */ static void MD5Transform (UINT4 state[4], unsigned char block[64]) { UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; Decode (x, block, 64); /* Round 1 */ FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ /* Round 2 */ GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ /* Round 3 */ HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ /* Round 4 */ II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; /* Zeroize sensitive information. */ MD5_memset ((POINTER)x, 0, sizeof (x)); } /* Encodes input (UINT4) into output (unsigned char). Assumes len is a multiple of 4. */ static void Encode (unsigned char *output, UINT4 *input, unsigned int len) { unsigned int i, j; for (i = 0, j = 0; j < len; i++, j += 4) { output[j] = (unsigned char)(input[i] & 0xff); output[j+1] = (unsigned char)((input[i] >> 8) & 0xff); output[j+2] = (unsigned char)((input[i] >> 16) & 0xff); output[j+3] = (unsigned char)((input[i] >> 24) & 0xff); } } /* Decodes input (unsigned char) into output (UINT4). Assumes len is a multiple of 4. */ static void Decode (UINT4 *output, unsigned char *input, unsigned int len) { unsigned int i, j; for (i = 0, j = 0; j < len; i++, j += 4) output[i] = ((UINT4)input[j]) | (((UINT4)input[j+1]) << 8) | (((UINT4)input[j+2]) << 16) | (((UINT4)input[j+3]) << 24); } static void MD5_memcpy (POINTER output, POINTER input, unsigned int len) { memcpy(output, input, len); } static void MD5_memset (POINTER output, int value, unsigned int len) { memset(output, value, len); } sipxtapi-3.3.0~test17/sipXtackLib/src/net/ProvisioningAgent.cpp0000644000175000017500000003134512205613256025351 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include "net/Url.h" #include "net/ProvisioningClass.h" #include "net/ProvisioningAttrList.h" #include "net/ProvisioningAgent.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgent::ProvisioningAgent // // SYNOPSIS: // // DESCRIPTION: Default constructor // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAgent::ProvisioningAgent(const char* pServerClass, bool persistentStore) : mServerClass(pServerClass) { // If this Provisioning Agent is to use persistent configuration, // Attempt to open or create the corresponding xml document. if (persistentStore) { OsPath workingDirectory; // First try and find the .xml file, either in the SIPX_CONFDIR or the CWD. // The ServerClass name is used as the root file name. if (OsFileSystem::exists(SIPX_CONFDIR)) { workingDirectory = SIPX_CONFDIR; OsPath path(workingDirectory); path.getNativePath(workingDirectory); } else { OsPath path; OsFileSystem::getWorkingDirectory(path); path.getNativePath(workingDirectory); } // Build up the configuration file path mpConfigFile = new OsPath(workingDirectory + OsPathBase::separator + pServerClass + ".xml"); mpXmlConfigDoc = new TiXmlDocument(mpConfigFile->data()); if (!OsFileSystem::exists(*mpConfigFile)) { // xml configuration file does not exist, so create an initial one. UtlString blankXml = "\n"; blankXml += "\n\n"; blankXml += "<" + mServerClass + ">\n"; blankXml += "\n"; mpXmlConfigDoc->Parse(blankXml.data()); mpXmlConfigDoc->SaveFile(); OsSysLog::add(FAC_ACD, PRI_DEBUG, "ProvisioningAgent::ProvisioningAgent - Creating initial configuration file: %s", mpConfigFile->data()); } else { // Now attempt to load the file and build the DOM mpXmlConfigDoc->LoadFile(); if (mpXmlConfigDoc->Error()) { // There were errors parsing the existing config file. // Rename it and create a new blank one. OsPath badFile(workingDirectory + OsPathBase::separator + pServerClass + ".xml_INVALID"); OsFileSystem::rename(*mpConfigFile, badFile); delete mpXmlConfigDoc; mpXmlConfigDoc = new TiXmlDocument(mpConfigFile->data()); // Now build up a new blank configuration file. UtlString blankXml = "\n"; blankXml += "\n\n"; blankXml += "<" + mServerClass + ">\n"; blankXml += "\n"; mpXmlConfigDoc->Parse(blankXml.data()); mpXmlConfigDoc->SaveFile(); OsSysLog::add(FAC_ACD, PRI_DEBUG, "ProvisioningAgent::ProvisioningAgent - Configuration file: %s corrupted, corrupted, creating blank file", mpConfigFile->data()); } } } else { // No configuration file or persistent storage mpConfigFile = NULL; mpXmlConfigDoc = NULL; } } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgent::~ProvisioningAgent // // SYNOPSIS: // // DESCRIPTION: Destructor // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAgent::~ProvisioningAgent(){ delete mpConfigFile; delete mpXmlConfigDoc; } /* ============================ MANIPULATORS ============================== */ //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgent::registerClass // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// OsStatus ProvisioningAgent::registerClass(ProvisioningClass* pProvisioningClass){ // Search to see if this class has already registered. const UtlString* pClassName = pProvisioningClass->getClassName(); if (mRegisteredClasses.contains(pClassName)) { // A class can only register once. return OS_FAILED; } else { // If not, add it to the list of Provisioning Classes. if (mRegisteredClasses.insertKeyAndValue((UtlString*)pClassName, pProvisioningClass) == NULL) { // The insert failed. Probably due to a collision. return OS_FAILED; } else { // Pass the registered provisioning class the pointer to the Xml Config Doc. pProvisioningClass->setXmlConfigDoc(mpXmlConfigDoc); } } return OS_SUCCESS; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgent::unregisterClass // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// OsStatus ProvisioningAgent::unregisterClass(ProvisioningClass* pProvisioningClass){ // If this class has already registered, remove it and delete the key store. if (mRegisteredClasses.removeReference(pProvisioningClass->getClassName()) != NULL) { return OS_SUCCESS; } else { // Did not find Class in list. return OS_FAILED; } } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgent::Create // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAttrList* ProvisioningAgent::Create(ProvisioningAttrList& rRequestAttributes){ // Extract and lookup the ProvisioningClass* pProvisioningClass = lookupProvisioningClass(rRequestAttributes); if (pProvisioningClass == NULL) { // Either the request was invalid or the Class isn't registered. return NULL; } else { // Call the target Provisioning Class. return pProvisioningClass->Create(rRequestAttributes); } } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgent::Delete // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAttrList* ProvisioningAgent::Delete(ProvisioningAttrList& rRequestAttributes){ // Extract and lookup the ProvisioningClass* pProvisioningClass = lookupProvisioningClass(rRequestAttributes); if (pProvisioningClass == NULL) { // Either the request was invalid or the Class isn't registered. return NULL; } else { // Call the target Provisioning Class. return pProvisioningClass->Delete(rRequestAttributes); } } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgent::Set // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAttrList* ProvisioningAgent::Set(ProvisioningAttrList& rRequestAttributes){ // Extract and lookup the ProvisioningClass* pProvisioningClass = lookupProvisioningClass(rRequestAttributes); if (pProvisioningClass == NULL) { // Either the request was invalid or the Class isn't registered. return NULL; } else { // Call the target Provisioning Class. return pProvisioningClass->Set(rRequestAttributes); } } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgent::Get // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAttrList* ProvisioningAgent::Get(ProvisioningAttrList& rRequestAttributes){ // Extract and lookup the ProvisioningClass* pProvisioningClass = lookupProvisioningClass(rRequestAttributes); if (pProvisioningClass == NULL) { // Either the request was invalid or the Class isn't registered. return NULL; } else { // Call the target Provisioning Class. return pProvisioningClass->Get(rRequestAttributes); } } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgent::Action // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAttrList* ProvisioningAgent::Action(ProvisioningAttrList& rRequestAttributes){ // Extract and lookup the ProvisioningClass* pProvisioningClass = lookupProvisioningClass(rRequestAttributes); if (pProvisioningClass == NULL) { // Either the request was invalid or the Class isn't registered. return NULL; } else { // Call the target Provisioning Class. return pProvisioningClass->Action(rRequestAttributes); } } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgent::lookupProvisioningClass // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningClass* ProvisioningAgent::lookupProvisioningClass(ProvisioningAttrList& rRequestAttributes){ const char* pTargetClass; ProvisioningClass* pProvisioningClass; // Extract the target class value from the parameter. if (rRequestAttributes.getAttribute("object-class", pTargetClass) == false) { // The tag was not found. Must be a bad request. OsSysLog::add(FAC_ACD, PRI_ERR, "ProvisioningAgent::lookupProvisioningClass - parameter not found."); return NULL; } // Now that we have the target class, try and find a registered Provisioning Class. UtlString targetClassString(pTargetClass); pProvisioningClass = dynamic_cast(mRegisteredClasses.findValue(&targetClassString)); if (pProvisioningClass == NULL) { // The class doesn't appear to be registered. OsSysLog::add(FAC_ACD, PRI_ERR, "ProvisioningAgent::lookupProvisioningClass - Provisioning Class: '%s' not registered.", pTargetClass); return NULL; } // Return a pointer to the target Provisioning Class. return pProvisioningClass; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/ProvisioningAgentXmlRpcAdapter.cpp0000644000175000017500000004006412205613256027776 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include "net/XmlRpcRequest.h" #include "net/XmlRpcResponse.h" #include "net/XmlRpcDispatch.h" #include "net/ProvisioningAgent.h" #include "net/ProvisioningAttrList.h" #include "net/ProvisioningAgentXmlRpcAdapter.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgentXmlRpcAdapter::ProvisioningAgentXmlRpcAdapter // // SYNOPSIS: // // DESCRIPTION: Default constructor // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAgentXmlRpcAdapter::ProvisioningAgentXmlRpcAdapter(const ProvisioningAgent* pProvisioningAgent, int serverPort, bool secureTransport) { mpXmlRpcServer = new XmlRpcDispatch(serverPort, secureTransport, "/RPC2"); mpXmlRpcServer->addMethod("create", (XmlRpcMethod::Get*)ProvisioningAgentXmlRpcCreate::get, (void*)pProvisioningAgent); mpXmlRpcServer->addMethod("delete", (XmlRpcMethod::Get*)ProvisioningAgentXmlRpcDelete::get, (void*)pProvisioningAgent); mpXmlRpcServer->addMethod("set", (XmlRpcMethod::Get*)ProvisioningAgentXmlRpcSet::get, (void*)pProvisioningAgent); mpXmlRpcServer->addMethod("get", (XmlRpcMethod::Get*)ProvisioningAgentXmlRpcGet::get, (void*)pProvisioningAgent); mpXmlRpcServer->addMethod("action", (XmlRpcMethod::Get*)ProvisioningAgentXmlRpcAction::get, (void*)pProvisioningAgent); OsSysLog::add(FAC_ACD, PRI_DEBUG, "Creating XmlRpcDispatch on port: %d(%s)", serverPort, secureTransport ? "SSL" : "NON-SSL"); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgentXmlRpcAdapter::~ProvisioningAgentXmlRpcAdapter // // SYNOPSIS: // // DESCRIPTION: Destructor // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAgentXmlRpcAdapter::~ProvisioningAgentXmlRpcAdapter() { delete mpXmlRpcServer; } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* ============================ RPC FUNCTIONS ============================= */ //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgentXmlRpcCreate::execute // // SYNOPSIS: // // DESCRIPTION: This is the actual method called by the underlying XmlRpc Dispatcher in // response to receiving a . It will call the corresponding // ProvisioningAgent Create method whos instance is supplied in the // provisioningAgentInstance argument. // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningAgentXmlRpcCreate::execute(const HttpRequestContext& rContext, UtlSList& rParameters, void* pProvisioningAgentInstance, XmlRpcResponse& rResponse, XmlRpcMethod::ExecutionStatus& rStatus) { rStatus = XmlRpcMethod::OK; // Extract the request argument structure from the head of the SList. UtlContainable *pRequestArgs = rParameters.at(0); // Verify that a parameter list was given if (pRequestArgs != NULL) { // Verify that the parameter list is a structure ("UtlHashMap"). if (UtlString(pRequestArgs->getContainableType()) == "UtlHashMap") { // Now call the Provisioning Agent. ProvisioningAttrList requestAttributes(dynamic_cast(pRequestArgs)); ProvisioningAttrList* pResponseAttributes; pResponseAttributes = ((ProvisioningAgent*)pProvisioningAgentInstance)->Create(requestAttributes); if (pResponseAttributes == NULL) { // Method failure. Report error back to client rResponse.setFault(METHOD_DISPATCH_FAULT_CODE, METHOD_DISPATCH_FAULT_STRING); } else { // Encode the response rResponse.setResponse(dynamic_cast(pResponseAttributes->getData())); // and clean up the responsettributes list. delete pResponseAttributes; } } else { // Bad parameter list. Report error back to client rResponse.setFault(EXPECTED_STRUCT_FAULT_CODE, EXPECTED_STRUCT_FAULT_STRING); } } else { // Missing parameter list. Report error back to client rResponse.setFault(EXPECTED_STRUCT_FAULT_CODE, EXPECTED_STRUCT_FAULT_STRING); } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgentXmlRpcDelete::execute // // SYNOPSIS: // // DESCRIPTION: This is the actual method called by the underlying XmlRpc Dispatcher in // response to receiving a . It will call the corresponding // ProvisioningAgent Delete method whos instance is supplied in the // provisioningAgentInstance argument. // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningAgentXmlRpcDelete::execute(const HttpRequestContext& rContext, UtlSList& rParameters, void* pProvisioningAgentInstance, XmlRpcResponse& rResponse, XmlRpcMethod::ExecutionStatus& rStatus) { rStatus = XmlRpcMethod::OK; // Extract the request argument structure from the head of the SList. UtlContainable *pRequestArgs = rParameters.at(0); // Verify that a parameter list was given if (pRequestArgs != NULL) { // Verify that the parameter list is a structure ("UtlHashMap"). if (UtlString(pRequestArgs->getContainableType()) == "UtlHashMap") { // Now call the Provisioning Agent. ProvisioningAttrList requestAttributes(dynamic_cast(pRequestArgs)); ProvisioningAttrList* pResponseAttributes; pResponseAttributes = ((ProvisioningAgent*)pProvisioningAgentInstance)->Delete(requestAttributes); if (pResponseAttributes == NULL) { // Method failure. Report error back to client rResponse.setFault(METHOD_DISPATCH_FAULT_CODE, METHOD_DISPATCH_FAULT_STRING); } else { // Encode the response rResponse.setResponse(dynamic_cast(pResponseAttributes->getData())); // and clean up the responsettributes list. delete pResponseAttributes; } } else { // Missing parameter list. Report error back to client rResponse.setFault(EXPECTED_STRUCT_FAULT_CODE, EXPECTED_STRUCT_FAULT_STRING); } } else { // Bad parameter list. Report error back to client rResponse.setFault(EXPECTED_STRUCT_FAULT_CODE, EXPECTED_STRUCT_FAULT_STRING); } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgentXmlRpcSet::execute // // SYNOPSIS: // // DESCRIPTION: This is the actual method called by the underlying XmlRpc Dispatcher in // response to receiving a . It will call the corresponding // ProvisioningAgent Set method whos instance is supplied in the // provisioningAgentInstance argument. // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningAgentXmlRpcSet::execute(const HttpRequestContext& rContext, UtlSList& rParameters, void* pProvisioningAgentInstance, XmlRpcResponse& rResponse, XmlRpcMethod::ExecutionStatus& rStatus) { rStatus = XmlRpcMethod::OK; // Extract the request argument structure from the head of the SList. UtlContainable *pRequestArgs = rParameters.at(0); // Verify that a parameter list was given if (pRequestArgs != NULL) { // Verify that the parameter list is a structure ("UtlHashMap"). if (UtlString(pRequestArgs->getContainableType()) == "UtlHashMap") { // Now call the Provisioning Agent. ProvisioningAttrList requestAttributes(dynamic_cast(pRequestArgs)); ProvisioningAttrList* pResponseAttributes; pResponseAttributes = ((ProvisioningAgent*)pProvisioningAgentInstance)->Set(requestAttributes); if (pResponseAttributes == NULL) { // Method failure. Report error back to client rResponse.setFault(METHOD_DISPATCH_FAULT_CODE, METHOD_DISPATCH_FAULT_STRING); } else { // Encode the response rResponse.setResponse(dynamic_cast(pResponseAttributes->getData())); // and clean up the responsettributes list. delete pResponseAttributes; } } else { // Missing parameter list. Report error back to client rResponse.setFault(EXPECTED_STRUCT_FAULT_CODE, EXPECTED_STRUCT_FAULT_STRING); } } else { // Bad parameter list. Report error back to client rResponse.setFault(EXPECTED_STRUCT_FAULT_CODE, EXPECTED_STRUCT_FAULT_STRING); } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgentXmlRpcGet::execute // // SYNOPSIS: // // DESCRIPTION: This is the actual method called by the underlying XmlRpc Dispatcher in // response to receiving a . It will call the corresponding // ProvisioningAgent Get method whos instance is supplied in the // provisioningAgentInstance argument. // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningAgentXmlRpcGet::execute(const HttpRequestContext& rContext, UtlSList& rParameters, void* pProvisioningAgentInstance, XmlRpcResponse& rResponse, XmlRpcMethod::ExecutionStatus& rStatus) { rStatus = XmlRpcMethod::OK; // Extract the request argument structure from the head of the SList. UtlContainable *pRequestArgs = rParameters.at(0); // Verify that a parameter list was given if (pRequestArgs != NULL) { // Verify that the parameter list is a structure ("UtlHashMap"). if (UtlString(pRequestArgs->getContainableType()) == "UtlHashMap") { // Now call the Provisioning Agent. ProvisioningAttrList requestAttributes(dynamic_cast(pRequestArgs)); ProvisioningAttrList* pResponseAttributes; pResponseAttributes = ((ProvisioningAgent*)pProvisioningAgentInstance)->Get(requestAttributes); if (pResponseAttributes == NULL) { // Method failure. Report error back to client rResponse.setFault(METHOD_DISPATCH_FAULT_CODE, METHOD_DISPATCH_FAULT_STRING); } else { // Encode the response rResponse.setResponse(dynamic_cast(pResponseAttributes->getData())); // and clean up the responsettributes list. delete pResponseAttributes; } } else { // Missing parameter list. Report error back to client rResponse.setFault(EXPECTED_STRUCT_FAULT_CODE, EXPECTED_STRUCT_FAULT_STRING); } } else { // Bad parameter list. Report error back to client rResponse.setFault(EXPECTED_STRUCT_FAULT_CODE, EXPECTED_STRUCT_FAULT_STRING); } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAgentXmlRpcAction::execute // // SYNOPSIS: // // DESCRIPTION: This is the actual method called by the underlying XmlRpc Dispatcher in // response to receiving a . It will call the corresponding // ProvisioningAgent Action method whos instance is supplied in the // provisioningAgentInstance argument. // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningAgentXmlRpcAction::execute(const HttpRequestContext& rContext, UtlSList& rParameters, void* pProvisioningAgentInstance, XmlRpcResponse& rResponse, XmlRpcMethod::ExecutionStatus& rStatus) { rStatus = XmlRpcMethod::OK; // Extract the request argument structure from the head of the SList. UtlContainable *pRequestArgs = rParameters.at(0); // Verify that a parameter list was given if (pRequestArgs != NULL) { // Verify that the parameter list is a structure ("UtlHashMap"). if (UtlString(pRequestArgs->getContainableType()) == "UtlHashMap") { // Now call the Provisioning Agent. ProvisioningAttrList requestAttributes(dynamic_cast(pRequestArgs)); ProvisioningAttrList* pResponseAttributes; pResponseAttributes = ((ProvisioningAgent*)pProvisioningAgentInstance)->Action(requestAttributes); if (pResponseAttributes == NULL) { // Method failure. Report error back to client rResponse.setFault(METHOD_DISPATCH_FAULT_CODE, METHOD_DISPATCH_FAULT_STRING); } else { // Encode the response rResponse.setResponse(dynamic_cast(pResponseAttributes->getData())); // and clean up the responsettributes list. delete pResponseAttributes; } } else { // Missing parameter list. Report error back to client rResponse.setFault(EXPECTED_STRUCT_FAULT_CODE, EXPECTED_STRUCT_FAULT_STRING); } } else { // Bad parameter list. Report error back to client rResponse.setFault(EXPECTED_STRUCT_FAULT_CODE, EXPECTED_STRUCT_FAULT_STRING); } return true; } sipxtapi-3.3.0~test17/sipXtackLib/src/net/ProvisioningAttrList.cpp0000644000175000017500000004454412205613256026066 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include "net/ProvisioningAttrList.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::ProvisioningAttrList // // SYNOPSIS: // // DESCRIPTION: Default constructor // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAttrList::ProvisioningAttrList(void) { mpData = new UtlHashMap; mIsReference = false; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::ProvisioningAttrList // // SYNOPSIS: // // DESCRIPTION: Reference constructor // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAttrList::ProvisioningAttrList(UtlHashMap* pData) { mpData = pData; mIsReference = true; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::~ProvisioningAttrList // // SYNOPSIS: // // DESCRIPTION: Destructor // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAttrList::~ProvisioningAttrList() { if (!mIsReference) { deleteAttrElements(dynamic_cast(mpData)); delete mpData; } } /* ============================ MANIPULATORS ============================== */ //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::setAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningAttrList::setAttribute(const char* pKey, UtlSList* pValue) { UtlContainable* results; results = mpData->insertKeyAndValue(new UtlString(pKey), pValue); if (results == NULL) { return false; } else { return true; } } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::setAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningAttrList::setAttribute(const char* pKey, const UtlString& rValue) { UtlContainable* results; results = mpData->insertKeyAndValue(new UtlString(pKey), new UtlString(rValue)); if (results == NULL) { return false; } else { return true; } } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::setAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningAttrList::setAttribute(const char* pKey, const char* pValue) { UtlContainable* results; results = mpData->insertKeyAndValue(new UtlString(pKey), new UtlString(pValue)); if (results == NULL) { return false; } else { return true; } } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::setAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningAttrList::setAttribute(const char* pKey, int value) { UtlContainable* results; results = mpData->insertKeyAndValue(new UtlString(pKey), new UtlInt(value)); if (results == NULL) { return false; } else { return true; } } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::setAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningAttrList::setAttribute(const char* pKey, bool value) { UtlContainable* results; results = mpData->insertKeyAndValue(new UtlString(pKey), new UtlBool(value)); if (results == NULL) { return false; } else { return true; } } /* ============================ ACCESSORS ================================= */ //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::getAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// UtlContainable* ProvisioningAttrList::getAttribute(const char* pKey) { UtlString utlKey(pKey); return dynamic_cast(mpData)->findValue(&utlKey); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::getAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningAttrList::getAttribute(const char* pKey, UtlString& rValue) { UtlString utlKey(pKey); UtlContainable* results; results = dynamic_cast(mpData)->findValue(&utlKey); if (results == NULL) { return false; } if (UtlString(results->getContainableType()) != "UtlString") { return false; } rValue = dynamic_cast(results)->data(); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::getAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningAttrList::getAttribute(const char* pKey, const char*& prValue) { UtlString utlKey(pKey); UtlContainable* results; results = dynamic_cast(mpData)->findValue(&utlKey); if (results == NULL) { return false; } if (UtlString(results->getContainableType()) != "UtlString") { return false; } prValue = dynamic_cast(results)->data(); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::getAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningAttrList::getAttribute(const char* pKey, int& rValue) { UtlString utlKey(pKey); UtlContainable* results; results = dynamic_cast(mpData)->findValue(&utlKey); if (results == NULL) { return false; } if (UtlString(results->getContainableType()) != "UtlInt") { return false; } rValue = dynamic_cast(results)->getValue(); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::getAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningAttrList::getAttribute(const char* pKey, bool& rValue) { UtlString utlKey(pKey); UtlContainable* results; results = dynamic_cast(mpData)->findValue(&utlKey); if (results == NULL) { return false; } if (UtlString(results->getContainableType()) != "UtlBool") { return false; } rValue = dynamic_cast(results)->getValue(); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::dumpAttributes // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// void ProvisioningAttrList::dumpAttributes(void) { dumpAttributes(dynamic_cast(mpData)); } /* ============================ INQUIRY =================================== */ //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::attributeMissing // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningAttrList::attributeMissing(const char* pKey) { UtlString utlKey(pKey); return !dynamic_cast(mpData)->contains(&utlKey); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::attributePresent // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningAttrList::attributePresent(const char* pKey) { UtlString utlKey(pKey); return dynamic_cast(mpData)->contains(&utlKey); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::validateAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// void ProvisioningAttrList::validateAttribute(const char* pKey, eAttributeType type, bool ignoreMissing) { UtlContainable* attribute; UtlString utlKey(pKey); attribute = dynamic_cast(mpData)->findValue(&utlKey); if (attribute == NULL) { if (ignoreMissing) { // If it is missing, just return return; } else { UtlString errorText("Missing attribute: '"); errorText += pKey; errorText += "'"; throw errorText; } } switch (type) { case ProvisioningAttrList::INT: if (UtlString(attribute->getContainableType()) != "UtlInt") { UtlString errorText("Attribute '"); errorText += pKey; errorText += "' must be of type: INT"; throw errorText; } break; case ProvisioningAttrList::BOOL: if (UtlString(attribute->getContainableType()) != "UtlBool") { UtlString errorText("Attribute: '"); errorText += pKey; errorText += "' must be of type: BOOL"; throw errorText; } break; case ProvisioningAttrList::STRING: if (UtlString(attribute->getContainableType()) != "UtlString") { UtlString errorText("Attribute: '"); errorText += pKey; errorText += "' must be of type: STRING"; throw errorText; } break; } } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::validateAttributeType // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// void ProvisioningAttrList::validateAttributeType(const char* pKey, eAttributeType type) { this->validateAttribute(pKey, type, true); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::deleteAttrElements // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// void ProvisioningAttrList::deleteAttrElements(UtlContainable* pAttrElements) { UtlString* pMemberName; UtlContainable* pMemberValue; if (UtlString(pAttrElements->getContainableType()) == "UtlHashMap") { UtlHashMapIterator structureIterator(*dynamic_cast(pAttrElements)); while ((pMemberName = dynamic_cast(structureIterator())) != NULL) { pMemberValue = dynamic_cast(pAttrElements)->findValue(pMemberName); if (UtlString(pMemberValue->getContainableType()) == "UtlHashMap" || UtlString(pMemberValue->getContainableType()) == "UtlSList") { deleteAttrElements(pMemberValue); } delete pMemberName; delete pMemberValue; } } else if (UtlString(pAttrElements->getContainableType()) == "UtlSList") { UtlSListIterator arrayIterator(*dynamic_cast(pAttrElements)); while ((pMemberValue = arrayIterator()) != NULL) { if (UtlString(pMemberValue->getContainableType()) == "UtlHashMap" || UtlString(pMemberValue->getContainableType()) == "UtlSList") { deleteAttrElements(pMemberValue); } delete pMemberValue; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningAttrList::dumpAttributes // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// void ProvisioningAttrList::dumpAttributes(const UtlContainable* pAttribute) { static UtlString* pMemberName; UtlContainable* pMemberValue; if (UtlString(pAttribute->getContainableType()) == "UtlHashMap") { UtlHashMapIterator structureIterator(*dynamic_cast(pAttribute)); while ((pMemberName = dynamic_cast(structureIterator())) != NULL) { pMemberValue = dynamic_cast(pAttribute)->findValue(pMemberName); if (UtlString(pMemberValue->getContainableType()) == "UtlHashMap" || UtlString(pMemberValue->getContainableType()) == "UtlSList") { dumpAttributes(pMemberValue); } if (UtlString(pMemberValue->getContainableType()) == "UtlBool") { osPrintf("{%s} = (BOOL) %s\n", pMemberName->data(), (dynamic_cast(pMemberValue)->getValue() ? "TRUE" : "FALSE")); } else if (UtlString(pMemberValue->getContainableType()) == "UtlInt") { osPrintf("{%s} = (INT) %d\n", pMemberName->data(), dynamic_cast(pMemberValue)->getValue()); } else if (UtlString(pMemberValue->getContainableType()) == "UtlString") { osPrintf("{%s} = (STRING) \"%s\"\n", pMemberName->data(), dynamic_cast(pMemberValue)->data()); } } } else if (UtlString(pAttribute->getContainableType()) == "UtlSList") { UtlSListIterator arrayIterator(*dynamic_cast(pAttribute)); int arrayIndex = 0; while ((pMemberValue = arrayIterator()) != NULL) { if (UtlString(pMemberValue->getContainableType()) == "UtlHashMap" || UtlString(pMemberValue->getContainableType()) == "UtlSList") { dumpAttributes(pMemberValue); } if (UtlString(pMemberValue->getContainableType()) == "UtlBool") { osPrintf("{%s}[%d] = (BOOL) %s\n", pMemberName->data(), arrayIndex++, (dynamic_cast(pMemberValue)->getValue() ? "TRUE" : "FALSE")); } else if (UtlString(pMemberValue->getContainableType()) == "UtlInt") { osPrintf("{%s}[%d] = (INT) %d\n", pMemberName->data(), arrayIndex++, dynamic_cast(pMemberValue)->getValue()); } else if (UtlString(pMemberValue->getContainableType()) == "UtlString") { osPrintf("{%s}[%d] = (STRING) \"%s\"\n", pMemberName->data(), arrayIndex++, dynamic_cast(pMemberValue)->data()); } } } } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/ProvisioningClass.cpp0000644000175000017500000004527012205613256025362 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include "net/ProvisioningAttrList.h" #include "net/ProvisioningClass.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS const UtlContainableType ProvisioningClass::TYPE = "ProvisioningClass"; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::ProvisioningClass // // SYNOPSIS: // // DESCRIPTION: Default constructor // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningClass::ProvisioningClass(const char* pClassName) : mClassName(pClassName) { mConfigurationLoaded = false; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::~ProvisioningClass // // SYNOPSIS: // // DESCRIPTION: Destructor // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningClass::~ProvisioningClass() { } /* ============================ MANIPULATORS ============================== */ //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::setXmlConfigDoc // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// void ProvisioningClass::setXmlConfigDoc(TiXmlDocument* pConfigDoc) { mpXmlConfigDoc = pConfigDoc; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::loadConfiguration // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningClass::loadConfiguration(void) { return false; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::Create // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAttrList* ProvisioningClass::Create(ProvisioningAttrList& rRequestAttributes) { return NULL; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::Delete // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAttrList* ProvisioningClass::Delete(ProvisioningAttrList& rRequestAttributes) { return NULL; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::Set // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAttrList* ProvisioningClass::Set(ProvisioningAttrList& rRequestAttributes) { return NULL; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::Get // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAttrList* ProvisioningClass::Get(ProvisioningAttrList& rRequestAttributes) { return NULL; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::Action // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// ProvisioningAttrList* ProvisioningClass::Action(ProvisioningAttrList& rRequestAttributes) { return NULL; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::deletePSInstance // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningClass::deletePSInstance(const char* pClassName, const char* pIndexAttr, const char* pIndexValue) { bool results = false; UtlString fullClassName(pClassName); TiXmlHandle docHandle(mpXmlConfigDoc); TiXmlNode* pClassNode; TiXmlNode* pInstanceNode; TiXmlNode* pIndexNode; TiXmlNode* pIndexValueNode; // Append the "-class" to the end of the class name given. fullClassName += "-class"; pClassNode = docHandle.FirstChild("sipxacd").FirstChild(fullClassName.data()).Node(); if (pClassNode == NULL) { // The class does not exist. return false; } for (pInstanceNode = pClassNode->FirstChild(); pInstanceNode; pInstanceNode = pInstanceNode->NextSibling()) { pIndexNode = pInstanceNode->FirstChild(pIndexAttr); if (pIndexNode == NULL) { // Index attribute not found. Keep looking. continue; } pIndexValueNode = pIndexNode->FirstChild(); if (pIndexValueNode == NULL) { // Index attribute value not found. Keep looking. continue; } if (strcmp(pIndexValueNode->Value(), pIndexValue) == 0) { // Index attribute value match. Delete it. pClassNode->RemoveChild(pInstanceNode); results = true; break; } } return results; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::createPSInstance // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// TiXmlNode* ProvisioningClass::createPSInstance(const char* pClassName, const char* pIndexAttr, const char* pIndexValue) { UtlString fullClassName(pClassName); TiXmlHandle docHandle(mpXmlConfigDoc); TiXmlNode* pRootNode; TiXmlNode* pClassNode; TiXmlNode* pInstanceNode; TiXmlNode* pIndexNode; TiXmlNode* pIndexValueNode; // Append the "-class" to the end of the class name given. fullClassName += "-class"; // First make sure that the instance does not already exist. pInstanceNode = findPSInstance(pClassName, pIndexAttr, pIndexValue); if (pInstanceNode != NULL) { // Already exists return pInstanceNode; } // Find the class pClassNode = docHandle.FirstChild("sipxacd").FirstChild(fullClassName.data()).Node(); if (pClassNode == NULL) { // The class does not exist, create it. pRootNode = mpXmlConfigDoc->FirstChild("sipxacd"); TiXmlElement classElement(fullClassName.data()); pClassNode = pRootNode->InsertEndChild(classElement); if (pClassNode == NULL) { // Insertion failed. return NULL; } } // Create the instance. TiXmlElement instanceElement(pClassName); pInstanceNode = pClassNode->InsertEndChild(instanceElement); if (pInstanceNode == NULL) { // Insertion failed. return NULL; } // Create the index. TiXmlElement indexElement(pIndexAttr); pIndexNode = pInstanceNode->InsertEndChild(indexElement); if (pIndexNode == NULL) { // Insertion failed. return NULL; } // Create the index value. TiXmlText indexValueText(pIndexValue); pIndexValueNode = pIndexNode->InsertEndChild(indexValueText); if (pIndexValueNode == NULL) { // Insertion failed. return NULL; } return pInstanceNode; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::setPSAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningClass::setPSAttribute(TiXmlNode* pClassInstance, const char* pAttribute, UtlString& rValue) { return setPSAttribute(pClassInstance, pAttribute, rValue.data()); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::setPSAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningClass::setPSAttribute(TiXmlNode* pClassInstance, const char* pAttribute, const char* pValue) { TiXmlNode* pAttributeNode; TiXmlNode* pAttributeValueNode; // Find the attribute pAttributeNode = pClassInstance->FirstChild(pAttribute); if (pAttributeNode == NULL) { // The attribute does not exist, create it. TiXmlElement attributeElement(pAttribute); pAttributeNode = pClassInstance->InsertEndChild(attributeElement); if (pAttributeNode == NULL) { // Insertion failed. return false; } } // See if the attribute value exists pAttributeValueNode = pAttributeNode->FirstChild(); if (pAttributeValueNode == NULL) { // The attribute value does not exist, create it. TiXmlText attributeValueText(pValue); pAttributeValueNode = pAttributeNode->InsertEndChild(attributeValueText); if (pAttributeValueNode == NULL) { // Insertion failed. return false; } } else { pAttributeValueNode->SetValue(pValue); } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::setPSAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningClass::setPSAttribute(TiXmlNode* pClassInstance, const char* pAttribute, int value) { char valueString[16]; snprintf(valueString, 16, "%d", value); return setPSAttribute(pClassInstance, pAttribute, valueString); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::setPSAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningClass::setPSAttribute(TiXmlNode* pClassInstance, const char* pAttribute, bool value) { if (value == true) { return setPSAttribute(pClassInstance, pAttribute, "TRUE"); } else { return setPSAttribute(pClassInstance, pAttribute, "FALSE"); } } /* ============================ ACCESSORS ================================= */ //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::getClassName // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// const UtlString* ProvisioningClass::getClassName(void) { return &mClassName; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::getPSAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningClass::getPSAttribute(TiXmlNode* pClassInstance, const char* pAttribute, UtlString& rValue) { TiXmlNode* pAttributeNode; TiXmlNode* pAttributeValueNode; // Find the attribute pAttributeNode = pClassInstance->FirstChild(pAttribute); if (pAttributeNode == NULL) { // The attribute does not exist. return false; } // See if the attribute value exists pAttributeValueNode = pAttributeNode->FirstChild(); if (pAttributeValueNode == NULL) { // The attribute value does not exist, interpret as NULL rValue = NULL; return true; } else { rValue = pAttributeValueNode->Value(); } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::getPSAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningClass::getPSAttribute(TiXmlNode* pClassInstance, const char* pAttribute, int& rValue) { UtlString stringValue; if (!getPSAttribute(pClassInstance, pAttribute, stringValue)) { // Failed to retrieve attribute value. return false; } rValue = atoi(stringValue.data()); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::getPSAttribute // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProvisioningClass::getPSAttribute(TiXmlNode* pClassInstance, const char* pAttribute, bool& rValue) { UtlString stringValue; if (!getPSAttribute(pClassInstance, pAttribute, stringValue)) { // Failed to retrieve attribute value. return false; } if (stringValue == "TRUE") { rValue = true; } else { rValue = false; } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::findPSInstance // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// TiXmlNode* ProvisioningClass::findPSInstance(const char* pClassName, const char* pIndexAttr, const char* pIndexValue) { UtlString fullClassName(pClassName); TiXmlHandle docHandle(mpXmlConfigDoc); TiXmlNode* pClassNode; TiXmlNode* pInstanceNode; TiXmlNode* pIndexNode; TiXmlNode* pIndexValueNode; // Append the "-class" to the end of the class name given. fullClassName += "-class"; pClassNode = docHandle.FirstChild("sipxacd").FirstChild(fullClassName.data()).Node(); if (pClassNode == NULL) { // The class does not exist. return NULL; } // See if this is a FIND FIRST operation. if (pIndexAttr == NULL) { return pClassNode->FirstChild(); } for (pInstanceNode = pClassNode->FirstChild(); pInstanceNode; pInstanceNode = pInstanceNode->NextSibling()) { pIndexNode = pInstanceNode->FirstChild(pIndexAttr); if (pIndexNode == NULL) { // Index attribute not found. Keep looking. continue; } pIndexValueNode = pIndexNode->FirstChild(); if (pIndexValueNode == NULL) { // Index attribute value not found. Keep looking. continue; } if (strcmp(pIndexValueNode->Value(), pIndexValue) == 0) { // Index attribute value match. break; } } return pInstanceNode; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::hash // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// unsigned ProvisioningClass::hash() const { return mClassName.hash(); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::getContainableType // // SYNOPSIS: // // DESCRIPTION: // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// UtlContainableType ProvisioningClass::getContainableType() const { return ProvisioningClass::TYPE; } /* ============================ INQUIRY =================================== */ //////////////////////////////////////////////////////////////////////////////////////////////////// // // NAME: ProvisioningClass::compareTo // // SYNOPSIS: // // DESCRIPTION: Compare the this object to another like-object. // // RETURNS: None. // // ERRORS: None. // // CAVEATS: None. // //////////////////////////////////////////////////////////////////////////////////////////////////// int ProvisioningClass::compareTo(UtlContainable const* pInVal) const { int result ; if (pInVal->isInstanceOf(ProvisioningClass::TYPE)) { result = mClassName.compareTo(((ProvisioningClass*)pInVal)->getClassName()); } else { result = -1; } return result; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SdpBody.cpp0000644000175000017500000037271412205617431023257 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define MAXIMUM_LONG_INT_CHARS 20 #define MAXIMUM_MEDIA_TYPES 30 #define MAXIMUM_VIDEO_SIZES 6 //#define TEST_PRINT // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define SDP_NAME_VALUE_DELIMITOR '=' #define SDP_SUBFIELD_SEPARATOR ' ' #define SDP_SUBFIELD_SEPARATORS "\t " #define SDP_RTP_MEDIA_TRANSPORT_TYPE "RTP/AVP" #define SDP_RTP_TCP_MEDIA_TRANSPORT_TYPE "TCP/RTP/AVP" #define SDP_SRTP_MEDIA_TRANSPORT_TYPE "RTP/SAVP" #define SDP_MLAW_PAYLOAD 0 #define SDP_ALAW_PAYLOAD 8 #define SDP_NETWORK_TYPE "IN" #define SDP_IP4_ADDRESS_TYPE "IP4" #define NTP_TO_EPOCH_DELTA 2208988800UL #define PRIORITY_OFFSET (10000000100ULL) // STATIC VARIABLE INITIALIZATIONS static int sSessionCount = 5 ; // Session version for SDP body static OsMutex sSessionLock(OsMutex::Q_FIFO) ; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SdpBody::SdpBody(const char* bodyBytes, int byteCount) : HttpBody(bodyBytes, byteCount) { mClassType = SDP_BODY_CLASS; remove(0); append(SDP_CONTENT_TYPE); sdpFields = new UtlSList(); if(bodyBytes) { if(byteCount < 0) { bodyLength = strlen(bodyBytes); } parseBody(bodyBytes, byteCount); } else { // this is the mandated order of the header fields addValue("v", "0" ); addValue("o", "sipX 5 5 IN IP4 127.0.0.1"); addValue("s"); addValue("i"); addValue("u"); addValue("e"); addValue("p"); addValue("c"); addValue("b"); } } // Copy constructor SdpBody::SdpBody(const SdpBody& rSdpBody) : HttpBody(rSdpBody) { mClassType = SDP_BODY_CLASS; if(rSdpBody.sdpFields) { sdpFields = new UtlSList(); NameValuePair* headerField; NameValuePair* copiedHeader = NULL; UtlSListIterator iterator((UtlSList&)(*(rSdpBody.sdpFields))); while((headerField = (NameValuePair*) iterator())) { copiedHeader = new NameValuePair(*headerField); sdpFields->append(copiedHeader); } } else { sdpFields = NULL; } } // Destructor SdpBody::~SdpBody() { if(sdpFields) { while(! sdpFields->isEmpty()) { delete sdpFields->get(); } delete sdpFields; } } /* ============================ MANIPULATORS ============================== */ void SdpBody::parseBody(const char* bodyBytes, int byteCount) { if(byteCount < 0) { bodyLength = strlen(bodyBytes); } if(bodyBytes) { UtlString name; UtlString value; int nameFound; NameValuePair* nameValue; UtlNameValueTokenizer parser(bodyBytes, byteCount); do { name.remove(0); value.remove(0); nameFound = parser.getNextPair(SDP_NAME_VALUE_DELIMITOR, &name, &value); if(nameFound) { nameValue = new NameValuePair(name.data(), value.data()); sdpFields->append(nameValue); } } while(nameFound); } } // Assignment operator SdpBody& SdpBody::operator=(const SdpBody& rhs) { if (this == &rhs) // handle the assignment to self case return *this; // Copy the base class stuff this->HttpBody::operator=((const HttpBody&)rhs); if(sdpFields) { sdpFields->destroyAll(); } if(rhs.sdpFields) { if(sdpFields == NULL) { sdpFields = new UtlSList(); } NameValuePair* headerField; NameValuePair* copiedHeader = NULL; UtlSListIterator iterator((UtlSList&)(*(rhs.sdpFields))); while((headerField = (NameValuePair*) iterator())) { copiedHeader = new NameValuePair(*headerField); sdpFields->append(copiedHeader); } } // Set the class type just to play it safe mClassType = SDP_BODY_CLASS; return *this; } /* ============================ ACCESSORS ================================= */ void SdpBody::setStandardHeaderFields(const char* sessionName, const char* emailAddress, const char* phoneNumber, const char* originatorAddress) { OsLock lock (sSessionLock) ; setOriginator("sipX", 5, sSessionCount++, (originatorAddress && *originatorAddress) ? originatorAddress : "127.0.0.1"); setSessionNameField(sessionName); if(emailAddress && strlen(emailAddress) > 0) { setEmailAddressField(emailAddress); } if(phoneNumber && strlen(phoneNumber) > 0) { setPhoneNumberField(phoneNumber); } } void SdpBody::setSessionNameField(const char* sessionName) { setValue("s", sessionName); } void SdpBody::setEmailAddressField(const char* emailAddress) { setValue("e", emailAddress); } void SdpBody::setPhoneNumberField(const char* phoneNumber) { setValue("p", phoneNumber); } void SdpBody::setValue(const char* name, const char* value) { NameValuePair nvToMatch(name); NameValuePair* nvFound = NULL; UtlSListIterator iterator(*sdpFields); nvFound = (NameValuePair*) iterator.findNext(&nvToMatch); if(nvFound) { // field exists - replace the value nvFound->setValue(value); } else { addValue(name, value); } } int SdpBody::getMediaSetCount() const { UtlSListIterator iterator(*sdpFields); NameValuePair mediaName("m"); int count = 0; while(iterator.findNext(&mediaName)) { count++; } return(count); } UtlBoolean SdpBody::getMediaType(int mediaIndex, UtlString* mediaType) const { return(getMediaSubfield(mediaIndex, 0, mediaType)); } UtlBoolean SdpBody::getMediaPort(int mediaIndex, int* port) const { UtlString portString; UtlBoolean portFound = getMediaSubfield(mediaIndex, 1, &portString); int portCountSeparator; if(!portString.isNull()) { // Remove the port pair count if it exists portCountSeparator = portString.index("/"); if(portCountSeparator >= 0) { portString.remove(portCountSeparator); } *port = atoi(portString.data()); portFound = TRUE; } return(portFound); } UtlBoolean SdpBody::getMediaRtcpPort(int mediaIndex, int* port) const { UtlBoolean bFound = FALSE ; int iRtpPort ; if (getMediaPort(mediaIndex, &iRtpPort)) { bFound = TRUE ; *port = iRtpPort + 1; UtlSListIterator iterator(*sdpFields); NameValuePair* nv = positionFieldInstance(mediaIndex, &iterator, "m"); if(nv) { while ((nv = findFieldNameBefore(&iterator, "a", "m"))) { //printf("->%s:%s\n", nv->data(), nv->getValue()) ; UtlString typeAttribute ; UtlString portAttribute ; UtlNameValueTokenizer::getSubField(nv->getValue(), 0, ":", &typeAttribute) ; UtlNameValueTokenizer::getSubField(nv->getValue(), 1, ":", &portAttribute) ; if (typeAttribute.compareTo("rtcp", UtlString::ignoreCase) == 0) { *port = atoi(portAttribute.data()) ; } } } } return bFound ; } UtlBoolean SdpBody::getControlTrackId(int mediaIndex, UtlString& trackId) const { UtlBoolean trackIdFound = FALSE; UtlSListIterator iterator(*sdpFields); if(positionFieldInstance(mediaIndex, &iterator, "m")) { NameValuePair* sdpAttribute = NULL; while ((sdpAttribute = findFieldNameBefore(&iterator, "a", "m"))) { UtlString value = sdpAttribute->getValue(); UtlString valueLowered(value); valueLowered.toLower(); UtlString token("control:trackid"); int tokenIndex = valueLowered.index(token); if(tokenIndex >=0) { value.remove(0, tokenIndex + token.length()); tokenIndex = value.index('='); if(tokenIndex >= 0) { value.remove(0, tokenIndex + 1); UtlNameValueTokenizer::getSubField(value, 0, " \t:=/", // separators &trackId); if(!trackId.isNull()) { trackIdFound = TRUE; } } } } } return(trackIdFound); } UtlBoolean SdpBody::getMediaStreamDirection(int mediaIndex, SessionDirection& direction) const { UtlBoolean found = FALSE; direction = Unknown; UtlString mediaType; if(getMediaType(mediaIndex, &mediaType)) { UtlSListIterator iterator(*sdpFields); NameValuePair* sdpAttribute = positionFieldInstance(mediaIndex, &iterator, "m"); if(sdpAttribute) { while ((sdpAttribute = findFieldNameBefore(&iterator, "a", "m"))) { UtlString directionToken = sdpAttribute->getValue(); if (directionToken.compareTo("inactive", UtlString::ignoreCase) == 0) { direction = Inactive; found = TRUE; } else if (directionToken.compareTo("sendonly", UtlString::ignoreCase) == 0) { direction = SendOnly; found = TRUE; } else if (directionToken.compareTo("recvonly", UtlString::ignoreCase) == 0) { direction = RecvOnly; found = TRUE; } else if (directionToken.compareTo("sendrecv", UtlString::ignoreCase) == 0) { direction = SendRecv; found = TRUE; } } } } return(found); } UtlBoolean SdpBody::getMediaProtocol(int mediaIndex, UtlString* transportProtocol) const { return(getMediaSubfield(mediaIndex, 2, transportProtocol)); } UtlBoolean SdpBody::getMediaPayloadType(int mediaIndex, int maxTypes, int* numTypes, int payloadTypes[]) const { UtlString payloadTypeString; int typeCount = 0; int index = 0 ; while (index < maxTypes && getMediaSubfield(mediaIndex, 3 + index++, &payloadTypeString)) { if(!payloadTypeString.isNull()) { // Add the payload type and increment typeCount if not // already in the list bool bFound = false ; int payload = atoi(payloadTypeString.data()) ; for (int i=0; i 0); } UtlBoolean SdpBody::getMediaSubfield(int mediaIndex, int subfieldIndex, UtlString* subField) const { UtlBoolean subfieldFound = FALSE; UtlSListIterator iterator(*sdpFields); NameValuePair* nv = positionFieldInstance(mediaIndex, &iterator, "m"); const char* value; subField->remove(0); if(nv) { value = nv->getValue(); UtlNameValueTokenizer::getSubField(value, subfieldIndex, SDP_SUBFIELD_SEPARATORS, subField); if(!subField->isNull()) { subfieldFound = TRUE; } } return(subfieldFound); } UtlBoolean SdpBody::getPayloadRtpMap(int mediaIndex, int payloadType, UtlString& mimeSubtype, int& sampleRate, int& numChannels) const { // an "a" record look something like: // "a=rtpmap: [/numChannels]" // Loop through all of the "a" records UtlBoolean foundRtpMap = FALSE; UtlSListIterator iterator(*sdpFields); NameValuePair* nv = NULL; int aFieldIndex = 0; const char* value; UtlString aFieldType; UtlString payloadString; UtlString sampleRateString; UtlString numChannelString; UtlString aFieldMatch("a"); // Position to the correct media line NameValuePair* mediaLineFound = positionFieldInstance(mediaIndex, &iterator, "m"); // Look at the a lines while(mediaLineFound && (nv = findFieldNameBefore(&iterator, "a", "m")) != NULL) //while((nv = (NameValuePair*) iterator.findNext(&aFieldMatch)) != NULL) { value = nv->getValue(); // Verify this is an rtpmap "a" record UtlNameValueTokenizer::getSubField(value, 0, " \t:/", // separators &aFieldType); if(aFieldType.compareTo("rtpmap", UtlString::ignoreCase) == 0) { // If this is the rtpmap for the requested payload type UtlNameValueTokenizer::getSubField(value, 1, " \t:/", // separators &payloadString); if(atoi(payloadString.data()) == payloadType) { // The mime subtype is the 3nd subfield UtlNameValueTokenizer::getSubField(value, 2, " \t:/", // separators &mimeSubtype); // The sample rate is the 4rd subfield UtlNameValueTokenizer::getSubField(value, 3, " \t:/", // separators &sampleRateString); sampleRate = atoi(sampleRateString.data()); if(sampleRate <= 0) sampleRate = -1; // The number of channels is the 5th subfield UtlNameValueTokenizer::getSubField(value, 4, " \t:/", // separators &numChannelString); numChannels = atoi(numChannelString.data()); if(numChannels <= 0) numChannels = -1; // we are all done foundRtpMap = TRUE; break; } } aFieldIndex++; } return(foundRtpMap); } UtlBoolean SdpBody::getPayloadFormat(int mediaIndex, int payloadType, UtlString& fmtp) const { // See SdpCodec for utilities to parse the fmtp field (e.g. getFmtpParameter and getVideoSizes) // an "a" record look something like: // "a=fmtp: " // Loop through all of the "a" records UtlBoolean foundPayloadFmtp = FALSE; UtlBoolean foundField; UtlSListIterator iterator(*sdpFields); UtlString aFieldType; UtlString payloadString; UtlString modifierString; NameValuePair* nv = NULL; int aFieldIndex = 0; const char* value; UtlString temp; UtlString aFieldMatch("a"); fmtp.remove(0); // Position to the correct media line NameValuePair* mediaLineFound = positionFieldInstance(mediaIndex, &iterator, "m"); // Look at the a lines while(mediaLineFound && (nv = findFieldNameBefore(&iterator, "a", "m")) != NULL) //while((nv = (NameValuePair*) iterator.findNext(&aFieldMatch)) != NULL) { value = nv->getValue(); // Verify this is an fmtp "a" record UtlNameValueTokenizer::getSubField(value, 0, " \t:/", // separators &aFieldType); if(aFieldType.compareTo("fmtp", UtlString::ignoreCase) == 0) { UtlNameValueTokenizer::getSubField(value, 1, " \t:/", // separators &payloadString); if(atoi(payloadString.data()) == payloadType) { const char *fmtpSubField; int subFieldLen; // If this is the fmtp for the requested payload type foundField = UtlNameValueTokenizer::getSubField(value, -1, 2, " \t:", // separators fmtpSubField, subFieldLen, 0); if(foundField) { fmtp = fmtpSubField; } foundPayloadFmtp = TRUE; } } aFieldIndex++; } return(foundPayloadFmtp); } UtlBoolean SdpBody::getSrtpCryptoField(int mediaIndex, int index, SdpSrtpParameters& params) const { UtlBoolean foundCrypto = FALSE; UtlBoolean foundField; UtlString aFieldType; UtlSListIterator iterator(*sdpFields); NameValuePair* nv = positionFieldInstance(mediaIndex, &iterator, "m"); const char* value; UtlString indexString; UtlString cryptoSuite; UtlString temp; int size; char srtpKey[SRTP_KEY_LENGTH+1]; size = sdpFields->entries(); while ((nv = findFieldNameBefore(&iterator, "a", "m"))) { value = nv->getValue(); // Verify this is an crypto "a" record UtlNameValueTokenizer::getSubField(value, 0, " \t:/", // separators &aFieldType); if(aFieldType.compareTo("crypto", UtlString::ignoreCase) == 0) { UtlNameValueTokenizer::getSubField(value, 1, " \t:/", // separators &indexString); if(atoi(indexString.data()) == index) { foundCrypto = TRUE; // Encryption & authentication on by default params.securityLevel = SRTP_ENCRYPTION | SRTP_AUTHENTICATION; UtlNameValueTokenizer::getSubField(value, 2, " \t:/", // separators &cryptoSuite); // Check the crypto suite if (cryptoSuite.compareTo("AES_CM_128_HMAC_SHA1_80", UtlString::ignoreCase) == 0) { params.cipherType = AES_CM_128_HMAC_SHA1_80; } else if (cryptoSuite.compareTo("AES_CM_128_HMAC_SHA1_32", UtlString::ignoreCase) == 0) { params.cipherType = AES_CM_128_HMAC_SHA1_32; } else if (cryptoSuite.compareTo("F8_128_HMAC_SHA1_80", UtlString::ignoreCase) == 0) { params.cipherType = F8_128_HMAC_SHA1_80; } else { //Couldn't find crypto suite, no secritiy params.securityLevel = 0; } // Get key foundField = UtlNameValueTokenizer::getSubField(value, 4, " \t/:|", // separators &temp); NetBase64Codec::decode(temp.length(), temp.data(), size, srtpKey); if (size <= SRTP_KEY_LENGTH) { srtpKey[size] = 0; } else { srtpKey[SRTP_KEY_LENGTH] = 0; } strcpy((char*)params.masterKey, srtpKey); // Modify security level with session parameters for (int index=5; foundField; ++index) { foundField = UtlNameValueTokenizer::getSubField(value, index, " \t/:|", // separators &temp); if (foundField) { if (temp.compareTo("UNENCRYPTED_SRTP", UtlString::ignoreCase) == 0) { params.securityLevel &= ~SRTP_ENCRYPTION; } if (temp.compareTo("UNAUTHENTICATED_SRTP", UtlString::ignoreCase) == 0) { params.securityLevel &= ~SRTP_AUTHENTICATION; } } } break; } } } return foundCrypto; } UtlBoolean SdpBody::getFramerateField(int mediaIndex, int& videoFramerate) const { UtlBoolean foundFramerate = FALSE; UtlString aFieldType; UtlSListIterator iterator(*sdpFields); NameValuePair* nv = positionFieldInstance(mediaIndex, &iterator, "m"); const char* value; UtlString aFieldMatch("a"); UtlString rateString; int size; UtlString temp; videoFramerate = 0; size = sdpFields->entries(); while((nv = (NameValuePair*) iterator.findNext(&aFieldMatch)) != NULL) { value = nv->getValue(); // Verify this is an crypto "a" record UtlNameValueTokenizer::getSubField(value, 0, " \t:/", // separators &aFieldType); if(aFieldType.compareTo("framerate", UtlString::ignoreCase) == 0) { UtlNameValueTokenizer::getSubField(value, 1, " \t:/", // separators &rateString); videoFramerate = atoi(rateString.data()); foundFramerate = TRUE; } } return foundFramerate; } UtlBoolean SdpBody::getBandwidthField(int& bandwidth) const { UtlBoolean bFound = FALSE; // Loop through all of the "b" records UtlSListIterator iterator(*sdpFields); NameValuePair* nv = NULL; const char* value; UtlString aFieldMatch("b"); UtlString aFieldModifier; UtlString temp; // Indicate no "b" field was sent with 0 bandwidth = 0; while((nv = (NameValuePair*) iterator.findNext(&aFieldMatch)) != NULL) { value = nv->getValue(); // Verify this is an crypto "a" record UtlNameValueTokenizer::getSubField(value, 0, " \t:/", // separators &aFieldModifier); if(aFieldModifier.compareTo("CT", UtlString::ignoreCase) == 0) { UtlNameValueTokenizer::getSubField(value, 1, " \t:/", // separators &temp); bandwidth = atoi(temp.data()); bFound = TRUE; } } return bFound; } UtlBoolean SdpBody::getValue(int fieldIndex, UtlString* name, UtlString* value) const { NameValuePair* nv = NULL; name->remove(0); value->remove(0); if(fieldIndex >=0) { nv = (NameValuePair*) sdpFields->at(fieldIndex); if(nv) { *name = *nv; *value = nv->getValue(); } } return(nv != NULL); } UtlBoolean SdpBody::getMediaData(int mediaIndex, UtlString* mediaType, int* mediaPort, int* mediaPortPairs, UtlString* mediaTransportType, int maxPayloadTypes, int* numPayloadTypes, int payloadTypes[]) const { UtlBoolean fieldFound = FALSE; UtlSListIterator iterator(*sdpFields); NameValuePair* nv = positionFieldInstance(mediaIndex, &iterator, "m"); const char* value; UtlString portString; UtlString portPairString; int portCountSeparator; int typeCount = 0; UtlString payloadTypeString; if(nv) { fieldFound = TRUE; value = nv->getValue(); // media Type UtlNameValueTokenizer::getSubField(value, 0, SDP_SUBFIELD_SEPARATORS, mediaType); // media port and media port pair count UtlNameValueTokenizer::getSubField(value, 1, SDP_SUBFIELD_SEPARATORS, &portString); if(!portString.isNull()) { // Copy for obtaining the pair count portPairString.append(portString); // Remove the port pair count if it exists portCountSeparator = portString.index("/"); if(portCountSeparator >= 0) { portString.remove(portCountSeparator); // Get the other part of the field portPairString.remove(0, portCountSeparator + 1); } else { portPairString.remove(0); } *mediaPort = atoi(portString.data()); if(portPairString.isNull()) { *mediaPortPairs = 1; } else { *mediaPortPairs = atoi(portPairString.data()); } } else { *mediaPort = 0; *mediaPortPairs = 0; } // media transport type UtlNameValueTokenizer::getSubField(value, 2, SDP_SUBFIELD_SEPARATORS, mediaTransportType); // media payload/codec types UtlNameValueTokenizer::getSubField(value, 3 + typeCount, SDP_SUBFIELD_SEPARATORS, &payloadTypeString); while(typeCount < maxPayloadTypes && !payloadTypeString.isNull()) { payloadTypes[typeCount] = atoi(payloadTypeString.data()); typeCount++; UtlNameValueTokenizer::getSubField(value, 3 + typeCount, SDP_SUBFIELD_SEPARATORS, &payloadTypeString); } *numPayloadTypes = typeCount; } return(fieldFound); } int SdpBody::findMediaType(const char* mediaType, int startMediaIndex) const { NameValuePair* mediaField; UtlSListIterator iterator(*sdpFields); UtlBoolean mediaTypeFound = FALSE; int index = startMediaIndex; NameValuePair mediaName("m"); mediaField = positionFieldInstance(startMediaIndex, &iterator, "m"); const char* value; while(mediaField && ! mediaTypeFound) { value = mediaField->getValue(); if(strstr(value, mediaType) == value) { mediaTypeFound = TRUE; break; } mediaField = (NameValuePair*) iterator.findNext(&mediaName); index++; } if(! mediaTypeFound) { index = -1; } return(index); } UtlBoolean SdpBody::getMediaAddress(int mediaIndex, UtlString* address) const { UtlSListIterator iterator(*sdpFields); NameValuePair* nv; address->remove(0); const char* value = NULL; int ttlIndex; // Try to find a specific address for the given media set nv = positionFieldInstance(mediaIndex, &iterator, "m"); if(nv) { nv = findFieldNameBefore(&iterator, "c", "m"); if(nv) { value = nv->getValue(); if(value) { UtlNameValueTokenizer::getSubField(value, 2, SDP_SUBFIELD_SEPARATORS, address); } } // Did not find a specific address try to find the default if(address->isNull()) { iterator.reset(); nv = findFieldNameBefore(&iterator, "c", "m"); // Default address exists in the header if(nv) { value = nv->getValue(); if(value) { UtlNameValueTokenizer::getSubField(value, 2, SDP_SUBFIELD_SEPARATORS, address); } } } if(!address->isNull()) { // Check if there is a time to live attribute and remove it ttlIndex = address->index("/"); if(ttlIndex >= 0) { address->remove(ttlIndex); } } } return(!address->isNull()); } UtlBoolean SdpBody::getPtime(int mediaIndex, int& pTime) const { UtlBoolean foundPtime = FALSE; UtlSListIterator iterator(*sdpFields); NameValuePair* nv; pTime = 0; const char* value = NULL; // Try to find a specific address for the given media set nv = positionFieldInstance(mediaIndex, &iterator, "m"); if(nv) { UtlString aParameterName; UtlString pTimeValueString; while((nv = findFieldNameBefore(&iterator, "a", "m"))) { value = nv->getValue(); if(value) { // Get the a line parameter name UtlNameValueTokenizer::getSubField(value, 0, " \t:/", // separators &aParameterName); // See if this is a ptime parameter if(aParameterName.compareTo("ptime", UtlString::ignoreCase) == 0) { // get the ptime value UtlNameValueTokenizer::getSubField(value, 1, " \t:/", // separators, &pTimeValueString); if(!pTimeValueString.isNull()) { pTime = atoi(pTimeValueString); // should only be one ptime per media set (m line) // Ignore all but the first one. if(pTime > 0) { foundPtime = TRUE; break; } } } } } } return(foundPtime); } #if 0 //{ void SdpBody::getBestAudioCodecs(int numRtpCodecs, SdpCodec rtpCodecs[], UtlString* rtpAddress, int* rtpPort, int* sendCodecIndex, int* receiveCodecIndex) const { int mediaIndex = 0; UtlBoolean sendCodecFound = FALSE; UtlBoolean receiveCodecFound = FALSE; int numTypes; int payloadTypes[MAXIMUM_MEDIA_TYPES]; int typeIndex; int codecIndex; rtpAddress->remove(0); *rtpPort = 0; *sendCodecIndex = -1; *receiveCodecIndex = -1; while(mediaIndex >= 0 && (!sendCodecFound || !receiveCodecFound)) { mediaIndex = findMediaType(SDP_AUDIO_MEDIA_TYPE, mediaIndex); if(mediaIndex >= 0) { getMediaPort(mediaIndex, rtpPort); if(*rtpPort >= 0) { getMediaPayloadType(mediaIndex, MAXIMUM_MEDIA_TYPES, &numTypes, payloadTypes); for(typeIndex = 0; typeIndex < numTypes; typeIndex++) { // Until the real SdpCodec is needed we assume all of // the rtpCodecs are send AND receive. // We are also going to cheat and assume that all of // the media records are send AND receive for(codecIndex = 0; codecIndex < numRtpCodecs; codecIndex++) { if(payloadTypes[typeIndex] == (rtpCodecs[codecIndex]).getCodecType()) { sendCodecFound = TRUE; receiveCodecFound = TRUE; *sendCodecIndex = codecIndex; *receiveCodecIndex = codecIndex; getMediaAddress(mediaIndex, rtpAddress); getMediaPort(mediaIndex, rtpPort); break; } } if(sendCodecFound && receiveCodecFound) { break; } } } mediaIndex++; } } } #endif //} // TODO: This interface is total broken and needs to be eliminated // It munges the codecs and payload types accross all of the m lines void SdpBody::getBestAudioCodecs(SdpCodecList& localRtpCodecs, int& numCodecsInCommon, SdpCodec**& commonCodecsForEncoder, //SdpCodec**& commonCodecsForDecoder, UtlString& rtpAddress, int& rtpPort, int& rtcpPort, int& videoRtpPort, int& videoRtcpPort, SdpSrtpParameters& localSrtpParams, SdpSrtpParameters& matchingSrtpParams, int localBandwidth, int& matchingBandwidth, int localVideoFramerate, int& matchingVideoFramerate) const { int mediaAudioIndex = 0; int mediaVideoIndex = 0; int numAudioTypes; int numVideoTypes; int bandwidth; int framerate; int audioPayloadTypes[MAXIMUM_MEDIA_TYPES]; int videoPayloadTypes[MAXIMUM_MEDIA_TYPES]; numCodecsInCommon = 0; commonCodecsForEncoder = new SdpCodec*[localRtpCodecs.getCodecCount()]; SdpCodec** commonCodecsForDecoder = new SdpCodec*[localRtpCodecs.getCodecCount()]; for(int codecIndex = 0; codecIndex < localRtpCodecs.getCodecCount(); codecIndex++) { commonCodecsForDecoder[codecIndex] = NULL; } SdpSrtpParameters remoteSrtpParams; memset((void*)&remoteSrtpParams, 0, sizeof(SdpSrtpParameters)); memset((void*)&matchingSrtpParams, 0, sizeof(SdpSrtpParameters)); rtpAddress.remove(0); rtpPort = 0; videoRtpPort = 0 ; while(mediaAudioIndex >= 0 || mediaVideoIndex >=0) { mediaAudioIndex = findMediaType(SDP_AUDIO_MEDIA_TYPE, mediaAudioIndex); mediaVideoIndex = findMediaType(SDP_VIDEO_MEDIA_TYPE, mediaVideoIndex); getBandwidthField(bandwidth); getBandwidthInCommon(localBandwidth, bandwidth, matchingBandwidth); getFramerateField(mediaVideoIndex, framerate); getVideoFramerateInCommon(localVideoFramerate, framerate, matchingVideoFramerate); if(mediaAudioIndex >= 0) { // This is kind of a bad assumption if there is more // than one media field, each might have a different // port and address getMediaPort(mediaAudioIndex, &rtpPort); getMediaRtcpPort(mediaAudioIndex, &rtcpPort); getSrtpCryptoField(mediaAudioIndex, 1, remoteSrtpParams); getMediaPort(mediaVideoIndex, &videoRtpPort); getMediaRtcpPort(mediaVideoIndex, &videoRtcpPort); getMediaAddress(mediaAudioIndex, &rtpAddress); if(rtpPort >= 0) { getMediaPayloadType(mediaAudioIndex, MAXIMUM_MEDIA_TYPES, &numAudioTypes, audioPayloadTypes); getMediaPayloadType(mediaVideoIndex, MAXIMUM_MEDIA_TYPES, &numVideoTypes, videoPayloadTypes); // TODO: // This method is broken as it munges information from multiple media lines // This should be removed. getCodecsInCommon(mediaAudioIndex, mediaVideoIndex, numAudioTypes, numVideoTypes, audioPayloadTypes, videoPayloadTypes, videoRtpPort, localRtpCodecs, numCodecsInCommon, commonCodecsForEncoder, commonCodecsForDecoder); getEncryptionInCommon(localSrtpParams, remoteSrtpParams, matchingSrtpParams); if (numCodecsInCommon >0) break; } mediaAudioIndex++; mediaVideoIndex++; } } if(commonCodecsForDecoder) { SdpCodecList::freeArray(localRtpCodecs.getCodecCount(), commonCodecsForDecoder); } } void SdpBody::getEncryptionInCommon(SdpSrtpParameters& audioParams, SdpSrtpParameters& remoteParams, SdpSrtpParameters& commonAudioParams) const { memset(&commonAudioParams, 0, sizeof(SdpSrtpParameters)); // Test for same cipher type and remote encryption being on if (audioParams.cipherType == remoteParams.cipherType && remoteParams.securityLevel) { // If we agree on a cipherType then the caller controls // if encryption is on - even if we switched it off locally. memcpy(&commonAudioParams, &remoteParams, sizeof(SdpSrtpParameters)); // Set encryption on sending and receiving - if we can figure out // how to negotiate this we can be more selective commonAudioParams.securityLevel |= SRTP_SEND | SRTP_RECEIVE; } } void SdpBody::getBandwidthInCommon(int localBandwidth, int remoteBandwidth, int& commonBandwidth) const { if (localBandwidth != 0 && remoteBandwidth != 0) { commonBandwidth = (remoteBandwidth <= localBandwidth) ? remoteBandwidth : localBandwidth; } else if (remoteBandwidth != 0) { commonBandwidth = remoteBandwidth; } else { commonBandwidth = localBandwidth; } } void SdpBody::getVideoFramerateInCommon(int localVideoFramerate, int remoteVideoFramerate, int& commonVideoFramerate) const { if (remoteVideoFramerate != 0 && remoteVideoFramerate < localVideoFramerate) { commonVideoFramerate = remoteVideoFramerate; } else { commonVideoFramerate = localVideoFramerate; } } UtlBoolean SdpBody::getMediaLine(int remoteMediaLineIndex, SdpMediaLine& mediaLine, const SdpCodecList* codecFactory) const { // Get the port, media type and codec payload IDs for this media line // Get the codecs definitions for the payload IDs for this media line return(SdpHelper::getMediaLine(*this, remoteMediaLineIndex, mediaLine, codecFactory)); } void SdpBody::addMediaLine(const SdpMediaLine& mediaLine, SdpBody& sdpBody) { SdpMediaLine::SdpMediaType mimeTypeEnum = mediaLine.getMediaType(); UtlString mimeType = SdpMediaLine::getStringForMediaType(mimeTypeEnum); int mediaPort = 0; // TODO: check for optional additional mediaPortPairs int mediaPortPairs = 1; UtlString mediaTransportType = SdpMediaLine::getStringForTransportProtocolType(mediaLine.getTransportProtocolType()); const SdpMediaLine::SdpConnection* connection = (SdpMediaLine::SdpConnection*) mediaLine.getConnections().first(); if(connection) { mediaPort = connection->getPort(); } const SdpCodecList* codecList = mediaLine.getCodecs(); int numCodecs; SdpCodec** codecArray = NULL; codecList->getCodecs(numCodecs, codecArray); int* payloadTypes = new int[numCodecs]; for(int codecIndex = 0; codecIndex < numCodecs; codecIndex++) { payloadTypes[codecIndex] = codecArray[codecIndex]->getCodecPayloadFormat(); } addMediaData(mimeType, mediaPort, mediaPortPairs, mediaTransportType, numCodecs, payloadTypes); // Address if(connection) { UtlString address = connection->getAddress(); if(!address.isNull()) { addConnectionAddress(connection->getNetTypeToken(), connection->getAddressTypeToken(), address); } } // TODO: Crypto //addSrtpCryptoField(commonAudioSrtpParams); // RTCP port const SdpMediaLine::SdpConnection* rtcpConnection = (SdpMediaLine::SdpConnection*) mediaLine.getRtcpConnections().first(); if(rtcpConnection) { int rtcpPort = rtcpConnection->getPort(); // Non-standard RTCP port if(rtcpPort > 0 && ( ((rtcpPort % 2) == 0) || // not odd number (rtcpPort != mediaPort + 1) // not port after RTP ) ) { // So we need to add an a record with the RTCP port number UtlString rtcpRecord("rtcp:"); rtcpRecord.appendFormat("%d", rtcpPort); addValue("a", rtcpRecord); } } // TODO:: TCP support // TODO: Candidate address/ports if(numCodecs) { addCodecParameters(numCodecs, codecArray, mimeType); } //dddd SdpCodecList::freeArray(numCodecs, codecArray); delete[] payloadTypes; } int SdpBody::getCodecsInCommon(const SdpMediaLine& localMediaLine, int remoteMediaLineIndex, SdpMediaLine& remoteMediaLine, SdpCodecList& localDecodeCodecs) const { // This SDP is assumed to be the remote offer int numCodecsInCommon = 0; // Get the codecs from the offer // Cheat the const on localMediaLine const SdpCodecList* localCodecList = ((SdpMediaLine&)localMediaLine).getCodecs(); if(getMediaLine(remoteMediaLineIndex, remoteMediaLine, localCodecList)) { if(remoteMediaLine.getMediaType() == localMediaLine.getMediaType()) { // Remove codecs that are not supported by this side SdpCodecList* remoteCodecList = (SdpCodecList*)remoteMediaLine.getCodecs(); remoteCodecList->limitCodecs(*localCodecList); numCodecsInCommon = remoteCodecList->getCodecCount(); // Need to copy payload IDs from remote codec list into local codec list // so that we do the friendly/interop thing and use the same payload ID as the // remote side where possible. localDecodeCodecs = *localCodecList; localDecodeCodecs.copyPayloadTypes(*remoteCodecList); } else { OsSysLog::add(FAC_NET, PRI_ERR, "SdpBody::getCodecsInCommon local m line type: %d remote m line type: %d differ for index: %d", localMediaLine.getMediaType(), remoteMediaLine.getMediaType(), remoteMediaLineIndex); } } else { localDecodeCodecs.clearCodecs(); OsSysLog::add(FAC_NET, PRI_ERR, "SdpBody::getCodecsInCommon media line index: %d does not exist", remoteMediaLineIndex); } return(numCodecsInCommon); } // TODO: This interface is total broken and needs to be eliminated // It munges the codecs and payload types accross all of the m lines void SdpBody::getCodecsInCommon(int audioMediaSetIndex, int videoMediaSetIndex, int audioPayloadIdCount, int videoPayloadIdCount, int audioPayloadTypes[], int videoPayloadTypes[], int videoRtpPort, SdpCodecList& localRtpCodecs, int& numCodecsInCommon, SdpCodec* commonCodecsForEncoder[], SdpCodec* commonCodecsForDecoder[]) const { //printf("getCodecsInCommon audioMediaSetIndex: %d videoMediaSetIndex: %d audioPayloadIdCount: %d videoPayloadIdCount: %d\n", // audioMediaSetIndex, videoMediaSetIndex, audioPayloadIdCount, videoPayloadIdCount); UtlString mimeSubtype; UtlString fmtp; int sampleRate; int numChannels; const SdpCodec* matchingCodec = NULL; int typeIndex; UtlBoolean commonCodec; int videoSizes[MAXIMUM_VIDEO_SIZES]; int numVideoSizes; numCodecsInCommon = 0; memset((void*)videoSizes, 0, sizeof(videoSizes)); // TODO: properly support media sets // This is a bit of a mess. We have completely blurred over the // concept of separate m lines other than the mime type separation // of audio and video. There may be different properties for the // same codecs which may appear in more than one media section // (m line) // So for example the ptime property is specific to a media // set (m line). At this point we no longer know which codec // comes from which media set. So for now we search through the // audio media sets until we find a ptime and assume the ptime // applies to all audio codecs. ptime mostly only make sense for // audio int defaultPtime = 0; UtlString mediaType; for(int mediaSetIndex = 0; getMediaType(mediaSetIndex, &mediaType); mediaSetIndex++) { if(mediaType.compareTo(MIME_TYPE_AUDIO, UtlString::ignoreCase) == 0) { if(getPtime(mediaSetIndex, defaultPtime) && defaultPtime > 0) { break; } } } for(typeIndex = 0; typeIndex < audioPayloadIdCount; typeIndex++) { // Until the real SdpCodec is needed we assume all of // the rtpCodecs are send AND receive. // We are also going to cheat and assume that all of // the media records are send AND receive // Get the rtpmap for the payload type if(getPayloadRtpMap(audioMediaSetIndex, audioPayloadTypes[typeIndex], mimeSubtype, sampleRate, numChannels)) { int codecMode; getPayloadFormat(audioMediaSetIndex, audioPayloadTypes[typeIndex], fmtp); SdpCodec::getFmtpParameter(fmtp, "mode", codecMode); // Workaround RFC bug with G.722 samplerate. // Read RFC 3551 Section 4.5.2 "G722" for details. if (mimeSubtype.compareTo("g722", UtlString::ignoreCase) == 0) { sampleRate = 16000; } // Find a match for the mime type matchingCodec = localRtpCodecs.getCodec(MIME_TYPE_AUDIO, mimeSubtype.data(), sampleRate, numChannels, fmtp); if (matchingCodec != NULL) { int frameSize = 0; commonCodec = TRUE; if (matchingCodec->getCodecType() == SdpCodec::SDP_CODEC_ILBC) { frameSize = codecMode; if (frameSize == 20 || frameSize == 30 || frameSize == 0) { if (frameSize == 0) { frameSize = 20; } } else { // Nothing in common here commonCodec = FALSE; } } else if(defaultPtime > 0) { frameSize = defaultPtime; } // Create a copy of the SDP codec and set // the payload type for it if (commonCodec) { commonCodecsForEncoder[numCodecsInCommon] = new SdpCodec(*matchingCodec); commonCodecsForDecoder[numCodecsInCommon] = new SdpCodec(*matchingCodec); // Let both decoder and encoder use the same payload type - this // is a friendly thing to do and minimize problems with other // clients. commonCodecsForEncoder[numCodecsInCommon]->setCodecPayloadFormat(audioPayloadTypes[typeIndex]); commonCodecsForDecoder[numCodecsInCommon]->setCodecPayloadFormat(audioPayloadTypes[typeIndex]); if (frameSize) { commonCodecsForEncoder[numCodecsInCommon]->setPacketSize(frameSize*1000); commonCodecsForDecoder[numCodecsInCommon]->setPacketSize(frameSize*1000); } } numCodecsInCommon++; } } // If no payload type set and this is a static payload // type assume the payload type is the same as our internal // codec id else if(audioPayloadTypes[typeIndex] <= SdpCodec::SDP_CODEC_MAXIMUM_STATIC_CODEC) { if((matchingCodec = localRtpCodecs.getCodecByType(audioPayloadTypes[typeIndex]))) { // Create a copy of the SDP codec commonCodecsForEncoder[numCodecsInCommon] = new SdpCodec(*matchingCodec); commonCodecsForDecoder[numCodecsInCommon] = new SdpCodec(*matchingCodec); // Set the preferred frame size if ptime was set if (defaultPtime > 0) { commonCodecsForEncoder[numCodecsInCommon]->setPacketSize(defaultPtime*1000); commonCodecsForDecoder[numCodecsInCommon]->setPacketSize(defaultPtime*1000); } numCodecsInCommon++; } } } #ifdef TEST_PRINT OsSysLog::add(FAC_NET, PRI_DEBUG, "SdpBody::getCodecsInCommon videoRtpPort=%d", videoRtpPort); #endif if (videoRtpPort != 0) { for(typeIndex = 0; typeIndex < videoPayloadIdCount; typeIndex++) { SdpCodec** sdpCodecArray; int numCodecs; int codecIndex; int videoSize; // Until the real SdpCodec is needed we assume all of // the rtpCodecs are send AND receive. // We are also going to cheat and assume that all of // the media records are send AND receive mimeSubtype = ""; numVideoSizes = 0; // Get the rtpmap for the payload type UtlBoolean bHasRtpMap = getPayloadRtpMap(videoMediaSetIndex, videoPayloadTypes[typeIndex], mimeSubtype, sampleRate, numChannels); // Get the video sizes in an array UtlBoolean bHasFmtp= getPayloadFormat(videoMediaSetIndex, videoPayloadTypes[typeIndex], fmtp); SdpCodec::getVideoSizes(fmtp, MAXIMUM_VIDEO_SIZES, numVideoSizes, videoSizes); UtlBoolean isH264 = (mimeSubtype.compareTo(MIME_SUBTYPE_H264, UtlString::ignoreCase) == 0); UtlString h264ProfileLevelId; UtlString h264LevelIdc; UtlString h264ProfileIdc; if(bHasFmtp && isH264) { SdpCodec::getFmtpParameter(fmtp, "profile-level-id", h264ProfileLevelId); // the last 2 of 6 hex chars of profile-level-id are level_idc h264LevelIdc = &(h264ProfileLevelId.data()[4]); h264LevelIdc.toLower(); // we ignore the middle 2 of 6 hex chars for now (profile-iop) // first 2 of 6 hex chars of profile-level-id are profile_idc h264ProfileIdc = h264ProfileLevelId; h264ProfileIdc.remove(2); } else { h264LevelIdc = ""; h264ProfileIdc = ""; } if (bHasRtpMap || bHasFmtp) { // Fixing iChat case where there is no rtpmap field for H263 if (mimeSubtype.length() == 0 && videoPayloadTypes[typeIndex] == 34) { mimeSubtype = "h263"; } // Get all codecs with the same mime subtype. Same codecs with different // video resolutions are added separately but have the same mime subtype. // The codec negotiation depends on the fact that codecs with the same // mime subtype are added sequentially. localRtpCodecs.getCodecs(numCodecs, sdpCodecArray, SDP_VIDEO_MEDIA_TYPE, mimeSubtype); #ifdef TEST_PRINT OsSysLog::add(FAC_NET, PRI_DEBUG, "SdpBody::getCodecsInCommon got %d local video codec(s)", numCodecs); #endif // Loop through the other side's video sizes first so we match the size // preferences of the other side if (numVideoSizes == 0) { // If no size parameter default to QCIF numVideoSizes = 1; videoSizes[0] = SDP_VIDEO_FORMAT_QCIF; } UtlString matchingCodecH264ProfileLevelId; UtlString matchingCodecH264ProfileIdc; UtlString priorH264ProfileIdc; for (videoSize = 0; videoSize < numVideoSizes; videoSize++) { UtlBoolean matchAlreadyFound = FALSE; for (codecIndex = 0; codecIndex < numCodecs; ++codecIndex) { matchingCodec = sdpCodecArray[codecIndex]; if(!h264ProfileIdc.isNull() && matchingCodec) { matchingCodec->getFmtpParameter("profile-level-id", matchingCodecH264ProfileLevelId); matchingCodecH264ProfileIdc = &(matchingCodecH264ProfileLevelId.data()[4]); matchingCodecH264ProfileIdc.toLower(); } else { matchingCodecH264ProfileIdc = ""; } // In addition to everything else do a bit-wise comparison of video formats. For // every codec with the same sub mime type that supports one of the video formats // add a seperate codec in the codecsInCommonArray. For H.264 size is not important. if((matchingCodec != NULL) && // Render sizes for non-H264 video codecs ((matchingCodec->getVideoFormat() == videoSizes[videoSize]) || // H264 specific fmpt parameter matching (isH264 && matchingCodec->isFmtpParameterSame(fmtp, "packetization-mode", "0") && !h264LevelIdc.isNull() && matchingCodecH264ProfileLevelId.index(h264ProfileIdc) == 0 ) ) && // Sample rate and num channels are pretty meaningless for video (matchingCodec->getSampleRate() == sampleRate || sampleRate == -1) && (matchingCodec->getNumChannels() == numChannels || numChannels == -1 )) { if(matchAlreadyFound) { // For now we are assuming that we want the closest match on the level-idc that is equal or // greater than that of the remote side's. We may find that we want to be less than, but // for now we are going with greater than. So there are 3 cases when the new codec is // better than the old one given that we have 3 codecs: the remote one, the prior matched one // and the new matched one: // new >= remote > prior // remote >= new > prior // prior > new >= remote // If this match is better than the prior, take this one instead if((matchingCodecH264ProfileIdc.compareTo(h264ProfileIdc, UtlString::ignoreCase) >= 0 && h264ProfileIdc.compareTo(priorH264ProfileIdc, UtlString::ignoreCase) > 0) || (h264ProfileIdc.compareTo(matchingCodecH264ProfileIdc, UtlString::ignoreCase) >= 0 && matchingCodecH264ProfileIdc.compareTo(priorH264ProfileIdc, UtlString::ignoreCase) > 0) || (priorH264ProfileIdc.compareTo(matchingCodecH264ProfileIdc, UtlString::ignoreCase) > 0 && matchingCodecH264ProfileIdc.compareTo(h264ProfileIdc, UtlString::ignoreCase) >= 0)) { OsSysLog::add(FAC_NET, PRI_DEBUG, "SdpBody::getCodecsInCommon match better than prior profile-idc, prior: %s better: %s remote: %s", priorH264ProfileIdc.data(), matchingCodecH264ProfileIdc.data(), h264ProfileIdc.data()); // Copy over prior added codec as this one is a better match *(commonCodecsForEncoder[numCodecsInCommon - 1]) = *matchingCodec; *(commonCodecsForDecoder[numCodecsInCommon - 1]) = *matchingCodec; commonCodecsForEncoder[numCodecsInCommon - 1]->setCodecPayloadFormat(videoPayloadTypes[typeIndex]); // decoder will use our SDP payload IDs, not those we received if(bHasFmtp) { commonCodecsForEncoder[numCodecsInCommon - 1]->setSdpFmtpField(fmtp); } priorH264ProfileIdc = matchingCodecH264ProfileIdc; } else { OsSysLog::add(FAC_NET, PRI_DEBUG, "SdpBody::getCodecsInCommon NOT better than prior profile-idc, prior: %s better: %s remote: %s", priorH264ProfileIdc.data(), matchingCodecH264ProfileIdc.data(), h264ProfileIdc.data()); } } else { // Create a copy of the SDP codec and set // the payload type for it commonCodecsForEncoder[numCodecsInCommon] = new SdpCodec(*matchingCodec); commonCodecsForDecoder[numCodecsInCommon] = new SdpCodec(*matchingCodec); commonCodecsForEncoder[numCodecsInCommon]->setCodecPayloadFormat(videoPayloadTypes[typeIndex]); // decoder will use our SDP payload IDs, not those we received if(bHasFmtp) { commonCodecsForEncoder[numCodecsInCommon]->setSdpFmtpField(fmtp); } priorH264ProfileIdc = matchingCodecH264ProfileIdc; numCodecsInCommon++; matchAlreadyFound = TRUE; } } else { if(matchingCodec == NULL) { OsSysLog::add(FAC_NET, PRI_DEBUG, "SdpBody::getCodecsInCommon matchingCodec NULL"); } else { UtlString matchFmtp; matchingCodec->getSdpFmtpField(matchFmtp); OsSysLog::add(FAC_NET, PRI_DEBUG, "SdpBody::getCodecsInCommon codec does not match mime subtype: %s match rate: %d remote rate: %d match channels: %d remote channels: %d match profile-level-id: %s remote level-idc: %s \nmatch fmtp: %s \nremote fmtp: %s", mimeSubtype.data(), matchingCodec->getSampleRate(), sampleRate, matchingCodec->getNumChannels(), numChannels, matchingCodecH264ProfileLevelId.data(), h264ProfileIdc.data(), matchFmtp.data(), fmtp.data()); } } } } // Delete the codec array we got to loop through codecs with the same mime subtype for (codecIndex = 0; codecIndex < numCodecs; ++codecIndex) { if (sdpCodecArray[codecIndex]) { delete sdpCodecArray[codecIndex]; sdpCodecArray[codecIndex] = NULL; } } delete[] sdpCodecArray; } // If no payload type set and this is a static payload // type assume the payload type is the same as our internal // codec id else if(videoPayloadTypes[typeIndex] <= SdpCodec::SDP_CODEC_MAXIMUM_STATIC_CODEC) { if((matchingCodec = localRtpCodecs.getCodecByType(videoPayloadTypes[typeIndex]))) { // Create a copy of the SDP codec and set // the payload type for it commonCodecsForEncoder[numCodecsInCommon] = new SdpCodec(*matchingCodec); commonCodecsForDecoder[numCodecsInCommon] = new SdpCodec(*matchingCodec); numCodecsInCommon++; } } } } } void SdpBody::addCodecsOffer(int iNumAddresses, const UtlString mediaAddresses[], int rtpAudioPorts[], int rtcpAudioPorts[], int rtpVideoPorts[], int rtcpVideoPorts[], RTP_TRANSPORT transportTypes[], int numRtpCodecs, SdpCodec* rtpCodecs[], SdpSrtpParameters& srtpParams, int totalBandwidth, int videoFramerate, RTP_TRANSPORT transportOffering) { int codecArray[MAXIMUM_MEDIA_TYPES]; int formatArray[MAXIMUM_MEDIA_TYPES]; UtlString videoFormat; int codecIndex; int destIndex; int firstMimeSubTypeIndex = 0; int preExistingMedia = getMediaSetCount(); UtlString mimeType; UtlString seenMimeType; UtlString mimeSubType; UtlString prevMimeSubType = "none"; int numAudioCodecs=0; int numVideoCodecs=0; const char* szTransportType = NULL; assert(iNumAddresses > 0) ; memset(formatArray, 0, sizeof(int)*MAXIMUM_MEDIA_TYPES); // If there are not media fields we only need one global one // for the SDP body if(!preExistingMedia) { setConnectionAddress(mediaAddresses[0]); char timeString[100]; sprintf(timeString, "%d %d", 0, //OsDateTime::getSecsSinceEpoch(), 0); addValue("t", timeString); } // Stuff the SDP audio codes in an integer array for(codecIndex = 0, destIndex = 0; codecIndex < MAXIMUM_MEDIA_TYPES && codecIndex < numRtpCodecs; codecIndex++) { rtpCodecs[codecIndex]->getMediaType(mimeType); if (mimeType.compareTo(SDP_AUDIO_MEDIA_TYPE, UtlString::ignoreCase) == 0 || mimeType.compareTo(SDP_VIDEO_MEDIA_TYPE, UtlString::ignoreCase) != 0) { seenMimeType = mimeType; ++numAudioCodecs; codecArray[destIndex++] = (rtpCodecs[codecIndex])->getCodecPayloadFormat(); } } if (rtpAudioPorts[0] > 0) { // If any security is enabled we set RTP/SAVP and add a crypto field if (srtpParams.securityLevel) { // Add the media record addMediaData(SDP_AUDIO_MEDIA_TYPE, rtpAudioPorts[0], 1, SDP_SRTP_MEDIA_TRANSPORT_TYPE, numAudioCodecs, codecArray); // The following are for RTSP support as the players seem to want to have // these fields in the SDP addValue("a", "control:trackID=1"); // If this is not the only media record we do need a local // address record for this media record if(preExistingMedia) { addConnectionAddress(mediaAddresses[0]); } addSrtpCryptoField(srtpParams); } else { if ((transportTypes[0] & RTP_TRANSPORT_UDP) == RTP_TRANSPORT_UDP) { szTransportType = SDP_RTP_MEDIA_TRANSPORT_TYPE; } else { szTransportType = SDP_RTP_TCP_MEDIA_TRANSPORT_TYPE; } // Add the media record addMediaData(SDP_AUDIO_MEDIA_TYPE, rtpAudioPorts[0], 1, szTransportType, numAudioCodecs, codecArray); // The following are for RTSP support as the players seem to want to have // these fields in the SDP addValue("a", "control:trackID=1"); // If this is not the only media record we do need a local // address record for this media record if(preExistingMedia) { addConnectionAddress(mediaAddresses[0]); } } // It is assumed that rtcp is the odd port immediately after the rtp port. // If that is not true, we must add a parameter to specify the rtcp port. if ( (rtcpAudioPorts[0] > 0) && ((rtcpAudioPorts[0] != rtpAudioPorts[0] + 1) || (rtcpAudioPorts[0] % 2) == 0)) { char cRtcpBuf[32] ; sprintf(cRtcpBuf, "rtcp:%d", rtcpAudioPorts[0]) ; addValue("a", cRtcpBuf) ; } // Add candidate addresses if available if (iNumAddresses > 1) { char szTransportString[16]; // http://tools.ietf.org/html/draft-ietf-mmusic-ice-17 // currently only UDP is defined strcpy(szTransportString, "UDP"); for (int i=0; i 0) ; if (rtpAudioPorts[0] && rtpAudioPorts[i] && mediaAddresses[i]) { addCandidateAttribute(i, "t", szTransportString, priority, mediaAddresses[i], rtpAudioPorts[i]) ; } if (rtcpAudioPorts[0] && rtcpAudioPorts[i] && mediaAddresses[i]) { addCandidateAttribute(i, "t", szTransportString, priority, mediaAddresses[i], rtcpAudioPorts[i]) ; } } } // add attribute records defining the extended types addCodecParameters(numRtpCodecs, rtpCodecs, seenMimeType); //, videoFramerate); } // Stuff the SDP video codecs codes in an integer array for(codecIndex = 0, destIndex = -1; codecIndex < MAXIMUM_MEDIA_TYPES && codecIndex < numRtpCodecs; codecIndex++) { rtpCodecs[codecIndex]->getMediaType(mimeType); rtpCodecs[codecIndex]->getEncodingName(mimeSubType); //#ifdef TEST_PRINT OsSysLog::add(FAC_NET, PRI_DEBUG, "SdpBody::addCodecsOffer (video loop) codec %s mime type: %s payload ID: %d\n", mimeSubType.data(), mimeType.data(), rtpCodecs[codecIndex]->getCodecPayloadFormat()); //#endif if (mimeType.compareTo(SDP_VIDEO_MEDIA_TYPE, UtlString::ignoreCase) == 0) { // printf("found video codec\n"); rtpCodecs[codecIndex]->getEncodingName(mimeSubType); // Cannot combine H264 fmtp strings as they will conflict // Not even sure this makes sense for other video codecs either if ((mimeSubType.compareTo(prevMimeSubType, UtlString::ignoreCase) == 0) && (mimeSubType.compareTo(MIME_SUBTYPE_H264, UtlString::ignoreCase) != 0)) { // printf("duplicate mime subtype\n"); // If we still have the same mime type only change format. We're depending on the // fact that codecs with the same mime subtype are added sequentially to the // codec factory. Otherwise this won't work. formatArray[destIndex] |= (rtpCodecs[codecIndex])->getVideoFormat(); (rtpCodecs[firstMimeSubTypeIndex])->setVideoFmtp(formatArray[destIndex]); (rtpCodecs[firstMimeSubTypeIndex])->setVideoFmtpString((rtpCodecs[codecIndex])->getVideoFormat()); } else { // TODO: Pick highest capability H264 codec and eliminate duplicates // printf("new format\n"); // New mime subtype - add new codec to codec list. Mark this index and put all // video format information into this codec because it will be looked at later. firstMimeSubTypeIndex = codecIndex; ++destIndex; prevMimeSubType = mimeSubType; ++numVideoCodecs; formatArray[destIndex] = (rtpCodecs[codecIndex])->getVideoFormat(); codecArray[destIndex] = (rtpCodecs[codecIndex])->getCodecPayloadFormat(); (rtpCodecs[firstMimeSubTypeIndex])->setVideoFmtp(formatArray[destIndex]); (rtpCodecs[firstMimeSubTypeIndex])->clearVideoFmtpString(); (rtpCodecs[firstMimeSubTypeIndex])->setVideoFmtpString((rtpCodecs[codecIndex])->getVideoFormat()); } } } // printf("rtpVideoPorts[0]=%d\n", rtpVideoPorts[0]); if (rtpVideoPorts[0] > 0) { // If any security is enabled we set RTP/SAVP and add a crypto field - not for video at this time if (0) { // Add the media record addMediaData(SDP_VIDEO_MEDIA_TYPE, rtpVideoPorts[0], 1, SDP_SRTP_MEDIA_TRANSPORT_TYPE, numVideoCodecs, codecArray); // The following are for RTSP support as the players seem to want to have // these fields in the SDP addValue("a", "control:trackID=2"); addSrtpCryptoField(srtpParams); // If this is not the only media record we do need a local // address record for this media record if(preExistingMedia) { addConnectionAddress(mediaAddresses[1]); } } else { if ((transportTypes[0] & RTP_TRANSPORT_UDP) == RTP_TRANSPORT_UDP) { szTransportType = SDP_RTP_MEDIA_TRANSPORT_TYPE; } else { szTransportType = SDP_RTP_TCP_MEDIA_TRANSPORT_TYPE; } // Add the media record addMediaData(SDP_VIDEO_MEDIA_TYPE, rtpVideoPorts[0], 1, szTransportType, numVideoCodecs, codecArray); // The following are for RTSP support as the players seem to want to have // these fields in the SDP addValue("a", "control:trackID=2"); // If this is not the only media record we do need a local // address record for this media record if(preExistingMedia) { addConnectionAddress(mediaAddresses[0]); } } // It is assumed that rtcp is the odd port immediately after the rtp port. // If that is not true, we must add a parameter to specify the rtcp port. if ((rtcpVideoPorts[0] > 0) && ((rtcpVideoPorts[0] != rtpVideoPorts[0] + 1) || (rtcpVideoPorts[0] % 2) == 0)) { char cRtcpBuf[32] ; sprintf(cRtcpBuf, "rtcp:%d", rtcpVideoPorts[0]) ; addValue("a", cRtcpBuf) ; } // Add candidate addresses if available if (iNumAddresses > 1) { char szTransportString[16]; // http://tools.ietf.org/html/draft-ietf-mmusic-ice-17 // currently only UDP is defined strcpy(szTransportString, "UDP"); for (int i=0; i 0) ; if (rtpVideoPorts[0] && rtpVideoPorts[i] && mediaAddresses[i]) { addCandidateAttribute(i, "t", szTransportString, priority, mediaAddresses[i], rtpVideoPorts[i]) ; } if (rtcpVideoPorts[0] && rtcpVideoPorts[i] && mediaAddresses[i]) { addCandidateAttribute(i, "t", szTransportString, priority, mediaAddresses[i], rtcpVideoPorts[i]) ; } } } // add attribute records defining the extended types addCodecParameters(numRtpCodecs, rtpCodecs, SDP_VIDEO_MEDIA_TYPE); //, videoFramerate); if (totalBandwidth != 0) { char ct[16]; sprintf(ct, "CT:%d", totalBandwidth); setValue("b", ct); } } else if(destIndex >= 0) { OsSysLog::add(FAC_NET, PRI_WARNING, "SdpBody %d video codecs enabled, but video port: %d < 0", destIndex + 1, rtpVideoPorts[0]); } } void SdpBody::addCodecParameters(int numRtpCodecs, SdpCodec* rtpCodecs[], const char *szMimeType) { const SdpCodec* codec = NULL; UtlString mimeSubtype; int payloadType; int sampleRate; int numChannels; int videoFmtp; UtlString formatParameters; UtlString mimeType; UtlString formatTemp; UtlString formatString; int pTime = 0; int codecPtime = 0; for(int codecIndex = 0; codecIndex < MAXIMUM_MEDIA_TYPES && codecIndex < numRtpCodecs; codecIndex++) { codec = rtpCodecs[codecIndex]; rtpCodecs[codecIndex]->getMediaType(mimeType); if(codec && mimeType.compareTo(szMimeType, UtlString::ignoreCase) == 0) { codec->getEncodingName(mimeSubtype); sampleRate = codec->getSampleRate(); numChannels = codec->getNumChannels(); codec->getSdpFmtpField(formatParameters); payloadType = codec->getCodecPayloadFormat(); #ifdef TEST_PRINT OsSysLog::add(FAC_NET, PRI_DEBUG, "SdpBody::addCodecParameters adding codec: %s payload ID: %d", mimeSubtype.data(), payloadType); #endif // Workarmund RFC bug with G.722 samplerate. // Read RFC 3551 Section 4.5.2 "G722" for details. if (codec->getCodecType() == SdpCodec::SDP_CODEC_G722) { sampleRate = 8000; } // Not sure what the right heuristic is for determining the // correct ptime. ptime is a media (m line) parameters. As such // it is a global property to all codecs for a single media // (m line) section. For now lets try using the largest one as // SDP does not support different ptime for each codec. codecPtime = (codec->getPacketLength()) / 1000; // converted to milliseconds if(codecPtime > pTime) { pTime = codecPtime; } // Build an rtpmap addRtpmap(payloadType, mimeSubtype.data(), sampleRate, numChannels); // Non H264 video codecs need to construct format string. // H.264 codecs just use the configured fmtp string for the codec. if ((videoFmtp=codec->getVideoFmtp()) != 0 && mimeSubtype.compareTo(MIME_SUBTYPE_H264, UtlString::ignoreCase)) { if (codec->getCodecPayloadFormat() != SdpCodec::SDP_CODEC_H263) { codec->getVideoFmtpString(formatString); formatTemp = "size:" + formatString; formatParameters = formatTemp(0, formatTemp.length()-1); } else { switch (codec->getCodecType()) { case SdpCodec::SDP_CODEC_H263_CIF: formatParameters = "imagesize 1"; break; case SdpCodec::SDP_CODEC_H263_QCIF: formatParameters = "imagesize 0"; break; default: break; } } } // Add the format specific parameters if present if(!formatParameters.isNull()) { addFormatParameters(payloadType, formatParameters.data()); /* Not quite sure if we want to send a global framerate limit if (codec->getCodecPayloadFormat() == SdpCodec::SDP_CODEC_H263 && videoFramerate != 0) { sprintf(valueBuf, "framerate:%d", videoFramerate); addValue("a", valueBuf); } */ } } #ifdef TEST_PRINT else { if(codec) { codec->getEncodingName(mimeSubtype); } OsSysLog::add(FAC_NET, PRI_DEBUG, "SdpBody::addCodecParameters skipping codec MIME type: %s/%s payload: %d expecting: %s", mimeType.data(), mimeSubtype.data(), codec ? codec->getCodecPayloadFormat() : -1, szMimeType); } #endif } // ptime only really make sense for audio if(pTime > 0 && strcmp(szMimeType, SDP_AUDIO_MEDIA_TYPE) == 0 ) { addPtime(pTime); } } void SdpBody::buildMediaLine(SdpMediaLine::SdpMediaType mediaType, int totalBandwidth, int iNumAddresses, UtlString hostAddresses[], int rtpPorts[], int rtcpPorts[], int numRtpCodecs, SdpCodec* rtpCodecs[], SdpMediaLine& mediaLine) { mediaLine.setMediaType(mediaType); // TODO: Conditional upon TCP or SRTP parameters mediaLine.setTransportProtocolType(SdpMediaLine::PROTOCOL_TYPE_RTP_AVP); if(totalBandwidth > 0) { mediaLine.addBandwidth(Sdp::BANDWIDTH_TYPE_CT, totalBandwidth); } // Loop through the codecs and add them to media line for(int codecIndex = 0; codecIndex < numRtpCodecs; codecIndex++) { UtlString codecMediaType; rtpCodecs[codecIndex]->getMediaType(codecMediaType); if(codecMediaType.compareTo(SdpMediaLine::getStringForMediaType(mediaType), UtlString::ignoreCase) == 0) { mediaLine.addCodec(new SdpCodec(*rtpCodecs[codecIndex])); } } // Add the connection c= mediaLine.addConnection(Sdp::NET_TYPE_IN, OsSocket::isIp4Address(hostAddresses[0]) ? Sdp::ADDRESS_TYPE_IP4 : Sdp::ADDRESS_TYPE_IP6, hostAddresses[0], rtpPorts[0]); mediaLine.addRtcpConnection(Sdp::NET_TYPE_IN, OsSocket::isIp4Address(hostAddresses[0]) ? Sdp::ADDRESS_TYPE_IP4 : Sdp::ADDRESS_TYPE_IP6, hostAddresses[0], rtcpPorts[0]); mediaLine.setDirection(rtpPorts[0] ? SdpMediaLine::DIRECTION_TYPE_SENDRECV : SdpMediaLine::DIRECTION_TYPE_INACTIVE); // Loop through the candidate port/addresses and add them to the m line if(iNumAddresses > 1) { for(int candidateIndex = 0; candidateIndex < iNumAddresses; candidateIndex++) { uint64_t priority = (iNumAddresses - candidateIndex) + PRIORITY_OFFSET; SdpCandidate* candidate = new SdpCandidate("t", candidateIndex, SdpCandidate::CANDIDATE_TRANSPORT_TYPE_UDP, priority, hostAddresses[candidateIndex], rtpPorts[candidateIndex]); mediaLine.addCandidate(candidate); } } // ptime not set for video. I think this is correct. } void SdpBody::addCodecsAnswer(int iNumAddresses, UtlString hostAddresses[], int rtpAudioPorts[], int rtcpAudioPorts[], int rtpVideoPorts[], int rtcpVideoPorts[], RTP_TRANSPORT transportTypes[], int numRtpCodecs, SdpCodec* rtpCodecs[], SdpSrtpParameters& srtpParams, int totalBandwidth, int videoFramerate, const SdpBody* sdpRequest) { #if 1 //{ const SdpMediaLine* mediaLines[2]; int numMediaLines = 0; mediaLines[0] = NULL; mediaLines[1] = NULL; // ************* Audio M line ************* int pTime = 0; SdpMediaLine audioMediaLine; audioMediaLine.setMediaType(SdpMediaLine::MEDIA_TYPE_AUDIO); //TODO: should this be conditional upon SdpSrtpParameters? // The old code assumed the tranport type from the offer. Not sure what we should do here //(audioTransportType.compareTo(SDP_RTP_MEDIA_TRANSPORT_TYPE, UtlString::ignoreCase) == 0) || //(audioTransportType.compareTo(SDP_RTP_TCP_MEDIA_TRANSPORT_TYPE, UtlString::ignoreCase) == 0) || //(audioTransportType.compareTo(SDP_SRTP_MEDIA_TRANSPORT_TYPE, UtlString::ignoreCase) == 0)) audioMediaLine.setTransportProtocolType(SdpMediaLine::PROTOCOL_TYPE_RTP_AVP); if(totalBandwidth > 0) { audioMediaLine.addBandwidth(Sdp::BANDWIDTH_TYPE_CT, totalBandwidth); } // Loop through the codecs and add them to media line for(int codecIndex = 0; codecIndex < numRtpCodecs; codecIndex++) { UtlString codecMediaType; rtpCodecs[codecIndex]->getMediaType(codecMediaType); if(codecMediaType.compareTo(SDP_AUDIO_MEDIA_TYPE, UtlString::ignoreCase) == 0) { audioMediaLine.addCodec(new SdpCodec(*rtpCodecs[codecIndex])); // convert micro seconds to milliseconds int codecPtime = (rtpCodecs[codecIndex]->getPacketLength()) / 1000; if(codecPtime > pTime) { pTime = codecPtime; } } } // Add the connection c= audioMediaLine.addConnection(Sdp::NET_TYPE_IN, OsSocket::isIp4Address(hostAddresses[0]) ? Sdp::ADDRESS_TYPE_IP4 : Sdp::ADDRESS_TYPE_IP6, hostAddresses[0], rtpAudioPorts[0]); audioMediaLine.addRtcpConnection(Sdp::NET_TYPE_IN, OsSocket::isIp4Address(hostAddresses[0]) ? Sdp::ADDRESS_TYPE_IP4 : Sdp::ADDRESS_TYPE_IP6, hostAddresses[0], rtcpAudioPorts[0]); audioMediaLine.setDirection(rtpAudioPorts[0] ? SdpMediaLine::DIRECTION_TYPE_SENDRECV : SdpMediaLine::DIRECTION_TYPE_INACTIVE); // Loop through the candidate port/addresses and add them to the m line if(iNumAddresses > 1) { for(int candidateIndex = 0; candidateIndex < iNumAddresses; candidateIndex++) { uint64_t priority = (iNumAddresses - candidateIndex) + PRIORITY_OFFSET; SdpCandidate* candidate = new SdpCandidate("t", candidateIndex, SdpCandidate::CANDIDATE_TRANSPORT_TYPE_UDP, priority, hostAddresses[candidateIndex], rtpAudioPorts[candidateIndex]); audioMediaLine.addCandidate(candidate); } } // Not sure what the right heuristic is for determining the // correct ptime. ptime is a media (m line) parameters. As such // it is a global property to all codecs for a single media // (m line) section. For now lets try using the largest one as // SDP does not support different ptime for each codec. if(pTime > 0) { audioMediaLine.setPacketTime(pTime); } // ************* Video M line ************* SdpMediaLine videoMediaLine; buildMediaLine(SdpMediaLine::MEDIA_TYPE_VIDEO, totalBandwidth, iNumAddresses, hostAddresses, rtpVideoPorts, rtcpVideoPorts, numRtpCodecs, rtpCodecs, videoMediaLine); // TODO: videoFramerate Does not look like this was ever set // Build the array of m lines for the streams supported on this side if(rtpAudioPorts[0]) { mediaLines[numMediaLines] = &audioMediaLine; numMediaLines++; } if(rtpVideoPorts[0]) { mediaLines[numMediaLines] = &videoMediaLine; numMediaLines++; } addMediaLinesAnswer(numMediaLines, mediaLines, *sdpRequest); #endif // } #if 0 //{ int preExistingMedia = getMediaSetCount(); int mediaIndex = 0; UtlBoolean fieldFound = TRUE; UtlBoolean commonVideo = FALSE; UtlString mediaType; int mediaPort, audioPort, videoPort; int mediaPortPairs, audioPortPairs, videoPortPairs; UtlString mediaTransportType, audioTransportType, videoTransportType; int numPayloadTypes, numAudioPayloadTypes, numVideoPayloadTypes; int payloadTypes[MAXIMUM_MEDIA_TYPES]; int audioPayloadTypes[MAXIMUM_MEDIA_TYPES]; int videoPayloadTypes[MAXIMUM_MEDIA_TYPES]; int supportedPayloadTypes[MAXIMUM_MEDIA_TYPES]; int formatArray[MAXIMUM_MEDIA_TYPES]; int remoteTotalBandwidth; int matchingBandwidth; SdpCodec* codecsInCommon[MAXIMUM_MEDIA_TYPES]; SdpCodec* codecsDummy[MAXIMUM_MEDIA_TYPES]; // just a dummy codec array int supportedPayloadCount; int destIndex; int firstMimeSubTypeIndex = 0; SdpSrtpParameters receivedSrtpParams; SdpSrtpParameters receivedAudioSrtpParams; SdpSrtpParameters receivedVideoSrtpParams; UtlString prevMimeSubType = "none"; UtlString mimeSubType; memset(formatArray, 0, sizeof(int)*MAXIMUM_MEDIA_TYPES); memset(&receivedSrtpParams,0, sizeof(SdpSrtpParameters)); // if there are no media fields already, add a global // address field if(!preExistingMedia) { setConnectionAddress(hostAddresses[0]); char timeString[100]; sprintf(timeString, "%d %d", 0, //OsDateTime::getSecsSinceEpoch(), 0); addValue("t", timeString); } numPayloadTypes = 0 ; memset(&payloadTypes, 0, sizeof(int) * MAXIMUM_MEDIA_TYPES) ; audioPort = 0 ; audioPortPairs = 0 ; numAudioPayloadTypes = 0 ; memset(&audioPayloadTypes, 0, sizeof(int) * MAXIMUM_MEDIA_TYPES) ; memset(&receivedAudioSrtpParams,0 , sizeof(SdpSrtpParameters)); videoPort = 0 ; videoPortPairs = 0 ; numVideoPayloadTypes = 0 ; memset(&videoPayloadTypes, 0, sizeof(int) * MAXIMUM_MEDIA_TYPES) ; memset(&receivedVideoSrtpParams,0 , sizeof(SdpSrtpParameters)); // Loop through the fields in the sdpRequest while(fieldFound) { fieldFound = sdpRequest->getMediaData(mediaIndex, &mediaType, &mediaPort, &mediaPortPairs, &mediaTransportType, MAXIMUM_MEDIA_TYPES, &numPayloadTypes, payloadTypes); sdpRequest->getBandwidthField(remoteTotalBandwidth); if(fieldFound) { #ifdef TEST_PRINT OsSysLog::add(FAC_NET, PRI_DEBUG, "SdpBody::addCodecsAnswer media type: %s", mediaType.data()); #endif // Check for unsupported stuff // i.e. non audio media, non RTP transported media, etc if( ( mediaType.compareTo(SDP_AUDIO_MEDIA_TYPE, UtlString::ignoreCase) != 0 && mediaType.compareTo(SDP_VIDEO_MEDIA_TYPE, UtlString::ignoreCase) != 0 ) || mediaPort <= 0 || mediaPortPairs <= 0 || ( mediaTransportType.compareTo(SDP_RTP_MEDIA_TRANSPORT_TYPE, UtlString::ignoreCase) != 0 && mediaTransportType.compareTo(SDP_RTP_TCP_MEDIA_TRANSPORT_TYPE, UtlString::ignoreCase) != 0 && mediaTransportType.compareTo(SDP_SRTP_MEDIA_TRANSPORT_TYPE, UtlString::ignoreCase) != 0 ) ) { mediaPort = 0; addMediaData(mediaType.data(), mediaPort, mediaPortPairs, mediaTransportType.data(), numPayloadTypes, payloadTypes); } // Copy media fields and replace the port with: // rtpPort if one or more of the codecs are supported // removing the unsupported codecs // zero if none of the codecs are supported else { sdpRequest->getSrtpCryptoField(mediaIndex, 1, receivedSrtpParams); if (mediaType.compareTo(SDP_AUDIO_MEDIA_TYPE, UtlString::ignoreCase) == 0) { audioPort = mediaPort; audioPortPairs = mediaPortPairs; audioTransportType = mediaTransportType; numAudioPayloadTypes = numPayloadTypes; memcpy(&audioPayloadTypes, &payloadTypes, sizeof(int)*MAXIMUM_MEDIA_TYPES); memcpy(&receivedAudioSrtpParams, &receivedSrtpParams, sizeof(SdpSrtpParameters)); } else { videoPort = mediaPort; videoPortPairs = mediaPortPairs; videoTransportType = mediaTransportType; numVideoPayloadTypes = numPayloadTypes; memcpy(&videoPayloadTypes, &payloadTypes, sizeof(int)*MAXIMUM_MEDIA_TYPES); memcpy(&receivedVideoSrtpParams, &receivedSrtpParams, sizeof(SdpSrtpParameters)); } } } mediaIndex++; } SdpCodecList codecFactory(numRtpCodecs, rtpCodecs); supportedPayloadCount = 0; sdpRequest->getCodecsInCommon(numAudioPayloadTypes, numVideoPayloadTypes, audioPayloadTypes, videoPayloadTypes, videoPort, codecFactory, supportedPayloadCount, codecsDummy, codecsInCommon); #ifdef TEST_PRINT OsSysLog::add(FAC_NET, PRI_DEBUG, "SdpBody::addCodecsAnswer audio codecs enabled: %d video codecs enabled: %d", numAudioPayloadTypes, numVideoPayloadTypes); #endif SdpSrtpParameters commonAudioSrtpParams; SdpSrtpParameters commonVideoSrtpParams; memset(&commonAudioSrtpParams,0 , sizeof(SdpSrtpParameters)); memset(&commonVideoSrtpParams,0 , sizeof(SdpSrtpParameters)); getEncryptionInCommon(srtpParams, receivedAudioSrtpParams, commonAudioSrtpParams); getBandwidthInCommon(totalBandwidth, remoteTotalBandwidth, matchingBandwidth); // Add the modified list of supported codecs if (supportedPayloadCount && srtpParams.securityLevel==commonAudioSrtpParams.securityLevel) { // Do this for audio first destIndex = 0; int payloadIndex; for(payloadIndex = 0; payloadIndex < supportedPayloadCount; payloadIndex++) { codecsInCommon[payloadIndex]->getMediaType(mediaType); if (mediaType.compareTo(SDP_AUDIO_MEDIA_TYPE, UtlString::ignoreCase) == 0) { supportedPayloadTypes[destIndex++] = codecsInCommon[payloadIndex]->getCodecPayloadFormat(); } } addMediaData(SDP_AUDIO_MEDIA_TYPE, rtpAudioPorts[0], 1, audioTransportType.data(), destIndex, supportedPayloadTypes); // The following are for RTSP support as the players seem to want to have // these fields in the SDP addValue("a", "control:trackID=1"); if (commonAudioSrtpParams.securityLevel) { addSrtpCryptoField(commonAudioSrtpParams); } //dddd if ( audioTransportType.compareTo(SDP_RTP_MEDIA_TRANSPORT_TYPE, UtlString::ignoreCase) == 0 || audioTransportType.compareTo(SDP_RTP_TCP_MEDIA_TRANSPORT_TYPE, UtlString::ignoreCase) == 0 || audioTransportType.compareTo(SDP_SRTP_MEDIA_TRANSPORT_TYPE, UtlString::ignoreCase) == 0 ) { // It is assumed that rtcp is the odd port immediately after // the rtp port. If that is not true, we must add a parameter // to specify the rtcp port. if ( rtcpAudioPorts[0] > 0 && ( rtcpAudioPorts[0] != rtpAudioPorts[0] + 1 || (rtcpAudioPorts[0] % 2) == 0 ) ) { char cRtcpBuf[32] ; sprintf(cRtcpBuf, "rtcp:%d", rtcpAudioPorts[0]) ; addValue("a", cRtcpBuf) ; } if (mediaTransportType.compareTo(SDP_RTP_TCP_MEDIA_TRANSPORT_TYPE, UtlString::ignoreCase) == 0) { // if transport == TCP, add the a=setup:actpass addValue("a", "setup:actpass"); } // Add candidate addresses if available if (iNumAddresses > 1) { for (int i=0; i 0) ; if (rtpAudioPorts[0] && rtpAudioPorts[i] && hostAddresses[i]) { addCandidateAttribute(i, "t", "UDP", priority, hostAddresses[i], rtpAudioPorts[i]) ; } if (rtcpAudioPorts[0] && rtcpAudioPorts[i] && hostAddresses[i]) { addCandidateAttribute(i, "t", "UDP", priority, hostAddresses[i], rtcpAudioPorts[i]) ; } } } } addCodecParameters(supportedPayloadCount, codecsInCommon, SDP_AUDIO_MEDIA_TYPE); //, videoFramerate); // Then do this for video destIndex = -1; for(payloadIndex = 0; payloadIndex < supportedPayloadCount; payloadIndex++) { codecsInCommon[payloadIndex]->getMediaType(mediaType); //#ifdef TEST_PRINT OsSysLog::add(FAC_NET, PRI_DEBUG, "SdpBody::addCodecsAnswer codecsInCommon[%d] looking for video, found: getMediaType=%s payload ID: %d internal codec ID: %d", payloadIndex, mediaType.data(), codecsInCommon[payloadIndex]->getCodecPayloadFormat(), codecsInCommon[payloadIndex]->getCodecType()); //#endif if (mediaType.compareTo(SDP_VIDEO_MEDIA_TYPE, UtlString::ignoreCase) == 0) { // We've found at least one common video codec commonVideo = TRUE; codecsInCommon[payloadIndex]->getEncodingName(mimeSubType); // If we still have the same mime type only change format. We're depending on the // fact that codecs with the same mime subtype are added sequentially to the // codec factory. Otherwise this won't work. // TODO: add better comparison of H264 codecs to check for duplicates if (prevMimeSubType.compareTo(MIME_SUBTYPE_H264, UtlString::ignoreCase) != 0 && prevMimeSubType.compareTo(mimeSubType, UtlString::ignoreCase) == 0) { formatArray[destIndex] |= (codecsInCommon[payloadIndex])->getVideoFormat(); (codecsInCommon[firstMimeSubTypeIndex])->setVideoFmtp(formatArray[destIndex]); (codecsInCommon[firstMimeSubTypeIndex])->setVideoFmtpString((codecsInCommon[payloadIndex])->getVideoFormat()); } else { ++destIndex; prevMimeSubType = mimeSubType; firstMimeSubTypeIndex = payloadIndex; formatArray[destIndex] = (codecsInCommon[payloadIndex])->getVideoFormat(); supportedPayloadTypes[destIndex] = codecsInCommon[firstMimeSubTypeIndex]->getCodecPayloadFormat(); (codecsInCommon[firstMimeSubTypeIndex])->setVideoFmtp(formatArray[destIndex]); (codecsInCommon[firstMimeSubTypeIndex])->clearVideoFmtpString(); (codecsInCommon[firstMimeSubTypeIndex])->setVideoFmtpString((codecsInCommon[payloadIndex])->getVideoFormat()); } } } // Only add m-line if we actually have common video codecs if (commonVideo) { addMediaData(SDP_VIDEO_MEDIA_TYPE, rtpVideoPorts[0], 1, videoTransportType.data(), destIndex+1, supportedPayloadTypes); // The following are for RTSP support as the players seem to want to have // these fields in the SDP addValue("a", "control:trackID=2"); // We do not support video encryption at this time //if (commonVideoSrtpParams.securityLevel) //{ // addSrtpCryptoField(commonAudioSrtpParams); //} if ( (audioTransportType.compareTo(SDP_RTP_MEDIA_TRANSPORT_TYPE, UtlString::ignoreCase) == 0) || (audioTransportType.compareTo(SDP_RTP_TCP_MEDIA_TRANSPORT_TYPE, UtlString::ignoreCase) == 0) || (audioTransportType.compareTo(SDP_SRTP_MEDIA_TRANSPORT_TYPE, UtlString::ignoreCase) == 0)) { // It is assumed that rtcp is the odd port immediately after // the rtp port. If that is not true, we must add a parameter // to specify the rtcp port. if ((rtcpVideoPorts[0] > 0) && ((rtcpVideoPorts[0] != rtpVideoPorts[0] + 1) || (rtcpVideoPorts[0] % 2) == 0)) { char cRtcpBuf[32] ; sprintf(cRtcpBuf, "rtcp:%d", rtcpVideoPorts[0]) ; addValue("a", cRtcpBuf) ; } } // Add candidate addresses if available if (iNumAddresses > 1) { for (int i=0; i 0) ; if (rtpVideoPorts[0] && rtpVideoPorts[i] && hostAddresses[i]) { addCandidateAttribute(i, "t", "UDP", priority, hostAddresses[i], rtpVideoPorts[i]) ; } if (rtcpVideoPorts[0] && rtcpVideoPorts[i] && hostAddresses[i]) { addCandidateAttribute(i, "t", "UDP", priority, hostAddresses[i], rtcpVideoPorts[i]) ; } } } addCodecParameters(supportedPayloadCount, codecsInCommon, SDP_VIDEO_MEDIA_TYPE); //, videoFramerate); } } // Zero out the port to indicate none are supported else { mediaPort = 0; addMediaData(SDP_AUDIO_MEDIA_TYPE, mediaPort, audioPortPairs, audioTransportType.data(), numAudioPayloadTypes, audioPayloadTypes); addMediaData(SDP_VIDEO_MEDIA_TYPE, mediaPort, videoPortPairs, videoTransportType.data(), numVideoPayloadTypes, videoPayloadTypes); } // Free up the codec copies for(int codecIndex = 0; codecIndex < supportedPayloadCount; codecIndex++) { delete codecsInCommon[codecIndex]; codecsInCommon[codecIndex] = NULL; delete codecsDummy[codecIndex]; codecsDummy[codecIndex] = NULL; } if(preExistingMedia) { addConnectionAddress(hostAddresses[0]); } // Indicate a low bandwidth client if bw <= 64 kpbs if (matchingBandwidth != 0 && matchingBandwidth <= 64) { char ct[16]; sprintf(ct, "CT:%d", matchingBandwidth); setValue("b", ct); } // Copy all atribute fields verbatum // someday #endif //} } void SdpBody::addMediaLinesAnswer(int numMediaLines, const SdpMediaLine* mediaLines[], const SdpBody& sdpOffer) { if(numMediaLines > 0 && mediaLines[0]) { int preExistingMedia = getMediaSetCount(); SdpMediaLine::SdpConnection* connection = (SdpMediaLine::SdpConnection*) mediaLines[0]->getConnections().index(0); UtlString gloablHostAddresses = connection ? connection->getAddress() : ""; // if there are no media fields already, add a global // address field if(!preExistingMedia) { if(! gloablHostAddresses.isNull()) { setConnectionAddress(gloablHostAddresses); } char timeString[100]; sprintf(timeString, "%d %d", 0, //OsDateTime::getSecsSinceEpoch(), 0); addValue("t", timeString); } UtlBoolean* streamsUsed = new UtlBoolean[numMediaLines]; int localStreamIndex; for(localStreamIndex = 0; localStreamIndex < numMediaLines; localStreamIndex++) { streamsUsed[localStreamIndex] = FALSE; } UtlString remoteMediaType; int remoteMediaPort; int remoteMediaPortPairs; UtlString remoteMediaTransportType; int numRemotePayloadTypes; int remotePayloadTypes[MAXIMUM_MEDIA_TYPES]; int remoteMediaIndex = 0; // Loop through the codecs on the remote side while(sdpOffer.getMediaData(remoteMediaIndex, &remoteMediaType, &remoteMediaPort, &remoteMediaPortPairs, &remoteMediaTransportType, MAXIMUM_MEDIA_TYPES, &numRemotePayloadTypes, remotePayloadTypes)) { UtlBoolean wroteMediaLine = FALSE; // Look through unused local streams to find a match for(localStreamIndex = 0; localStreamIndex < numMediaLines; localStreamIndex++) { if(! streamsUsed[localStreamIndex] && mediaLines[localStreamIndex]->getMediaType() == SdpMediaLine::getMediaTypeFromString(remoteMediaType)) { SdpMediaLine remoteMediaLine; SdpCodecList localDecodeCodecs; // Mime types match, check if any codecs match sdpOffer.getCodecsInCommon(*mediaLines[localStreamIndex], remoteMediaIndex, remoteMediaLine, localDecodeCodecs); if(remoteMediaLine.getCodecs()->getCodecCount()) { // Mark this local stream as used so we do not have multiple // remote streams sending to the same socket/stream. streamsUsed[localStreamIndex] = TRUE; wroteMediaLine = TRUE; // Create a temporary mediaLine for the local side which uses the codec payload ID of the // the rmoete side where possible. SdpMediaLine tempLocalMediaLine = *mediaLines[localStreamIndex]; tempLocalMediaLine.setCodecs(localDecodeCodecs); // Write out the SDP for this media line addMediaLine(tempLocalMediaLine, *this); // A unique track ID is needed for each media line when used with RTSP UtlString trackString("control:trackID="); trackString.appendFormat("%d", localStreamIndex + 1); addValue("a", trackString); // Break out of the for loop we found a match break; } } } // There was no match to this remote media line, write out a inactive m line if(!wroteMediaLine) { // c line is manditory and must go before any a lines addConnectionAddress("0.0.0.0"); remoteMediaPort = 0; addMediaData(remoteMediaType, remoteMediaPort, remoteMediaPortPairs, remoteMediaTransportType, numRemotePayloadTypes, remotePayloadTypes); // Mark media line as inactive addValue("a", "inactive"); } remoteMediaIndex++; } delete[] streamsUsed; } } void SdpBody::addRtpmap(int payloadType, const char* mimeSubtype, int sampleRate, int numChannels) { UtlString fieldValue("rtpmap:"); char buffer[256]; sprintf(buffer, "%d %s/%d", payloadType, mimeSubtype, sampleRate); fieldValue.append(buffer); if(numChannels > 0) { sprintf(buffer, "/%d", numChannels); fieldValue.append(buffer); } // Add the "a" field addValue("a", fieldValue.data()); } void SdpBody::addSrtpCryptoField(SdpSrtpParameters& params) { UtlString fieldValue("crypto:1 "); switch (params.cipherType) { case AES_CM_128_HMAC_SHA1_80: fieldValue.append("AES_CM_128_HMAC_SHA1_80 "); break; case AES_CM_128_HMAC_SHA1_32: fieldValue.append("AES_CM_128_HMAC_SHA1_32 "); break; case F8_128_HMAC_SHA1_80: fieldValue.append("F8_128_HMAC_SHA1_80 "); break; default: break; } fieldValue.append("inline:"); // Base64-encode key string UtlString base64Key; NetBase64Codec::encode(SRTP_KEY_LENGTH, (char*)params.masterKey, base64Key); // Remove padding while (base64Key(base64Key.length()-1) == '=') { base64Key = base64Key(0, base64Key.length()-1); } fieldValue.append(base64Key); if (!(params.securityLevel & SRTP_ENCRYPTION)) { fieldValue.append(" UNENCRYPTED_SRTP"); } if (!(params.securityLevel & SRTP_AUTHENTICATION)) { fieldValue.append(" UNAUTHENTICATED_SRTP"); } // Add the "a" field for the crypto attribute addValue("a", fieldValue.data()); } void SdpBody::addFormatParameters(int payloadType, const char* formatParameters) { // Build "a" field: // "a=fmtp " UtlString fieldValue("fmtp:"); char buffer[100]; sprintf(buffer, "%d ", payloadType); fieldValue.append(buffer); fieldValue.append(formatParameters); // Add the "a" field addValue("a", fieldValue.data()); } void SdpBody::addPtime(int pTime) { // Build "a" field for ptime" // a=ptime: UtlString fieldValue("ptime:"); char buffer[100]; sprintf(buffer, "%d", pTime); fieldValue.append(buffer); // Add the "a" field addValue("a", fieldValue); } void SdpBody::addCandidateAttribute(int candidateId, const char* transportId, const char* transportType, uint64_t qValue, const char* candidateIp, int candidatePort) { UtlString attributeData ; char buffer[64] ; attributeData.append("candidate:") ; sprintf(buffer, "%d", candidateId) ; attributeData.append(buffer) ; attributeData.append(" ") ; attributeData.append(transportId) ; attributeData.append(" ") ; attributeData.append(transportType) ; attributeData.append(" ") ; sprintf(buffer, "%" FORMAT_INTLL "u", qValue) ; attributeData.append(buffer) ; attributeData.append(" ") ; attributeData.append(candidateIp) ; attributeData.append(" ") ; sprintf(buffer, "%d", candidatePort) ; attributeData.append(buffer) ; addValue("a", attributeData) ; } UtlBoolean SdpBody::getCandidateAttribute(int mediaIndex, int candidateIndex, int& rCandidateId, UtlString& rTransportId, UtlString& rTransportType, uint64_t& rQvalue, UtlString& rCandidateIp, int& rCandidatePort) const { UtlBoolean found = FALSE; UtlSListIterator iterator(*sdpFields); NameValuePair* nv = NULL; int aFieldIndex = 0; const char* value; UtlString aFieldMatch("a"); UtlString aFieldType ; nv = positionFieldInstance(mediaIndex, &iterator, "m"); if(nv) { while ((nv = findFieldNameBefore(&iterator, aFieldMatch, "m"))) { value = nv->getValue(); // Verify this is an candidate "a" record UtlTokenizer tokenizer(value) ; if (tokenizer.next(aFieldType, ":")) { aFieldType.toLower() ; aFieldType.strip(UtlString::both, ' ') ; if(aFieldType.compareTo("candidate", UtlString::ignoreCase) == 0) { if (aFieldIndex == candidateIndex) { UtlString tmpCandidateId ; UtlString tmpQvalue ; UtlString tmpCandidatePort ; if ( tokenizer.next(tmpCandidateId, " \t") && tokenizer.next(rTransportId, " \t") && tokenizer.next(rTransportType, " \t") && tokenizer.next(tmpQvalue, " \t") && tokenizer.next(rCandidateIp, " \t") && tokenizer.next(tmpCandidatePort, " \t")) { // Strip leading : from id -- is this a UtlTokenizer Bug?? tmpCandidateId.strip(UtlString::leading, ':') ; rCandidateId = atoi(tmpCandidateId) ; rQvalue = UtlLongLongInt::stringToLongLong(tmpQvalue) ; rCandidatePort = atoi(tmpCandidatePort) ; found = TRUE; break; } } aFieldIndex++ ; } } } } return(found) ; } UtlBoolean SdpBody::getCandidateAttributes(const char* szMimeType, int nMaxAddresses, int candidateIds[], UtlString transportIds[], UtlString transportTypes[], uint64_t qvalues[], UtlString candidateIps[], int candidatePorts[], int& nActualAddresses) const { int mediaIndex = findMediaType(szMimeType, 0) ; return getCandidateAttributes(mediaIndex, nMaxAddresses, candidateIds, transportIds, transportTypes, qvalues, candidateIps, candidatePorts, nActualAddresses); } UtlBoolean SdpBody::getCandidateAttributes(int mediaIndex, int nMaxAddresses, int candidateIds[], UtlString transportIds[], UtlString transportTypes[], uint64_t qvalues[], UtlString candidateIps[], int candidatePorts[], int& nActualAddresses) const { nActualAddresses = 0 ; while (nActualAddresses < nMaxAddresses) { if (getCandidateAttribute(mediaIndex, nActualAddresses, candidateIds[nActualAddresses], transportIds[nActualAddresses], transportTypes[nActualAddresses], qvalues[nActualAddresses], candidateIps[nActualAddresses], candidatePorts[nActualAddresses])) { nActualAddresses++ ; } else { break ; } } return (nActualAddresses > 0) ; } void SdpBody::addMediaData(const char* mediaType, int portNumber, int portPairCount, const char* mediaTransportType, int numPayloadTypes, int payloadTypes[]) { #ifdef TEST_PRINT UtlString payloadString; for(int payloadIndex = 0; payloadIndex < numPayloadTypes; payloadIndex++) { if(payloadIndex > 0) { payloadString.append(", "); } payloadString.appendFormat("%d", payloadTypes); } OsSysLog::add(FAC_NET, PRI_DEBUG, "SdpBody::addMediaData mediaType: %s numPayloadTypes: %d {%s}", mediaType, numPayloadTypes, payloadString.data()); #endif UtlString value; char integerString[MAXIMUM_LONG_INT_CHARS]; int codecIndex; // Media type (i.e. audio, application or video) value.append(mediaType); value.append(SDP_SUBFIELD_SEPARATOR); // Port and optional number of port pairs sprintf(integerString, "%d", portNumber); value.append(integerString); if(portPairCount > 1) { sprintf(integerString, "%d", portPairCount); value.append("/"); value.append(integerString); } value.append(SDP_SUBFIELD_SEPARATOR); // Media transport type value.append(mediaTransportType); //value.append(SDP_SUBFIELD_SEPARATOR); for(codecIndex = 0; codecIndex < numPayloadTypes; codecIndex++) { // Media payload type (i.e. alaw, mlaw, etc.) sprintf(integerString, "%c%d", SDP_SUBFIELD_SEPARATOR, payloadTypes[codecIndex]); value.append(integerString); } // printf("adding m line: \"%s\"\n", value.data()); addValue("m", value.data()); } void SdpBody::addConnectionAddress(const char* ipAddress) { const char* networkType = SDP_NETWORK_TYPE; const char* addressType = SDP_IP4_ADDRESS_TYPE; addConnectionAddress(networkType, addressType, ipAddress); } void SdpBody::addConnectionAddress(const char* networkType, const char* addressType, const char* ipAddress) { UtlString value; value.append(networkType); value.append(SDP_SUBFIELD_SEPARATOR); value.append(addressType); value.append(SDP_SUBFIELD_SEPARATOR); value.append(ipAddress); addValue("c", value.data()); } void SdpBody::setConnectionAddress(const char* ipAddress) { const char* networkType = SDP_NETWORK_TYPE; const char* addressType = SDP_IP4_ADDRESS_TYPE; setConnectionAddress(networkType, addressType, ipAddress); } void SdpBody::setConnectionAddress(const char* networkType, const char* addressType, const char* ipAddress) { UtlString value; value.append(networkType); value.append(SDP_SUBFIELD_SEPARATOR); value.append(addressType); value.append(SDP_SUBFIELD_SEPARATOR); value.append(ipAddress); setValue("c", value.data()); } void SdpBody::addValue(const char* name, const char* value, int fieldIndex) { NameValuePair* nv = new NameValuePair(name, value); if(-1 == fieldIndex) { sdpFields->append(nv); } else { sdpFields->insertAt(fieldIndex, nv); } } void SdpBody::addEpochTime(unsigned long epochStartTime, unsigned long epochEndTime) { epochStartTime += NTP_TO_EPOCH_DELTA; if(epochEndTime != 0) // zero means unbounded in sdp, so don't convert it { epochEndTime += NTP_TO_EPOCH_DELTA; } addNtpTime(epochStartTime, epochEndTime); } void SdpBody::addNtpTime(unsigned long ntpStartTime, unsigned long ntpEndTime) { char integerString[MAXIMUM_LONG_INT_CHARS]; UtlString value; sprintf(integerString, "%lu", ntpStartTime); value.append(integerString); value.append(SDP_SUBFIELD_SEPARATOR); sprintf(integerString, "%lu", ntpEndTime); value.append(integerString); size_t timeLocation = findFirstOf("zkam"); addValue("t", value.data(), timeLocation); } void SdpBody::setOriginator(const char* userId, int sessionId, int sessionVersion, const char* address) { char integerString[MAXIMUM_LONG_INT_CHARS]; UtlString value; const char* networkType = SDP_NETWORK_TYPE; const char* addressType = SDP_IP4_ADDRESS_TYPE; //o=
// o=mhandley 2890844526 2890842807 IN IP4 126.16.64.4 value.append(userId); value.append(SDP_SUBFIELD_SEPARATOR); sprintf(integerString, "%d", sessionId); value.append(integerString); value.append(SDP_SUBFIELD_SEPARATOR); sprintf(integerString, "%d", sessionVersion); value.append(integerString); value.append(SDP_SUBFIELD_SEPARATOR); value.append(networkType); value.append(SDP_SUBFIELD_SEPARATOR); value.append(addressType); value.append(SDP_SUBFIELD_SEPARATOR); value.append(address); setValue("o", value.data()); } int SdpBody::getLength() const { UtlSListIterator iterator(*sdpFields); NameValuePair* nv = NULL; const char* value; int length = 0; while((nv = static_cast(iterator()))) { value = nv->getValue(); if(value) { length += ( nv->length() + 3 // SDP_NAME_VALUE_DELIMITOR + CARRIAGE_RETURN_NEWLINE + strlen(value) ); } else if (!isOptionalField(nv->data())) { // not optional, so append it even if empty length += ( nv->length() + 3 // SDP_NAME_VALUE_DELIMITOR + CARRIAGE_RETURN_NEWLINE ); } } return(length); } void SdpBody::getBytes(const char** bytes, int* length) const { // This version of getBytes exists so that a caller who is // calling this method through an HttpBody will get the right // thing - we fill in the mBody string and then return that. UtlString tempBody; getBytes( &tempBody, length ); ((SdpBody*)this)->mBody = tempBody.data(); *bytes = mBody.data(); } void SdpBody::getBytes(UtlString* bytes, int* length) const { UtlSListIterator iterator(*sdpFields); NameValuePair* nv = NULL; const char* value; bytes->remove(0); while((nv = static_cast(iterator()))) { value = nv->getValue(); if(value) { bytes->append(nv->data()); bytes->append(SDP_NAME_VALUE_DELIMITOR); bytes->append(value); bytes->append(CARRIAGE_RETURN_NEWLINE); } else if (!isOptionalField(nv->data())) { // not optional, so append it even if empty bytes->append(nv->data()); bytes->append(SDP_NAME_VALUE_DELIMITOR); bytes->append(CARRIAGE_RETURN_NEWLINE); } } *length = bytes->length(); } int SdpBody::getFieldCount() const { return(sdpFields->entries()); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ bool SdpBody::isOptionalField(const char* name) const { const UtlString OptionalStandardFields("iuepcbzkar"); return OptionalStandardFields.index(name) != UtlString::UTLSTRING_NOT_FOUND; } size_t SdpBody::findFirstOf( const char* headers ) { size_t first = UTL_NOT_FOUND; size_t found; size_t lookingFor; size_t headersToTry; for ( lookingFor = 0, headersToTry = strlen(headers); lookingFor < headersToTry; lookingFor++ ) { char thisHeader[2]; thisHeader[0] = headers[lookingFor]; thisHeader[1] = '\0'; NameValuePair header(thisHeader,NULL); found = sdpFields->index(&header); if ( UTL_NOT_FOUND != found ) { first = (UTL_NOT_FOUND == first) ? found : first > found ? found : first; } } return first; } NameValuePair* SdpBody::positionFieldInstance(int fieldInstanceIndex, UtlSListIterator* iter, const char* fieldName) { UtlContainable* nv = NULL; if ( fieldInstanceIndex >= 0 ) { NameValuePair fieldNV(fieldName); iter->reset(); int index = 0; nv = iter->findNext(&fieldNV); while(nv && index < fieldInstanceIndex) { nv = iter->findNext(&fieldNV); index++; } } return((NameValuePair*) nv); } NameValuePair* SdpBody::findFieldNameBefore(UtlSListIterator* iter, const char* targetFieldName, const char* beforeFieldName) { // Find a default address if one exist NameValuePair* nv = (NameValuePair*) (*iter)(); while(nv) { // Target field not found before beforeFieldName if(strcmp(nv->data(), beforeFieldName) == 0) { nv = NULL; break; } // Target field found else if(strcmp(nv->data(), targetFieldName) == 0) { break; } nv = (NameValuePair*) (*iter)(); } return(nv); } UtlBoolean SdpBody::findValueInField(const char* pField, const char* pvalue) const { UtlSListIterator iterator(*sdpFields); NameValuePair* nv = positionFieldInstance(0, &iterator, "m"); UtlString aFieldMatch(pField); while((nv = (NameValuePair*) iterator.findNext(&aFieldMatch)) != NULL) { if ( strcmp(nv->getValue(), pvalue) == 0 ) return TRUE; } return FALSE; } const bool SdpBody::isTransportAvailable(const OsSocket::IpProtocolSocketType protocol, const SIPX_MEDIA_TYPE mediaType) const { bool bIsAvailable = false; int mediaIndex = 0; UtlString sdpMediaType; int mediaPort; int mediaPortPairs; UtlString mediaTransportType; int maxPayloadTypes = 32; int numPayloadTypes; int payloadTypes[32]; UtlBoolean bFound = true; while ((protocol == OsSocket::UDP || protocol == OsSocket::TCP) && bFound) { bFound = getMediaData(mediaIndex, &sdpMediaType, &mediaPort, &mediaPortPairs, &mediaTransportType, maxPayloadTypes, &numPayloadTypes, payloadTypes); if (bFound) { bool bMediaTypeMatch = false; bool bTransportTypeMatch = false; if (protocol == OsSocket::UDP && mediaTransportType.compareTo(SDP_RTP_MEDIA_TRANSPORT_TYPE, UtlString::ignoreCase) == 0) { bTransportTypeMatch = true; } if (protocol == OsSocket::TCP && mediaTransportType.compareTo(SDP_RTP_TCP_MEDIA_TRANSPORT_TYPE, UtlString::ignoreCase) == 0) { bTransportTypeMatch = true; } if (mediaType == MEDIA_TYPE_AUDIO && sdpMediaType.compareTo(SDP_AUDIO_MEDIA_TYPE, UtlString::ignoreCase) == 0) { bMediaTypeMatch = true; } if (mediaType == MEDIA_TYPE_VIDEO && sdpMediaType.compareTo(SDP_VIDEO_MEDIA_TYPE, UtlString::ignoreCase) == 0) { bMediaTypeMatch = true; } if (bMediaTypeMatch && bTransportTypeMatch) { bIsAvailable = true; break; } } mediaIndex++; } return bIsAvailable; } // set all media attributes to either a=setup:actpass, a=setup:active, or a=setup:passive void SdpBody::setRtpTcpRole(RtpTcpRoles role) { UtlString sRole; if ((role & RTP_TCP_ROLE_ACTPASS) == RTP_TCP_ROLE_ACTPASS) { sRole = "actpass"; } else if ((role & RTP_TCP_ROLE_ACTIVE) == RTP_TCP_ROLE_ACTIVE) { sRole = "active"; } else { sRole = "passive"; } UtlSListIterator iterator((UtlSList&)(*(sdpFields))); NameValuePair* headerField; UtlString value; while((headerField = (NameValuePair*) iterator())) { value = headerField->getValue(); if (value.contains("setup:")) { value = "setup:" + sRole; headerField->setValue(value); } } } UtlString SdpBody::getRtpTcpRole() const { UtlSListIterator iterator((UtlSList&)(*(sdpFields))); UtlString sRole; UtlString value; NameValuePair* headerField; while((headerField = (NameValuePair*) iterator())) { value = headerField->getValue(); if (value.contains("setup:")) { sRole = value.data() + 6; break; } } return sRole; } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SdpHelper.cpp0000644000175000017500000004130312205613256023565 0ustar00danieldaniel00000000000000// // Copyright (C) 2008-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2007 Plantronics // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007-2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Scott Godin (sgodin AT SipSpectrum DOT com) #ifndef EXCLUDE_SIPX_SDP_HELPER // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define MAXIMUM_MEDIA_TYPES 30 // should match values from SdpBody.cpp #define MAXIMUM_VIDEO_SIZES 6 #define MAXIMUM_CANDIDATES 20 // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ SdpMediaLine::SdpCryptoSuiteType SdpHelper::convertCryptoSuiteType(int sdpBodyType) { switch(sdpBodyType) { case AES_CM_128_HMAC_SHA1_80: return SdpMediaLine::CRYPTO_SUITE_TYPE_AES_CM_128_HMAC_SHA1_80; case AES_CM_128_HMAC_SHA1_32: return SdpMediaLine::CRYPTO_SUITE_TYPE_AES_CM_128_HMAC_SHA1_32; case F8_128_HMAC_SHA1_80: return SdpMediaLine::CRYPTO_SUITE_TYPE_F8_128_HMAC_SHA1_80; default: return SdpMediaLine::CRYPTO_SUITE_TYPE_NONE; } } Sdp* SdpHelper::createSdpFromSdpBody(const SdpBody& sdpBody, const SdpCodecList* codecFactory) { bool rtcpEnabled = true; Sdp* sdp = new Sdp(); // !slg! Note: the current implementation of SdpBody does not allow access to all of the data in the SDP body // in the future codec similar to that present in SdpHelperResip should be implemented // Get Bandwidth - !slg! Current SdpBody implementation does not support getting non CT bandwidths or to get medialine specific bandwidths int bandwidth; if(sdpBody.getBandwidthField(bandwidth)) { sdp->addBandwidth(Sdp::BANDWIDTH_TYPE_CT, (unsigned int) bandwidth); } // Iterate through the m= lines int i; for(i = 0; i < sdpBody.getMediaSetCount(); i++) { bool rtcpEnabledForMedia = rtcpEnabled; // Default to Session setting SdpMediaLine* mediaLine = new SdpMediaLine(); // Get data out of SdpBody and stuff it into SdpMediaLine for the i'th // media line in the SdpBody. getMediaLine(sdpBody, i, *mediaLine, codecFactory); // Add the media line to the sdp sdp->addMediaLine(mediaLine); } return sdp; } UtlBoolean SdpHelper::getMediaLine(const SdpBody& sdpBody, int mediaLineIndex, SdpMediaLine& mediaLine, const SdpCodecList* codecFactory) { UtlString utlString; // Temp String UtlString mediaType; int mediaPort=0; int mediaNumPorts=0; UtlString mediaTransportType; int numPayloadTypes=0; int payloadTypes[MAXIMUM_MEDIA_TYPES]; UtlBoolean foundMline = sdpBody.getMediaData(mediaLineIndex, &mediaType, &mediaPort, &mediaNumPorts, &mediaTransportType, MAXIMUM_MEDIA_TYPES, &numPayloadTypes, payloadTypes); mediaLine.setMediaType(SdpMediaLine::getMediaTypeFromString(mediaType.data())); mediaLine.setTransportProtocolType(SdpMediaLine::getTransportProtocolTypeFromString(mediaTransportType.data())); // Get PTime for media line to assign to codecs int mediaLinePtime=0; sdpBody.getPtime(mediaLineIndex, mediaLinePtime); // Iterate Through Codecs { int typeIndex; for(typeIndex = 0; typeIndex < numPayloadTypes; typeIndex++) { UtlString mimeSubType; UtlString payloadFormat; int sampleRate = 0; int numChannels = 0; const SdpCodec* matchingCodec = NULL; int ptime; int numVideoSizes = MAXIMUM_VIDEO_SIZES; int videoSizes[MAXIMUM_VIDEO_SIZES]; sdpBody.getPayloadFormat(mediaLineIndex, payloadTypes[typeIndex], payloadFormat); SdpCodec::getVideoSizes(payloadFormat, MAXIMUM_VIDEO_SIZES, numVideoSizes, videoSizes); if(!sdpBody.getPayloadRtpMap(mediaLineIndex, payloadTypes[typeIndex], mimeSubType, sampleRate, numChannels)) { if(codecFactory == NULL) { // static codecs as defined in RFC 3551 switch(payloadTypes[typeIndex]) { case 0: mimeSubType = "PCMU"; sampleRate = 8000; break; case 3: mimeSubType = "GSM"; sampleRate = 8000; break; case 4: mimeSubType = "G723"; sampleRate = 8000; ptime = 30; break; case 5: mimeSubType = "DVI4"; sampleRate = 8000; break; case 6: mimeSubType = "DVI4"; sampleRate = 16000; break; case 7: mimeSubType = "LPC"; sampleRate = 8000; break; case 8: mimeSubType = "PCMA"; sampleRate = 8000; break; case 9: mimeSubType = "G722"; sampleRate = 16000; break; case 10: mimeSubType = "L16"; sampleRate = 44100; numChannels = 2; break; case 11: mimeSubType = "L16"; sampleRate = 44100; break; case 12: mimeSubType = "QCELP"; sampleRate = 8000; break; case 13: mimeSubType = "CN"; sampleRate = 8000; break; case 14: mimeSubType = "MPA"; sampleRate = 90000; break; case 15: mimeSubType = "G728"; sampleRate = 8000; break; case 16: mimeSubType = "DVI4"; sampleRate = 11025; break; case 17: mimeSubType = "DVI4"; sampleRate = 22050; break; case 18: mimeSubType = "G729"; sampleRate = 8000; break; case 25: mimeSubType = "CelB"; sampleRate = 90000; break; case 26: mimeSubType = "JPEG"; sampleRate = 90000; break; case 28: mimeSubType = "nv"; sampleRate = 90000; break; case 31: mimeSubType = "H261"; sampleRate = 90000; break; case 32: mimeSubType = "MPV"; sampleRate = 90000; break; case 33: mimeSubType = "MP2T"; sampleRate = 90000; break; case 34: mimeSubType = "H263"; sampleRate = 90000; break; } } else { if(payloadTypes[typeIndex] <= SdpCodec::SDP_CODEC_MAXIMUM_STATIC_CODEC) { matchingCodec = codecFactory->getCodecByType(payloadTypes[typeIndex]); } } } else { // TODO: A lot of this should probably go in a codec factory method // Workaround RFC bug with G.722 samplerate. // Read RFC 3551 Section 4.5.2 "G722" for details. if (mimeSubType.compareTo(MIME_SUBTYPE_G722, UtlString::ignoreCase) == 0) { sampleRate = 16000; } else if(mimeSubType.compareTo(MIME_SUBTYPE_ILBC, UtlString::ignoreCase) == 0) { // TODO: move this to SdpCodec /* if(fmtpMode == 0) { fmtpMode = 20; } if(fmtpMode == 20 || fmtpMode == 30) { ptime = fmtpMode; } else if(codecFactory) { // Other iLBC framing not supported, prevent match mimeSubType = ""; } */ } if(numChannels == -1) // Note: SdpBody returns -1 if no numChannels is specified - default should be one { numChannels = 1; } if(codecFactory) { // Find a match in the factory to the given codec parameters matchingCodec = codecFactory->getCodec(mediaType.data(), mimeSubType.data(), sampleRate, numChannels, payloadFormat); } } if(codecFactory == NULL) { SdpCodec* codec = new SdpCodec(payloadTypes[typeIndex], mediaType.data(), mimeSubType.data(), sampleRate, ptime * 1000, numChannels, payloadFormat); mediaLine.addCodec(codec); } else { if(matchingCodec) { SdpCodec* codecToAdd = new SdpCodec(*matchingCodec); // Need to use payload ID of remote side, not that set in codec factory codecToAdd->setCodecPayloadFormat(payloadTypes[typeIndex]); codecToAdd->setPacketSize((ptime ? ptime : mediaLinePtime) * 1000); mediaLine.addCodec(codecToAdd); } } } } // Add Connection UtlString mediaAddress; sdpBody.getMediaAddress(mediaLineIndex, &mediaAddress); // TODO: //sdpBody.getMediaNetworkType(mediaLineIndex, &utlString); !slg! not implemented in SdpBody //Sdp::SdpAddressType addrType = Sdp::getAddressTypeFromString(utlString.data()); Sdp::SdpAddressType addrType = Sdp::ADDRESS_TYPE_IP4; if(mediaPort != 0) { int j; for(j = 0; j < mediaNumPorts; j++) { mediaLine.addConnection(Sdp::NET_TYPE_IN, addrType, mediaAddress.data(), mediaPort + (2 * j)); } } // Add Rtcp Connection int rtcpPort = 0; sdpBody.getMediaRtcpPort(mediaLineIndex, &rtcpPort); if(rtcpPort != 0) { int j; for(j = 0; j < mediaNumPorts; j++) { mediaLine.addRtcpConnection(Sdp::NET_TYPE_IN, addrType, mediaAddress.data(), rtcpPort + (2 * j)); } } // Set direction, a=sendrecv, a=sendonly, a=recvonly, a=inactive // !slg! Note: SdpBody does not currenlty support reading attributes from a particular media line SdpMediaLine::SdpDirectionType direction = SdpMediaLine::DIRECTION_TYPE_SENDRECV; // default if(sdpBody.findValueInField("a", "sendrecv")) { direction = SdpMediaLine::DIRECTION_TYPE_SENDRECV; } else if(sdpBody.findValueInField("a", "sendonly")) { direction = SdpMediaLine::DIRECTION_TYPE_SENDONLY; } else if(sdpBody.findValueInField("a", "recvonly")) { direction = SdpMediaLine::DIRECTION_TYPE_RECVONLY; } else if(sdpBody.findValueInField("a", "inactive")) { direction = SdpMediaLine::DIRECTION_TYPE_INACTIVE; } mediaLine.setDirection(direction); UtlString trackId; if(sdpBody.getControlTrackId(mediaLineIndex, trackId)) { mediaLine.setControlTrackId(trackId); } int frameRate; if(sdpBody.getFramerateField(mediaLineIndex, frameRate)) { mediaLine.setFrameRate((unsigned int)frameRate); } // TCP Setup Attribute - !slg! SdpBody currently does not support getting this for a particular media line mediaLine.setTcpSetupAttribute(SdpMediaLine::getTcpSetupAttributeFromString(sdpBody.getRtpTcpRole().data())); // Get the SRTP Crypto Settings SdpSrtpParameters srtpParameters; int index=1; while(sdpBody.getSrtpCryptoField(mediaLineIndex, index, srtpParameters)) { SdpMediaLine::SdpCrypto* sdpCrypto = new SdpMediaLine::SdpCrypto; sdpCrypto->setTag(index); sdpCrypto->setSuite(convertCryptoSuiteType(srtpParameters.cipherType)); UtlString encodedKey; // Note: Key returned from SdpBody is Base64 decoded, but Sdp container expects encoded key NetBase64Codec::encode(sizeof(srtpParameters.masterKey)-1, (const char*)srtpParameters.masterKey, encodedKey); sdpCrypto->addCryptoKeyParam(SdpMediaLine::CRYPTO_KEY_METHOD_INLINE, encodedKey.data()); sdpCrypto->setEncryptedSrtp((srtpParameters.securityLevel & SRTP_ENCRYPTION) != 0); sdpCrypto->setAuthenticatedSrtp((srtpParameters.securityLevel & SRTP_AUTHENTICATION) != 0); mediaLine.addCryptoSettings(sdpCrypto); index++; } // Get Ice Candidate(s) - !slg! note: ice candidate support in SdpBody is old and should be updated - at which time the following code // should also be updated int candidateIds[MAXIMUM_CANDIDATES]; UtlString transportIds[MAXIMUM_CANDIDATES]; UtlString transportTypes[MAXIMUM_CANDIDATES]; uint64_t qvalues[MAXIMUM_CANDIDATES]; UtlString candidateIps[MAXIMUM_CANDIDATES]; int candidatePorts[MAXIMUM_CANDIDATES]; int numCandidates; if(sdpBody.getCandidateAttributes(mediaLineIndex, MAXIMUM_CANDIDATES, candidateIds, transportIds, transportTypes, qvalues, candidateIps, candidatePorts, numCandidates)) { UtlString userFrag; // !slg! Currently no way to retrieve these UtlString password; // TODO: //mediaLine.setIceUserFrag(userFrag.data()); //mediaLine.setIcePassword(password.data()); int idx; for(idx = 0; idx < numCandidates; idx++) { mediaLine.addCandidate(transportIds[idx].data(), candidateIds[idx], SdpCandidate::getCandidateTransportTypeFromString(transportTypes[idx].data()), qvalues[idx], candidateIps[idx].data(), candidatePorts[idx], SdpCandidate::CANDIDATE_TYPE_NONE); } } return(foundMline); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ #endif sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipClient.cpp0000644000175000017500000007503312205613256023600 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include //#define TEST_PRINT // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include #ifdef SIP_TLS #include "os/OsTLSConnectionSocket.h" #include "os/OsTLSClientConnectionSocket.h" #endif #define SIP_DEFAULT_RTT 500 // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // All requests must contain at least 72 characters: /* X Y SIP/2.0 \n\r i: A\n\r f: B\n\r t: C\n\r c: 1\n\r v: SIP/2.0/UDP D\n\r l: 0 \n\r \n\r */ // However to be tolerant of malformed messages we allow smaller: #define MINIMUM_SIP_MESSAGE_SIZE 30 #define MAX_UDP_PACKET_SIZE (1024 * 64) // STATIC VARIABLE INITIALIZATIONS #define TEST_PRINT //#define LOG_TIME /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipClient::SipClient(OsSocket* socket) : OsTask("SipClient-%d"), clientSocket(socket), mSocketType(socket ? socket->getIpProtocol() : OsSocket::UNKNOWN), sipUserAgent(NULL), mRemoteViaPort(PORT_NONE), mRemoteReceivedPort(PORT_NONE), mSocketLock(OsBSem::Q_FIFO, OsBSem::FULL), mFirstResendTimeoutMs(SIP_DEFAULT_RTT * 4), // for first transaction time out mInUseForWrite(0), mWaitingList(NULL), mbSharedSocket(FALSE) { touch(); if(clientSocket) { clientSocket->getRemoteHostName(&mRemoteHostName); clientSocket->getRemoteHostIp(&mRemoteSocketAddress, &mRemoteHostPort); #ifdef TEST_PRINT UtlString remoteSocketHost; socket->getRemoteHostName(&remoteSocketHost); osPrintf("SipClient created with socket descriptor: %d host: %s port: %d\n", socket->getSocketDescriptor(), remoteSocketHost.data(), socket->getRemoteHostPort()); #endif } } // Copy constructor SipClient::SipClient(const SipClient& rSipClient) : mSocketLock(OsBSem::Q_FIFO, OsBSem::FULL) { } // Destructor SipClient::~SipClient() { #ifdef TEST_PRINT osPrintf("SipClient::~SipClient Start\n"); #endif // Do not delete the event listers they are not subordinate // Free the socket if(clientSocket) { // Close the socket to unblock the run method // in case it is blocked in a waitForReadyToRead or // a read on the clientSocket. This should also // cause the run method to exit. #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient::~SipClient %p socket %p closing %s socket", this, clientSocket, OsSocket::ipProtocolString(mSocketType)); osPrintf("SipClient::~SipClient closing socket\n"); #endif if (!mbSharedSocket) { clientSocket->close(); } // Signal everybody to stop waiting for this SipClient signalAllAvailableForWrite(); // Wait for the task to exit so that it does not // reference the socket or other members after they // get deleted. if(isStarted() || isShuttingDown()) { #ifdef TEST_PRINT osPrintf("SipClient::~SipClient waitUntilShutDown\n"); #endif waitUntilShutDown(); } #ifdef TEST_PRINT osPrintf("SipClient::~SipClient shutDown\n"); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient::~SipClient %p socket %p deleting socket", this, clientSocket); #endif if (!mbSharedSocket) { delete clientSocket; } clientSocket = NULL; } else if(isStarted() || isShuttingDown()) { #ifdef TEST_PRINT osPrintf("SipClient::~SipClient Wait until shutdown\n"); #endif // It should not get here but just in case waitUntilShutDown(); } if(mWaitingList) { int numEvents = mWaitingList->entries(); if(numEvents) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipClient::~SipClient has %d waiting events", numEvents); } delete mWaitingList; mWaitingList = NULL; } // Do not delete the event listers they are not subordinate } /* ============================ MANIPULATORS ============================== */ int SipClient::run(void* runArg) { int bytesRead; UtlString buffer; SipMessage* message = NULL; UtlString remoteHostName; UtlString viaProtocol; UtlString fromIpAddress; int fromPort; int numFailures = 0; UtlBoolean internalShutdown = FALSE; UtlBoolean readAMessage = FALSE; int readBufferSize = HTTP_DEFAULT_SOCKET_BUFFER_SIZE; if(mSocketType == OsSocket::UDP) { readBufferSize = MAX_UDP_PACKET_SIZE; } while( !isShuttingDown() && !internalShutdown && clientSocket && clientSocket->isOk()) { if(clientSocket) { #ifdef LOG_TIME OsTimeLog eventTimes; #endif message = new SipMessage(); // first, if this is a TLS socket, make sure the handshake is complete #ifdef SIP_TLS OsTLSClientConnectionSocket* pSslSocket = dynamic_cast (clientSocket); if (pSslSocket) { pSslSocket->waitForHandshake(-1); } #endif // Block and wait for the socket to be ready to read // clientSocket shouldn't be null // in this case some sort of race with the destructor. This should // not actually ever happen. #ifdef TEST_SOCKET OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient::run readAMessage = %d, " "buffer.length() = %d, clientSocket = %p", readAMessage, buffer.length(), clientSocket); #endif if(clientSocket && ((readAMessage && buffer.length() >= MINIMUM_SIP_MESSAGE_SIZE) || waitForReadyToRead())) { #ifdef LOG_TIME eventTimes.addEvent("locking"); #endif // Lock to prevent multi-treaded read or write mSocketLock.acquire(); #ifdef LOG_TIME eventTimes.addEvent("locked"); #endif // This second check is in case there is // some sort of race with the destructor. This should // not actually ever happen. if(clientSocket) { if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient::run %p socket %p host: %s " "sock addr: %s via addr: %s rcv addr: %s " "sock type: %s read ready %s, socket: %s numFailures: %d", this, clientSocket, mRemoteHostName.data(), mRemoteSocketAddress.data(), mRemoteViaAddress.data(), mReceivedAddress.data(), OsSocket::ipProtocolString(clientSocket->getIpProtocol()), isReadyToRead() ? "READY" : "NOT READY", clientSocket->isOk() ? "OK" : "NOT OK", numFailures ); } #ifdef LOG_TIME eventTimes.addEvent("reading"); #endif message->setFromThisSide(false); bytesRead = message->read(clientSocket, readBufferSize, &buffer); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient::run HttpMessage::read returned: %d message size(bytesRead)", bytesRead); } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipClient::run client 0%p socket attempt to read NULL", this); bytesRead = 0; } mSocketLock.release(); #ifdef LOG_TIME eventTimes.addEvent("released"); #endif message->replaceShortFieldNames(); message->getSendAddress(&fromIpAddress, &fromPort); # if 0 // turn on to check socket address problems OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient::run new msg got addr %s:%d", fromIpAddress.data(), fromPort); # endif } else { bytesRead = 0; if(clientSocket == NULL) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipClient::run client 0%p socket is NULL", this); } } if(clientSocket // This second check is in case there is // some sort of race with the destructor. This should // not actually ever happen. && (bytesRead < 0 || // Framed sockets (e.g. UDP) can get zero byte reads when STUN or TURN packets come in, ignore these // Not sure why non-Framed (e.g. TCP) sockets get into a mode of reading zero bytes and yet poll // says there is no error and the socket is open, probably due to some connection error. Need to figure this out // at some point and trap the error. (!clientSocket->isFramed(clientSocket->getIpProtocol()) && bytesRead == 0) || !clientSocket->isOk())) { numFailures++; readAMessage = FALSE; if(numFailures > 12 || !clientSocket->isOk()) { // The socket has gone sour close down the client remoteHostName.remove(0); clientSocket->getRemoteHostName(&remoteHostName); OsSysLog::add(FAC_SIP, PRI_DEBUG, "Shutting down client: %s due to failed socket (%d)? bytes: %d isOk: %s", remoteHostName.data(), clientSocket->getSocketDescriptor(), bytesRead, (clientSocket->isOk() ? "OK" : "NO") ); clientSocket->close(); internalShutdown = TRUE; } } else if(bytesRead > 0) { numFailures = 0; touch(); #ifdef TEST_PRINT osPrintf("Read SIP message:\n%s====================END====================\n", buffer.data()); #endif if(sipUserAgent) { UtlString socketRemoteHost; UtlString lastAddress; UtlString lastProtocol; int lastPort; // Only bother processing if the logs are enabled if (sipUserAgent->isMessageLoggingEnabled() || OsSysLog::willLog(FAC_SIP_INCOMING, PRI_INFO)) { UtlString logMessage; logMessage.append("Read SIP message:\n"); logMessage.append("----Remote Host:"); logMessage.append(fromIpAddress); logMessage.append("---- Port: "); char buff[10]; sprintf(buff, "%d", !portIsValid(fromPort) ? 5060 : fromPort); logMessage.append(buff); logMessage.append("----\n"); logMessage.append(buffer.data(), bytesRead); UtlString messageString; logMessage.append(messageString); logMessage.append("====================END====================\n"); sipUserAgent->logMessage(logMessage.data(), logMessage.length()); OsSysLog::add(FAC_SIP_INCOMING, PRI_INFO, "%s", logMessage.data()); } #ifdef DEBUG_POLL_NO_BYTES OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient line: %d", __LINE__); #endif // Set the date field if not present long epochDate; if(!message->getDateField(&epochDate)) { message->setDateField(); } #ifdef DEBUG_POLL_NO_BYTES OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient line: %d", __LINE__); #endif message->setSendProtocol(mSocketType); message->setTransportTime(touchedTime); clientSocket->getRemoteHostIp(&socketRemoteHost); // Keep track of where this message came from message->setSendAddress(fromIpAddress.data(), fromPort); // Keep track of the interface on which this message was // received. message->setLocalIp(clientSocket->getLocalIp()); if(mReceivedAddress.isNull()) { mReceivedAddress = fromIpAddress; mRemoteReceivedPort = fromPort; } #ifdef DEBUG_POLL_NO_BYTES OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient line: %d", __LINE__); #endif // If this is a request if(!message->isResponse()) { int receivedPort; UtlBoolean receivedSet; UtlBoolean maddrSet; UtlBoolean receivedPortSet; // fill in 'received' and 'rport' in top via if needed. message->setReceivedViaParams(fromIpAddress, fromPort); // get the addresses from the topmost via. message->getLastVia(&lastAddress, &lastPort, &lastProtocol, &receivedPort, &receivedSet, &maddrSet, &receivedPortSet); if ( ( mSocketType == OsSocket::TCP || mSocketType == OsSocket::SSL_SOCKET ) && !receivedPortSet ) { // we can use this socket as if it were // connected to the port specified in the // via field mRemoteReceivedPort = lastPort; } // Keep track of the address the other // side said they sent from. Note, this cannot // be trusted unless this transaction is // authenticated if(mRemoteViaAddress.isNull()) { mRemoteViaAddress = lastAddress; mRemoteViaPort = portIsValid(lastPort) ? lastPort : 5060; } } // We read a whole message whether it is a valid one or // not does not matter readAMessage = TRUE; // Check that we have the minimum data to define a transaction UtlString callId; UtlString fromField; UtlString toField; message->getCallIdField(&callId); message->getFromField(&fromField); message->getToField(&toField); #ifdef DEBUG_POLL_NO_BYTES OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient line: %d", __LINE__); OsSysLog::flush(); #endif if(!( callId.isNull() || fromField.isNull() || toField.isNull())) { #ifdef DEBUG_POLL_NO_BYTES OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient line: %d", __LINE__); OsSysLog::flush(); #endif #ifdef LOG_TIME eventTimes.addEvent("dispatching"); #endif sipUserAgent->dispatch(message); #ifdef DEBUG_POLL_NO_BYTES OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient line: %d", __LINE__); OsSysLog::flush(); #endif #ifdef LOG_TIME eventTimes.addEvent("dispatched"); #endif message = NULL; // protect the dispatched message from deletion below } else { #ifdef DEBUG_POLL_NO_BYTES OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient line: %d", __LINE__); OsSysLog::flush(); #endif // Only bother processing if the logs are enabled if (sipUserAgent->isMessageLoggingEnabled()) { UtlString msgBytes; int msgLen; message->getBytes(&msgBytes, &msgLen); msgBytes.insert(0, "Received incomplete message (missing To, From or Call-Id header)\n"); msgBytes.append("++++++++++++++++++++END++++++++++++++++++++\n"); sipUserAgent->logMessage(msgBytes.data(), msgBytes.length()); } #ifdef DEBUG_POLL_NO_BYTES OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient line: %d", __LINE__); OsSysLog::flush(); #endif delete message; message = NULL; } } //if sipuseragent // Get rid of the consumed stuff in the buffer so it // contains only bytes which are part of the next message buffer.remove(0, bytesRead); if( mSocketType == OsSocket::UDP && buffer.length() ) { OsSysLog::add(FAC_SIP, // For UDP, this is an error, but not // for TCP or TLS. (clientSocket->getIpProtocol() == OsSocket::UDP) ? PRI_ERR : PRI_DEBUG, "SipClient::run buffer residual bytes: %"PRIuPTR"\n===>%s<===\n", buffer.length(), buffer.data()); } } #ifdef LOG_TIME UtlString timeString; eventTimes.getLogString(timeString); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient::run time log: %s", timeString.data()); #endif #ifdef DEBUG_POLL_NO_BYTES OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient line: %d", __LINE__); OsSysLog::flush(); #endif if(message) { delete message; } message = NULL; } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipClient::run client 0%p socket is NULL yielding", this); yield(); // I do not know why this yield is here } #ifdef DEBUG_POLL_NO_BYTES OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient line: %d", __LINE__); OsSysLog::flush(); #endif } // while this client is ok #ifdef DEBUG_POLL_NO_BYTES OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient line: %d", __LINE__); OsSysLog::flush(); #endif return(0); } // Test whether the socket is ready to read. (Does not block.) UtlBoolean SipClient::isReadyToRead() { return clientSocket->isReadyToRead(0); } // Wait until the socket is ready to read (or has an error). UtlBoolean SipClient::waitForReadyToRead() { return clientSocket->isReadyToRead(-1); } UtlBoolean SipClient::send(SipMessage* message) { #ifdef TEST_PRINT osPrintf("BEGIN SipClient::send\n"); #endif UtlBoolean sendOk = FALSE; UtlString viaProtocol; if(clientSocket) { if(!clientSocket->isOk()) { clientSocket->reconnect(); #ifdef TEST_SOCKET if(clientSocket) osPrintf("SipClient reconnected with socket descriptor: %d\n", reconnect->getSocketDescriptor()); #endif } else { #ifdef LOG_TIME OsTimeLog eventTimes; eventTimes.addEvent("wait to write"); #endif // Wait until the socket is ready to write if(clientSocket->isReadyToWrite(mFirstResendTimeoutMs)) { #ifdef LOG_TIME eventTimes.addEvent("wait to lock"); #endif //Lock to prevent multitreaded read or write mSocketLock.acquire(); #ifdef LOG_TIME eventTimes.addEvent("writing"); #endif sendOk = message->write(clientSocket); #ifdef LOG_TIME eventTimes.addEvent("releasing"); #endif mSocketLock.release(); #ifdef LOG_TIME eventTimes.addEvent("released"); UtlString timeString; eventTimes.getLogString(timeString); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient::send time log: %s", timeString.data()); #endif if(sendOk) { touch(); } } else { clientSocket->close(); } } } #ifdef TEST_PRINT osPrintf("END SipClient::send\n"); #endif return(sendOk); } UtlBoolean SipClient::sendTo(const SipMessage& message, const char* address, int port) { UtlBoolean sendOk = FALSE; UtlString viaProtocol; if(clientSocket) { switch (mSocketType) { case OsSocket::UDP: { UtlString buffer; int bufferLen; int bytesWritten; message.getBytes(&buffer, &bufferLen); // Wait until the socket is ready to write if(clientSocket->isReadyToWrite(mFirstResendTimeoutMs)) { //Lock to prevent multitreaded read or write mSocketLock.acquire(); bytesWritten = ((OsDatagramSocket*)clientSocket)-> write(buffer.data(), bufferLen, address, // PORT_NONE means use default. (port == PORT_NONE) ? SIP_PORT : port ); mSocketLock.release(); if(bufferLen == bytesWritten) { sendOk = TRUE; touch(); } else { sendOk = FALSE; } } } break; case OsSocket::TCP: case OsSocket::SSL_SOCKET: sendOk = send((SipMessage*) &message) ; break; default: OsSysLog::add(FAC_SIP, PRI_CRIT, "SipClient::sendTo called for invalid socket type %d", mSocketType ); sendOk = FALSE; } } else { OsSysLog::add(FAC_SIP, PRI_CRIT, "SipClient::sendTo called for client without socket" ); sendOk = FALSE; } return(sendOk); } // Assignment operator SipClient& SipClient::operator=(const SipClient& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } void SipClient::notifyWhenAvailableForWrite(OsEvent& availableEvent) { if(mWaitingList == NULL) { mWaitingList = new UtlSList(); } UtlVoidPtr* eventNode = new UtlVoidPtr((void*)&availableEvent); mWaitingList->append(eventNode); } void SipClient::signalNextAvailableForWrite() { if(mWaitingList) { #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient::signalNextAvailableForWrite %p", this); #endif // Remove the first event that is waiting for this transaction UtlVoidPtr* eventNode = (UtlVoidPtr*) mWaitingList->get(); if(eventNode) { OsEvent* waitingEvent = (OsEvent*) eventNode->getValue(); #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient::signalNextAvailableForWrite %p signaling: %p", this, waitingEvent); #endif if(waitingEvent) { // If the other side is done accessing the event // and has already signalled it, then we can delete // this. Otherwise the other side must do the delete. if(OS_ALREADY_SIGNALED == waitingEvent->signal(1)) { delete waitingEvent; waitingEvent = NULL; } } delete eventNode; eventNode = NULL; } } } void SipClient::signalAllAvailableForWrite() { if(mWaitingList) { #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient::signalAllAvailableForWrite %p", this); #endif // Remove the first event that is waiting for this transaction UtlVoidPtr* eventNode = NULL; while((eventNode = (UtlVoidPtr*) mWaitingList->get())) { if(eventNode) { OsEvent* waitingEvent = (OsEvent*) eventNode->getValue(); #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient::signalAllAvailableForWrite %p signaling: %p", this, waitingEvent); #endif if(waitingEvent) { // If the other side is done accessing the event // and has already signalled it, then we can delete // this. Otherwise the other side must do the delete. if(OS_ALREADY_SIGNALED == waitingEvent->signal(1)) { delete waitingEvent; waitingEvent = NULL; } } delete eventNode; eventNode = NULL; } } } } void SipClient::setSharedSocket(UtlBoolean bShared) { mbSharedSocket = bShared ; } /* ============================ ACCESSORS ================================= */ void SipClient::getClientNames(UtlString& clientNames) const { char portString[40]; // host DNS name sprintf(portString, "%d", mRemoteHostPort); clientNames = "\tremote host: "; clientNames.append(mRemoteHostName); clientNames.append(":"); clientNames.append(portString); // host IP address clientNames.append("\n\tremote IP: "); clientNames.append(mRemoteSocketAddress); clientNames.append(":"); clientNames.append(portString); // via address sprintf(portString, "%d", mRemoteViaPort); clientNames.append("\n\tremote Via address: "); clientNames.append(mRemoteViaAddress); clientNames.append(":"); clientNames.append(portString); // recieved address sprintf(portString, "%d", mRemoteReceivedPort); clientNames.append("\n\treceived address: "); clientNames.append(mReceivedAddress); clientNames.append(":"); clientNames.append(portString); } void SipClient::setUserAgent(SipUserAgentBase* sipUA) { sipUserAgent = sipUA; //mFirstResendTimeoutMs = (sipUserAgent->getFirstResendTimeout()) * 4; } long SipClient::getLastTouchedTime() const { return(touchedTime); } void SipClient::touch() { OsTime time; OsDateTime::getCurTimeSinceBoot(time); touchedTime = time.seconds(); //OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient::touch client: %p time: %d\n", // this, touchedTime); } int SipClient::isInUseForWrite(void) { return(mInUseForWrite); } /* ============================ INQUIRY =================================== */ UtlBoolean SipClient::isOk() { return(clientSocket->isOk() && !isShuttingDown()); } UtlBoolean SipClient::isConnectedTo(UtlString& hostName, int hostPort) { UtlBoolean isSame = FALSE; int tempHostPort = portIsValid(hostPort) ? hostPort : SIP_PORT; // :TODO: not correct for TLS // If the ports match and the host is the same as either the // original name that the socket was constructed with or the // name it was resolved to (usual an IP address). if ( mRemoteHostPort == tempHostPort && ( hostName.compareTo(mRemoteHostName, UtlString::ignoreCase) == 0 || hostName.compareTo(mRemoteSocketAddress, UtlString::ignoreCase) == 0)) { isSame = TRUE; } else if ( mRemoteReceivedPort == tempHostPort && hostName.compareTo(mReceivedAddress, UtlString::ignoreCase) == 0) { isSame = TRUE; } else if ( mRemoteViaPort == tempHostPort && hostName.compareTo(mRemoteViaAddress, UtlString::ignoreCase) == 0) { // Cannot trust what the other side said was their IP address // as this is a bad spoofing/denial of service whole OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipClient::isConnectedTo matches %s:%d but is not trusted", mRemoteViaAddress.data(), mRemoteViaPort); } return(isSame); } void SipClient::markInUseForWrite() { OsTime time; OsDateTime::getCurTimeSinceBoot(time); mInUseForWrite = time.seconds(); } void SipClient::markAvailbleForWrite() { mInUseForWrite = 0; signalNextAvailableForWrite(); } const UtlString& SipClient::getLocalIp() { return clientSocket->getLocalIp(); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipContactDb.cpp0000644000175000017500000004704512205613256024225 0ustar00danieldaniel00000000000000// // Copyright (C) 2008 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "net/SipContactDb.h" #include "utl/UtlInt.h" #include "utl/UtlVoidPtr.h" #include "os/OsLock.h" #include "os/OsDefs.h" #include "utl/UtlHashMapIterator.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // MACROS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipContactDb::SipContactDb() : mNextContactId(1), mLock(OsMutex::Q_FIFO), mbTurnEnabled(FALSE) { } // Destructor SipContactDb::~SipContactDb() { UtlHashMapIterator iterator(mContacts); UtlInt* pKey = NULL; while (pKey = (UtlInt*)iterator()) { UtlVoidPtr* pValue = NULL; pValue = (UtlVoidPtr*)iterator.value(); if (pValue) { delete (SIPX_CONTACT_ADDRESS*)pValue->getValue(); } } mContacts.destroyAll(); } /* ============================ MANIPULATORS ============================== */ const bool SipContactDb::addContact(SIPX_CONTACT_ADDRESS& contact) { OsLock lock(mLock); bool bRet = false; assert (contact.id < 1); if (!isDuplicate(contact.cIpAddress, contact.iPort, contact.eContactType, contact.eTransportType)) { assignContactId(contact); SIPX_CONTACT_ADDRESS* pContactCopy = new SIPX_CONTACT_ADDRESS(contact); mContacts.insertKeyAndValue(new UtlInt(pContactCopy->id), new UtlVoidPtr(pContactCopy)); // If turn is enabled, duplicate the contact with a relay type if (mbTurnEnabled && contact.eContactType == CONTACT_LOCAL) { pContactCopy = new SIPX_CONTACT_ADDRESS(contact); pContactCopy->eContactType = CONTACT_RELAY ; pContactCopy->id = 0; addContact(*pContactCopy); } bRet = true; } else { // fill out the information in the contact, // to match what is already in the database contact = *(find(contact.cIpAddress, contact.iPort, contact.eContactType)); } return bRet; } const bool SipContactDb::updateContact(SIPX_CONTACT_ADDRESS& contact) { bool bFound = false ; OsLock lock(mLock); UtlHashMapIterator iterator(mContacts); UtlVoidPtr* pValue = NULL; SIPX_CONTACT_ADDRESS* pContact = NULL; UtlInt* pKey; UtlString replacedAddress ; int replacedPort ; // Pass one: replace the exact match while (pKey = (UtlInt*)iterator()) { pValue = (UtlVoidPtr*)mContacts.findValue(pKey); assert(pValue); pContact = (SIPX_CONTACT_ADDRESS*)pValue->getValue(); assert(pContact) ; if ( (pContact->eContactType == contact.eContactType) && (pContact->eTransportType == contact.eTransportType) && (strcasecmp(pContact->cInterface, contact.cInterface) == 0) && (strcasecmp(pContact->cCustomTransportName, contact.cCustomTransportName) == 0) && (strcasecmp(pContact->cCustomRouteID, contact.cCustomRouteID) == 0) ) { bFound = true ; replacedAddress = pContact->cIpAddress ; replacedPort = pContact->iPort ; strcpy(pContact->cIpAddress, contact.cIpAddress) ; pContact->iPort = contact.iPort ; break ; } } // Pass two: replace anything else that had the same IP/port combo. // This pass adjusted relay and external transport duplicates. if (bFound) { while (pKey = (UtlInt*)iterator()) { pValue = (UtlVoidPtr*)mContacts.findValue(pKey); assert(pValue); pContact = (SIPX_CONTACT_ADDRESS*)pValue->getValue(); assert(pContact) ; if (( replacedAddress.compareTo(pContact->cIpAddress) == 0) && (replacedPort == pContact->iPort)) { strcpy(pContact->cIpAddress, contact.cIpAddress) ; pContact->iPort = contact.iPort ; } } } return bFound ; } const bool SipContactDb::deleteContact(const SIPX_CONTACT_ID id) { OsLock lock(mLock); UtlInt idKey(id); return mContacts.destroy(&idKey) ? true : false; } SIPX_CONTACT_ADDRESS* SipContactDb::find(SIPX_CONTACT_ID id) { OsLock lock(mLock); SIPX_CONTACT_ADDRESS* pContact = NULL; UtlInt idKey(id); UtlVoidPtr* pValue = (UtlVoidPtr*)mContacts.findValue(&idKey); if (pValue) { pContact = (SIPX_CONTACT_ADDRESS*)pValue->getValue(); } return pContact; } // Finds the first contact by a given contact type SIPX_CONTACT_ADDRESS* SipContactDb::findByType(SIPX_CONTACT_TYPE type, SIPX_TRANSPORT_TYPE transportType, UtlString sCustomTransport) { OsLock lock(mLock); UtlHashMapIterator iterator(mContacts); SIPX_CONTACT_ADDRESS* pRC = NULL ; UtlVoidPtr* pValue = NULL; SIPX_CONTACT_ADDRESS* pContact = NULL; UtlInt* pKey; while (pKey = (UtlInt*)iterator()) { pValue = (UtlVoidPtr*)mContacts.findValue(pKey); assert(pValue); pContact = (SIPX_CONTACT_ADDRESS*)pValue->getValue(); assert(pContact) ; if (transportType != OsSocket::UNKNOWN && (((transportType < TRANSPORT_CUSTOM) && transportType == pContact->eTransportType) || ((transportType == TRANSPORT_CUSTOM) && pContact->eTransportType >= TRANSPORT_CUSTOM))) { if (pContact->eContactType == type) { if (sCustomTransport.length() == 0) { pRC = pContact ; break ; } else { if (sCustomTransport.compareTo(pContact->cCustomTransportName, UtlString::ignoreCase) == 0) { pRC = pContact; } } } } } return pRC ; } // Return a transport type given the specified transport name. The name // could be tls, tcp, udp, or a custom transport type. SIPX_TRANSPORT_TYPE SipContactDb::findTransportType(const char* transportName) { SIPX_TRANSPORT_TYPE eType = TRANSPORT_UDP ; assert(transportName) ; if (transportName && strlen(transportName)) { UtlString transport(transportName) ; if (transport.compareTo("tcp", UtlString::ignoreCase) == 0) { eType = TRANSPORT_TCP ; } else if (transport.compareTo("udp", UtlString::ignoreCase)== 0) { eType = TRANSPORT_UDP ; } else if (transport.compareTo("tls", UtlString::ignoreCase)== 0) { eType = TRANSPORT_TLS ; } else { OsLock lock(mLock); UtlHashMapIterator iterator(mContacts); UtlVoidPtr* pValue; UtlInt* pKey; SIPX_CONTACT_ADDRESS* pContact = NULL; while (pKey = (UtlInt*)iterator()) { pValue = (UtlVoidPtr*)mContacts.findValue(pKey); assert(pValue); // Should NEVER happen pContact = (SIPX_CONTACT_ADDRESS*)pValue->getValue(); assert(pContact) ; // Should NEVER happen if ( (pContact->eTransportType >= TRANSPORT_CUSTOM) && (transport.compareTo(pContact->cCustomTransportName, UtlString::ignoreCase) == 0)) { eType = pContact->eTransportType ; break ; } } } } return eType ; } // Find the local contact from a contact id SIPX_CONTACT_ADDRESS* SipContactDb::getLocalContact(SIPX_CONTACT_ID id) { OsLock lock(mLock); SIPX_CONTACT_ADDRESS* pRC = NULL ; SIPX_CONTACT_ADDRESS* pOriginal = find(id) ; if (pOriginal) { if (pOriginal->eContactType == CONTACT_LOCAL) { pRC = pOriginal ; } else { UtlHashMapIterator iterator(mContacts); UtlVoidPtr* pValue = NULL; SIPX_CONTACT_ADDRESS* pContact = NULL; UtlInt* pKey; while (pKey = (UtlInt*)iterator()) { pValue = (UtlVoidPtr*)mContacts.findValue(pKey); assert(pValue); pContact = (SIPX_CONTACT_ADDRESS*)pValue->getValue(); assert(pContact) ; if ((strcmp(pContact->cInterface, pOriginal->cInterface) == 0) && (pContact->eContactType == CONTACT_LOCAL)) { pRC = pContact ; break ; } } } } return pRC ; } SIPX_CONTACT_ADDRESS* SipContactDb::find(const UtlString ipAddress, const int port, SIPX_CONTACT_TYPE type) { OsLock lock(mLock); bool bFound = false; UtlHashMapIterator iterator(mContacts); UtlVoidPtr* pValue = NULL; SIPX_CONTACT_ADDRESS* pContact = NULL; UtlInt* pKey; while (pKey = (UtlInt*)iterator()) { pValue = (UtlVoidPtr*)mContacts.findValue(pKey); assert(pValue); pContact = (SIPX_CONTACT_ADDRESS*)pValue->getValue(); if ( (pContact->eContactType == type) && (strcmp(pContact->cIpAddress, ipAddress.data()) == 0)) { if (port < 0 || port == pContact->iPort) { bFound = true; break; } } } if (!bFound) { pContact = NULL; } return pContact; } void SipContactDb::getAll(SIPX_CONTACT_ADDRESS* contacts[], int& actualNum) const { OsLock lock(mLock); UtlHashMapIterator iterator(mContacts); UtlVoidPtr* pValue = NULL; SIPX_CONTACT_ADDRESS* pContact = NULL; UtlInt* pKey; actualNum = 0; // array index while (pKey = (UtlInt*)iterator()) { pValue = (UtlVoidPtr*)mContacts.findValue(pKey); assert(pValue); pContact = (SIPX_CONTACT_ADDRESS*)pValue->getValue(); contacts[actualNum] = pContact; actualNum++; } return; } const bool SipContactDb::getRecordForAdapter(SIPX_CONTACT_ADDRESS& contact, const char* szAdapter, const SIPX_CONTACT_TYPE contactFilter) const { bool bRet = false; OsLock lock(mLock); UtlHashMapIterator iterator(mContacts); UtlVoidPtr* pValue = NULL; SIPX_CONTACT_ADDRESS* pContact = NULL; UtlInt* pKey; while (pKey = (UtlInt*)iterator()) { pValue = (UtlVoidPtr*)mContacts.findValue(pKey); assert(pValue); pContact = (SIPX_CONTACT_ADDRESS*)pValue->getValue(); if (0 != strcmp(pContact->cInterface, szAdapter)) { continue; } if (pContact->eContactType != contactFilter) { continue; } contact = *pContact; bRet = true; break; } return bRet; } const bool SipContactDb::getRecordForAdapter(SIPX_CONTACT_ADDRESS& contact, const char* szAdapter, const SIPX_CONTACT_TYPE contactFilter, const SIPX_TRANSPORT_TYPE transportFilter) const { bool bRet = false; OsLock lock(mLock); UtlHashMapIterator iterator(mContacts); UtlVoidPtr* pValue = NULL; SIPX_CONTACT_ADDRESS* pContact = NULL; UtlInt* pKey; while (pKey = (UtlInt*)iterator()) { pValue = (UtlVoidPtr*)mContacts.findValue(pKey); assert(pValue); pContact = (SIPX_CONTACT_ADDRESS*)pValue->getValue(); if (0 != strcmp(pContact->cInterface, szAdapter)) continue; if (pContact->eContactType != contactFilter) continue ; if (transportFilter == TRANSPORT_CUSTOM) { if (pContact->eTransportType < TRANSPORT_CUSTOM) continue; } else { if (pContact->eTransportType != transportFilter) continue; } contact = *pContact; bRet = true; break; } return bRet; } void SipContactDb::getAllForAdapter(const SIPX_CONTACT_ADDRESS* contacts[], const char* szAdapter, int& actualNum, const SIPX_CONTACT_TYPE contactFilter) const { OsLock lock(mLock); UtlHashMapIterator iterator(mContacts); UtlVoidPtr* pValue = NULL; SIPX_CONTACT_ADDRESS* pContact = NULL; UtlInt* pKey; actualNum = 0; // array index while (pKey = (UtlInt*)iterator()) { pValue = (UtlVoidPtr*)mContacts.findValue(pKey); assert(pValue); pContact = (SIPX_CONTACT_ADDRESS*)pValue->getValue(); if (0 != strcmp(pContact->cInterface, szAdapter)) { continue; } if (contactFilter != CONTACT_ALL && pContact->eContactType != contactFilter) { continue; } contacts[actualNum] = pContact; actualNum++; } return; } void SipContactDb::enableTurn(bool bEnable) { OsLock lock(mLock); UtlHashMapIterator iterator(mContacts); mbTurnEnabled = bEnable ; UtlVoidPtr* pValue = NULL; SIPX_CONTACT_ADDRESS* pContact = NULL; UtlInt* pKey; while (pKey = (UtlInt*)iterator()) { pValue = (UtlVoidPtr*)mContacts.findValue(pKey); assert(pValue); pContact = (SIPX_CONTACT_ADDRESS*)pValue->getValue(); if (pContact) { if (mbTurnEnabled) { if ((pContact->eContactType == CONTACT_LOCAL) && (pContact->eTransportType == TRANSPORT_UDP)) { SIPX_CONTACT_ADDRESS* pContactCopy = new SIPX_CONTACT_ADDRESS(*pContact); pContactCopy->eContactType = CONTACT_RELAY ; assignContactId(*pContactCopy) ; mContacts.insertKeyAndValue(new UtlInt(pContactCopy->id), new UtlVoidPtr(pContactCopy)); } } else { if (pContact->eContactType == CONTACT_RELAY) { deleteContact(pContact->id) ; } } } } } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ const bool SipContactDb::isDuplicate(const SIPX_CONTACT_ID id) { OsLock lock(mLock); bool bRet = false; UtlInt idKey(id); UtlVoidPtr* pValue = (UtlVoidPtr*)mContacts.findValue(&idKey); if (pValue) { bRet = true; } return bRet; } const bool SipContactDb::isDuplicate(const UtlString& ipAddress, const int port, SIPX_CONTACT_TYPE type, SIPX_TRANSPORT_TYPE transportType) { OsLock lock(mLock); bool bRet = false; UtlHashMapIterator iterator(mContacts); UtlVoidPtr* pValue = NULL; SIPX_CONTACT_ADDRESS* pContact = NULL; UtlInt* pKey; while (pKey = (UtlInt*)iterator()) { pValue = (UtlVoidPtr*)mContacts.findValue(pKey); assert(pValue); pContact = (SIPX_CONTACT_ADDRESS*)pValue->getValue(); if ( (pContact->eContactType == type) && (strcmp(pContact->cIpAddress, ipAddress.data()) == 0) && pContact->eTransportType == transportType) { if (port < 0 || port == pContact->iPort) { bRet = true; break; } } } return bRet; } const bool SipContactDb::assignContactId(SIPX_CONTACT_ADDRESS& contact) { OsLock lock(mLock); contact.id = mNextContactId; mNextContactId++; return true; } void SipContactDb::replicateForTransport(const SIPX_TRANSPORT_TYPE originalTransportType, const SIPX_TRANSPORT_TYPE newTransport, const char* szTransport, const char* szRoutingID) { OsLock lock(mLock); UtlHashMapIterator iterator(mContacts); UtlVoidPtr* pValue = NULL; SIPX_CONTACT_ADDRESS* pContact = NULL; UtlInt* pKey; int index = 0; // array index while (pKey = (UtlInt*)iterator()) { pValue = (UtlVoidPtr*)mContacts.findValue(pKey); assert(pValue); pContact = (SIPX_CONTACT_ADDRESS*)pValue->getValue(); if (pContact->eTransportType == originalTransportType) { SIPX_CONTACT_ADDRESS* newContact = new SIPX_CONTACT_ADDRESS(*pContact); newContact->id = 0; newContact->eTransportType = newTransport; memset(newContact->cCustomTransportName, 0, sizeof(newContact->cCustomTransportName)) ; if (szTransport) strncpy(newContact->cCustomTransportName, szTransport, sizeof(newContact->cCustomTransportName)); memset(newContact->cCustomRouteID, 0, sizeof(newContact->cCustomRouteID)) ; if (szRoutingID) strncpy(newContact->cCustomRouteID, szRoutingID, sizeof(newContact->cCustomRouteID)); addContact(*newContact); } index++; } return; } void SipContactDb::removeForTransport(const SIPX_TRANSPORT_TYPE transport) { OsLock lock(mLock); UtlHashMapIterator iterator(mContacts); UtlVoidPtr* pValue = NULL; SIPX_CONTACT_ADDRESS* pContact = NULL; UtlInt* pKey; int index = 0; // array index while (pKey = (UtlInt*)iterator()) { pValue = (UtlVoidPtr*)mContacts.findValue(pKey); assert(pValue); pContact = (SIPX_CONTACT_ADDRESS*)pValue->getValue(); if (pContact->eTransportType == transport) { deleteContact(pContact->id); } index++; } return; } void SipContactDb::dump(UtlString& output) { OsLock lock(mLock); UtlHashMapIterator iterator(mContacts); output.append("\nSipContactDB Dump:\n") ; UtlVoidPtr* pValue = NULL; SIPX_CONTACT_ADDRESS* pContact = NULL; UtlInt* pKey; int index = 0; // array index while (pKey = (UtlInt*)iterator()) { pValue = (UtlVoidPtr*)mContacts.findValue(pKey); assert(pValue); pContact = (SIPX_CONTACT_ADDRESS*)pValue->getValue(); char cFoo[512] ; sprintf(cFoo, " %d %d %d %s/%s:%d %s %s\n", pContact->id, pContact->eContactType, pContact->eTransportType, pContact->cInterface, pContact->cIpAddress, pContact->iPort, pContact->cCustomTransportName, pContact->cCustomRouteID) ; output.append(cFoo) ; } return; } /* ============================ TESTING =================================== */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipConfigServerAgent.cpp0000644000175000017500000003503212205613256025730 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include #include #include "os/OsFS.h" #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define CONFIG_ETC_DIR SIPX_CONFDIR #define CONFIG_LOG_DIR SIPX_LOGDIR #define CONFIG_LOG_FILE "sds.log" #define CONFIG_SETTINGS_FILE "sds-config" #define DEFAULT_EXPIRES 60*60*24 //24 hrs // Configuration names pulled from config-file #define CONFIG_SETTING_LOG_LEVEL "SIP_SDS_LOG_LEVEL" #define CONFIG_SETTING_LOG_CONSOLE "SIP_SDS_LOG_CONSOLE" #define CONFIG_SETTING_LOG_DIR "SIP_SDS_LOG_DIR" // STATIC VARIABLE INITIALIZATIONS SipConfigServerAgent* SipConfigServerAgent::spInstance = NULL ; OsBSem SipConfigServerAgent::sLock(OsBSem::Q_PRIORITY, OsBSem::FULL); /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipConfigServerAgent::SipConfigServerAgent(SipUserAgent* userAgent) : OsServerTask("SipConfigServerAgent-%d", NULL, 2000) { osPrintf("---> BEGIN Starting SipConfigServerAgent...\r\n") ; if(userAgent) { mpSipUserAgent = userAgent; mpSipUserAgent->addMessageObserver(*(this->getMessageQueue()), SIP_NOTIFY_METHOD, FALSE, // do not want to get requests TRUE, // do want responses TRUE, // Incoming messages FALSE); // Don't want to see out going messages mpSipUserAgent->addMessageObserver(*(this->getMessageQueue()), SIP_SUBSCRIBE_METHOD, TRUE, // do want to get requests FALSE, // do not want responses TRUE, // Incoming messages FALSE); // Don't want to see out going messages } else osPrintf("---> NULL user agent passed to SipConfigServerAgent constructor\r\n") ; osPrintf("---> END Starting SipConfigServerAgent...\r\n") ; } // Copy constructor SipConfigServerAgent::SipConfigServerAgent(const SipConfigServerAgent& rSipConfigServerAgent) { } // Destructor SipConfigServerAgent::~SipConfigServerAgent() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipConfigServerAgent& SipConfigServerAgent::operator=(const SipConfigServerAgent& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } UtlBoolean SipConfigServerAgent::handleMessage(OsMsg& eventMessage) { osPrintf("---> SipConfigServerAgent: handleMessage...\r\n") ; int msgType = eventMessage.getMsgType(); int msgSubType = eventMessage.getMsgSubType(); // if this is a SIP message if(msgType == OsMsg::PHONE_APP && msgSubType == SipMessage::NET_SIP_MESSAGE) { const SipMessage* sipMessage = ((SipMessageEvent&)eventMessage).getMessage(); int messageType = ((SipMessageEvent&)eventMessage).getMessageStatus(); osPrintf("SipConfigServerAgent::messageType: %d\n", messageType); UtlString method; // This is a request which failed to get sent if(messageType == SipMessageEvent::TRANSPORT_ERROR) { sipMessage->getRequestMethod(&method); osPrintf("SipConfigServerAgent:: Processing message transport error method: %s\n", sipMessage->isResponse() ? method.data() : "response"); if(sipMessage->isResponse()) { int seqNum; sipMessage->getCSeqField(&seqNum, &method); // SUBSCIBE (enrollment) response if(method.compareTo(SIP_SUBSCRIBE_METHOD)) { // We are sad the device is not there osPrintf("SipConfigServerAgent::handleMessage enroll FAILURE: no response\n"); } } } else if(messageType == SipMessageEvent::AUTHENTICATION_RETRY) { } // If this is a response else if(sipMessage->isResponse()) { int seqNum; sipMessage->getCSeqField(&seqNum, &method); // SUBSCIBE (enrollment) response if(method.compareTo(SIP_NOTIFY_METHOD) && mfpNotifyResponseCallbackFunc) { mfpNotifyResponseCallbackFunc(*sipMessage); } } // This is a request else { sipMessage->getRequestMethod(&method); UtlString eventType; sipMessage->getEventField(eventType); eventType.toLower(); // SUBSRIBE (enrollment) request if(method.compareTo(SIP_SUBSCRIBE_METHOD) == 0 && eventType.index(SIP_EVENT_CONFIG) >= 0 && mfpEnrollmentCallbackFunc) { SipMessage response; SipMessage copyOfRequest(*sipMessage); // add a to tag to the sip message. This to tag will // be bubbled up to the Java layer. Also the same to tag will // be sent back in the response UtlString toAddr; UtlString toProto; int toPort; UtlString toTag; sipMessage->getToAddress(&toAddr, &toPort, &toProto, NULL, NULL, &toTag); if( toTag.isNull()) { int epochTime = OsDateTime::getSecsSinceEpoch(); // Build a to tag char tagBuffer[100]; sprintf(tagBuffer, "%dasd", epochTime); copyOfRequest.setToFieldTag(tagBuffer); } int responseCode = mfpEnrollmentCallbackFunc(copyOfRequest); switch(responseCode) { case SIP_ACCEPTED_CODE: { response.setExpiresField(DEFAULT_EXPIRES); response.setResponseData(©OfRequest, SIP_ACCEPTED_CODE, SIP_ACCEPTED_TEXT); } break; default: response.setResponseData(©OfRequest, SIP_BAD_REQUEST_CODE, SIP_BAD_REQUEST_TEXT); break; } if(mpSipUserAgent) mpSipUserAgent->send(response); } } } return(TRUE); } SipConfigServerAgent* SipConfigServerAgent::startAgents(const char* configFileName) { int sipTcpPort; int sipUdpPort; int sipTlsPort; OsConfigDb configDb; if(configDb.loadFromFile(configFileName) == OS_SUCCESS) { osPrintf("Found config file: %s\n", configFileName); } else { configDb.set("SIP_SDS_UDP_PORT", "5090"); configDb.set("SIP_SDS_TCP_PORT", "5090"); configDb.set("SIP_SDS_TLS_PORT", "5091"); configDb.set(CONFIG_SETTING_LOG_DIR, ""); configDb.set(CONFIG_SETTING_LOG_LEVEL, ""); configDb.set(CONFIG_SETTING_LOG_CONSOLE, ""); if (configDb.storeToFile(configFileName) != OS_SUCCESS) osPrintf("Could not store config file: %s\n", configFileName); } sipTcpPort = configDb.getPort("SIP_SDS_UDP_PORT") ; sipUdpPort = configDb.getPort("SIP_SDS_TCP_PORT") ; sipTlsPort = configDb.getPort("SIP_SDS_TLS_PORT") ; // Start the sip stack SipUserAgent* pAgent = new SipUserAgent(sipTcpPort, sipUdpPort, sipTlsPort, NULL, // public IP address (nopt used in proxy) NULL, // default user (not used in proxy) NULL, // default SIP address (not used in proxy) NULL, // outbound proxy NULL, // directory server NULL, // registry server NULL, // auth scheme NULL, //auth realm NULL, // auth DB NULL, // auth user IDs NULL, // auth passwords NULL, // line mgr SIP_DEFAULT_RTT, // first resend timeout TRUE, // default to UA transaction SIPUA_DEFAULT_SERVER_UDP_BUFFER_SIZE, // socket layer read buffer size SIPUA_DEFAULT_SERVER_OSMSG_QUEUE_SIZE // OsServerTask message queue size ); pAgent->start(); // Start the SipConfigServerAgent SipConfigServerAgent* pConfigAgent = new SipConfigServerAgent(pAgent) ; pConfigAgent->start() ; return(pConfigAgent); } SipUserAgent* SipConfigServerAgent::getSipUserAgent() { return mpSipUserAgent ; } SipConfigServerAgent* SipConfigServerAgent::getSipConfigServerAgent() { UtlBoolean isStarted ; // If the task object already exists, and the corresponding low-level task // has been started, then use it if (spInstance != NULL && spInstance->isStarted()) return spInstance; // If the task does not yet exist or hasn't been started, then acquire // the lock to ensure that only one instance of the task is started sLock.acquire(); if (spInstance == NULL) { OsPath workingDirectory ; if ( OsFileSystem::exists( CONFIG_ETC_DIR ) ) { workingDirectory = CONFIG_ETC_DIR; OsPath path(workingDirectory); path.getNativePath(workingDirectory); } else { OsPath path; OsFileSystem::getWorkingDirectory(path); path.getNativePath(workingDirectory); } UtlString ConfigfileName = workingDirectory + OsPathBase::separator + CONFIG_SETTINGS_FILE ; // Initialize the OsSysLog OsConfigDb configDb ; configDb.loadFromFile(ConfigfileName) ; initializeLog(&configDb) ; spInstance = startAgents(ConfigfileName); } isStarted = spInstance->isStarted(); if (!isStarted) { isStarted = spInstance->start(); // assert(isStarted); } sLock.release(); return spInstance; } /* ============================ ACCESSORS ================================= */ void SipConfigServerAgent::setEnrollmentCallback(EnrollmentCallbackFunc callback) { mfpEnrollmentCallbackFunc = callback ; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ // Initialize the OsSysLog void SipConfigServerAgent::initializeLog(OsConfigDb* pConfig) { UtlString logLevel; // Controls Log Verbosity UtlString consoleLogging; // Enable console logging by default? UtlString fileTarget; // Path to store log file. UtlBoolean bSpecifiedDirError ; // Set if the specified log dir does not // exist struct tagPrioriotyLookupTable { const char* pIdentity; OsSysLogPriority ePriority; }; struct tagPrioriotyLookupTable lkupTable[] = { { "DEBUG", PRI_DEBUG}, { "INFO", PRI_INFO}, { "NOTICE", PRI_NOTICE}, { "WARNING", PRI_WARNING}, { "ERR", PRI_ERR}, { "CRIT", PRI_CRIT}, { "ALERT", PRI_ALERT}, { "EMERG", PRI_EMERG} }; OsSysLog::initialize(0, "SDS"); // // Get/Apply Log Filename // fileTarget.remove(0) ; if ((pConfig->get(CONFIG_SETTING_LOG_DIR, fileTarget) != OS_SUCCESS) || fileTarget.isNull() || !OsFileSystem::exists(fileTarget)) { bSpecifiedDirError = !fileTarget.isNull() ; // If the log file directory exists use that, otherwise place the log // in the current directory OsPath workingDirectory; if (OsFileSystem::exists(CONFIG_LOG_DIR)) { fileTarget = CONFIG_LOG_DIR; OsPath path(fileTarget); path.getNativePath(workingDirectory); osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ; OsSysLog::add(FAC_SIP, PRI_INFO, "%s : %s\n", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ; } else { OsPath path; OsFileSystem::getWorkingDirectory(path); path.getNativePath(workingDirectory); osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ; OsSysLog::add(FAC_SIP, PRI_INFO, "%s : %s\n", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ; } fileTarget = workingDirectory + OsPathBase::separator + CONFIG_LOG_FILE; } else { bSpecifiedDirError = false ; osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, fileTarget.data()) ; OsSysLog::add(FAC_SIP, PRI_INFO, "%s : %s\n", CONFIG_SETTING_LOG_DIR, fileTarget.data()) ; fileTarget = fileTarget + OsPathBase::separator + CONFIG_LOG_FILE; } OsSysLog::setOutputFile(0, fileTarget) ; // // Get/Apply Log Level // if ((pConfig->get(CONFIG_SETTING_LOG_LEVEL, logLevel) != OS_SUCCESS) || logLevel.isNull()) { logLevel = "ERR"; } logLevel.toUpper(); OsSysLogPriority priority = PRI_ERR; int iEntries = sizeof(lkupTable)/sizeof(struct tagPrioriotyLookupTable); for (int i=0; iget(CONFIG_SETTING_LOG_CONSOLE, consoleLogging) == OS_SUCCESS)) { consoleLogging.toUpper(); if (consoleLogging == "ENABLE") { OsSysLog::enableConsoleOutput(true); bConsoleLoggingEnabled = true ; } } osPrintf("%s : %s\n", CONFIG_SETTING_LOG_CONSOLE, bConsoleLoggingEnabled ? "ENABLE" : "DISABLE") ; OsSysLog::add(FAC_SIP, PRI_INFO, "%s : %s\n", CONFIG_SETTING_LOG_CONSOLE, bConsoleLoggingEnabled ? "ENABLE" : "DISABLE") ; if (bSpecifiedDirError) { OsSysLog::add(FAC_LOG, PRI_CRIT, "Cannot access %s directory; please check configuration.", CONFIG_SETTING_LOG_DIR); } } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipDialog.cpp0000644000175000017500000006745712205613256023574 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie (dpetrie AT SIPez DOT com) ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipDialog::SipDialog(const SipMessage* initialMessage, UtlBoolean isFromLocal) { if(initialMessage) { UtlString callId; initialMessage->getCallIdField(&callId); append(callId); // The transaction was initiated from this side if((!initialMessage->isResponse() && isFromLocal) || (initialMessage->isResponse() && !isFromLocal)) { mLocalInitatedDialog = TRUE; initialMessage->getFromUrl(mLocalField); mLocalField.getFieldParameter("tag", mLocalTag); initialMessage->getToUrl(mRemoteField); mRemoteField.getFieldParameter("tag", mRemoteTag); initialMessage->getCSeqField(&mInitialLocalCseq, &mInitialMethod); mLastLocalCseq = mInitialLocalCseq; mLastRemoteCseq = -1; mInitialRemoteCseq = -1; } // The transaction was initiated from the other side else { mLocalInitatedDialog = FALSE; initialMessage->getFromUrl(mRemoteField); mRemoteField.getFieldParameter("tag", mRemoteTag); initialMessage->getToUrl(mLocalField); mLocalField.getFieldParameter("tag", mLocalTag); initialMessage->getCSeqField(&mInitialRemoteCseq, &mInitialMethod); mLastRemoteCseq = mInitialRemoteCseq; mLastLocalCseq = -1; mInitialLocalCseq = -1; } if(!initialMessage->isResponse()) { UtlString uri; initialMessage->getRequestUri(&uri); if(isFromLocal) { msRemoteRequestUri = uri; } else { msLocalRequestUri = uri; } } UtlString contact; initialMessage->getContactUri(0, &contact); if(isFromLocal) { mLocalContact = contact; } else { mRemoteContact = contact; } } else { mLastLocalCseq = -1; mLastRemoteCseq = -1; mInitialLocalCseq = -1; mInitialRemoteCseq = -1; } mDialogState = DIALOG_UNKNOWN; } // Constructor SipDialog::SipDialog(const char* callId, const char* localField, const char* remoteField) : UtlString(callId) { mRemoteField = Url(remoteField); mRemoteField.getFieldParameter("tag", mRemoteTag); mLocalField = Url(localField); mLocalField.getFieldParameter("tag", mLocalTag); mInitialLocalCseq = -1; mInitialRemoteCseq = -1; mLastLocalCseq = -1; mLastRemoteCseq = -1; mDialogState = DIALOG_UNKNOWN; } // Copy constructor SipDialog::SipDialog(const SipDialog& rSipDialog) : UtlString(rSipDialog) { mLocalField = rSipDialog.mLocalField; mLocalTag = rSipDialog.mLocalTag; mRemoteField = rSipDialog.mRemoteField; mRemoteTag = rSipDialog.mRemoteTag; mLocalContact = rSipDialog.mLocalContact; mRemoteContact = rSipDialog.mRemoteContact; mRouteSet = rSipDialog.mRouteSet; mInitialMethod = rSipDialog.mInitialMethod; mLocalInitatedDialog = rSipDialog.mLocalInitatedDialog; mInitialLocalCseq = rSipDialog.mInitialLocalCseq; mInitialRemoteCseq = rSipDialog.mInitialRemoteCseq; mLastLocalCseq = rSipDialog.mLastLocalCseq; mLastRemoteCseq = rSipDialog.mLastRemoteCseq; mDialogState = rSipDialog.mDialogState; msLocalRequestUri = rSipDialog.msLocalRequestUri; msRemoteRequestUri = rSipDialog.msRemoteRequestUri; } // Destructor SipDialog::~SipDialog() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipDialog& SipDialog::operator=(const SipDialog& rhs) { if (this == &rhs) // handle the assignment to self case return *this; UtlString::operator=(rhs); // assign fields for parent class mLocalField = rhs.mLocalField; mLocalTag = rhs.mLocalTag; mRemoteField = rhs.mRemoteField; mRemoteTag = rhs.mRemoteTag; mLocalContact = rhs.mLocalContact; mRemoteContact = rhs.mRemoteContact; mRouteSet = rhs.mRouteSet; mInitialMethod = rhs.mInitialMethod; mLocalInitatedDialog = rhs.mLocalInitatedDialog; mInitialLocalCseq = rhs.mInitialLocalCseq; mInitialRemoteCseq = rhs.mInitialRemoteCseq; mLastLocalCseq = rhs.mLastLocalCseq; mLastRemoteCseq = rhs.mLastRemoteCseq; mDialogState = rhs.mDialogState; msLocalRequestUri = rhs.msLocalRequestUri; msRemoteRequestUri = rhs.msRemoteRequestUri; // Do not copy mApplicationData return *this; } void SipDialog::updateDialogData(const SipMessage& message) { UtlString messageCallId; message.getCallIdField(&messageCallId); Url messageFromUrl; message.getFromUrl(messageFromUrl); UtlString messageFromTag; messageFromUrl.getFieldParameter("tag", messageFromTag); Url messageToUrl; message.getToUrl(messageToUrl); UtlString messageToTag; messageToUrl.getFieldParameter("tag", messageToTag); int cSeq; UtlString method; message.getCSeqField(&cSeq, &method); int responseCode = message.getResponseStatusCode(); // Figure out if the request is from the local or // the remote side if(isTransactionLocallyInitiated(messageCallId, messageFromTag, messageToTag)) { // This message is part of a transaction initiated by // the local side of the dialog if(cSeq > mLastLocalCseq) { mLastLocalCseq = cSeq; } if(cSeq >= mLastLocalCseq) { // Always update the contact if it is set UtlString messageContact; if(message.getContactUri(0, &messageContact) && !messageContact.isNull()) { // Add the angle brackets for contact Url url(messageContact); url.includeAngleBrackets(); messageContact = url.toString(); if(message.isResponse()) { mRemoteContact = messageContact; } else { mLocalContact = messageContact; } } } // Cannot assume that we only establish a dialog with the // initial cseq. For example if there is an authentication // challenge, the dialog will not be established until the // second transaction. if(cSeq == mLastLocalCseq) { // A successful response to an INVITE or SUBSCRIBE // make this early dialog a set up dialog if(mLocalInitatedDialog && message.isResponse() && responseCode >= SIP_2XX_CLASS_CODE && // successful dialog setup responseCode < SIP_3XX_CLASS_CODE && mRemoteTag.isNull() && // tag not set mRouteSet.isNull()) // have not yet set the route set { // Change this early dialog to a set up dialog. // The tag gets set in the 2xx response // so we need to update the URL message.getToUrl(mRemoteField); mRemoteField.getFieldParameter("tag", mRemoteTag); // Need to get the route set as well message.buildRouteField(&mRouteSet); } } } else if(isTransactionRemotelyInitiated(messageCallId, messageFromTag, messageToTag)) { int prevRemoteCseq = mLastRemoteCseq; // This message is part of a transaction initiated by // the callee/destination of the session if(cSeq > mLastRemoteCseq) { mLastRemoteCseq = cSeq; } if(cSeq >= mLastRemoteCseq) { // Always update the contact if it is set UtlString messageContact; if(message.getContactUri(0, &messageContact) && !messageContact.isNull()) { if(message.isResponse()) { mLocalContact = messageContact; } else { mRemoteContact = messageContact; } } } // First transaction from the otherside if(cSeq == mLastRemoteCseq && prevRemoteCseq == -1) { // A response (e.g. NOTIFY) can come before we get the // successful response to the initial transaction if(!mLocalInitatedDialog && !message.isResponse() && mRemoteTag.isNull()) // tag not set { // Change this early dialog to a set up dialog. // The tag gets set in the 2xx response // so we need to update the URL message.getFromUrl(mRemoteField); mRemoteField.getFieldParameter("tag", mRemoteTag); } } // First successful response from the local side if(cSeq == mLastRemoteCseq) { if(!mLocalInitatedDialog && message.isResponse() && responseCode >= SIP_2XX_CLASS_CODE && // successful dialog setup responseCode < SIP_3XX_CLASS_CODE && mLocalTag.isNull()) { // Update the local tag message.getToUrl(mLocalField); mLocalField.getFieldParameter("tag", mLocalTag); } } } } void SipDialog::setRequestData(SipMessage& request, const char* method) { UtlString methodString(method ? method : ""); if(methodString.isNull()) { request.getRequestMethod(&methodString); } // The request URI should be the remote contact UtlString remoteContact; mRemoteContact.removeAngleBrackets(); mRemoteContact.removeUrlParameters(); mRemoteContact.toString(remoteContact); // If the remote contact is empty, use the remote request uri if (remoteContact.compareTo("sip:") == 0) { OsSysLog::add(FAC_ACD, PRI_DEBUG, "SipDialog::setRequestData - using remote request uri %s", msRemoteRequestUri.data()); request.setSipRequestFirstHeaderLine(methodString, msRemoteRequestUri); } else { // Need to convert the remoteContact to a URI as it may be in // name-addr format Url remoteContactUrl(remoteContact); UtlString remoteContactInUriFormat; remoteContactUrl.getUri(remoteContactInUriFormat); OsSysLog::add(FAC_ACD, PRI_DEBUG, "SipDialog::setRequestData - remoteContact: \"%s\" URI formated: \"%s\"", remoteContact.data(), remoteContactInUriFormat.data()); request.setSipRequestFirstHeaderLine(methodString, remoteContactInUriFormat); } // The local field is the From field UtlString fromField; mLocalField.toString(fromField); request.setRawFromField(fromField); // The remote field is the To field UtlString toField; mRemoteField.toString(toField); request.setRawToField(toField); // Get the next local Cseq, the method should already be set getNextLocalCseq(); request.setCSeqField(mLastLocalCseq, methodString); // Set the route header according to the route set if(!mRouteSet.isNull()) { request.setRouteField(mRouteSet); } // Set the call-id request.setCallIdField(*this); // Set the contact to the incoming request URI if(!msLocalRequestUri.isNull()) { request.setContactField(msLocalRequestUri); } } /* ============================ ACCESSORS ================================= */ void SipDialog::getHandle(UtlString& dialogHandle) const { dialogHandle = *this; // callId dialogHandle.append(DIALOG_HANDLE_SEPARATOR); dialogHandle.append(mLocalTag); dialogHandle.append(DIALOG_HANDLE_SEPARATOR); dialogHandle.append(mRemoteTag); } void SipDialog::getEarlyHandle(UtlString& earlyDialogHandle) const { // Do not add the tag for the side that did not initiate the dialog earlyDialogHandle = *this; // callId earlyDialogHandle.append(DIALOG_HANDLE_SEPARATOR); if(mLocalInitatedDialog) { earlyDialogHandle.append(mLocalTag); } earlyDialogHandle.append(DIALOG_HANDLE_SEPARATOR); if(!mLocalInitatedDialog) { earlyDialogHandle.append(mRemoteTag); } } void SipDialog::parseHandle(const char* dialogHandle, UtlString& callId, UtlString& localTag, UtlString& remoteTag) { callId=""; localTag = ""; remoteTag = ""; // The call-id ends at the first comma const char* callIdEnd = strchr(dialogHandle,DIALOG_HANDLE_SEPARATOR); if(callIdEnd) { // Move past the first comma const char* localTagBegin = callIdEnd + 1; // Copy the call id callId.append(dialogHandle, callIdEnd - dialogHandle); // The local tag ends at the second comma const char* localTagEnd = strchr(localTagBegin, DIALOG_HANDLE_SEPARATOR); if(localTagEnd) { // Copy the local tag localTag.append(localTagBegin, localTagEnd - localTagBegin); // The remote tag begins beyond the comma const char* remoteTagBegin = localTagEnd + 1; // Copy the remote tag remoteTag.append(remoteTagBegin); } } } void SipDialog::reverseTags(const char* dialogHandle, UtlString& reversedHandle) { UtlString tag1; UtlString tag2; parseHandle(dialogHandle, reversedHandle, tag1, tag2); reversedHandle.capacity(strlen(dialogHandle) + 2); reversedHandle.append(DIALOG_HANDLE_SEPARATOR); reversedHandle.append(tag2); reversedHandle.append(DIALOG_HANDLE_SEPARATOR); reversedHandle.append(tag1); } void SipDialog::getCallId(UtlString& callId) const { callId = *this; } void SipDialog::setCallId(const char* callId) { remove(0); append(callId ? callId : ""); } void SipDialog::getLocalField(Url& localField) const { localField = mLocalField; } void SipDialog::getLocalTag(UtlString& localTag) const { localTag = mLocalTag; } void SipDialog::setLocalField(const Url& localField) { mLocalField = localField; } void SipDialog::getRemoteField(Url& remoteField) const { remoteField = mRemoteField; } void SipDialog::getRemoteTag(UtlString& remoteTag) const { remoteTag = mRemoteTag; } void SipDialog::setRemoteField(const Url& remoteField) { mRemoteField = remoteField; } void SipDialog::getRemoteContact(Url& remoteContact) const { remoteContact = mRemoteContact; } void SipDialog::setRemoteContact(const Url& remoteContact) { mRemoteContact = remoteContact; } void SipDialog::getLocalContact(Url& localContact) const { localContact = mLocalContact; } void SipDialog::setLocalContact(const Url& localContact) { mLocalContact = localContact; } void SipDialog::getLocalRequestUri(UtlString& requestUri) const { requestUri = msLocalRequestUri; } void SipDialog::setLocalRequestUri(const UtlString& requestUri) { msLocalRequestUri = requestUri; } void SipDialog::getRemoteRequestUri(UtlString& requestUri) const { requestUri = msRemoteRequestUri; } void SipDialog::setRemoteRequestUri(const UtlString& requestUri) { msRemoteRequestUri = requestUri; } void SipDialog::getInitialMethod(UtlString& method) const { method = mInitialMethod; } void SipDialog::setInitialMethod(const char* method) { mInitialMethod = method; } int SipDialog::getLastLocalCseq() const { return(mLastLocalCseq); } void SipDialog::setLastLocalCseq(int lastLocalCseq) { mLastLocalCseq = lastLocalCseq; } int SipDialog::getLastRemoteCseq() const { return(mLastRemoteCseq); } void SipDialog::setLastRemoteCseq(int lastRemoteCseq) { mLastRemoteCseq = lastRemoteCseq; } int SipDialog::getNextLocalCseq() { mLastLocalCseq++; return(mLastLocalCseq); } //int SipDialog::getDialogState() const //{ // return mDialogState; //} /* ============================ INQUIRY =================================== */ UtlBoolean SipDialog::isSameDialog(const SipMessage& message) const { UtlString messageCallId; message.getCallIdField(&messageCallId); UtlBoolean isSameDialog = FALSE; if(messageCallId.compareTo(*this, UtlString::ignoreCase) == 0) { Url messageFromUrl; message.getFromUrl(messageFromUrl); UtlString messageFromTag; messageFromUrl.getFieldParameter("tag", messageFromTag); if(messageFromTag.compareTo(mLocalTag, UtlString::ignoreCase) == 0) { Url messageToUrl; message.getToUrl(messageToUrl); UtlString messageToTag; messageToUrl.getFieldParameter("tag", messageToTag); if(messageToTag.compareTo(mRemoteTag, UtlString::ignoreCase) == 0) { isSameDialog = TRUE; } } else if(messageFromTag.compareTo(mRemoteTag, UtlString::ignoreCase) == 0) { Url messageToUrl; message.getToUrl(messageToUrl); UtlString messageToTag; messageToUrl.getFieldParameter("tag", messageToTag); if(messageToTag.compareTo(mLocalTag, UtlString::ignoreCase) == 0) { isSameDialog = TRUE; } } } return(isSameDialog); } UtlBoolean SipDialog::isSameDialog(const UtlString& callId, const UtlString& localTag, const UtlString& remoteTag) const { // Literal/exact match of tags only // i.e. do not allow a null tag to match a set tag UtlBoolean isSameDialog = FALSE; if(callId.compareTo(*this, UtlString::ignoreCase) == 0) { if(localTag.compareTo(mLocalTag, UtlString::ignoreCase) == 0 && remoteTag.compareTo(mRemoteTag, UtlString::ignoreCase) == 0) { isSameDialog = TRUE; } else if(remoteTag.compareTo(mLocalTag, UtlString::ignoreCase) == 0 && localTag.compareTo(mRemoteTag, UtlString::ignoreCase) == 0) { isSameDialog = TRUE; } } return(isSameDialog); } UtlBoolean SipDialog::isSameDialog(const char* dialogHandle) { UtlString callId; UtlString localTag; UtlString remoteTag; parseHandle(dialogHandle, callId, localTag, remoteTag); return(isSameDialog(callId, localTag, remoteTag)); } UtlBoolean SipDialog::isEarlyDialogFor(const SipMessage& message) const { UtlString handle; message.getDialogHandle(handle); UtlString callId; UtlString localTag; UtlString remoteTag; parseHandle(handle, callId, localTag, remoteTag); return(isEarlyDialogFor(callId, localTag, remoteTag)); } UtlBoolean SipDialog::isEarlyDialogFor(const UtlString& callId, const UtlString& localTag, const UtlString& remoteTag) const { UtlBoolean isSameEarlyDialog = FALSE; // If the local tag is NULL the remote tag must match one of the // two given tags, to be an early dialog for the given dialog info if(mLocalTag.isNull()) { if(localTag.compareTo(mRemoteTag, UtlString::ignoreCase) == 0 || remoteTag.compareTo(mRemoteTag, UtlString::ignoreCase) == 0) { isSameEarlyDialog = TRUE; } } // If the remote tag is NULL the local tag must match one of the // two given tags, to be an early dialog for the given dialog info else if(mRemoteTag.isNull()) { if(localTag.compareTo(mLocalTag, UtlString::ignoreCase) == 0 || remoteTag.compareTo(mLocalTag, UtlString::ignoreCase) == 0) { isSameEarlyDialog = TRUE; } } return(isSameEarlyDialog); } UtlBoolean SipDialog::wasEarlyDialogFor(const UtlString& callId, const UtlString& localTag, const UtlString& remoteTag) const { UtlBoolean wasSameEarlyDialog = FALSE; // Assume that if any either of the given tags matches // one of the dialog's tags that they shared the same // early dialog if(localTag.compareTo(mRemoteTag, UtlString::ignoreCase) == 0 || remoteTag.compareTo(mRemoteTag, UtlString::ignoreCase) == 0 || localTag.compareTo(mLocalTag, UtlString::ignoreCase) == 0 || remoteTag.compareTo(mLocalTag, UtlString::ignoreCase) == 0) { wasSameEarlyDialog = TRUE; } return(wasSameEarlyDialog); } UtlBoolean SipDialog::isTransactionLocallyInitiated(const UtlString& callId, const UtlString& fromTag, const UtlString& toTag) const { UtlBoolean isLocalDialog = FALSE; if(callId.compareTo(*this, UtlString::ignoreCase) == 0) { if(fromTag.compareTo(mLocalTag, UtlString::ignoreCase) == 0 && (toTag.compareTo(mRemoteTag, UtlString::ignoreCase) == 0 || toTag.isNull() || mRemoteTag.isNull())) { isLocalDialog = TRUE; } } return(isLocalDialog); } UtlBoolean SipDialog::isTransactionRemotelyInitiated(const UtlString& callId, const UtlString& fromTag, const UtlString& toTag) const { UtlBoolean isRemoteDialog = FALSE; if(callId.compareTo(*this, UtlString::ignoreCase) == 0) { if((toTag.compareTo(mLocalTag, UtlString::ignoreCase) == 0 || toTag.isNull() || mLocalTag.isNull()) && fromTag.compareTo(mRemoteTag, UtlString::ignoreCase) == 0 || mRemoteTag.isNull()) // If this is remotely initiated fromTag // cannot be a null string. mRemoteTag can be a null string // as occurs when a remotely initiated NOTIFY is received // before the SUBSCRIBE response is received. { isRemoteDialog = TRUE; } } return(isRemoteDialog); } UtlBoolean SipDialog::isEarlyDialog() const { // For now make the simple assumption that if one of // the tags is not set that this is an early dialog // Note: RFC 2543 clients only needed to optionally // set the tags. I do not think we need to support // RFC 2543 in this class. UtlBoolean tagNotSet = FALSE; if(mLocalTag.isNull() || mRemoteTag.isNull()) { tagNotSet = TRUE; } return(tagNotSet); } UtlBoolean SipDialog::isEarlyDialog(const char* handle) { // For now make the simple assumption that if one of // the tags is not set that this is an early dialog // Note: RFC 2543 clients only needed to optionally // set the tags. I do not think we need to support // RFC 2543 in this class. UtlBoolean tagNotSet = FALSE; if(handle && *handle) { UtlString dialogHandle(handle); UtlString callId; UtlString localTag; UtlString remoteTag; parseHandle(dialogHandle, callId, localTag, remoteTag); if(localTag.isNull() || remoteTag.isNull()) { tagNotSet = TRUE; } } return(tagNotSet); } UtlBoolean SipDialog::isSameLocalCseq(const SipMessage& message) const { int cseq; message.getCSeqField(&cseq, NULL); return(cseq == mLastLocalCseq); } UtlBoolean SipDialog::isSameRemoteCseq(const SipMessage& message) const { int cseq; message.getCSeqField(&cseq, NULL); return(cseq == mLastRemoteCseq); } UtlBoolean SipDialog::isNextLocalCseq(const SipMessage& message) const { int cseq; message.getCSeqField(&cseq, NULL); return(cseq > mLastLocalCseq); } UtlBoolean SipDialog::isNextRemoteCseq(const SipMessage& message) const { int cseq; message.getCSeqField(&cseq, NULL); return(cseq > mLastRemoteCseq); } void SipDialog::toString(UtlString& dialogDumpString) { // Serialize all the members into the dumpString char numberString[20]; dialogDumpString="SipDialog: "; sprintf(numberString, "%p", this); dialogDumpString.append(numberString); dialogDumpString.append("\nCall-Id:"); // The callId is stored in the UtlString base class data element dialogDumpString.append(*this); dialogDumpString.append("\nmLocalField:"); UtlString tmpString; mLocalField.toString(tmpString); dialogDumpString.append(tmpString); dialogDumpString.append("\nmRemoteField:"); mRemoteField.toString(tmpString); dialogDumpString.append(tmpString); dialogDumpString.append("\nmLocalTag:"); dialogDumpString.append(mLocalTag); dialogDumpString.append("\nmRemoteTag:"); dialogDumpString.append(mRemoteTag); dialogDumpString.append("\nmLocalContact:"); mLocalContact.toString(tmpString); dialogDumpString.append(tmpString); dialogDumpString.append("\nmRemoteContact:"); mRemoteContact.toString(tmpString); dialogDumpString.append(tmpString); dialogDumpString.append("\nmRouteSet:"); dialogDumpString.append(mRouteSet); dialogDumpString.append("\nmInitialMethod:"); dialogDumpString.append(mInitialMethod); dialogDumpString.append("\nmsLocalRequestUri:"); dialogDumpString.append(msLocalRequestUri); dialogDumpString.append("\nmsRemoteRequestUri:"); dialogDumpString.append(msRemoteRequestUri); dialogDumpString.append("\nmLocalInitatedDialog:"); dialogDumpString.append(mLocalInitatedDialog); sprintf(numberString, "%d", mInitialLocalCseq); dialogDumpString.append("\nmInitialLocalCseq:"); dialogDumpString.append(numberString); sprintf(numberString, "%d", mInitialRemoteCseq); dialogDumpString.append("\nmInitialRemoteCseq:"); dialogDumpString.append(numberString); sprintf(numberString, "%d", mLastLocalCseq); dialogDumpString.append("\nmLastLocalCseq:"); dialogDumpString.append(numberString); sprintf(numberString, "%d", mLastRemoteCseq); dialogDumpString.append("\nmLastRemoteCseq:"); dialogDumpString.append(numberString); sprintf(numberString, "%d", mDialogState); dialogDumpString.append("\nmDialogState:"); dialogDumpString.append(numberString); } void SipDialog::getStateString(DialogState state, UtlString& stateString) { switch(state) { case DIALOG_UNKNOWN: stateString = "DIALOG_UNKNOWN"; break; case DIALOG_EARLY: stateString = "DIALOG_EARLY"; break; case DIALOG_ESTABLISHED: stateString = "DIALOG_ESTABLISHED"; break; case DIALOG_FAILED: stateString = "DIALOG_FAILED"; break; case DIALOG_TERMINATED: stateString = "DIALOG_TERMINATED"; break; // This should not happen default: stateString = "DIALOG_????: "; char stateCode[20]; sprintf(stateCode, "%d", state); stateString.append(stateCode); break; } } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipDialogEvent.cpp0000644000175000017500000005241512205613256024562 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2005 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS const UtlContainableType Dialog::TYPE = "Dialog"; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor Dialog::Dialog(const char* dialogId, const char* callId, const char* localTag, const char* remoteTag, const char* direction) { mId = dialogId; mCallId = callId; mLocalTag = localTag; mRemoteTag = remoteTag; mDirection = direction; setIdentifier(); } // Destructor Dialog::~Dialog() { } /* ============================ MANIPULATORS ============================== */ void Dialog::setIdentifier() { // Compose a unique identifier for the dialog by concatenating the // call-id, to-tag, and from-tag. mIdentifier.append(mCallId); mIdentifier.append("\001"); mIdentifier.append(mLocalTag); mIdentifier.append("\001"); mIdentifier.append(mRemoteTag); } /* ============================ ACCESSORS ================================= */ void Dialog::getDialog(UtlString& dialogId, UtlString& callId, UtlString& localTag, UtlString& remoteTag, UtlString& direction) const { dialogId = mId; callId = mCallId; localTag = mLocalTag; remoteTag = mRemoteTag; direction = mDirection; } void Dialog::getCallId(UtlString& callId) const { callId = mCallId; } void Dialog::setDialogId(const char* dialogId) { mId = dialogId; setIdentifier(); } void Dialog::getDialogId(UtlString& dialogId) const { dialogId = mId; } void Dialog::setState(const char* state, const char* event, const char* code) { mState = state; mEvent = event; mCode = code; } void Dialog::setTags(const char* localTag, const char* remoteTag) { mLocalTag = localTag; mRemoteTag = remoteTag; setIdentifier(); } void Dialog::getState(UtlString& state, UtlString& event, UtlString& code) const { state = mState; event = mEvent; code = mCode; } void Dialog::setDuration(const unsigned long duration) { mDuration = duration; } unsigned long Dialog::getDuration() const { return mDuration; } void Dialog::setReplaces(const char* callId, const char* localTag, const char* remoteTag) { mNewCallId = callId; mNewLocalTag = localTag; mNewRemoteTag = remoteTag; } void Dialog::getReplaces(UtlString& callId, UtlString& localTag, UtlString& remoteTag) const { callId = mNewCallId; localTag = mNewLocalTag; remoteTag = mNewRemoteTag; } void Dialog::setReferredBy(const char* url, const char* display) { mReferredBy = url; mDisplay = display; } void Dialog::getReferredBy(UtlString& url, UtlString& display) const { url = mReferredBy; display = mDisplay; } void Dialog::setLocalIdentity(const char* identity, const char* display) { mLocalIdentity = identity; mLocalDisplay = display; } void Dialog::getLocalIdentity(UtlString& identity, UtlString& display) const { identity = mLocalIdentity; display = mLocalDisplay; } void Dialog::setRemoteIdentity(const char* identity, const char* display) { mRemoteIdentity = identity; mRemoteDisplay = display; } void Dialog::getRemoteIdentity(UtlString& identity, UtlString& display) const { identity = mRemoteIdentity; display = mRemoteDisplay; } void Dialog::setLocalTarget(const char* url) { mLocalTarget = url; } void Dialog::getLocalTarget(UtlString& url) const { url = mLocalTarget; } void Dialog::setRemoteTarget(const char* url) { mRemoteTarget = url; } void Dialog::getRemoteTarget(UtlString& url) const { url = mRemoteTarget; } int Dialog::compareTo(const UtlContainable *b) const { return mIdentifier.compareTo(((Dialog *) b)->mIdentifier); } unsigned int Dialog::hash() const { return mIdentifier.hash(); } const UtlContainableType Dialog::getContainableType() const { return TYPE; } /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipDialogEvent::SipDialogEvent(const char* state, const char* entity) : mLock(OsBSem::Q_PRIORITY, OsBSem::FULL), // Generate the initial report with version 1, so we can generate // the default report with version 0 in // DialogDefaultConstructor::generateDefaultContent (in // DialogEventPublisher.cpp). mVersion(1), mDialogState(state), mEntity(entity) { remove(0); append(DIALOG_EVENT_CONTENT_TYPE); } SipDialogEvent::SipDialogEvent(const char* bodyBytes) : mLock(OsBSem::Q_PRIORITY, OsBSem::FULL) { remove(0); append(DIALOG_EVENT_CONTENT_TYPE); if(bodyBytes) { bodyLength = strlen(bodyBytes); parseBody(bodyBytes); } mBody = bodyBytes; } // Destructor SipDialogEvent::~SipDialogEvent() { // Clean up all the dialog elements mDialogs.destroyAll(); } /* ============================ MANIPULATORS ============================== */ void SipDialogEvent::parseBody(const char* bodyBytes) { bool foundDialogs = false; if(bodyBytes) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogEvent::parseBody incoming package = %s\n", bodyBytes); TiXmlDocument doc("dialogEvent.xml"); doc.Parse(bodyBytes); if (!doc.Error()) { TiXmlNode * rootNode = doc.FirstChild ("dialog-info"); TiXmlElement* ucElement = 0; if (rootNode != NULL) { ucElement = rootNode->ToElement(); if (ucElement) { mVersion = atoi(ucElement->Attribute("version")); mDialogState = ucElement->Attribute("state"); mEntity = ucElement->Attribute("entity"); } // Parse each dialog for (TiXmlNode *groupNode = rootNode->FirstChild("dialog"); groupNode; groupNode = groupNode->NextSibling("dialog")) { UtlString dialogId, callId, localTag, remoteTag, direction; foundDialogs = true; // Get the attributes in dialog ucElement = groupNode->ToElement(); if (ucElement) { dialogId = ucElement->Attribute("id"); callId = ucElement->Attribute("call-id"); localTag = ucElement->Attribute("local-tag"); remoteTag = ucElement->Attribute("remote-tag"); direction = ucElement->Attribute("direction"); } Dialog* pDialog = new Dialog(dialogId, callId, localTag, remoteTag, direction); // Get the state element UtlString state, event, code; state = (groupNode->FirstChild("state"))->FirstChild()->Value(); ucElement = groupNode->FirstChild("state")->ToElement(); if (ucElement) { event = ucElement->Attribute("event"); code = ucElement->Attribute("code"); pDialog->setState(state, event, code); } // Get the duration element UtlString duration; TiXmlNode *subNode = groupNode->FirstChild("duration"); if (subNode) { duration = subNode->FirstChild()->Value(); pDialog->setDuration((unsigned long)atoi(duration.data())); } else { pDialog->setDuration(0); } // Get the local element UtlString identity, display, target; subNode = groupNode->FirstChild("local"); if (subNode) { TiXmlNode *subNode1 = subNode->FirstChild("identity"); if (subNode1) { identity = subNode1->FirstChild()->Value(); ucElement = subNode1->ToElement(); if (ucElement) { display = ucElement->Attribute("display"); pDialog->setLocalIdentity(identity, display); } } ucElement = subNode->FirstChild("target")->ToElement(); if (ucElement) { target = ucElement->Attribute("uri"); pDialog->setLocalTarget(target); } } // Get the remote element subNode = groupNode->FirstChild("remote"); if (subNode) { TiXmlNode *subNode1 = subNode->FirstChild("identity"); if (subNode1) { identity = subNode1->FirstChild()->Value(); ucElement = subNode1->ToElement(); if (ucElement) { display = ucElement->Attribute("display"); pDialog->setRemoteIdentity(identity, display); } } ucElement = subNode->FirstChild("target")->ToElement(); if (ucElement) { target = ucElement->Attribute("uri"); pDialog->setRemoteTarget(target); } } // Insert it into the list insertDialog(pDialog); } if (foundDialogs == false) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogEvent::parseBody no dialogs found"); } } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipDialogEvent::parseBody not found"); } } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipDialogEvent::parseBody xml parsing error"); } } } // Assignment operator SipDialogEvent& SipDialogEvent::operator=(const SipDialogEvent& rhs) { if (this == &rhs) // handle the assignment to self case return *this; // TODO: need to add code to copy members here OsSysLog::add(FAC_SIP, PRI_ERR, "SipDialogEvent::operator= not implemented"); return *this; } void SipDialogEvent::insertDialog(Dialog* dialog) { mLock.acquire(); if (mDialogs.insert(dialog) != NULL) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogEvent::insertDialog Dialog = %p", dialog); } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipDialogEvent::insertDialog Dialog = %p failed", dialog); } mLock.release(); } Dialog* SipDialogEvent::removeDialog(Dialog* dialog) { mLock.acquire(); UtlContainable *foundValue; foundValue = mDialogs.remove(dialog); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogEvent::removeDialog Dialog = %p", foundValue); mLock.release(); return (Dialog *) foundValue; } Dialog* SipDialogEvent::getDialog(UtlString& callId, UtlString& localTag, UtlString& remoteTag) { mLock.acquire(); UtlSListIterator dialogIterator(mDialogs); Dialog* pDialog; UtlString foundDialogId, foundCallId, foundLocalTag, foundRemoteTag, foundDirection; while ((pDialog = (Dialog *) dialogIterator())) { pDialog->getDialog(foundDialogId, foundCallId, foundLocalTag, foundRemoteTag, foundDirection); if (foundCallId.compareTo(callId) == 0 && foundLocalTag.compareTo(localTag) == 0 && (foundRemoteTag.isNull() || foundRemoteTag.compareTo(remoteTag) == 0)) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogEvent::getDialog found Dialog = %p for callId = '%s', local tag = '%s', remote tag = '%s'", pDialog, callId.data(), localTag.data(), remoteTag ? remoteTag.data() : NULL); mLock.release(); return pDialog; } } OsSysLog::add(FAC_SIP, PRI_WARNING, "SipDialogEvent::getDialog could not find the Dialog for callId = '%s', local tag = '%s', remote tag = '%s'", callId.data(), localTag ? localTag.data() : NULL, remoteTag ? remoteTag.data() : NULL); mLock.release(); return NULL; } Dialog* SipDialogEvent::getDialogByCallId(UtlString& callId) { mLock.acquire(); UtlSListIterator dialogIterator(mDialogs); Dialog* pDialog; UtlString foundDialogId, foundCallId, foundLocalTag, foundRemoteTag, foundDirection; while ((pDialog = (Dialog *) dialogIterator())) { pDialog->getDialog(foundDialogId, foundCallId, foundLocalTag, foundRemoteTag, foundDirection); if (foundCallId.compareTo(callId) == 0) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogEvent::getDialog found Dialog = %p for callId = '%s'", pDialog, callId.data()); mLock.release(); return pDialog; } } OsSysLog::add(FAC_SIP, PRI_WARNING, "SipDialogEvent::getDialog could not find the Dialog for callId = '%s'", callId.data()); mLock.release(); return NULL; } UtlBoolean SipDialogEvent::isEmpty() { return (mDialogs.isEmpty()); } int SipDialogEvent::getLength() const { int length; UtlString tempBody; getBytes(&tempBody, &length); return length; } UtlSListIterator* SipDialogEvent::getDialogIterator() { return new UtlSListIterator(mDialogs); } void SipDialogEvent::buildBody() const { UtlString dialogEvent; UtlString singleLine; char version[20]; char durationBuffer[20]; // Construct the xml document of dialog event dialogEvent = UtlString(XML_VERSION_1_0); // Dialog Information Structure dialogEvent.append(BEGIN_DIALOG_INFO); Url entityUri(mEntity); sprintf(version, "%d", mVersion); dialogEvent.append(VERSION_EQUAL); singleLine = DOUBLE_QUOTE + UtlString(version) + DOUBLE_QUOTE; dialogEvent += singleLine; dialogEvent.append(STATE_EQUAL); singleLine = DOUBLE_QUOTE + mDialogState + DOUBLE_QUOTE; dialogEvent += singleLine; dialogEvent.append(ENTITY_EQUAL); singleLine = DOUBLE_QUOTE + entityUri.toString() + DOUBLE_QUOTE; dialogEvent += singleLine; dialogEvent.append(END_LINE); // Take the lock (we will be modifying the state even though 'this' // is read-only). ((SipDialogEvent*)this)->mLock.acquire(); // Dialog elements UtlSListIterator dialogIterator(mDialogs); Dialog* pDialog; while ((pDialog = (Dialog *) dialogIterator())) { UtlString id, callId, localTag, remoteTag, direction; pDialog->getDialog(id, callId, localTag, remoteTag, direction); dialogEvent.append(BEGIN_DIALOG); singleLine = DOUBLE_QUOTE + id + DOUBLE_QUOTE; dialogEvent += singleLine; if (!callId.isNull()) { dialogEvent.append(CALL_ID_EQUAL); singleLine = DOUBLE_QUOTE + callId + DOUBLE_QUOTE; dialogEvent += singleLine; } if (!localTag.isNull()) { dialogEvent.append(LOCAL_TAG_EQUAL); singleLine = DOUBLE_QUOTE + localTag + DOUBLE_QUOTE; dialogEvent += singleLine; } if (!remoteTag.isNull()) { dialogEvent.append(REMOTE_TAG_EQUAL); singleLine = DOUBLE_QUOTE + remoteTag + DOUBLE_QUOTE; dialogEvent += singleLine; } if (!direction.isNull()) { dialogEvent.append(DIRECTION_EQUAL); singleLine = DOUBLE_QUOTE + direction + DOUBLE_QUOTE; dialogEvent += singleLine; } dialogEvent.append(END_LINE); // State element UtlString state, event, code; pDialog->getState(state, event, code); dialogEvent.append(BEGIN_STATE); if (!event.isNull()) { dialogEvent.append(EVENT_EQUAL); singleLine = DOUBLE_QUOTE + event + DOUBLE_QUOTE; dialogEvent += singleLine; } if (!code.isNull()) { dialogEvent.append(CODE_EQUAL); singleLine = DOUBLE_QUOTE + code + DOUBLE_QUOTE; dialogEvent += singleLine; } // End of state element singleLine = END_BRACKET + state + END_STATE; dialogEvent += singleLine; // Duration element int duration = pDialog->getDuration(); if (duration !=0) { duration = OsDateTime::getSecsSinceEpoch() - pDialog->getDuration(); sprintf(durationBuffer, "%d", duration); dialogEvent += BEGIN_DURATION + UtlString(durationBuffer) + END_DURATION; } // Local element UtlString identity, displayName, target; pDialog->getLocalIdentity(identity, displayName); pDialog->getLocalTarget(target); dialogEvent.append(BEGIN_LOCAL); if (!identity.isNull()) { dialogEvent.append(BEGIN_IDENTITY); if (!displayName.isNull()) { displayName.strip(UtlString::both, '\"'); dialogEvent.append(DISPLAY_EQUAL); singleLine = DOUBLE_QUOTE + displayName + DOUBLE_QUOTE; dialogEvent += singleLine; } singleLine = END_BRACKET + identity + END_IDENTITY; dialogEvent += singleLine; } if (!target.isNull() && target.compareTo("sip:") != 0) { singleLine = BEGIN_TARTGET + target + END_TARGET; dialogEvent += singleLine; } // End of local element dialogEvent.append(END_LOCAL); // Remote element pDialog->getRemoteIdentity(identity, displayName); pDialog->getRemoteTarget(target); dialogEvent.append(BEGIN_REMOTE); if (!identity.isNull()) { dialogEvent.append(BEGIN_IDENTITY); if (!displayName.isNull()) { displayName.strip(UtlString::both, '\"'); dialogEvent.append(DISPLAY_EQUAL); singleLine = DOUBLE_QUOTE + displayName + DOUBLE_QUOTE; dialogEvent += singleLine; } singleLine = END_BRACKET + identity + END_IDENTITY; dialogEvent += singleLine; } if (!target.isNull() && target.compareTo("sip:") != 0) { singleLine = BEGIN_TARTGET + target + END_TARGET; dialogEvent += singleLine; } // End of remote element dialogEvent.append(END_REMOTE); // End of dialog element dialogEvent.append(END_DIALOG); } // End of dialog-info element dialogEvent.append(END_DIALOG_INFO); // Update body text and version number (even though 'this' is read-only). ((SipDialogEvent*)this)->mBody = dialogEvent; ((SipDialogEvent*)this)->bodyLength = dialogEvent.length(); ((SipDialogEvent*)this)->mVersion++; ((SipDialogEvent*)this)->mLock.release(); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogEvent::buildBody Dialog content = \n%s", mBody.data()); } void SipDialogEvent::getBytes(const char** bytes, int* length) const { *bytes = mBody.data(); *length = bodyLength; } void SipDialogEvent::getBytes(UtlString* bytes, int* length) const { buildBody(); *bytes = mBody; *length = bodyLength; } void SipDialogEvent::setEntity(const char* entity) { mEntity = entity; } void SipDialogEvent::getEntity(UtlString& entity) const { entity = mEntity; } void SipDialogEvent::setState(const char* state) { mDialogState = state; } void SipDialogEvent::getState(UtlString& state) const { state = mDialogState; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipDialogMgr.cpp0000644000175000017500000003420712205613256024225 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie (dpetrie AT SIPez DOT com) // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipDialogMgr::SipDialogMgr() : mDialogMgrMutex(OsMutex::Q_FIFO) { } // Copy constructor NOT IMPLEMENTED SipDialogMgr::SipDialogMgr(const SipDialogMgr& rSipDialogMgr) : mDialogMgrMutex(OsMutex::Q_FIFO) { } // Destructor SipDialogMgr::~SipDialogMgr() { // Iterate through and delete all the dialogs // TODO: } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipDialogMgr& SipDialogMgr::operator=(const SipDialogMgr& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } UtlBoolean SipDialogMgr::createDialog(const SipMessage& message, UtlBoolean messageIsFromLocalSide, const char* dialogHandle) { UtlBoolean createdDialog = FALSE; UtlString handle(dialogHandle ? dialogHandle : ""); // If the dialog handle was not set, get it from the message if(handle.isNull()) { message.getDialogHandle(handle); } // Check to see if the dialog exists if(dialogExists(handle) || earlyDialogExistsFor(handle)) { // Should not try to create a dialog for one that // already exists OsSysLog::add(FAC_SIP, PRI_ERR, "SipDialogMgr::createDialog called with handle: %s for existing dialog", handle.data()); } // Dialog needs to be created else { createdDialog = TRUE; SipDialog* dialog = new SipDialog(&message, messageIsFromLocalSide); lock(); mDialogs.insert(dialog); unlock(); } return(createdDialog); } UtlBoolean SipDialogMgr::updateDialog(const SipMessage& message, const char* dialogHandle) { UtlString handle(dialogHandle ? dialogHandle : ""); // If the dialog handle was not set, get it from the message if(handle.isNull()) { message.getDialogHandle(handle); } lock(); SipDialog* dialog = findDialog(handle, TRUE, // if established handle, find early dialog FALSE); // do not want established dialogs for early handle if(dialog) { #ifdef TEST_PRINT UtlString dialogDump; dialog->toString(dialogDump); printf("SipDialogMgr::updateDialog dialog before:\n%s\n", dialogDump.data()); #endif dialog->updateDialogData(message); #ifdef TEST_PRINT dialog->toString(dialogDump); printf("SipDialogMgr::updateDialog dialog after:\n%s\n", dialogDump.data()); #endif } unlock(); return(dialog != NULL); } UtlBoolean SipDialogMgr::setNextLocalTransactionInfo(SipMessage& request, const char* method, const char* dialogHandle) { UtlBoolean requestSet = FALSE; UtlString dialogHandleString(dialogHandle ? dialogHandle : ""); if(dialogHandleString.isNull()) { request.getDialogHandle(dialogHandleString); } lock(); SipDialog* dialog = findDialog(dialogHandleString, FALSE, // If established only want exact match dialogs TRUE); // If message is from a prior transaction // when the dialog was in an early state // allow it to match and established // dialog if(dialog) { dialog->setRequestData(request, method); requestSet = TRUE; #ifdef TEST_PRINT UtlString dialogDump; dialog->toString(dialogDump); printf("SipDialogMgr::setNextLocalTransactionInfo dialog:\n%s\n", dialogDump.data()); #endif } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipDialogMgr::setNextLocalTransactionInfo could not find dialog with handle %s", dialogHandle); } unlock(); return(requestSet); } /* ============================ ACCESSORS ================================= */ UtlBoolean SipDialogMgr::getEarlyDialogHandleFor(const char* establishedDialogHandle, UtlString& earlyDialogHandle) { UtlBoolean foundDialog = FALSE; UtlString handle(establishedDialogHandle ? establishedDialogHandle : ""); lock(); SipDialog* dialog = findDialog(handle, TRUE, // if established, match early dialog FALSE); // if early, match established dialog if(dialog) { dialog->getEarlyHandle(earlyDialogHandle); foundDialog = TRUE; } else { earlyDialogHandle = ""; } unlock(); return(foundDialog); } UtlBoolean SipDialogMgr::getEstablishedDialogHandleFor(const char* earlyDialogHandle, UtlString& establishedDialogHandle) { UtlBoolean foundDialog = FALSE; UtlString handle(earlyDialogHandle ? earlyDialogHandle : ""); lock(); // Looking for an dialog that matches this earlyHandle, if there // is not an exact match see if there is an established dialog // that matches SipDialog* dialog = findDialog(handle, FALSE, // if established, match early dialog TRUE); // if early, match established dialog if(dialog && !dialog->isEarlyDialog()) { dialog->getHandle(establishedDialogHandle); foundDialog = TRUE; } else { establishedDialogHandle = ""; } unlock(); return(foundDialog); } int SipDialogMgr::countDialogs() const { return(mDialogs.entries()); } int SipDialogMgr::toString(UtlString& dumpString) { int dialogCount = 0; dumpString = ""; UtlString oneDialogDump; SipDialog* dialog = NULL; UtlHashBagIterator iterator(mDialogs); // Look at all the dialogs with the same call-id while((dialog = (SipDialog*) iterator())) { if(dialogCount) { dumpString.append('\n'); } dialog->toString(oneDialogDump); dumpString.append(oneDialogDump); dialogCount++; } return(dialogCount); } /* ============================ INQUIRY =================================== */ UtlBoolean SipDialogMgr::earlyDialogExists(const char* dialogHandle) { UtlBoolean foundDialog = FALSE; UtlString handle(dialogHandle ? dialogHandle : ""); lock(); // Looking for an dialog that matches this handle, if there // is not an exact match see if there is an early dialog // that matches the given presumably established dialog handle SipDialog* dialog = findDialog(handle, TRUE, // if established, match early dialog FALSE); // if early, match established dialog // We only want early dialogs if(dialog && dialog->isEarlyDialog()) { foundDialog = TRUE; } unlock(); return(foundDialog); } UtlBoolean SipDialogMgr::earlyDialogExistsFor(const char* establishedDialogHandle) { UtlBoolean foundDialog = FALSE; UtlString handle(establishedDialogHandle ? establishedDialogHandle : ""); // If we have an established dialog handle if(!SipDialog::isEarlyDialog(handle)) { lock(); // Looking for an dialog that matches this handle, if there // is not an exact match see if there is an early dialog // that matches the given presumably established dialog handle SipDialog* dialog = findDialog(handle, TRUE, // if established, match early dialog FALSE); // if early, match established dialog if(dialog && !dialog->isEarlyDialog()) { foundDialog = TRUE; } unlock(); } return(foundDialog); } UtlBoolean SipDialogMgr::dialogExists(const char* dialogHandle) { UtlBoolean foundDialog = FALSE; UtlString handle(dialogHandle ? dialogHandle : ""); lock(); // Looking for an dialog that exactly matches this handle SipDialog* dialog = findDialog(handle, FALSE, // if established, match early dialog FALSE); // if early, match established dialog if(dialog) { foundDialog = TRUE; } unlock(); return(foundDialog); } UtlBoolean SipDialogMgr::isLastLocalTransaction(const SipMessage& message, const char* dialogHandle) { UtlBoolean matchesTransaction = FALSE; UtlString handle(dialogHandle ? dialogHandle : ""); // If the dialog handle was not set, get it from the message if(handle.isNull()) { message.getDialogHandle(handle); } UtlString callId; UtlString fromTag; UtlString toTag; SipDialog::parseHandle(handle, callId, fromTag, toTag); lock(); // Looking for any dialog that matches this handle SipDialog* dialog = findDialog(handle, TRUE, // if established, match early dialog TRUE); // if early, match established dialog if(dialog && dialog->isTransactionLocallyInitiated(callId, fromTag, toTag) && dialog->isSameLocalCseq(message)) { matchesTransaction = TRUE; } unlock(); return(matchesTransaction); } UtlBoolean SipDialogMgr::isNewRemoteTransaction(const SipMessage& message) { UtlBoolean matchesTransaction = FALSE; UtlString handle; message.getDialogHandle(handle); UtlString callId; UtlString fromTag; UtlString toTag; SipDialog::parseHandle(handle, callId, fromTag, toTag); lock(); // Looking for any dialog that matches this handle SipDialog* dialog = findDialog(handle, TRUE, // if established, match early dialog TRUE); // if early, match established dialog if(dialog && dialog->isTransactionRemotelyInitiated(callId, fromTag, toTag) && dialog->isNextRemoteCseq(message)) { matchesTransaction = TRUE; } unlock(); return(matchesTransaction); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ SipDialog* SipDialogMgr::findDialog(UtlString& dailogHandle, UtlBoolean ifHandleEstablishedFindEarlyDialog, UtlBoolean ifHandleEarlyFindEstablishedDialog) { UtlString callId; UtlString localTag; UtlString remoteTag; SipDialog::parseHandle(dailogHandle, callId, localTag, remoteTag); return(findDialog(callId, localTag, remoteTag, ifHandleEstablishedFindEarlyDialog, ifHandleEarlyFindEstablishedDialog)); } SipDialog* SipDialogMgr::findDialog(UtlString& callId, UtlString& localTag, UtlString& remoteTag, UtlBoolean ifHandleEstablishedFindEarlyDialog, UtlBoolean ifHandleEarlyFindEstablishedDialog) { SipDialog* dialog = NULL; UtlHashBagIterator iterator(mDialogs, &callId); // Look at all the dialogs with the same call-id while((dialog = (SipDialog*) iterator())) { // Check for exact match on the dialog handle if(dialog->isSameDialog(callId,localTag, remoteTag)) { break; } } // Check if this established dialog handle matches an early dialog if(!dialog && ifHandleEstablishedFindEarlyDialog) { iterator.reset(); while((dialog = (SipDialog*) iterator())) { // Check for match on the early dialog for the handle if(dialog->isEarlyDialogFor(callId, localTag, remoteTag)) { break; } } } // Check if this early dialog handle matches an established dialog if(!dialog && ifHandleEarlyFindEstablishedDialog) { iterator.reset(); while((dialog = (SipDialog*) iterator())) { // Check for match on the early dialog for the handle if(dialog->wasEarlyDialogFor(callId, localTag, remoteTag)) { break; } } } return(dialog); } UtlBoolean SipDialogMgr::deleteDialog(const char* dialogHandle) { UtlBoolean dialogRemoved = FALSE; UtlString handle(dialogHandle ? dialogHandle : ""); lock(); // Not sure if it should match all flavors of dialog, especially the // last one (i.e. ealy handle matching an established SipDialog* dialog = findDialog(handle, TRUE, // match early dialogs for handle TRUE); // if early, match established if(dialog) { dialogRemoved = TRUE; mDialogs.removeReference(dialog); delete dialog; dialog = NULL; } unlock(); return(dialogRemoved); } void SipDialogMgr::lock() { mDialogMgrMutex.acquire(); } void SipDialogMgr::unlock() { mDialogMgrMutex.release(); } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipDialogMonitor.cpp0000644000175000017500000005631612205613256025134 0ustar00danieldaniel00000000000000// // // Copyright (C) 2006-2010 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2005 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2005 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include #include #include #include // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STRUCTS // TYPEDEFS // FORWARD DECLARATIONS // STATIC VARIABLE INITIALIZATIONS // Constructor SipDialogMonitor::SipDialogMonitor(SipUserAgent* userAgent, UtlString& domainName, int hostPort, int refreshTimeout, bool toBePublished) : mLock(OsBSem::Q_PRIORITY, OsBSem::FULL) { mpUserAgent = userAgent; mDomainName = domainName; UtlString localAddress; OsSocket::getHostIp(&localAddress); Url url(localAddress); url.setHostPort(hostPort); url.includeAngleBrackets(); mContact = url.toString(); mRefreshTimeout = refreshTimeout; mToBePublished = toBePublished; // Create the SIP Subscribe Client mpRefreshMgr = new SipRefreshManager(*mpUserAgent, mDialogManager); // Component for refreshing the subscription mpRefreshMgr->start(); mpSipSubscribeClient = new SipSubscribeClient(*mpUserAgent, mDialogManager, *mpRefreshMgr); mpSipSubscribeClient->start(); if (mToBePublished) { // Create the SIP Subscribe Server mpSubscriptionMgr = new SipSubscriptionMgr(); // Component for holding the subscription data mpSubscribeServer = new SipSubscribeServer(*mpUserAgent, mSipPublishContentMgr, *mpSubscriptionMgr, mPolicyHolder); mpSubscribeServer->enableEventType(DIALOG_EVENT_TYPE); mpSubscribeServer->start(); } else { mpSubscriptionMgr = NULL; mpSubscribeServer = NULL; } } // Destructor SipDialogMonitor::~SipDialogMonitor() { if (mpSipSubscribeClient) { mpSipSubscribeClient->endAllSubscriptions(); delete mpSipSubscribeClient; } if (mpRefreshMgr) { delete mpRefreshMgr; } if (mpSubscriptionMgr) { delete mpSubscriptionMgr; } if (mpSubscribeServer) { delete mpSubscribeServer; } mMonitoredLists.destroyAll(); mDialogEventList.destroyAll(); mStateChangeNotifiers.destroyAll(); } bool SipDialogMonitor::addExtension(UtlString& groupName, Url& contactUrl) { bool result = false; mLock.acquire(); // Check whether the group already exists. If not, create one. SipResourceList* list = static_cast (mMonitoredLists.findValue(&groupName)); if (list == NULL) { UtlString* listName = new UtlString(groupName); list = new SipResourceList((UtlBoolean)TRUE, listName->data(), DIALOG_EVENT_TYPE); mMonitoredLists.insertKeyAndValue(listName, list); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::addExtension insert listName %s and object %p to the resource list", groupName.data(), list); } // Check whether the contact has already been added to the group. UtlString resourceId; contactUrl.getIdentity(resourceId); Resource* resource = list->getResource(resourceId); if (resource == NULL) { // If not, add it. resource = new Resource(resourceId); UtlString userName; contactUrl.getDisplayName(userName); resource->setName(userName); UtlString id; NetMd5Codec::encode(resourceId, id); resource->setInstance(id, STATE_PENDIND); list->insertResource(resource); // Set up the subscription to the URI. OsSysLog::add(FAC_LOG, PRI_DEBUG, "SipDialogMonitor::addExtension Sending out the SUBSCRIBE to contact %s", resourceId.data()); UtlString toUrl; contactUrl.toString(toUrl); UtlString fromUri = "dialogMonitor@" + mDomainName; UtlString earlyDialogHandle; UtlBoolean status = mpSipSubscribeClient->addSubscription(resourceId.data(), DIALOG_EVENT_TYPE, DIALOG_EVENT_CONTENT_TYPE, fromUri.data(), toUrl.data(), mContact.data(), mRefreshTimeout, (void *) this, SipDialogMonitor::subscriptionStateCallback, SipDialogMonitor::notifyEventCallback, earlyDialogHandle); if (!status) { result = false; OsSysLog::add(FAC_LOG, PRI_ERR, "SipDialogMonitor::addExtension Subscription failed to contact %s.", resourceId.data()); } else { mDialogHandleList.insertKeyAndValue(new UtlString(resourceId), new UtlString(earlyDialogHandle)); createDialogState(&earlyDialogHandle); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::addExtension Added earlyDialogHandle: %s", earlyDialogHandle.data()); result = true; } } else { OsSysLog::add(FAC_LOG, PRI_WARNING, "SipDialogMonitor::addExtension contact %s already exists.", resourceId.data()); } list->buildBody(); mLock.release(); return result; } bool SipDialogMonitor::removeExtension(UtlString& groupName, Url& contactUrl) { bool result = false; mLock.acquire(); // Check whether the group exists or not. If not, return false. SipResourceList* list = static_cast (mMonitoredLists.findValue(&groupName)); if (list == NULL) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::removeExtension group %s does not exist", groupName.data()); } else { // Check whether the contact exists in the group or not. UtlString resourceId; contactUrl.getIdentity(resourceId); Resource* resource = list->getResource(resourceId); if (resource) { // If it exists, get the early dialog handle for the SUBSCRIBE, // which specifies all of its subscriptions. UtlString* earlyDialogHandle = static_cast (mDialogHandleList.findValue(&resourceId)); if (earlyDialogHandle) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::removeExtension Calling endSubscription(%s)", earlyDialogHandle->data()); // Terminate the subscription. UtlBoolean status = mpSipSubscribeClient->endSubscription(earlyDialogHandle->data()); if (!status) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipDialogMonitor::removeExtension Unsubscription failed for %s.", resourceId.data()); } // Remove the remembered state for dialog event notices. destroyDialogState(earlyDialogHandle); } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipDialogMonitor::removeExtension no dialogHandle for %s.", resourceId.data()); } // Now delete all the references to this URI. mDialogHandleList.destroy(&resourceId); resource = list->removeResource(resource); delete resource; result = true; } else { OsSysLog::add(FAC_LOG, PRI_WARNING, "SipDialogMonitor::removeExtension subscription for contact %s does not exists.", resourceId.data()); } } mLock.release(); return result; } // Add 'dialogEvent' to mDialogEventList as the last dialog event for // AOR 'contact'. // Call notifyStateChange(), and if mToBePUblished, publishContent() // to report this information. void SipDialogMonitor::addDialogEvent(UtlString& contact, SipDialogEvent* dialogEvent, const char* earlyDialogHandle, const char* dialogHandle) { if (mDialogEventList.find(&contact) == NULL) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::addDialogEvent adding dialogEvent %p for contact '%s'", dialogEvent, contact.data()); } else { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::addDialogEvent dialogEvent %p for contact '%s' already exists, updating the content.", dialogEvent, contact.data()); // Get the object from the dialog event list UtlContainable* oldKey; UtlContainable* foundValue; oldKey = mDialogEventList.removeKeyAndValue(&contact, foundValue); delete oldKey; SipDialogEvent* oldDialogEvent = static_cast (foundValue); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::addDialogEvent removing the dialogEvent %p for contact '%s'", oldDialogEvent, contact.data()); if (oldDialogEvent) { delete oldDialogEvent; } } // Insert the AOR that we subscribed to into the DialogEvent // object, to overwrite the entity URI provided in the body of the // dialog event. dialogEvent->setEntity(contact.data()); // Rebuild the body. dialogEvent->buildBody(); // Insert it into the dialog event list // :TODO: This does not merge partial dialogs with the previous state. mDialogEventList.insertKeyAndValue(new UtlString(contact), dialogEvent); if (mToBePublished) { // Publish the content to the resource list. publishContent(contact, dialogEvent); } // Merge the information in the current NOTIFY with the recorded state. // Return the on/off hook status. StateChangeNotifier::Status status = mergeEventInformation(dialogEvent, earlyDialogHandle, dialogHandle); // Notify listeners of the state change. notifyStateChange(contact, status); } void SipDialogMonitor::publishContent(UtlString& contact, SipDialogEvent* dialogEvent) { bool contentChanged; // Loop through all the resource lists UtlHashMapIterator iterator(mMonitoredLists); UtlString* listUri; SipResourceList* list; Resource* resource; UtlString id, state; while ((listUri = static_cast (iterator()))) { contentChanged = false; list = static_cast (mMonitoredLists.findValue(listUri)); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::publishContent listUri %s list %p", listUri->data(), list); // Search for the contact in this list resource = list->getResource(contact); if (resource) { resource->getInstance(id, state); // :TODO: // The following code is incorrect. The "state" of a resource in a // resource list reports on the status of the subscription // from the resource list server to the resource's event // publisher (draft-ietf-simple-event-list-07, top of p. 10), // not the on-hook/off-hook status of a SIP agent for an AOR. if (dialogEvent->isEmpty()) { resource->setInstance(id, STATE_TERMINATED); } else { resource->setInstance(id, STATE_ACTIVE); } list->buildBody(); contentChanged = true; } if (contentChanged) { // Publish the content to the subscribe server // Make a copy, because mpSipPublishContentMgr will own it. HttpBody* pHttpBody = new HttpBody(*(HttpBody*)list); mSipPublishContentMgr.publish(listUri->data(), DIALOG_EVENT_TYPE, DIALOG_EVENT_TYPE, 1, &pHttpBody); } } } void SipDialogMonitor::subscriptionStateCallback(SipSubscribeClient::SubscriptionState newState, const char* earlyDialogHandle, const char* dialogHandle, void* applicationData, int responseCode, const char* responseText, long expiration, const SipMessage* subscribeResponse) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::subscriptionStateCallback is called with responseCode = %d (%s)", responseCode, responseText); } // Callback to handle incoming NOTIFYs. void SipDialogMonitor::notifyEventCallback(const char* earlyDialogHandle, const char* dialogHandle, void* applicationData, const SipMessage* notifyRequest) { // Receive the notification and process the message // Our SipdialogMonitor is pointed to by the applicationData. SipDialogMonitor* pThis = (SipDialogMonitor *) applicationData; pThis->handleNotifyMessage(notifyRequest, earlyDialogHandle, dialogHandle); } /// Non-static callback to handle incoming NOTIFYs. void SipDialogMonitor::handleNotifyMessage(const SipMessage* notifyMessage, const char* earlyDialogHandle, const char* dialogHandle) { Url fromUrl; notifyMessage->getFromUrl(fromUrl); UtlString contact; fromUrl.getIdentity(contact); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::handleNotifyMessage receiving a notify message from %s", contact.data()); const HttpBody* notifyBody = notifyMessage->getBody(); if (notifyBody) { UtlString messageContent; int bodyLength; notifyBody->getBytes(&messageContent, &bodyLength); // Parse the content and store it in a SipDialogEvent object SipDialogEvent* sipDialogEvent = new SipDialogEvent(messageContent); // Add the SipDialogEvent object to the hash table addDialogEvent(contact, sipDialogEvent, earlyDialogHandle, dialogHandle); } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipDialogMonitor::handleNotifyMessage receiving an empty notify body from %s", contact.data()); } } void SipDialogMonitor::addStateChangeNotifier(const char* listUri, StateChangeNotifier* notifier) { mLock.acquire(); UtlString* name = new UtlString(listUri); UtlVoidPtr* value = new UtlVoidPtr(notifier); mStateChangeNotifiers.insertKeyAndValue(name, value); mLock.release(); } void SipDialogMonitor::removeStateChangeNotifier(const char* listUri) { mLock.acquire(); UtlString name(listUri); mStateChangeNotifiers.destroy(&name); mLock.release(); } // Report to all the notifiers in mStateChangeNotifiers a new event // 'dialogEvent' for AOR 'contact'. void SipDialogMonitor::notifyStateChange(UtlString& contact, StateChangeNotifier::Status status) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::notifyStateChange " "AOR = '%s', status = %s", contact.data(), (status == StateChangeNotifier::ON_HOOK ? "ON_HOOK" : status == StateChangeNotifier::OFF_HOOK ? "OFF_HOOK" : "UNKNOWN")); Url contactUrl(contact); // Loop through the notifier list, reporting the status to the notifiers. UtlHashMapIterator iterator(mStateChangeNotifiers); UtlString* listUri; UtlVoidPtr* container; StateChangeNotifier* notifier; while ((listUri = static_cast (iterator()))) { container = static_cast (mStateChangeNotifiers.findValue(listUri)); notifier = (StateChangeNotifier *) container->getValue(); // Report the status to the notifier. notifier->setStatus(contactUrl, status); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::notifyStateChange setting state to %d", status); } } StateChangeNotifier::Status SipDialogMonitor::mergeEventInformation(SipDialogEvent* dialogEvent, const char* earlyDialogHandle, const char* dialogHandle) { // Status to be returned to caller. StateChangeNotifier::Status rc; OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::mergeEventInformation " "earlyDialogHandle = '%s', dialogHandle = '%s'", earlyDialogHandle, dialogHandle); // Get the list of active dialogs for the group of subscriptions generated // by this SUBSCRIBE. UtlString earlyDialogHandleString(earlyDialogHandle); UtlHashBag* active_dialog_list = static_cast (mDialogState.findValue(&earlyDialogHandleString)); // Ignore the event if there is no entry in mDialogState -- this is a // NOTIFY that arrived after and un-SUBSCRIBE terminated its subscription. if (active_dialog_list) { // If this is a full update, remove from the active list any dialog // for this dialog handle. UtlString notify_state; dialogEvent->getState(notify_state); if (notify_state.compareTo("full") == 0) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::mergeEventInformation " "active_dialog_list elements for handle '%s'", dialogHandle); // Iterate through the active dialog list, removing elements // for this dialog handle. UtlHashBagIterator dialog_id_itor(*active_dialog_list); UtlString* dialog_id; while ((dialog_id = static_cast (dialog_id_itor()))) { // Extract the dialog handle part of the dialog identifier string // and compare it to the dialog handle of this event notice. if (strcmp(dialogHandle, dialog_id->data() + dialog_id->index("\001") + 1) == 0) { // This is a dialog for this subscription, so remove it. active_dialog_list->remove(dialog_id); } } } // Iterate through the dialog event, updating active_dialog_list for // each dialog mentioned. UtlSListIterator* dialog_itor = dialogEvent->getDialogIterator(); Dialog* dialog; UtlString state, event, code, dialogId; while ((dialog = static_cast ((*dialog_itor)()))) { // Construct the dialog identifier string, // dialog->getDialogId(dialogId); dialogId.append("\001"); dialogId.append(dialogHandle); dialog->getState(state, event, code); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::mergeEventInformation " "dialogId '%s' state '%s' event '%s' code '%s'", dialogId.data(), state.data(), event.data(), code.data()); if (state.compareTo("terminated") != 0) { // Active dialog. // If it is not in active_dialog_list, add it. if (!active_dialog_list->contains(&dialogId)) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::mergeEventInformation " "adding dialog '%s'", dialogId.data()); active_dialog_list->insert(new UtlString(dialogId)); } } else { // Terminated dialog // If it is in active_dialog_list, remove it. OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::mergeEventInformation " "removing dialog '%s'", dialogId.data()); active_dialog_list->destroy(&dialogId); } } delete dialog_itor; // If debugging, list the active dialog list. if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { UtlHashBagIterator dialog_list_itor(*active_dialog_list); UtlString* dialog; while ((dialog = static_cast (dialog_list_itor()))) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::mergeEventInformation " "active dialog '%s'", dialog->data()); } OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::mergeEventInformation " "End of list"); } // Set the return code based on whether there are any active dialogs. rc = active_dialog_list->isEmpty() ? StateChangeNotifier::ON_HOOK : StateChangeNotifier::OFF_HOOK; } else { // This is a late NOTIFY and there are (should be) no notifiers for it, // so the return code is arbitrary. OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::mergeEventInformation " "No active dialog list found"); rc = StateChangeNotifier::ON_HOOK; } return rc; } void SipDialogMonitor::createDialogState(UtlString* earlyDialogHandle) { mDialogState.insertKeyAndValue(new UtlString(*earlyDialogHandle), new UtlHashBag); } void SipDialogMonitor::destroyDialogState(UtlString* earlyDialogHandle) { // Remove the remembered state for the subscriptions with this // early dialog handle. UtlHashBag* active_dialog_list = static_cast (mDialogState.findValue(earlyDialogHandle)); // Remove the contents of the UtlHashBag which is the value. active_dialog_list->destroyAll(); // Now remove the entry in mDialogState and the UtlHashBag itself. mDialogState.destroy(earlyDialogHandle); } sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipLine.cpp0000644000175000017500000003145112205613256023245 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #if defined(_VXWORKS) # include # include #endif #include #include #include #include #include #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// // Copy constructor SipLine::SipLine(const SipLine& rSipLine) { mIsVisible = rSipLine.mIsVisible ; mIdentity = rSipLine.mIdentity ; mUserEnteredUrl = rSipLine.mUserEnteredUrl; mUser = rSipLine.mUser ; mCurrentState = rSipLine.mCurrentState ; mIsAutoEnabled = rSipLine.mIsAutoEnabled ; mIsUsingCallHandling = rSipLine.mIsUsingCallHandling; mCanonicalUrl = rSipLine.mCanonicalUrl; mLineId = rSipLine.mLineId; mPreferredContactUri = rSipLine.mPreferredContactUri ; meContactType = rSipLine.meContactType; copyCredentials(rSipLine); } SipLine& SipLine::operator=(const SipLine& rSipLine) { if (this == &rSipLine) // handle the assignment to self case return *this; else { mIsVisible = rSipLine.mIsVisible ; mIdentity = rSipLine.mIdentity ; mUserEnteredUrl = rSipLine.mUserEnteredUrl; mCanonicalUrl = rSipLine.mCanonicalUrl; mUser = rSipLine.mUser ; mCurrentState = rSipLine.mCurrentState ; mIsAutoEnabled = rSipLine.mIsAutoEnabled ; mIsUsingCallHandling = rSipLine.mIsUsingCallHandling; mLineId = rSipLine.mLineId; mPreferredContactUri = rSipLine.mPreferredContactUri ; meContactType = rSipLine.meContactType; copyCredentials(rSipLine); } return *this; } //deep copy of credentials void SipLine::copyCredentials(const SipLine &rSipLine) { UtlString Realm; UtlString UserID; UtlString Type; UtlString Password; if(!mCredentials.isEmpty()) { mCredentials.destroyAll(); } if (! rSipLine.mCredentials.isEmpty()) { UtlHashBagIterator observerIterator(const_cast (rSipLine.mCredentials)); SipLineCredentials* credential = NULL; do { credential = (SipLineCredentials*) observerIterator(); if ( credential) { credential->getRealm(&Realm); credential->getUserId(&UserID); credential->getType(&Type); credential->getPasswordToken(&Password); addCredentials(Realm , UserID , Password , Type); } } while(credential != NULL) ; } } SipLine::SipLine(Url userEnteredUrl, Url identityUri, UtlString user, UtlBoolean visible, int state, UtlBoolean isAutoEnabled, UtlBoolean useCallHandling) { if (user.isNull()) { mUser = userEnteredUrl.toString(); } else { mUser = user; } mIsVisible = visible; mCurrentState = state; mIsAutoEnabled = isAutoEnabled; mIsUsingCallHandling = useCallHandling; mUserEnteredUrl = userEnteredUrl; meContactType = LINE_CONTACT_NAT_MAPPED ; if (identityUri.toString().isNull()) { //then get uri from user entered url ...uri is complete in it UtlString uri; mUserEnteredUrl.getUri(uri); mIdentity = Url(uri); } else { mIdentity = identityUri; } //construct a complete url from identity and userEntered Url. mCanonicalUrl = mUserEnteredUrl; UtlString address; mUserEnteredUrl.getHostAddress(address); if (address.isNull()) { UtlString identityHost; mIdentity.getHostAddress(identityHost); int identityPort = mIdentity.getHostPort(); mCanonicalUrl.setHostAddress(identityHost); mCanonicalUrl.setHostPort(identityPort); } // create new Line Id for this line generateLineID(mLineId); } SipLine::~SipLine() { mCredentials.destroyAll(); } UtlString& SipLine::getLineId() { return mLineId; } UtlBoolean SipLine::isDeviceLine() { return (getUser().compareTo("Device", UtlString::ignoreCase) == 0) ; } int SipLine::getState() { return mCurrentState; } void SipLine::setState(int state) { mCurrentState = state; } UtlString& SipLine::getUser() { return mUser; } void SipLine::setUser(const UtlString user) { mUser.remove(0); mUser.append(user); } void SipLine::getIdentityAndUrl(Url &identity, Url &userEnteredUrl) { identity = mIdentity; userEnteredUrl = mUserEnteredUrl; } void SipLine::setIdentityAndUrl(Url identity, Url userEnteredUrl) { UtlString identityHost; UtlString address; int identityPort; mIdentity = identity; mLineId.remove(0); generateLineID(mLineId); mUserEnteredUrl = userEnteredUrl; //construct a complete url from identity and userEntered Url. mCanonicalUrl = mUserEnteredUrl; mUserEnteredUrl.getHostAddress(address); if (address.isNull()) { mIdentity.getHostAddress(identityHost); identityPort = mIdentity.getHostPort(); mCanonicalUrl.setHostAddress(identityHost); mCanonicalUrl.setHostPort(identityPort); } } Url& SipLine::getUserEnteredUrl() { return mUserEnteredUrl; } Url& SipLine::getIdentity() { return mIdentity; } Url& SipLine::getCanonicalUrl() { return mCanonicalUrl; } void SipLine::setAutoEnableStatus( UtlBoolean isAutoEnabled) { mIsAutoEnabled = isAutoEnabled; } UtlBoolean SipLine::getAutoEnableStatus() { return mIsAutoEnabled ; } void SipLine::setVisibility(UtlBoolean isEnable) { mIsVisible = isEnable; } UtlBoolean SipLine::getVisibility() { return mIsVisible; } void SipLine::setCallHandling(UtlBoolean useCallHandling) { mIsUsingCallHandling = useCallHandling; } UtlBoolean SipLine::getCallHandling() { return mIsUsingCallHandling; } UtlBoolean SipLine::addCredentials( const UtlString& strRealm, const UtlString& strUserID, const UtlString& strPasswd, const UtlString& Type) { UtlBoolean isAdded = FALSE; if(!IsDuplicateRealm(strRealm, Type)) { SipLineCredentials* credential = new SipLineCredentials(strRealm , strUserID, strPasswd, Type); mCredentials.insert((UtlString*)credential); isAdded = TRUE; #ifdef TEST_PRINT OsSysLog::add(FAC_AUTH, PRI_DEBUG, "SipLine::addCredentials(realm=%s, userId=%s, password=%s, type=%s) number of credentials: %d for line: %s", strRealm.data(), strUserID.data(), strPasswd.isNull() ? "" : "******", Type.data(), mCredentials.entries(), mIdentity.toString().data()); #endif } else { OsSysLog::add(FAC_AUTH, PRI_DEBUG, "SipLine::addCredentials(realm=%s, userId=%s, ...) not added as its a duplicate", strRealm.data(), strUserID.data()); } return isAdded; } int SipLine::GetNumOfCredentials() { return mCredentials.entries(); } UtlBoolean SipLine::getCredentials(const UtlString& type /*[in]*/, const UtlString& realm /*[in]*/, UtlString* userID /*[out]*/, UtlString* MD5_token /*[out]*/) { UtlBoolean credentialsFound = FALSE; UtlString matchRealm(realm); UtlString emptyRealm(NULL); UtlString userPassword; *MD5_token = ""; #ifdef TEST_PRINT OsSysLog::add(FAC_AUTH, PRI_DEBUG, "SipLine::getCredentials credential count: %d for line: %s", mCredentials.entries(), mIdentity.toString().data()); #endif SipLineCredentials* credential = (SipLineCredentials*) mCredentials.find(&matchRealm); if (credential) { #ifdef TEST_PRINT OsSysLog::add(FAC_AUTH, PRI_DEBUG, "SipLine::getCredentials found credentials for realm: <%s>", matchRealm.data()); #endif credential->getUserId(userID); credential->getPasswordToken(&userPassword); credentialsFound = TRUE; credential = NULL; HttpMessage::buildMd5UserPasswordDigest(userID->data(), matchRealm.data(), userPassword.data(), *MD5_token); } else { credential = (SipLineCredentials*) mCredentials.find(&emptyRealm); if (credential) { #ifdef TEST_PRINT OsSysLog::add(FAC_AUTH, PRI_DEBUG, "SipLine::getCredentials found credentials for realm: <%s>", emptyRealm.data()); #endif credential->getUserId(userID); credential->getPasswordToken(&userPassword); credentialsFound = TRUE; credential = NULL; HttpMessage::buildMd5UserPasswordDigest(userID->data(), realm.data(), userPassword.data(), *MD5_token); } #ifdef TEST_PRINT else { OsSysLog::add(FAC_AUTH, PRI_DEBUG, "SipLine::getCredentials found no credentials"); } #endif } return credentialsFound ; } UtlBoolean SipLine::getDuplicateCredentials(const UtlString& type /*[in]*/, const UtlString& realm /*[in]*/) { UtlBoolean credentialsFound = FALSE; UtlString matchRealm(realm); UtlString emptyRealm(NULL); if (realm.length() == 0) { SipLineCredentials* credential = (SipLineCredentials*) mCredentials.find(&emptyRealm); if (credential) { credentialsFound = TRUE; credential = NULL; } } else { SipLineCredentials* credential = (SipLineCredentials*) mCredentials.find(&matchRealm); if (credential) { credentialsFound = TRUE; credential = NULL; } } return credentialsFound ; } UtlBoolean SipLine::removeCredential(const UtlString *realm) { UtlString matchRealm(*realm); #if 0 OsSysLog::add(FAC_SIP, PRI_INFO, "SipLine::removeCredential mCredentials contains: %d credentials for realm: \"%s\"", mCredentials.entries(), matchRealm.data()); #endif UtlContainable* wasRemoved = mCredentials.remove(&matchRealm); if(wasRemoved) { delete wasRemoved; } return(wasRemoved != NULL); } void SipLine::removeAllCredentials() { mCredentials.destroyAll(); } void SipLine::setPreferredContactUri(const Url& preferredContactUri) { mPreferredContactUri = preferredContactUri ; } UtlBoolean SipLine::getPreferredContactUri(Url& preferredContactUri) const { UtlString host ; preferredContactUri = mPreferredContactUri ; preferredContactUri.getHostAddress(host) ; return (host.length() > 0) ; } LINE_CONTACT_TYPE SipLine::getContactType() const { return meContactType ; } void SipLine::setContactType(LINE_CONTACT_TYPE eContactType) { meContactType = eContactType ; } UtlBoolean SipLine::getAllCredentials( int MaxEnteries/*[in]*/ , int& actualEnteries /*[out/int]*/, UtlString realm[]/*[out/int]*/, UtlString userId[]/*[out/int]*/, UtlString type[]/*[out/int]*/, UtlString passtoken[]/*[out/int]*/) { UtlBoolean credentialsFound = FALSE; UtlString Realm; UtlString UserID; UtlString Type; UtlString Password; UtlString PassToken; int i = 0; UtlHashBagIterator observerIterator(mCredentials); SipLineCredentials* credential = NULL; do { credential = (SipLineCredentials*) observerIterator(); if ( credential) { credential->getRealm(&Realm); credential->getUserId(&UserID); credential->getType(&Type); credential->getPasswordToken(&Password) ; PassToken = ""; HttpMessage::buildMd5UserPasswordDigest(UserID.data(), Realm.data(), Password.data(), PassToken); realm[i].remove(0); realm[i].append(Realm); userId[i].remove(0); userId[i].append(UserID); type[i].remove(0); type[i].append(Type); passtoken[i].remove(0) ; passtoken[i].append(PassToken) ; i++; credentialsFound = TRUE; } } while(credential != NULL && i< MaxEnteries) ; actualEnteries = i; return credentialsFound ; } UtlBoolean SipLine::IsDuplicateRealm(const UtlString realm, const UtlString scheme) { UtlString userID; UtlString passToken; if (getDuplicateCredentials(scheme, realm)) return TRUE; else return FALSE; } void SipLine::generateLineID(UtlString& lineId) { NetMd5Codec::encode(mIdentity.toString().data(), lineId); // Shorten the line Ids to 12 chars (from 32) lineId.remove(12) ; } sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipLineCredentials.cpp0000644000175000017500000000324412205613256025422 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SipLineCredentials.cpp: implementation of the SipLineCredentials class. // ////////////////////////////////////////////////////////////////////// #include ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// SipLineCredentials::SipLineCredentials( const UtlString realm, const UtlString userId, const UtlString passwordToken, const UtlString type) :UtlString(realm) { mType = type; mPasswordToken = passwordToken; mUserId = userId; mRealm = realm; } SipLineCredentials::~SipLineCredentials() { } void SipLineCredentials::getRealm(UtlString* realm) { realm->remove(0); realm->append(mRealm); } void SipLineCredentials::getUserId(UtlString* UserId) { UserId->remove(0); UserId->append(mUserId); } void SipLineCredentials::getPasswordToken(UtlString* passToken) { passToken->remove(0); passToken->append(mPasswordToken); } void SipLineCredentials::getType(UtlString* type) { type->remove(0); type->append(mType); } sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipLineEvent.cpp0000644000175000017500000000503312205613256024244 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SipLineEvent.cpp: implementation of the SipLineEvent class. // ////////////////////////////////////////////////////////////////////// #include ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// SipLineEvent::SipLineEvent(SipLine* Line, int msgType, UtlString realm, UtlString scheme, int SipReturnCode, UtlString SipReturnText, void* observerData) :OsMsg(OsMsg::LINE_MGR_MSG, SipLineEvent::SIP_LINE_EVENT_FAILED) { if (Line) mLine = *Line; mRealm.remove(0); mScheme.remove(0); mRealm = realm; mScheme = scheme; mSipReturnText = SipReturnText; mSipReturnCode = SipReturnCode; mMessageType = msgType; mObserverData = observerData; } SipLineEvent::~SipLineEvent() { } SipLine* SipLineEvent::getLine() { return &mLine; } UtlString& SipLineEvent::getSipReturnText() { return mSipReturnText; } int SipLineEvent::getSipReturnCode() { return mSipReturnCode; } UtlString& SipLineEvent::getRealm() { return mRealm; } UtlString& SipLineEvent::getScheme() { return mScheme; } void SipLineEvent::setMessageType(int status) { mMessageType= status; } int SipLineEvent::getMessageType() const { return(mMessageType); } void SipLineEvent::setObserverData(void* pData) { mObserverData = pData; } void* SipLineEvent::getObserverData() { return mObserverData; } SipLineEvent& SipLineEvent::operator=(const SipLineEvent& rhs) { if (this == &rhs) // handle the assignment to self case return *this; mLine = rhs.mLine ; mRealm = rhs.mRealm ; mScheme = rhs.mScheme ; mSipReturnText = rhs.mSipReturnText; mSipReturnCode = rhs.mSipReturnCode ; mMessageType = rhs.mMessageType ; mObserverData = rhs.mObserverData ; return *this; } OsMsg* SipLineEvent::createCopy(void) const { SipLine line = mLine ; return new SipLineEvent(&line, mMessageType, mRealm, mScheme, mSipReturnCode, mSipReturnText, mObserverData) ; } sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipLineList.cpp0000644000175000017500000002463512205613256024107 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include "net/SipLineList.h" #include "os/OsSysLog.h" //#define TEST_PRINT ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// SipLineList::SipLineList() {} SipLineList::~SipLineList() { while (SipLine* pLine = (SipLine*) m_LineList.pop()) { delete pLine ; } } void SipLineList::add(SipLine *newLine) { m_LineList.push(newLine); } UtlBoolean SipLineList::remove(SipLine *line) { // Changed this to call common code Url lineIdentityUrl = line->getIdentity(); return remove( lineIdentityUrl ); } UtlBoolean SipLineList::remove(const Url& lineIdentityUrl) { SipLine* nextline = NULL; int iteratorHandle = m_LineList.getIteratorHandle(); while(NULL != (nextline = (SipLine*) m_LineList.next(iteratorHandle))) { // compare the line identities Url nextLineUrl = nextline->getIdentity(); if (lineIdentityUrl.isUserHostPortEqual(nextLineUrl)) { m_LineList.remove(iteratorHandle); break; } } m_LineList.releaseIteratorHandle(iteratorHandle); return( nextline != NULL ); } UtlBoolean SipLineList::isDuplicate( SipLine *line ) { // Changed this to call common code Url lineIdentityUrl = line->getIdentity(); return isDuplicate( lineIdentityUrl ); } UtlBoolean SipLineList::isDuplicate( const Url& lineIdentityUrl ) { SipLine* nextline = NULL; UtlBoolean isDuplicate = FALSE; int iteratorHandle = m_LineList.getIteratorHandle(); while(NULL != (nextline = (SipLine*) m_LineList.next(iteratorHandle))) { // compare the line identities Url nextLineUrl = nextline->getIdentity(); if (lineIdentityUrl.isUserHostPortEqual(nextLineUrl)) { isDuplicate = TRUE; break; } } m_LineList.releaseIteratorHandle(iteratorHandle); return isDuplicate; } SipLine* SipLineList::getLine( const Url& lineIdentityUrl ) { SipLine* nextline = NULL; int iteratorHandle = m_LineList.getIteratorHandle(); while(NULL != (nextline = (SipLine*) m_LineList.next(iteratorHandle))) { // compare the line identities Url nextLineUrl = nextline->getIdentity(); if (lineIdentityUrl.isUserHostPortEqual(nextLineUrl)) { break ; } } m_LineList.releaseIteratorHandle(iteratorHandle); return nextline; } SipLine* SipLineList::getLine(const UtlString& lineId) { SipLine* nextline = NULL; if ( !lineId.isNull() ) { int iteratorHandle = m_LineList.getIteratorHandle(); while(NULL != (nextline = (SipLine*) m_LineList.next(iteratorHandle))) { // compare the line identities UtlString nextLineId = nextline->getLineId(); if (!nextLineId.isNull()) { #ifdef TEST_PRINT osPrintf( "SipLineList::getLine Comparing %s to %s \n", lineId.data(), nextLineId.data() ); #endif if( lineId == nextLineId ) { #ifdef TEST_PRINT osPrintf("SipLineList::getLine TRUE\n"); #endif break; } } } m_LineList.releaseIteratorHandle(iteratorHandle); } return nextline; } SipLine* SipLineList::getLine ( const UtlString& userId, int& numOfMatches ) { SipLine* nextline = NULL; SipLine* firstMatchedLine = NULL; UtlString nextUserId; numOfMatches = 0; if (!userId.isNull()) { int iteratorHandle = m_LineList.getIteratorHandle(); while(NULL != (nextline = (SipLine*) m_LineList.next(iteratorHandle))) { nextUserId.remove(0); Url identity = nextline->getIdentity(); identity.getUserId( nextUserId ); if (!nextUserId.isNull()) { #ifdef TEST_PRINT osPrintf( "SipLineList::getLine Comparing %s to %s \n", nextUserId.data(), userId.data() ); #endif if( nextUserId.compareTo( userId ) == 0 ) { #ifdef TEST_PRINT osPrintf("SipLineList::getLine TRUE\n"); #endif if( numOfMatches == 0) { firstMatchedLine = nextline; } numOfMatches ++; } } } m_LineList.releaseIteratorHandle(iteratorHandle); } return firstMatchedLine; } int SipLineList::getListSize() { return m_LineList.getCount(); } UtlBoolean SipLineList::linesInArray( int maxSize, int *returnSize, SipLine Line[]) { int counter = 0 ; UtlBoolean retVal; int iteratorHandle = m_LineList.getIteratorHandle(); SipLine* nextLine = NULL; while (counter < maxSize && ((nextLine = (SipLine*) m_LineList.next(iteratorHandle))!= NULL)) { //return copy of the line Line[counter] = *nextLine; counter++; } m_LineList.releaseIteratorHandle(iteratorHandle); *returnSize = counter; counter > 0 ? retVal = true : retVal = false; return retVal; } UtlBoolean SipLineList::linesInArray( int maxSize, int *returnSize, SipLine *Line[]) { int counter = 0 ; UtlBoolean retVal; int iteratorHandle = m_LineList.getIteratorHandle(); SipLine* nextLine = NULL; while (counter < maxSize && ((nextLine = (SipLine*) m_LineList.next(iteratorHandle))!= NULL)) { //return copy of the line *Line[counter] = *nextLine; counter++; } m_LineList.releaseIteratorHandle(iteratorHandle); *returnSize = counter; counter > 0 ? retVal = true : retVal = false; return retVal; } UtlBoolean SipLineList::getFirstLine( SipLine *Line ) { UtlBoolean retVal = FALSE; int iteratorHandle = m_LineList.getIteratorHandle(); SipLine* nextLine = NULL; nextLine = (SipLine*) m_LineList.next(iteratorHandle); if(nextLine) { //return copy of the line *Line = *nextLine; retVal = TRUE; } m_LineList.releaseIteratorHandle(iteratorHandle); return retVal; } UtlBoolean SipLineList::getDeviceLine(SipLine *line) { UtlBoolean retVal = FALSE; UtlString user; int iteratorHandle = m_LineList.getIteratorHandle(); SipLine* nextLine = NULL; while ((nextLine = (SipLine*) m_LineList.next(iteratorHandle))!= NULL) { user = nextLine->getUser(); if ( user.compareTo("device" , UtlString::ignoreCase) == 0) { *line = *nextLine; retVal = TRUE; break; } user.remove(0); } m_LineList.releaseIteratorHandle(iteratorHandle); return retVal; } // // Priorities: // 1. Matches first lineID & realm // 2. Matches first matches toFromUrl & realm // 3. Matches first user & realm // 4. Matches first default line & realm // SipLine* SipLineList::findLine(const char* lineId, const char* realm, const Url& toFromUrl, const char* userId, const Url& defaultLine) { SipLine* pLineMatchingLineID = NULL ; SipLine* pLineMatchingUrl = NULL ; SipLine* pLineMatchingUser = NULL ; SipLine* pLineMatchingDefault = NULL ; int iteratorHandle = m_LineList.getIteratorHandle(); SipLine* nextLine = NULL; while ((nextLine = (SipLine*) m_LineList.next(iteratorHandle))!= NULL) { // If the realm doesn't match, simply skip it if ((realm != NULL) && strlen(realm) && (!nextLine->IsDuplicateRealm(realm))) { continue ; } // // Priority 1: Check LineId // if (lineId != NULL) { if (nextLine->getLineId().compareTo(lineId) == 0) { // We have match for the given lineId pLineMatchingLineID = nextLine ; break ; } } Url nextLineIdentity = nextLine->getIdentity(); // // Priority 2: check ToFromUrl // if (pLineMatchingUrl == NULL) { if (nextLineIdentity.isUserHostPortEqual(toFromUrl)) { pLineMatchingUrl = nextLine ; // Continue searching, because we may find a better match } } // // Priority 3: Matches user & realm // UtlString user = nextLine->getUser() ; if ((pLineMatchingUser == NULL) && (userId != NULL)) { if (user.compareTo(userId) == 0) // should be case sensitive { pLineMatchingUser = nextLine ; // Continue searching, because we may find a better match } } // // Priority 4: Check for default line // if (nextLineIdentity.isUserHostPortEqual(defaultLine)) { pLineMatchingDefault = nextLine ; // Continue searching, because we may find a better match } } m_LineList.releaseIteratorHandle(iteratorHandle) ; // This is ugly, but needed for the desired effect if (pLineMatchingLineID) return pLineMatchingLineID ; else if (pLineMatchingUrl) return pLineMatchingUrl ; else if (pLineMatchingUser) return pLineMatchingUser ; else if (pLineMatchingDefault) return pLineMatchingDefault ; else return NULL ; } void SipLineList::dumpLines() { SipLine* nextline = NULL; int iteratorHandle = m_LineList.getIteratorHandle(); int i = 0; while(NULL != (nextline = (SipLine*) m_LineList.next(iteratorHandle))) { // compare the line identities Url nextLineUrl = nextline->getIdentity(); OsSysLog::add(FAC_LINE_MGR, PRI_DEBUG, "LineList %p [%d]: %s", this, i++, nextLineUrl.toString().data() ) ; } m_LineList.releaseIteratorHandle(iteratorHandle); } sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipLineMgr.cpp0000644000175000017500000015304712205613256023721 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #if defined(_VXWORKS) # include # include #endif #include #include // APPLICATION INCLUDES #include "utl/UtlHashBagIterator.h" #include "os/OsDateTime.h" #include "os/OsQueuedEvent.h" #include "os/OsTimer.h" #include "os/OsEventMsg.h" #include "os/OsConfigDb.h" #include "os/OsRWMutex.h" #include "os/OsReadLock.h" #include "os/OsWriteLock.h" #include "net/Url.h" #include "net/SipLineMgr.h" #include "net/SipObserverCriteria.h" #include "net/SipUserAgent.h" #include "net/SipMessage.h" #include "net/NetMd5Codec.h" #include "net/TapiMgr.h" #include "net/SipRefreshMgr.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC INITIALIZERS //#define TEST_PRINT 1 ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// SipLineMgr::SipLineMgr(const char* authenticationScheme) : OsServerTask( "SipLineMgr-%d" ), mAuthenticationScheme (HTTP_DIGEST_AUTHENTICATION), mpRefreshMgr (NULL), mObserverMutex(OsRWMutex::Q_FIFO) { // Authentication if(authenticationScheme) { mAuthenticationScheme.append(authenticationScheme); // Do not require authentication if not Basic or Digest if( 0 != mAuthenticationScheme.compareTo(HTTP_BASIC_AUTHENTICATION, UtlString::ignoreCase ) && 0 != mAuthenticationScheme.compareTo(HTTP_DIGEST_AUTHENTICATION, UtlString::ignoreCase ) ) { mAuthenticationScheme.remove(0); } } } SipLineMgr::~SipLineMgr() { dumpLines(); waitUntilShutDown(); // Do not delete the refresh manager as it was // created in another context and we do not know // who else may be using it } void SipLineMgr::dumpLines() { sLineList.dumpLines(); // now for sTempLineList sLineList.dumpLines(); } void SipLineMgr::StartLineMgr() { if(!isStarted()) { // start the thread start(); } mIsStarted = TRUE; } UtlBoolean SipLineMgr::handleMessage(OsMsg &eventMessage) { UtlBoolean messageProcessed = FALSE; int msgType = eventMessage.getMsgType(); // int msgSubType = eventMessage.getMsgSubType(); UtlString method; if(msgType == OsMsg::PHONE_APP ) { const SipMessage* sipMsg = static_cast(((SipMessageEvent&)eventMessage).getMessage()); int messageType = ((SipMessageEvent&)eventMessage).getMessageStatus(); //get line information related to this identity UtlString Address; UtlString Protocol; UtlString User; int Port; UtlString toUrl; UtlString Label; sipMsg->getToAddress(&Address, &Port, &Protocol, &User, &Label); SipMessage::buildSipUrl( &toUrl , Address , Port, Protocol, User , Label); SipLine* line = NULL; Url tempUrl ( toUrl ); line = sLineList.getLine( tempUrl ); if ( line) { // is this a request with a timeout? if ( !sipMsg->isResponse() && (messageType==SipMessageEvent::TRANSPORT_ERROR) ) { int CSeq; UtlString method; sipMsg->getCSeqField(&CSeq , &method); if (CSeq == 1) //first time registration - go directly to expired state { line->setState(SipLine::LINE_STATE_EXPIRED); SipLineEvent lineEvent(line, SipLineEvent::SIP_LINE_EVENT_NO_RESPONSE,"","",0,"No Response"); queueMessageToObservers(lineEvent); } else { line->setState(SipLine::LINE_STATE_FAILED); SipLineEvent lineEvent(line, SipLineEvent::SIP_LINE_EVENT_FAILED,"","",0,"No Response"); queueMessageToObservers(lineEvent); } // Log the failure syslog(FAC_LINE_MGR, PRI_ERR, "failed to register line (cseq=%d, no response): %s", CSeq, line->getLineId().data()) ; } else if( sipMsg->isResponse() ) { int responseCode = sipMsg->getResponseStatusCode(); UtlString sipResponseText; sipMsg->getResponseStatusText(&sipResponseText); if( (responseCode>= SIP_2XX_CLASS_CODE && responseCode < SIP_3XX_CLASS_CODE )) { //set line state to correct line->setState(SipLine::LINE_STATE_REGISTERED); SipLineEvent lineEvent(line, SipLineEvent::SIP_LINE_EVENT_SUCCESS,"","",responseCode,sipResponseText); queueMessageToObservers(lineEvent); // Log the success int CSeq; UtlString method; sipMsg->getCSeqField(&CSeq , &method); syslog(FAC_LINE_MGR, PRI_DEBUG, "registered line (cseq=%d): %s", CSeq, line->getLineId().data()) ; } else if( responseCode >= SIP_3XX_CLASS_CODE ) { // get error codes UtlString nonce; UtlString opaque; UtlString realm; UtlString scheme; UtlString algorithm; UtlString qop; //get realm and scheme if ( responseCode == HTTP_UNAUTHORIZED_CODE) { sipMsg->getAuthenticationData(&scheme, &realm, &nonce, &opaque, &algorithm, &qop, HttpMessage::SERVER); } else if ( responseCode == HTTP_PROXY_UNAUTHORIZED_CODE) { sipMsg->getAuthenticationData(&scheme, &realm, &nonce, &opaque, &algorithm, &qop, HttpMessage::PROXY); } //SDUATODO: LINE_STATE_FAILED after timing mechanism in place line->setState(SipLine::LINE_STATE_EXPIRED); SipLineEvent lineEvent( line, SipLineEvent::SIP_LINE_EVENT_FAILED, realm, scheme, responseCode, sipResponseText ); queueMessageToObservers(lineEvent); // Log the failure int CSeq; UtlString method; sipMsg->getCSeqField(&CSeq , &method); syslog(FAC_LINE_MGR, PRI_ERR, "failed to register line (cseq=%d, auth): %s\nnonce=%s, opaque=%s,\nrealm=%s,scheme=%s,\nalgorithm=%s, qop=%s", CSeq, line->getLineId().data(), nonce.data(), opaque.data(), realm.data(), scheme.data(), algorithm.data(), qop.data()) ; } } messageProcessed = TRUE; } // if line line = NULL; } return messageProcessed ; } UtlBoolean SipLineMgr::addLine(SipLine& line, UtlBoolean doEnable) { UtlBoolean added = FALSE; // check if it is a duplicate url if (!sLineList.isDuplicate(&line)) { addToList(&line); if (line.getState() == SipLine::LINE_STATE_REGISTERED) { if (doEnable) { enableLine(line.getIdentity()); } } added = TRUE; SipLineEvent lineEvent(&line, SipLineEvent::SIP_LINE_EVENT_LINE_ADDED); queueMessageToObservers(lineEvent); syslog(FAC_LINE_MGR, PRI_INFO, "SipLineMgr::addLine added line: %s", line.getIdentity().toString().data()) ; } dumpLines(); return added; } void SipLineMgr::deleteLine(const Url& identity) { SipLine *line = NULL; SipLine *pDeleteLine = NULL ; line = sLineList.getLine(identity) ; if (line == NULL) { syslog(FAC_LINE_MGR, PRI_ERR, "SipLineMgr::deleteLine unable to delete line (not found): %s", identity.toString().data()) ; return; } // we don't un-register any more // if (line->getState() == SipLine::LINE_STATE_REGISTERED ) // { // // Add to temporary list - needed if challenged for credentials. // addToTempList(line); // disableLine(identity, 0, identity.toString()); // } // else { removeFromList(line); removeFromTempList(line); pDeleteLine = line ; } // notify the observers that the line was deleted SipLineEvent lineEvent( line, SipLineEvent::SIP_LINE_EVENT_LINE_DELETED ); queueMessageToObservers( lineEvent ); syslog(FAC_LINE_MGR, PRI_INFO, "SipLineMgr::deleteLine deleted line: %s", identity.toString().data()) ; if (pDeleteLine) { delete pDeleteLine ; } dumpLines(); } void SipLineMgr::lineHasBeenUnregistered(const Url& identity) { SipLine *line = NULL; line = sLineList.getLine(identity) ; if (line == NULL) { syslog(FAC_LINE_MGR, PRI_ERR, "unable to delete line (not found): %s", identity.toString().data()) ; return; } //removeFromList(line); //delete line; } UtlBoolean SipLineMgr::enableLine(const Url& identity) { SipLine *line = NULL; line = sLineList.getLine(identity) ; if ( line == NULL) { syslog(FAC_LINE_MGR, PRI_ERR, "unable to enable line (not found): %s", identity.toString().data()) ; return FALSE; } //SipLineEvent lineEvent(line, SipLineEvent::SIP_LINE_EVENT_LINE_ENABLED); //queueMessageToObservers(lineEvent); line->setState(SipLine::LINE_STATE_TRYING); Url canonical = line->getCanonicalUrl(); Url preferredContact ; Url* pPreferredContact = NULL ; if (line->getPreferredContactUri(preferredContact)) { pPreferredContact = &preferredContact ; } if (!mpRefreshMgr->newRegisterMsg(canonical, line->getLineId(), -1, pPreferredContact)) { //duplicate ...call reregister mpRefreshMgr->reRegister(identity); } line = NULL; syslog(FAC_LINE_MGR, PRI_INFO, "enabled line: %s", identity.toString().data()) ; return TRUE; } void SipLineMgr::disableLine( const Url& identity, UtlBoolean onStartup, const UtlString& lineId) { SipLine *line = sLineList.getLine(identity) ; if ( line == NULL) { syslog(FAC_LINE_MGR, PRI_ERR, "SipLineMgr::disableLine unable to disable line (not found): %s", identity.toString().data()) ; } // we don't implicitly un-register any more if (line->getState() == SipLine::LINE_STATE_REGISTERED || line->getState() == SipLine::LINE_STATE_TRYING) { mpRefreshMgr->unRegisterUser(identity, onStartup, lineId); } SipLineEvent lineEvent(line, SipLineEvent::SIP_LINE_EVENT_LINE_DISABLED); queueMessageToObservers(lineEvent); syslog(FAC_LINE_MGR, PRI_INFO, "SipLineMgr::disableLine disabled line: %s", identity.toString().data()) ; } void SipLineMgr::notifyChangeInLineProperties(Url& identity) { SipLine *line = sLineList.getLine(identity) ; if (line == NULL) { // Ignore error, will be logged on remove/enable/disable/etc } SipLineEvent lineEvent(line, SipLineEvent::SIP_LINE_EVENT_LINE_CHANGED); queueMessageToObservers(lineEvent); } void SipLineMgr::notifyChangeInOutboundLine(Url& identity) { SipLine *line = sLineList.getLine(identity) ; if ( line == NULL) { // Ignore error, will be logged on remove/enable/disable/etc } SipLineEvent lineEvent(line, SipLineEvent::SIP_LINE_EVENT_OUTBOUND_CHANGED); queueMessageToObservers(lineEvent); } void SipLineMgr::setOwner(const UtlString& owner) { mOwner.remove(0); mOwner.append(owner); } const UtlString& SipLineMgr::getOwner() const { return mOwner; } void SipLineMgr::setDefaultOutboundLine(const Url& outboundLine) { mOutboundLine = outboundLine; syslog(FAC_LINE_MGR, PRI_INFO, "default line changed: %s", outboundLine.toString().data()) ; notifyChangeInOutboundLine( mOutboundLine ); } void SipLineMgr::getDefaultOutboundLine(UtlString &rOutBoundLine) { // check if default outbound is valid? UtlString host; mOutboundLine.getHostAddress(host); if( host.isNull()) { setFirstLineAsDefaultOutBound(); } rOutBoundLine.remove(0); rOutBoundLine.append(mOutboundLine.toString()); } void SipLineMgr::setFirstLineAsDefaultOutBound() { SipLine line; if (!sLineList.getDeviceLine(&line)) { sLineList.getFirstLine(&line); } Url outbound = line.getCanonicalUrl(); setDefaultOutboundLine(outbound); } UtlBoolean SipLineMgr::getLines( int maxLines /*[in]*/, int& actualLines /*[in/out]*/, SipLine lines[]/*[in/out]*/ ) const { UtlBoolean linesFound = FALSE; linesFound = sLineList.linesInArray( maxLines, &actualLines, lines); return linesFound; } UtlBoolean SipLineMgr::getLines( int maxLines /*[in]*/, int& actualLines /*[in/out]*/, SipLine* lines[]/*[in/out]*/) const { UtlBoolean linesFound = FALSE; linesFound = sLineList.linesInArray( maxLines, &actualLines, lines ); return linesFound; } int SipLineMgr::getNumLines() const { return sLineList.getListSize(); } UtlBoolean SipLineMgr::getLine( const UtlString& toField, const UtlString& localContact, SipLine& sipline ) const { UtlString temp; if( localContact.index("<") == UTL_NOT_FOUND) { temp.append("<"); temp.append(localContact); temp.append(">"); } else { temp.append(localContact); } Url localContactUrl(temp); UtlString lineId; UtlString userId; SipLine* line = NULL; localContactUrl.getUrlParameter( SIP_LINE_IDENTIFIER , lineId ); localContactUrl.getUserId(userId); Url toUrl(toField); int userIdmatches = 0; if( !lineId.isNull()) { line = sLineList.getLine(lineId) ; } if(!line && !userId.isNull()) { line = sLineList.getLine(userId, userIdmatches) ; if(userIdmatches > 1) { line = sLineList.getLine(toUrl) ; } } if(!line) { // try with just the userId UtlString userId; toUrl.getUserId(userId); line = sLineList.getLine(userId, userIdmatches ); } if(line) { sipline = *line; return TRUE; } return FALSE; } SipLine* SipLineMgr::getLineforAuthentication( const SipMessage* request /*[in]*/, const SipMessage* response /*[in]*/, const UtlBoolean& isIncomingRequest, const UtlBoolean& fromTempList) const { SipLine* line = NULL; UtlString lineId; Url toFromUrl; UtlString toFromUri; UtlString userId; UtlString nonce; UtlString opaque; UtlString realm; UtlString scheme; UtlString algorithm; UtlString qop; // Get realm and scheme (hard way but not too expensive) if (response != NULL) { if (!response->getAuthenticationData(&scheme, &realm, &nonce, &opaque, &algorithm, &qop, SipMessage::PROXY)) { if (!response->getAuthenticationData(&scheme, &realm, &nonce, &opaque, &algorithm, &qop, SipMessage::SERVER)) { // Report inability to get auth criteria UtlString callId ; UtlString method ; int sequenceNum ; response->getCallIdField(&callId); response->getCSeqField(&sequenceNum, &method); OsSysLog::add(FAC_LINE_MGR, PRI_ERR, "unable get auth data for message:\ncallid=%s\ncseq=%d\nmethod=%s", callId.data(), sequenceNum, method.data()) ; } else { OsSysLog::add(FAC_AUTH, PRI_DEBUG, "SERVER auth request:scheme=%s\nrealm=%s\nnounce=%s\nopaque=%s\nalgorithm=%s\nqop=%s", scheme.data(), realm.data(), nonce.data(), opaque.data(), algorithm.data(), qop.data()) ; } } else { OsSysLog::add(FAC_AUTH, PRI_DEBUG, "PROXY auth request:scheme=%s\nrealm=%s\nnounce=%s\nopaque=%s\nalgorithm=%s\nqop=%s", scheme.data(), realm.data(), nonce.data(), opaque.data(), algorithm.data(), qop.data()) ; } } // Get the LineID and userID if(isIncomingRequest) { //check line id in request uri UtlString requestUri; request->getRequestUri(&requestUri); UtlString temp; temp.append("<"); temp.append(requestUri); temp.append(">"); Url requestUriUrl(temp); requestUriUrl.getUrlParameter(SIP_LINE_IDENTIFIER , lineId); requestUriUrl.getUserId(userId); } else { //check line ID in contact UtlString contact; request->getContactEntry(0, &contact); Url contactUrl(contact); contactUrl.getUrlParameter(SIP_LINE_IDENTIFIER , lineId); contactUrl.getUserId(userId); } // Get the fromURL request->getFromUrl(toFromUrl); toFromUrl.removeFieldParameters(); toFromUrl.setDisplayName(""); toFromUrl.removeAngleBrackets(); UtlString emptyRealm(NULL); if (fromTempList) { line = sTempLineList.findLine(lineId.data(), realm.data(), toFromUrl, userId.data(), mOutboundLine) ; if (line == NULL) { line = sTempLineList.findLine(lineId.data(), emptyRealm.data(), toFromUrl, userId.data(), mOutboundLine) ; } } if (line == NULL) { line = sLineList.findLine(lineId.data(), realm.data(), toFromUrl, userId.data(), mOutboundLine) ; if (line == NULL) { line = sLineList.findLine(lineId.data(), emptyRealm.data(), toFromUrl, userId.data(), mOutboundLine) ; } } if (line == NULL) { // Get the toURL request->getToUrl(toFromUrl); toFromUrl.removeFieldParameters(); toFromUrl.setDisplayName(""); toFromUrl.removeAngleBrackets(); if (fromTempList) { line = sTempLineList.findLine(lineId.data(), realm.data(), toFromUrl, userId.data(), mOutboundLine) ; if (line == NULL) { line = sTempLineList.findLine(lineId.data(), emptyRealm.data(), toFromUrl, userId.data(), mOutboundLine) ; } } if (line == NULL) { line = sLineList.findLine(lineId.data(), realm.data(), toFromUrl, userId.data(), mOutboundLine) ; if (line == NULL) { line = sLineList.findLine(lineId.data(), emptyRealm.data(), toFromUrl, userId.data(), mOutboundLine) ; } } } if (line == NULL) { // Log the failure OsSysLog::add(FAC_AUTH, PRI_ERR, "line manager is unable to find line for auth \nuser=%s\nrealm=%s\nlineid=%s", userId.data(), realm.data(), lineId.data()) ; } else { // Log the SUCCESS OsSysLog::add(FAC_AUTH, PRI_INFO, "line manager found matching line for auth \nuser=%s\nrealm=%s\nlineid=%s", userId.data(), realm.data(), lineId.data()) ; } return line; } UtlBoolean SipLineMgr::isUserIdDefined( const SipMessage* request /*[in]*/ ) const { SipLine* line = NULL; line = getLineforAuthentication(request, NULL, TRUE); if(line) return TRUE; else return FALSE; } UtlBoolean SipLineMgr::buildAuthenticatedRequest( const SipMessage* response /*[in]*/, const SipMessage* request /*[in]*/, SipMessage* newAuthRequest /*[out]*/) { UtlBoolean createdResponse = FALSE; // Get the userId and password from the DB for the URI int sequenceNum; int authorizationEntity = HttpMessage::SERVER; UtlString uri; UtlString method; UtlString nonce; UtlString opaque; UtlString realm; UtlString scheme; UtlString algorithm; UtlString qop; UtlString callId; response->getCSeqField(&sequenceNum, &method); response->getCallIdField(&callId) ; int responseCode = response->getResponseStatusCode(); // Use the To uri as key to user and password to use if(responseCode == HTTP_UNAUTHORIZED_CODE) { authorizationEntity = HttpMessage::SERVER; } else if(responseCode == HTTP_PROXY_UNAUTHORIZED_CODE) { // For proxy we use the uri for the key to userId and password authorizationEntity = HttpMessage::PROXY; } // Get the digest authentication info. needed to create // a request with credentials response->getAuthenticationData( &scheme, &realm, &nonce, &opaque, &algorithm, &qop, authorizationEntity); UtlBoolean alreadyTriedOnce = FALSE; int requestAuthIndex = 0; UtlString requestUser; UtlString requestRealm; // if scheme is basic , we dont support it anymore and we //should not sent request again because the password has been //converterd to digest already and the BASIC authentication will fail anyway if(scheme.compareTo(HTTP_BASIC_AUTHENTICATION, UtlString::ignoreCase) == 0) { alreadyTriedOnce = TRUE; //so that we never send request with basic authenticatiuon // Log error OsSysLog::add(FAC_AUTH, PRI_ERR, "line manager is unable to handle basic auth:\ncallid=%s\nmethod=%s\ncseq=%d\nrealm=%s", callId.data(), method.data(), sequenceNum, realm.data()) ; } else { // Check to see if we already tried to send the credentials while(request->getDigestAuthorizationData( &requestUser, &requestRealm, NULL, NULL, NULL, NULL, authorizationEntity, requestAuthIndex) ) { if(realm.compareTo(requestRealm) == 0) { alreadyTriedOnce = TRUE; break; } requestAuthIndex++; } } // Find the line that sent the request that was challenged Url fromUrl; UtlString fromUri; UtlString userID; UtlString passToken; UtlBoolean credentialFound = FALSE; SipLine* line = NULL; //if challenged for an unregister request - then get credentials from temp lsit of lines int expires; int contactIndexCount = 0; UtlString contactEntry; if (!request->getExpiresField(&expires)) { while ( request->getContactEntry(contactIndexCount , &contactEntry )) { UtlString expireStr; Url contact(contactEntry); contact.getFieldParameter(SIP_EXPIRES_FIELD, expireStr); expires = atoi(expireStr.data()); if( expires == 0) break; contactIndexCount++; } } if( method.compareTo(SIP_REGISTER_METHOD) ==0 && expires == 0 ) { line = getLineforAuthentication(request, response, FALSE, TRUE); if(line) { if(line->getCredentials(scheme, realm, &userID, &passToken)) { credentialFound = TRUE; } removeFromTempList(line); } } else { line = getLineforAuthentication(request, response, FALSE); if(line) { if(line->getCredentials(scheme, realm, &userID, &passToken)) { OsSysLog::add(FAC_AUTH, PRI_DEBUG, "SipLineMgr::buildAuthenticatedRequest line->getCredentials(scheme=%s, realm=%s, userID=%s, passToken=%s)", scheme.data(), realm.data(), userID.data(), passToken.isNull() ? "" : "*****"); credentialFound = TRUE; } else { OsSysLog::add(FAC_AUTH, PRI_INFO, "SipLineMgr::buildAuthenticatedRequest line->getCredentials(scheme=%s, realm=%s, ....) failed to find userID and passToken", scheme.data(), realm.data()); } } } if( !alreadyTriedOnce && credentialFound ) { if ( line->getCredentials(scheme, realm, &userID, &passToken)) { OsSysLog::add(FAC_AUTH, PRI_INFO, "found auth credentials for:\nlineId:%s\ncallid=%s\nscheme=%s\nmethod=%s\ncseq=%d\nrealm=%s", fromUri.data(), callId.data(), scheme.data(), method.data(), sequenceNum, realm.data()) ; // Construct a new request with authorization and send it // the Sticky DNS fields will be copied by the copy constructor *newAuthRequest = *request; // Reset the transport parameters #ifdef TEST_PRINT int transportTimeStamp = newAuthRequest->getTransportTime(); int lastResendDuration = newAuthRequest->getResendDuration(); int timesSent = newAuthRequest->getTimesSent(); int transportProtocol = newAuthRequest->getSendProtocol(); //OsSocket::UNKNOWN; int mFirstSent = newAuthRequest->isFirstSend(); OsSysLog::add(FAC_AUTH, PRI_DEBUG, "LineMgr::BuildAuthenticated response transTime: %d resendDur: %d timesSent: %d sendProtocol: %d isFirst: %d\n", transportTimeStamp, lastResendDuration, timesSent, transportProtocol, mFirstSent); #endif newAuthRequest->resetTransport(); #ifdef TEST_PRINT transportTimeStamp = newAuthRequest->getTransportTime(); lastResendDuration = newAuthRequest->getResendDuration(); timesSent = newAuthRequest->getTimesSent(); transportProtocol = newAuthRequest->getSendProtocol(); //OsSocket::UNKNOWN; mFirstSent = newAuthRequest->isFirstSend(); OsSysLog::add(FAC_AUTH, PRI_DEBUG, "LineMgr::BuildAuthenticated response transTime: %d resendDur: %d timesSent: %d sendProtocol: %d isFirst: %d\n", transportTimeStamp, lastResendDuration, timesSent, transportProtocol, mFirstSent); #endif // Get rid of the via as another will be added. newAuthRequest->removeLastVia(); if(scheme.compareTo(HTTP_DIGEST_AUTHENTICATION, UtlString::ignoreCase) == 0) { UtlString responseHash; int nonceCount; // create the authorization in the request request->getRequestUri(&uri); // :TBD: cheat and use the cseq instead of a real nonce-count request->getCSeqField(&nonceCount, &method); nonceCount = (nonceCount + 1) / 2; request->getRequestMethod(&method); // Use unique tokens which are constant for this // session to generate a cnonce Url fromUrl; UtlString cnonceSeed; UtlString fromTag; UtlString cnonce; request->getCallIdField(&cnonceSeed); request->getFromUrl(fromUrl); fromUrl.getFieldParameter("tag", fromTag); cnonceSeed.append(fromTag); cnonceSeed.append("blablacnonce"); // secret NetMd5Codec::encode(cnonceSeed, cnonce); // Get the digest of the body const HttpBody* body = request->getBody(); UtlString bodyDigest; const char* bodyString = ""; if(body) { int len; body->getBytes(&bodyString, &len); if(bodyString == NULL) bodyString = ""; } NetMd5Codec::encode(bodyString, bodyDigest); // Build the Digest hash response HttpMessage::buildMd5Digest( passToken.data(), algorithm.data(), nonce.data(), cnonce.data(), nonceCount, qop.data(), method.data(), uri.data(), bodyDigest.data(), &responseHash); newAuthRequest->setDigestAuthorizationData( userID.data(), realm.data(), nonce.data(), uri.data(), responseHash.data(), algorithm.data(), cnonce.data(), opaque.data(), qop.data(), nonceCount, authorizationEntity); } // This is a new version of the message so increment the sequence number newAuthRequest->incrementCSeqNumber(); // If the first hop of this message is strict routed, // we need to add the request URI host back in the route // field so that the send will work correctly // // message is: // METHOD something // Route: xyz, abc // // change to xyz: // METHOD something // Route: something, xyz, abc // // which sends as: // METHOD something // Route: xyz, abc // // But if the first hop is loose routed: // // message is: // METHOD something // Route: xyz;lr, abc // // leave URI and routes alone if ( newAuthRequest->isClientMsgStrictRouted() ) { UtlString requestUri; newAuthRequest->getRequestUri(&requestUri); newAuthRequest->addRouteUri(requestUri); #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipLineMgr::buildAuthenticatedRequest strict routed request, pushing URI: \"%s\" onto route stack", requestUri.data()); } else { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipLineMgr::buildAuthenticatedRequest loose routed request"); } #else } #endif // TEST_PRINT createdResponse = TRUE; } else { OsSysLog::add(FAC_AUTH, PRI_ERR, "could not find auth credentials for:\nlineId:%s\ncallid=%s\nscheme=%s\nmethod=%s\ncseq=%d\nrealm=%s", fromUri.data(), callId.data(), scheme.data(), method.data(), sequenceNum, realm.data()) ; } } // Else we already tried to provide authentication // Or we do not have a userId and password for this uri // Let this error message throught to the application #ifdef TEST_PRINT else { UtlString authField; OsSysLog::add(FAC_AUTH, PRI_DEBUG, "Giving up on entity %d authorization, line: \"%s\" alreadyTriedOnce: %d credentialFound: %d", authorizationEntity, fromUri.data(), alreadyTriedOnce, credentialFound); OsSysLog::add(FAC_AUTH, PRI_DEBUG, "authorization failed previously sent: %d\n", request->getAuthorizationField(&authField, authorizationEntity)); } #endif #ifdef TEST_PRINT UtlString authBytes; int authBytesLen; newAuthRequest->getBytes(&authBytes, &authBytesLen); OsSysLog::add(FAC_AUTH, PRI_DEBUG, "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nAuth. message:\n%s^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", authBytes.data()); #endif line = NULL; return( createdResponse ); } void SipLineMgr::addMessageObserver(OsMsgQ& messageQueue, void* observerData) { SipObserverCriteria* observer = new SipObserverCriteria(observerData, &messageQueue, "", FALSE, FALSE, FALSE, FALSE, NULL); { // Add the observer and its filter criteria to the list lock scope OsWriteLock lock(mObserverMutex); mMessageObservers.insert(observer); } } UtlBoolean SipLineMgr::removeMessageObserver(OsMsgQ& messageQueue, void* pObserverData) { OsWriteLock lock(mObserverMutex); SipObserverCriteria* pObserver = NULL ; UtlBoolean bRemovedObservers = FALSE ; // Traverse all of the observers and remove any that match the // message queue/observer data. If the pObserverData is null, all // matching message queues will be removed. Otherwise, only those // observers that match both the message queue and observer data // are removed. UtlHashBagIterator iterator(mMessageObservers); while((pObserver = (SipObserverCriteria*) iterator())) { if (pObserver->getObserverQueue() == &messageQueue) { if ((pObserverData == NULL) || (pObserverData == pObserver->getObserverData())) { bRemovedObservers = true ; UtlContainable* wasRemoved = mMessageObservers.removeReference(pObserver); if(wasRemoved) { delete wasRemoved; } } } } return bRemovedObservers ; } void SipLineMgr::queueMessageToObservers(SipLineEvent& event) { // Find all of the observers which are interested in this method and post the message UtlString observerMatchingKey(""); SipObserverCriteria* observerCriteria = NULL; OsReadLock lock(mObserverMutex); UtlHashBagIterator observerIterator(mMessageObservers, &observerMatchingKey); do { observerCriteria = (SipObserverCriteria*) observerIterator(); // If this message matches the filter criteria if(observerCriteria) { OsMsgQ* observerQueue = observerCriteria->getObserverQueue(); void* observerData = observerCriteria->getObserverData(); // Put the message in the observers queue event.setObserverData(observerData); observerQueue->send(event); } } while(observerCriteria != NULL); } void SipLineMgr::addToList(SipLine *line) { sLineList.add(new SipLine(*line)); } void SipLineMgr::removeFromList(SipLine *line) { sLineList.remove(line); } void SipLineMgr::addToTempList(SipLine *line) { sTempLineList.add(new SipLine(*line)); } void SipLineMgr::removeFromTempList(SipLine *line) { sTempLineList.remove(line); } void SipLineMgr::setDefaultContactUri(const Url& contactUri) { mDefaultContactUri = contactUri; } UtlBoolean SipLineMgr::initializeRefreshMgr(SipRefreshMgr *refershMgr) { if (refershMgr) { mpRefreshMgr = refershMgr; mpRefreshMgr->addMessageObserver(*(getMessageQueue()), SIP_REGISTER_METHOD, TRUE, // do want to get requests TRUE, // do want responses TRUE, // Incoming messages FALSE); // Don't want to see out going messages return true; } else { osPrintf("ERROR::SipLineMgr::SipLineMgr SIP REFRESH MGR NULL\n"); return false; } } UtlBoolean SipLineMgr::addCredentialForLine( const Url& identity, const UtlString strRealm, const UtlString strUserID, const UtlString strPasswd, const UtlString type) { SipLine *line = NULL; if (! (line = sLineList.getLine(identity)) ) { UtlString id; identity.getIdentity(id); OsSysLog::add(FAC_SIP, PRI_ERR, "SipLineMgr::addCredentialForLine() - No Line for identity: %s", id.data()); return false; } if (!line->addCredentials(strRealm , strUserID, strPasswd, type)) { line = NULL; UtlString id; identity.getIdentity(id); OsSysLog::add(FAC_SIP, PRI_ERR, "SipLineMgr::addCredentialForLine() - Duplicate Realm: %s for identity: %s", strRealm.data(), id.data()); return false; } return true; } UtlBoolean SipLineMgr::deleteCredentialForLine(const Url& identity, const UtlString strRealm) { UtlBoolean wasRemoved = FALSE; SipLine *line = NULL; if (! (line = sLineList.getLine(identity)) ) { UtlString id; identity.getIdentity(id); OsSysLog::add(FAC_SIP, PRI_ERR, "SipLineMgr::deleteCredentialForLine() - No Line for identity: %s", id.data()); return false; } wasRemoved = line->removeCredential(&strRealm); return(wasRemoved); } int SipLineMgr::getNumOfCredentialsForLine( const Url& identity ) const { int numOfCredentials = 0; SipLine *line = NULL; if (! (line = sLineList.getLine( identity )) ) { osPrintf("ERROR::SipLineMgr::getNumOfCredentialsForLine() - No Line for identity \n"); } else { numOfCredentials = line->GetNumOfCredentials(); } return numOfCredentials; } UtlBoolean SipLineMgr::getCredentialListForLine( const Url& identity, int maxEnteries, int & actualEnteries, UtlString realmList[], UtlString userIdList[], UtlString typeList[], UtlString passTokenList[] ) { UtlBoolean retVal = FALSE; SipLine *line = NULL; if (! (line = sLineList.getLine(identity)) ) { osPrintf("ERROR::SipLineMgr::getCredentialListForLine() - No Line for identity \n"); } else { retVal = line->getAllCredentials(maxEnteries, actualEnteries, realmList, userIdList, typeList, passTokenList); } return retVal; } //line Call Handling void SipLineMgr::setCallHandlingForLine(const Url& identity , UtlBoolean useCallHandling) { SipLine *line = NULL; if (! (line = sLineList.getLine(identity)) ) { osPrintf("ERROR::SipLineMgr::setCallHandlingForLine() - No Line for identity\n"); return; } line->setCallHandling(useCallHandling); line = NULL; } UtlBoolean SipLineMgr::getCallHandlingForLine(const Url& identity) const { UtlBoolean retVal = FALSE; SipLine *line = NULL; if (! (line = sLineList.getLine(identity)) ) { osPrintf("ERROR::SipLineMgr::getCallHandlingForLine() - No Line for identity \n"); } else { retVal = line->getCallHandling(); line = NULL; } return retVal; } //line auto enable void SipLineMgr::setAutoEnableForLine(const Url& identity , UtlBoolean isAutoEnable) { SipLine *line = NULL; if (! (line = sLineList.getLine(identity)) ) { osPrintf("ERROR::SipLineMgr::setAutoEnableStatus() - No Line for identity\n"); return; } line->setAutoEnableStatus(isAutoEnable); line = NULL; } UtlBoolean SipLineMgr::getEnableForLine(const Url& identity) const { UtlBoolean retVal = FALSE; SipLine *line = NULL; if (! (line = sLineList.getLine(identity)) ) { osPrintf("ERROR::SipLineMgr::getEnableForLine() - No Line for identity \n"); } else { retVal = line->getAutoEnableStatus(); line = NULL; } return retVal; } //can only get state int SipLineMgr::getStateForLine( const Url& identity ) const { int State = SipLine::LINE_STATE_UNKNOWN; SipLine *line = NULL; if (! (line = sLineList.getLine(identity)) ) { osPrintf("ERROR::SipLineMgr::getStateForLine() - No Line for identity \n"); } else { State =line->getState(); line = NULL; } return State; } void SipLineMgr::setStateForLine( const Url& identity, int state ) { SipLine *line = NULL; if (! (line = sLineList.getLine(identity)) ) { osPrintf("ERROR::SipLineMgr::setStateForLine() - No Line for identity\n"); return; } int previousState =line->getState(); line->setState(state); if ( previousState != SipLine::LINE_STATE_PROVISIONED && state == SipLine::LINE_STATE_PROVISIONED) { /* We no longer implicitly unregister */ //disableLine(identity); } else if( previousState == SipLine::LINE_STATE_PROVISIONED && state == SipLine::LINE_STATE_REGISTERED) { enableLine(identity); } line = NULL; } // Line visibility UtlBoolean SipLineMgr::getVisibilityForLine( const Url& identity ) const { UtlBoolean retVal = FALSE; SipLine *line = NULL; if (! (line = sLineList.getLine(identity)) ) { osPrintf("ERROR::SipLineMgr::getVisibilityForLine() - No Line for identity \n"); } else { retVal = line->getVisibility(); line = NULL; } return retVal; } void SipLineMgr::setVisibilityForLine(const Url& identity , UtlBoolean Visibility) { SipLine *line = NULL; if (! (line = sLineList.getLine(identity)) ) { osPrintf("ERROR::SipLineMgr::setVisibilityForLine() - No Line for identity\n"); return; } line->setVisibility(Visibility); line = NULL; } //line User UtlBoolean SipLineMgr::getUserForLine(const Url& identity, UtlString &User) const { UtlBoolean retVal = FALSE; SipLine *line = NULL; if (! (line = sLineList.getLine(identity)) ) { osPrintf("ERROR::SipLineMgr::getUserForLine() - No Line for identity \n"); } else { User.remove(0); UtlString UserStr = line->getUser(); User.append(UserStr); retVal = TRUE; line = NULL; } return retVal; } void SipLineMgr::setUserForLine(const Url& identity, const UtlString User) { SipLine *line = NULL; if (! (line = sLineList.getLine(identity)) ) { osPrintf("ERROR::SipLineMgr::setUserForLine() - No Line for identity\n"); return; } line->setUser(User); line = NULL; } void SipLineMgr::setUserEnteredUrlForLine(const Url& identity, UtlString sipUrl) { SipLine *line = NULL; if (! (line = sLineList.getLine(identity)) ) { osPrintf("ERROR::SipLineMgr::setUserEnteredUrlForLine() - No Line for this Url\n"); return; } line->setIdentityAndUrl(identity, Url(sipUrl)); line = NULL; } UtlBoolean SipLineMgr::getUserEnteredUrlForLine( const Url& identity, UtlString& rSipUrl) const { UtlBoolean retVal = FALSE; SipLine *line = NULL; if (! (line = sLineList.getLine(identity)) ) { osPrintf("ERROR::SipLineMgr::getUserEnteredUrlForLine() - No Line for this Url \n"); } else { rSipUrl.remove(0); Url userEnteredUrl = line->getUserEnteredUrl(); rSipUrl.append(userEnteredUrl.toString()); retVal = TRUE; line = NULL; } return retVal; } UtlBoolean SipLineMgr::getCanonicalUrlForLine( const Url& identity, UtlString& rSipUrl) const { UtlBoolean retVal = FALSE; SipLine *line = NULL; if (! (line = sLineList.getLine(identity)) ) { osPrintf("ERROR::SipLineMgr::getUserForLine() - No Line for this Url \n"); } else { rSipUrl.remove(0); Url canonicalUrl = line->getCanonicalUrl(); rSipUrl.append(canonicalUrl.toString()); retVal = TRUE; line = NULL; } return retVal; } // Delete all line definitions from the specified configuration db. void SipLineMgr::purgeLines( OsConfigDb *pConfigDb ) { UtlString keyLast ; UtlString keyNext ; UtlString valueNext ; if (pConfigDb != NULL) { // Remove all PHONESET_LINE. keys OsConfigDb phonesetSubHash ; if (pConfigDb->getSubHash(BASE_PHONESET_LINE_KEY, phonesetSubHash) == OS_SUCCESS) { while (phonesetSubHash.getNext(keyLast, keyNext, valueNext) == OS_SUCCESS) { UtlString removeKey(BASE_PHONESET_LINE_KEY) ; removeKey.append(keyNext) ; pConfigDb->remove(removeKey) ; keyLast = keyNext ; } } // Remove all USER_LINE. keys OsConfigDb userSubHash ; keyLast.remove(0) ; if (pConfigDb->getSubHash(BASE_USER_LINE_KEY, userSubHash) == OS_SUCCESS) { while (userSubHash.getNext(keyLast, keyNext, valueNext) == OS_SUCCESS) { UtlString removeKey(BASE_USER_LINE_KEY) ; removeKey.append(keyNext) ; pConfigDb->remove(removeKey) ; keyLast = keyNext ; } } // Remove the Default outbound line pConfigDb->remove(USER_DEFAULT_OUTBOUND_LINE) ; } } // Load a single line UtlBoolean SipLineMgr::loadLine( OsConfigDb* pConfigDb, UtlString strSubKey, SipLine& line ) { UtlBoolean bSuccess = false ; UtlBoolean bAllowForwarding ; int iRegistration = SipLine::LINE_STATE_UNKNOWN; UtlString strKey ; UtlString strUrl ; UtlString strValue ; if ( pConfigDb != NULL ) { // Get URL strKey = strSubKey ; strKey.append(LINE_PARAM_URL) ; if (pConfigDb->get(strKey, strUrl)) { if (!strUrl.isNull()) { UtlString address; Url url(strUrl) ; Url identity(url); url.getHostAddress(address); if( address.isNull()) //dynamic IP address { //get address and port from contact uri UtlString contactHost; mDefaultContactUri.getHostAddress(contactHost); int contactPort = mDefaultContactUri.getHostPort(); identity.setHostAddress(contactHost); identity.setHostPort(contactPort); } else { UtlString uri; url.getUri(uri); identity = Url(uri); } line.setIdentityAndUrl(identity,url); bSuccess = true ; // Get Allow Forwarding (Default is ENABLE) strKey = strSubKey ; strKey.append(LINE_PARAM_ALLOW_FORWARDING) ; if ((pConfigDb->get(strKey, strValue)) && strValue.compareTo(LINE_ALLOW_FORWARDING_ENABLE, UtlString::ignoreCase)==0) { bAllowForwarding = true ; } else { bAllowForwarding = false ; } line.setCallHandling(bAllowForwarding) ; // Get Registration (Default is Provision) strKey = strSubKey ; strKey.append(LINE_PARAM_REGISTRATION) ; if ((pConfigDb->get(strKey, strValue)) && strValue.compareTo(LINE_REGISTRATION_REGISTER, UtlString::ignoreCase)==0) { iRegistration = SipLine::LINE_STATE_REGISTERED ; } else { iRegistration = SipLine::LINE_STATE_PROVISIONED; } //The list registration behaviour is independent of the autoenable behaviour. //The autoEnable behaviour is just for persistence. Since we do not have guest //login all the lines right now by default should have autoenable status true //since this line is read from a file( ie is persistent) is is autoenabled. line.setState(iRegistration) ; line.setAutoEnableStatus(TRUE); // Load Credentials. Attempt to load the max number of // credentials, however, if any credentials fail to load, // kick out. This is a safe optimization assuming that // credentials numbers are sequential. line.removeAllCredentials() ; for (int i=0; iset(strKey, urlLine.toString()) ; // Store Registration Type strKey = strSubKey ; strKey.append(LINE_PARAM_REGISTRATION) ; //get line state and if it is anything other than PROVISION, //set the line state to REGISTER because the other states are set //only for REGISTRATION behaviour int iLineState = line.getState(); if (iLineState == SipLine::LINE_STATE_PROVISIONED) pConfigDb->set(strKey, LINE_REGISTRATION_PROVISION) ; else pConfigDb->set(strKey, LINE_REGISTRATION_REGISTER) ; //there is no need to set the autoenable state because if we are //saving it then it has to be autoenabled. The check should be performed //before saving the line // Store Call Handling Settings strKey = strSubKey ; strKey.append(LINE_PARAM_ALLOW_FORWARDING) ; if (line.getCallHandling()) pConfigDb->set(strKey, LINE_ALLOW_FORWARDING_ENABLE) ; else pConfigDb->set(strKey, LINE_ALLOW_FORWARDING_DISABLE) ; int noOfCredentials = line.GetNumOfCredentials(); if (noOfCredentials > 0) { UtlString *strRealms = new UtlString[noOfCredentials] ; UtlString *strUserIds = new UtlString[noOfCredentials] ; UtlString *strTypes = new UtlString[noOfCredentials] ; UtlString *strPassTokens = new UtlString[noOfCredentials] ; int iCredentials = 0 ; if (line.getAllCredentials(noOfCredentials, iCredentials, strRealms, strUserIds, strTypes, strPassTokens)) { for (int i=0; iget(strKey, strRealm) ; // Get User ID strKey = strSubKey ; strKey.append(LINE_PARAM_CREDENTIAL_USERID) ; pConfigDb->get(strKey, strUserId) ; // Get Password Token strKey = strSubKey ; strKey.append(LINE_PARAM_CREDENTIAL_PASSTOKEN) ; pConfigDb->get(strKey, strPassToken) ; if (!strUserId.isNull() && !strPassToken.isNull()) { bSuccess = true ; line.addCredentials(strRealm, strUserId, strPassToken, HTTP_DIGEST_AUTHENTICATION) ; } } return bSuccess ; } // Store/save a single credential void SipLineMgr::storeCredential(OsConfigDb* pConfigDb, UtlString strSubKey, UtlString strRealm, UtlString strUserId, UtlString strPassToken, UtlString strType) { UtlString strKey ; if (pConfigDb != NULL) { // Store Realm strKey = strSubKey ; strKey.append(LINE_PARAM_CREDENTIAL_REALM) ; pConfigDb->set(strKey, strRealm) ; // Store User ID strKey = strSubKey ; strKey.append(LINE_PARAM_CREDENTIAL_USERID) ; pConfigDb->set(strKey, strUserId) ; // Store Password Token strKey = strSubKey ; strKey.append(LINE_PARAM_CREDENTIAL_PASSTOKEN) ; pConfigDb->set(strKey, strPassToken) ; } } void SipLineMgr::enableAllLines() { int noOfLines = getNumLines() ; int actualLines; int i = 0; // Allocate Lines SipLine *lines = new SipLine[noOfLines] ; // Get Actual lines and disable first if (getLines(noOfLines, actualLines, lines)) { for( i =0 ; i< actualLines; i++) { if ( lines[i].getState() == SipLine::LINE_STATE_REGISTERED) { /* We no longer implicitly unregister */ //disableLine(lines[i].getIdentity(), TRUE, lines[i].getLineId());//unregister for startup } } } // enable lines again if (getLines(noOfLines, actualLines, lines)) { for( i =0 ; i< actualLines; i++) { if ( lines[i].getState() == SipLine::LINE_STATE_REGISTERED) { enableLine(lines[i].getIdentity()); } } } // Free Lines delete []lines ; } sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipMessage.cpp0000644000175000017500000050550712205613256023752 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie (dpetrie AT SIPez DOT com) // SYSTEM INCLUDES #include #include //uncomment next line to track the create and destroy of messages //#define TRACK_LIFE // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define MAXIMUM_INTEGER_STRING_LENGTH 20 // STATIC VARIABLES SipMessage::SipMessageFieldProps SipMessage::sSipMessageFieldProps; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipMessage::SipMessage(const char* messageBytes, int byteCount) : HttpMessage(messageBytes, byteCount), mpSecurity(NULL), mpEventData(NULL), mbFromThisSide(true) { mbUseShortNames = false ; mLocalIp = ""; mpSipTransaction = NULL; replaceShortFieldNames(); #ifdef TRACK_LIFE osPrintf("Created SipMessage @ address:%X\n",this); #endif } SipMessage::SipMessage(OsSocket* inSocket, int bufferSize) : HttpMessage(inSocket, bufferSize), mpSecurity(NULL), mpEventData(NULL), mbFromThisSide(true) { #ifdef TRACK_LIFE osPrintf("Created SipMessage @ address:%X\n",this); #endif mbUseShortNames = false ; mpSipTransaction = NULL; replaceShortFieldNames(); } // Copy constructor SipMessage::SipMessage(const SipMessage& rSipMessage) : HttpMessage(rSipMessage), mpSecurity(NULL) { #ifdef TRACK_LIFE osPrintf("Created SipMessage @ address:%X\n",this); #endif replaceShortFieldNames(); //SDUA mLocalIp = rSipMessage.mLocalIp; m_dnsProtocol = rSipMessage.m_dnsProtocol; m_dnsAddress = rSipMessage.m_dnsAddress; m_dnsPort = rSipMessage.m_dnsPort; mpSipTransaction = rSipMessage.mpSipTransaction; mbFromThisSide = rSipMessage.mbFromThisSide; mCustomRouteId = rSipMessage.mCustomRouteId; mbUseShortNames = rSipMessage.mbUseShortNames; } // Destructor SipMessage::~SipMessage() { #ifdef TRACK_LIFE osPrintf("Deleted SipMessage from address :%X\n",this); #endif } // Assignment operator SipMessage& SipMessage::operator=(const SipMessage& rSipMessage) { HttpMessage::operator =((HttpMessage&)rSipMessage); if (this != &rSipMessage) { replaceShortFieldNames(); mLocalIp = rSipMessage.mLocalIp; m_dnsProtocol = rSipMessage.m_dnsProtocol; m_dnsAddress = rSipMessage.m_dnsAddress; m_dnsPort = rSipMessage.m_dnsPort; mpSipTransaction = rSipMessage.mpSipTransaction; mbFromThisSide = rSipMessage.mbFromThisSide; mCustomRouteId = rSipMessage.mCustomRouteId; mbUseShortNames = rSipMessage.mbUseShortNames; } return *this; } /* ============================ MANIPULATORS ============================== */ UtlBoolean SipMessage::getShortName(const char* longFieldName, UtlString* shortFieldName) { NameValuePair longNV(longFieldName); UtlBoolean nameFound = FALSE; shortFieldName->remove(0); NameValuePair* shortNV = (NameValuePair*) sSipMessageFieldProps.mLongFieldNames.find(&longNV); if(shortNV) { shortFieldName->append(shortNV->getValue()); nameFound = TRUE; } return(nameFound); } UtlBoolean SipMessage::getLongName(const char* shortFieldName, UtlString* longFieldName) { UtlBoolean nameFound = FALSE; // Short names are currently only 1 character long // If the short name is exactly 1 character long if(shortFieldName && shortFieldName[0] && shortFieldName[1] == '\0') { UtlString shortNV(shortFieldName); // Convert to lower case shortNV.toLower(); NameValuePair* longNV = (NameValuePair*) sSipMessageFieldProps.mShortFieldNames.find(&shortNV); if(longNV) { *longFieldName = longNV->getValue(); nameFound = TRUE; } else { // Now try upper case shortNV.toUpper(); longNV = (NameValuePair*) sSipMessageFieldProps.mShortFieldNames.find(&shortNV); if(longNV) { *longFieldName = longNV->getValue(); nameFound = TRUE; } } // Optimization in favor of utility //else //{ // longFieldName->remove(0); //} } return(nameFound); } void SipMessage::replaceShortFieldNames() { NameValuePair* nvPair; UtlString longName; size_t position; for ( position= 0; (nvPair = static_cast(mNameValues.at(position))); position++ ) { if(getLongName(nvPair->data(), &longName)) { // There is a long form for this name, so replace it. mHeaderCacheClean = FALSE; NameValuePair* modified; /* * NOTE: the header name is the containable key, so we must remove the * NameValuePair from the mNameValues list and then reinsert the * modified version; you are not allowed to modify key values while * an object is in a container. */ modified = static_cast(mNameValues.removeAt(position)); nvPair->remove(0); nvPair->append(longName); mNameValues.insertAt(position, modified); } } } void SipMessage::replaceLongFieldNames() { UtlDListIterator iterator(mNameValues); NameValuePair* nvPair; UtlString shortName; while ((nvPair = (NameValuePair*) iterator())) { if(getShortName(nvPair->data(), &shortName)) { mHeaderCacheClean = FALSE; nvPair->remove(0); nvPair->append(shortName.data()); } } mNameValues.rehash() ; } /* ============================ ACCESSORS ================================= */ void SipMessage::setSipRequestFirstHeaderLine(const char* method, const char* uri, const char* protocolVersion) { //fix for bug : 1667 - 12/18/2001 Url tempRequestUri(uri, TRUE); UtlString strRequestUri; tempRequestUri.removeUrlParameter("method"); tempRequestUri.removeAngleBrackets(); tempRequestUri.getUri(strRequestUri); setRequestFirstHeaderLine(method, strRequestUri.data(), protocolVersion); } void SipMessage::setRegisterData(const char* registererUri, const char* registerAsUri, const char* registrarServerUri, const char* takeCallsAtUri, const char* callId, int sequenceNumber, int expiresInSeconds) { setRequestData(SIP_REGISTER_METHOD, registrarServerUri, // uri registererUri, // from registerAsUri, // to callId, sequenceNumber); setContactField(takeCallsAtUri); setExpiresField(expiresInSeconds); } void SipMessage::setReinviteData(SipMessage* invite, const char* farEndContact, const char* contactUrl, UtlBoolean inviteFromThisSide, const char* routeField, int sequenceNumber, int sessionReinviteTimer) { UtlString toField; UtlString fromField; UtlString callId; UtlString contactUri; UtlString lastResponseContact; mbFromThisSide = inviteFromThisSide ? true : false; setTransportInfo(invite) ; // Get the to, from and callId fields if(inviteFromThisSide) { invite->getToField(&toField); invite->getFromField(&fromField); } else// Reverse the to from, this invite came from the other side { invite->getToField(&fromField); invite->getFromField(&toField); } invite->getCallIdField(&callId); if (farEndContact) lastResponseContact.append(farEndContact); if ( !inviteFromThisSide && lastResponseContact.isNull()) { //if invite from other side and LastResponseContact is null because there has not been any //final responses from the other side yet ...check the otherside's invite request and get the //contact field from the request invite->getContactUri(0, &lastResponseContact); } setInviteData(fromField, toField, lastResponseContact, contactUrl, callId, sequenceNumber, sessionReinviteTimer); setRouteField(routeField); } void SipMessage::setInviteData(const char* fromField, const char* toField, const char* farEndContact, const char* contactUrl, const char* callId, int sequenceNumber, int sessionReinviteTimer) { UtlString bodyString; UtlString uri; Url toUrl(toField); // Create the top header line // If we have a contact for the other side use it // for the URI, otherwise use the To field if (farEndContact && *farEndContact) { uri = farEndContact; } else { // Clean out the header field parameters if they exist Url uriUrl(toUrl); // copy constructor is more efficient than parsing the toField string //uri.append(uriUrl.toString()); uriUrl.removeHeaderParameters(); uriUrl.getUri(uri); } // Check for header fields in the To URL UtlString headerName; UtlString headerValue; int headerIndex = 0; // Look through the headers and add them to the message while(toUrl.getHeaderParameter(headerIndex, headerName, headerValue)) { // If the header is allowed to be passed through if(isUrlHeaderAllowed(headerName.data())) { if (isUrlHeaderUnique(headerName.data())) { // If the field exists, change it, if does not exist, create it. setHeaderValue(headerName.data(), headerValue.data(), 0); } else { addHeaderField(headerName.data(), headerValue.data()); } #ifdef TEST_PRINT osPrintf("SipMessage::setInviteData: name=%s, value=%s\n", headerName.data(), headerValue.data()); #endif } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipMessage::setInviteData " "URL header '%s: %s' may not be added using a header parameter", headerName.data(), headerValue.data()); } headerIndex++; } // Remove the header fields from the URL as them // have been added to the message toUrl.removeHeaderParameters(); UtlString toFieldString; toUrl.toString(toFieldString); setRequestData(SIP_INVITE_METHOD, uri, // URI fromField, toFieldString.data(), callId, sequenceNumber, contactUrl); // Set the session timer in seconds if(sessionReinviteTimer > 0) setSessionExpires(sessionReinviteTimer); #ifdef TEST osPrintf("SipMessage::setInviteData rtpAddress: %s\n", rtpAddress); #endif } void SipMessage::addSdpBody(int nRtpContacts, UtlString hostAddresses[], int rtpAudioPorts[], int rtcpAudioPorts[], int rtpVideoPorts[], int rtcpVideoPorts[], RTP_TRANSPORT transportTypes[], int numRtpCodecs, SdpCodec* rtpCodecs[], SdpSrtpParameters* srtpParams, int videoBandwidth, int videoFramerate, const SipMessage* pRequest, RTP_TRANSPORT rtpTransportOptions) { if(numRtpCodecs > 0) { UtlString bodyString; int len; // Create and add the SDP body SdpBody* sdpBody = new SdpBody(); sdpBody->setStandardHeaderFields("call", NULL, NULL, hostAddresses[0]); // Originator address if (pRequest && pRequest->getSdpBody()) { sdpBody->addCodecsAnswer(nRtpContacts, hostAddresses, rtpAudioPorts, rtcpAudioPorts, rtpVideoPorts, rtcpVideoPorts, transportTypes, numRtpCodecs, rtpCodecs, *srtpParams, videoBandwidth, videoFramerate, pRequest->getSdpBody()); } else { sdpBody->addCodecsOffer(nRtpContacts, hostAddresses, rtpAudioPorts, rtcpAudioPorts, rtpVideoPorts, rtcpVideoPorts, transportTypes, numRtpCodecs, rtpCodecs, *srtpParams, videoBandwidth, videoFramerate, rtpTransportOptions); } setBody(sdpBody); // Add the content type for the body setContentType(SDP_CONTENT_TYPE); // Add the content length sdpBody->getBytes(&bodyString, &len); setContentLength(len); } } void SipMessage::setSecurityAttributes(const SIPXTACK_SECURITY_ATTRIBUTES* const pSecurity) { mpSecurity = (SIPXTACK_SECURITY_ATTRIBUTES*)pSecurity; } const SdpBody* SipMessage::getSdpBody(SIPXTACK_SECURITY_ATTRIBUTES* const pSecurity, const void* pEventData) const { if (pEventData) { mpEventData = (void*)pEventData; } const SdpBody* body = NULL; UtlString contentType; UtlString sdpType(SDP_CONTENT_TYPE); UtlString smimeType(CONTENT_SMIME_PKCS7); getContentType(&contentType); // Make them all lower case so they compare contentType.toLower(); sdpType.toLower(); smimeType.toLower(); // If the body is of SDP type, return it const HttpBody* genericBody = getBody(); if(genericBody && genericBody->getClassType() == HttpBody::SDP_BODY_CLASS) { body = static_cast (getBody()); } #if __SMIME // If we have a private key and this is a S/MIME body else if(pSecurity && genericBody && genericBody->getClassType() == HttpBody::SMIME_BODY_CLASS ) { if (genericBody) { SmimeBody* smimeBody = static_cast(genericBody); assert(smimeBody); // Try to decrypt if it has not already been decrypted if(! smimeBody->isDecrypted()) { if (pSecurity) { mpSecurity = pSecurity; } // Try to decrypt using the given private key pwd and signer cert. smimeBody->decrypt(NULL, 0, NULL, pSecurity->szCertDbPassword, pSecurity->szSmimeKeyDer, pSecurity->nSmimeKeyLength, (ISmimeNotifySink*)this); } // If it did not get encrypted, act like there is no SDP body if(smimeBody->isDecrypted()) { const HttpBody* decryptedHttpBody = smimeBody->getDecryptedBody(); // If the decrypted body is an SDP body type, use it if(strcmp(decryptedHttpBody->getContentType(), sdpType) == 0) { body = (const SdpBody*) decryptedHttpBody; } } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "Could not decrypt S/MIME body"); } } } #endif // Else if this is a multipart MIME body see // if there is an SDP part else { const HttpBody* multipartBody = genericBody; if(multipartBody && multipartBody->isMultipart()) { int partIndex = 0; const HttpBody* bodyPart = NULL; while ((bodyPart = multipartBody->getMultipart(partIndex))) { if(strcmp(bodyPart->getContentType(), SDP_CONTENT_TYPE) == 0) { // Temporarily disable while fixing multipart bodies body = (const SdpBody*) bodyPart; break; } #ifdef SMIME // Check for S/MIME body else if(strcmp(bodyPart->getContentType(), smimeType) == 0 && pSecurity) { SmimeBody* smimeBody = (SmimeBody*) bodyPart; // Try to decrypt if it has not already been decrypted if(! smimeBody->isDecrypted()) { // Try to decrypt using the given private pwd and signer cert. smimeBody->decrypt(NULL, 0, NULL, pSecurity->szCertDbPassword, pSecurity->szSmimeKeyDer, pSecurity->nSmimeKeyLength, (ISmimeNotifySink*)this); } // If it did not get encrypted, act like there is no SDP body if(smimeBody->isDecrypted()) { const HttpBody* decryptedHttpBody = smimeBody->getDecryptedBody(); // If the decrypted body is an SDP body type, use it if(strcmp(decryptedHttpBody->getContentType(), sdpType) == 0) { body = (const SdpBody*) decryptedHttpBody; break; } } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "Could not decrypt S/MIME body"); } } #endif partIndex++ ; } } } return(body); } void SipMessage::setRequestData(const char* method, const char* uri, const char* fromField, const char* toField, const char* callId, int sequenceNumber, const char* contactUrl) { // Create the top header line setSipRequestFirstHeaderLine(method, uri, SIP_PROTOCOL_VERSION); // Add the From field setRawFromField(fromField); // Add the to field setRawToField(toField); // Add the call-id field setCallIdField(callId); // Add the CSeq field setCSeqField(sequenceNumber, method); if(contactUrl && *contactUrl) { setContactField(contactUrl); } } void SipMessage::setResponseData(int statusCode, const char* statusText, const char* fromField, const char* toField, const char* callId, int sequenceNumber, const char* sequenceMethod, const char* localContact ) { // Create the top header line setResponseFirstHeaderLine(SIP_PROTOCOL_VERSION, statusCode, statusText); // Add the From field setRawFromField(fromField); // Add the to field setRawToField(toField); // Add the call-id field setCallIdField(callId); // Add the CSeq field if(sequenceNumber >= 0) { setCSeqField(sequenceNumber, sequenceMethod); } // Local Contact if (localContact) { setContactField(localContact) ; } } void SipMessage::setTryingResponseData(const SipMessage* request) { setResponseData(request, SIP_TRYING_CODE, SIP_TRYING_TEXT); } void SipMessage::setInviteRingingData(const SipMessage* inviteRequest) { setResponseData(inviteRequest, SIP_RINGING_CODE, SIP_RINGING_TEXT); } void SipMessage::setQueuedResponseData(const SipMessage* inviteRequest) { setResponseData(inviteRequest, SIP_QUEUED_CODE, SIP_QUEUED_TEXT); } void SipMessage::setInviteBusyData(const char* fromField, const char* toField, const char* callId, int sequenceNumber) { setResponseData(SIP_BUSY_CODE, SIP_BUSY_TEXT, fromField, toField, callId, sequenceNumber, SIP_INVITE_METHOD); } void SipMessage::setBadTransactionData(const SipMessage* inviteRequest) { setResponseData(inviteRequest, SIP_BAD_TRANSACTION_CODE, SIP_BAD_TRANSACTION_TEXT); } void SipMessage::setLoopDetectedData(const SipMessage* inviteRequest) { setResponseData(inviteRequest, SIP_LOOP_DETECTED_CODE, SIP_LOOP_DETECTED_TEXT); } void SipMessage::setInviteBusyData(const SipMessage* inviteRequest) { setInviteErrorData(inviteRequest, SIP_BUSY_CODE, SIP_BUSY_TEXT); } void SipMessage::setInviteErrorData(const SipMessage* inviteRequest, int errorCode, const UtlString& errorText) { UtlString fromField; UtlString toField; UtlString callId; int sequenceNum; UtlString sequenceMethod; setTransportInfo(inviteRequest) ; inviteRequest->getFromField(&fromField); inviteRequest->getToField(&toField); inviteRequest->getCallIdField(&callId); inviteRequest->getCSeqField(&sequenceNum, &sequenceMethod); setResponseData(errorCode, errorText, fromField, toField, callId, sequenceNum, SIP_INVITE_METHOD); setViaFromRequest(inviteRequest); } void SipMessage::setRequestPendingData(const SipMessage* inviteRequest) { UtlString fromField; UtlString toField; UtlString callId; int sequenceNum; UtlString sequenceMethod; setTransportInfo(inviteRequest) ; inviteRequest->getFromField(&fromField); inviteRequest->getToField(&toField); inviteRequest->getCallIdField(&callId); inviteRequest->getCSeqField(&sequenceNum, &sequenceMethod); setResponseData(SIP_REQUEST_PENDING_CODE, SIP_REQUEST_PENDING_TEXT, fromField, toField, callId, sequenceNum, SIP_INVITE_METHOD); setViaFromRequest(inviteRequest); } void SipMessage::setForwardResponseData(const SipMessage* request, const char* forwardAddress) { setResponseData(request, SIP_TEMPORARY_MOVE_CODE, SIP_TEMPORARY_MOVE_TEXT); // Add the contact field for the forward address UtlString contactAddress; Url contactUrl(forwardAddress); contactUrl.removeFieldParameters(); contactUrl.toString(contactAddress); setContactField(contactAddress.data()); } void SipMessage::setInviteBadCodecs(const SipMessage* inviteRequest, SipUserAgent* ua) { char warningCodeString[MAXIMUM_INTEGER_STRING_LENGTH + 1]; UtlString warningField; setResponseData(inviteRequest, SIP_REQUEST_NOT_ACCEPTABLE_HERE_CODE, SIP_REQUEST_NOT_ACCEPTABLE_HERE_TEXT); // Add a media not available warning // The text message must be a quoted string sprintf(warningCodeString, "%d ", SIP_WARN_MEDIA_INCOMPAT_CODE); warningField.append(warningCodeString); // Construct the agent field from information extracted from the // SipUserAgent. UtlString address; int port; // Get the address/port for UDP, since it's too hard to figure out what // protocol this message arrived on. UtlString receivedFromAddress ; int receivedFromPort ; inviteRequest->getSendAddress(&receivedFromAddress, &receivedFromPort) ; ua->getViaInfo(OsSocket::UDP, address, port, receivedFromAddress.data(), &receivedFromPort) ; warningField.append(address); if ((port != 5060) && (port > 0)) // Port 5060 is treated as default port { sprintf(warningCodeString, ":%d", port); warningField.append(warningCodeString); } warningField.append(" \""); warningField.append(SIP_WARN_MEDIA_INCOMPAT_TEXT); warningField.append("\""); addHeaderField(SIP_WARNING_FIELD, warningField.data()); } void SipMessage::setInviteForbidden(const SipMessage* request) { setResponseData(request, SIP_FORBIDDEN_CODE, SIP_FORBIDDEN_TEXT); } void SipMessage::setRequestBadMethod(const SipMessage* request, const char* allowedMethods) { setResponseData(request, SIP_BAD_METHOD_CODE, SIP_BAD_METHOD_TEXT); // Add a methods supported field addHeaderField(SIP_ALLOW_FIELD, allowedMethods); } void SipMessage::setRequestUnimplemented(const SipMessage* request) { setResponseData(request, SIP_UNIMPLEMENTED_METHOD_CODE, SIP_UNIMPLEMENTED_METHOD_TEXT); } void SipMessage::setRequestBadExtension(const SipMessage* request, const char* disallowedExtension) { setResponseData(request, SIP_BAD_EXTENSION_CODE, SIP_BAD_EXTENSION_TEXT); // Add a methods supported field addHeaderField(SIP_UNSUPPORTED_FIELD, disallowedExtension); } void SipMessage::setRequestBadContentEncoding(const SipMessage* request, const char* allowedEncodings) { setResponseData(request, SIP_BAD_MEDIA_CODE, SIP_BAD_MEDIA_TEXT); // Add a encodings supported field addHeaderField(SIP_ACCEPT_ENCODING_FIELD, allowedEncodings); addHeaderField(SIP_ACCEPT_FIELD, "application/sdp"); const char* explanation = "Content Encoding value not supported"; setBody(new HttpBody(explanation, strlen(explanation), CONTENT_TYPE_TEXT_PLAIN)); } void SipMessage::setRequestBadAddress(const SipMessage* request) { setResponseData(request, SIP_BAD_ADDRESS_CODE, SIP_BAD_ADDRESS_TEXT); } void SipMessage::setRequestBadVersion(const SipMessage* request) { setResponseData(request, SIP_BAD_VERSION_CODE, SIP_BAD_VERSION_TEXT); } void SipMessage::setRequestBadRequest(const SipMessage* request) { setResponseData(request, SIP_BAD_REQUEST_CODE, SIP_BAD_REQUEST_TEXT); } void SipMessage::setRequestBadUrlType(const SipMessage* request) { setResponseData(request, SIP_UNSUPPORTED_URI_SCHEME_CODE, SIP_UNSUPPORTED_URI_SCHEME_TEXT); } void SipMessage::setInviteOkData(const SipMessage* inviteRequest, int maxSessionExpiresSeconds, const char* localContact) { UtlString fromField; UtlString toField; UtlString callId; int sequenceNum; UtlString sequenceMethod; const SdpBody* inviteSdp = NULL; setTransportInfo(inviteRequest) ; inviteRequest->getFromField(&fromField); inviteRequest->getToField(&toField); inviteRequest->getCallIdField(&callId); inviteRequest->getCSeqField(&sequenceNum, &sequenceMethod); inviteSdp = inviteRequest->getSdpBody(mpSecurity); if (mpSecurity && !inviteSdp) { setResponseData(SIP_REQUEST_UNDECIPHERABLE_CODE, SIP_REQUEST_UNDECIPHERABLE_TEXT, fromField, toField, callId, sequenceNum, SIP_INVITE_METHOD, localContact); } else { setResponseData(SIP_OK_CODE, SIP_OK_TEXT, fromField, toField, callId, sequenceNum, SIP_INVITE_METHOD, localContact); setViaFromRequest(inviteRequest); setInviteOkRoutes(*inviteRequest); int inviteSessionExpires; UtlString refresher ; // If max session timer is less than the requested timer length // or if the other side did not request a timer, use // the max session timer if(!inviteRequest->getSessionExpires(&inviteSessionExpires, &refresher) || (maxSessionExpiresSeconds > 0 && inviteSessionExpires > maxSessionExpiresSeconds)) { inviteSessionExpires = maxSessionExpiresSeconds; } // We are the UAS. If the UAC volunteered or we can make the UAC be the // refersher, then we are ok with session timer. if(inviteSessionExpires > 0 && ( refresher.isNull() || (refresher.compareTo(SIP_REFRESHER_UAC, UtlString::ignoreCase) == 0) ) ) { // Allow passive session timer. setSessionExpires(inviteSessionExpires, SIP_REFRESHER_UAC); } } } int SipMessage::setInviteOkRoutes(const SipMessage& inviteRequest) { UtlString recordRouteField; int recordRouteIndex = 0; while(inviteRequest.getRecordRouteField(recordRouteIndex, &recordRouteField)) { setRecordRouteField(recordRouteField.data(), recordRouteIndex); recordRouteIndex++; } return(recordRouteIndex); } void SipMessage::setOkResponseData(const SipMessage* request, const char* localContact) { setResponseData(request, SIP_OK_CODE, SIP_OK_TEXT, localContact); } void SipMessage::setNotifyData(SipMessage *subscribeRequest, int localCSequenceNumber, const char* route, const char* stateField, const char* eventField, const char* id) { UtlString fromField; UtlString toField; UtlString uri; UtlString callId; int dummySequenceNum; UtlString sequenceMethod; setTransportInfo(subscribeRequest) ; subscribeRequest->getFromField(&fromField); subscribeRequest->getToField(&toField); subscribeRequest->getCallIdField(&callId); subscribeRequest->getCSeqField(&dummySequenceNum, &sequenceMethod); // Set the NOTIFY event type if(eventField && *eventField) { UtlString eventHeaderValue(eventField); if (id && *id) { eventHeaderValue.append(";id="); eventHeaderValue.append(id); } setEventField(eventHeaderValue.data()); } else { // Try to get it from the subscribe message UtlString subscribeEventField; subscribeRequest->getEventField(subscribeEventField); if(!subscribeEventField.isNull()) { setEventField(subscribeEventField.data()); } } // Set the Subscription-State header if(stateField && *stateField) { setHeaderValue(SIP_SUBSCRIPTION_STATE_FIELD, stateField); } else { setHeaderValue(SIP_SUBSCRIPTION_STATE_FIELD, SIP_SUBSCRIPTION_ACTIVE); } // Set the route for the NOTIFY request setRouteField(route); // Use contact if present if(subscribeRequest->getContactUri(0, &uri) && !uri.isNull()) { } // Use the from field as we have nothing better to use else { uri.append(fromField.data()); } setRequestData(SIP_NOTIFY_METHOD, uri.data(), toField.data(), fromField.data(), callId, localCSequenceNumber); } void SipMessage::setNotifyData(const char* uri, const char* fromField, const char* toField, const char* callId, int lastNotifyCseq, const char* eventField, const char* id, const char* state, const char* contact, const char* routeField) { // if uri is not set set it to the toField UtlString uriStr; if( uri && *uri ) { uriStr.append(uri); } else if ( toField ) { // check for toField null uriStr.append( toField ); } // if contact is not set set it to the fromField UtlString contactStr; if( contact && *contact ) { contactStr.append(contact); } else if ( fromField ) { // check for toField null contactStr.append( fromField ); } // Set the NOTIFY event type if( eventField && *eventField ) { UtlString eventHeaderValue(eventField); if (id && *id) { eventHeaderValue.append(";id="); eventHeaderValue.append(id); } setEventField(eventHeaderValue.data()); } // Set the Subscription-State header if(state && *state) { setHeaderValue(SIP_SUBSCRIPTION_STATE_FIELD, state); } else { // Force the caller to pass a valid subscription context -- add a default // param if needed... // setHeaderValue(SIP_SUBSCRIPTION_STATE_FIELD, SIP_SUBSCRIPTION_ACTIVE); } setRouteField(routeField ); setRequestData( SIP_NOTIFY_METHOD, uriStr.data(), fromField, toField, callId, lastNotifyCseq, contactStr.data() ); } void SipMessage::setSubscribeData(const char* uri, const char* fromField, const char* toField, const char* callId, int cseq, const char* eventField, const char* acceptField, const char* id, const char* contact, const char* routeField, int expiresInSeconds) { Url toUrl(toField); Url fromUrl(fromField); toUrl.includeAngleBrackets(); fromUrl.includeAngleBrackets(); setRequestData(SIP_SUBSCRIBE_METHOD, uri, fromUrl.toString(), toUrl.toString(), callId, cseq, contact); // Set the event type, if any. if( eventField && *eventField ) { UtlString eventHeaderValue(eventField); if (id && *id) { eventHeaderValue.append(";id="); eventHeaderValue.append(id); } setEventField(eventHeaderValue.data()); setHeaderValue(SIP_EVENT_FIELD, eventHeaderValue, 0); } // Set the content type, if any. if( acceptField && *acceptField ) { setHeaderValue(SIP_ACCEPT_FIELD, acceptField, 0); } // Set the route, if any. if (routeField && *routeField) { setRouteField(routeField); } //setExpires setExpiresField(expiresInSeconds); } void SipMessage::setEnrollmentData(const char* uri, const char* fromField, const char* toField, const char* callId, int CSeq, const char* contactUrl, const char* protocolField, const char* profileField, int expiresInSeconds) { setRequestData(SIP_SUBSCRIBE_METHOD, uri, fromField, toField, callId, CSeq, contactUrl); // Set the event type setHeaderValue(SIP_EVENT_FIELD, SIP_EVENT_CONFIG, 0); // Set the protocols setHeaderValue(SIP_CONFIG_ALLOW_FIELD, protocolField, 0); // Set the profile setHeaderValue(SIP_CONFIG_REQUIRE_FIELD, profileField, 0); //setRxpires setExpiresField(expiresInSeconds); } // RFC 3248 MWI /******** SAMPLE CODE FOR CREATING MWI NOTIFY message**************************** SipMessage notifyRequest; UtlString fromField; UtlString toData; UtlString contactField; UtlString msgSummaryData; char *uri = "sip:100@127.0.0.1:3000"; sipMessage->getFromField(&fromField); sipMessage->getToField(&toData); sipMessage->getContactField(0,contactField); notifyRequest.setMessageSummaryData(msgSummaryData,"udit@3com.com",TRUE, TRUE,FALSE,FALSE,4,2); notifyRequest.setMWIData(SIP_NOTIFY_METHOD, fromField.data(), toData.data(),uri, contactField.data(),"1",1,msgSummaryData); **********************************************************************************/ void SipMessage::setMessageSummaryData( UtlString& msgSummaryData, const char* msgAccountUri, UtlBoolean bNewMsgs, UtlBoolean bVoiceMsgs, UtlBoolean bFaxMsgs, UtlBoolean bEmailMsgs, int numNewMsgs, int numOldMsgs, int numFaxNewMsgs, int numFaxOldMsgs, int numEmailNewMsgs, int numEmailOldMsgs ) { char integerString[255]; // Adding Message-summary information sprintf(integerString,"\r\n"); msgSummaryData.append(integerString); if(NULL != msgAccountUri) { sprintf(integerString,"Message-Account: %s\r\n",msgAccountUri); msgSummaryData.append(integerString); } if (TRUE == bNewMsgs) { // Adding Messages-waiting Yes sprintf(integerString,"Messages-Waiting: yes\r\n"); } else { // Adding Messages-waiting No sprintf(integerString,"Messages-Waiting: no\r\n"); } msgSummaryData.append(integerString); if (bVoiceMsgs) { sprintf(integerString,"Voice-Message: %d/%d\r\n",numNewMsgs,numOldMsgs); msgSummaryData.append(integerString); } if (bFaxMsgs) { sprintf(integerString,"Fax-Message: %d/%d\r\n",numFaxNewMsgs,numFaxOldMsgs); msgSummaryData.append(integerString); } if (bEmailMsgs) { sprintf(integerString,"Email-Message: %d/%d\r\n",numEmailNewMsgs,numEmailOldMsgs); msgSummaryData.append(integerString); } } // Added by Udit for RFC 3248 MWI void SipMessage::setMWIData(const char *method, const char* fromField, const char* toField, const char* uri, const char* contactUrl, const char* callId, int CSeq, UtlString bodyString) { setRequestData(method, uri, fromField, toField, callId, CSeq, contactUrl); // Set the allow field setHeaderValue(SIP_ACCEPT_FIELD, CONTENT_TYPE_SIMPLE_MESSAGE_SUMMARY, 0); // Set the event type setHeaderValue(SIP_EVENT_FIELD, SIP_EVENT_MESSAGE_SUMMARY, 0); // Add the content type setContentType(CONTENT_TYPE_SIMPLE_MESSAGE_SUMMARY); // Create and add the Http body HttpBody *httpBody = new HttpBody(bodyString.data(),bodyString.length(), CONTENT_TYPE_SIMPLE_MESSAGE_SUMMARY); setContentLength(bodyString.length()); setBody(httpBody); } void SipMessage::setVoicemailData(const char* fromField, const char* toField, const char* uri, const char* contactUrl, const char* callId, int CSeq, int expiresInSeconds) { setRequestData(SIP_SUBSCRIBE_METHOD, uri, fromField, toField, callId, CSeq, contactUrl); // Set the event type setHeaderValue(SIP_EVENT_FIELD, SIP_EVENT_MESSAGE_SUMMARY, 0); // Set the allow field setHeaderValue(SIP_ACCEPT_FIELD, CONTENT_TYPE_SIMPLE_MESSAGE_SUMMARY, 0); setExpiresField(expiresInSeconds); } void SipMessage::setRequestTerminatedResponseData(const SipMessage* request) { setResponseData(request, SIP_REQUEST_TERMINATED_CODE, SIP_REQUEST_TERMINATED_TEXT); } void SipMessage::setRequestUnauthorized(const SipMessage* request, const char* authenticationScheme, const char* authenticationRealm, const char* authenticationNonce, const char* authenticationOpaque, enum HttpEndpointEnum authEntity) { setTransportInfo(request) ; if(authEntity == SERVER) { setResponseData(request, HTTP_UNAUTHORIZED_CODE, HTTP_UNAUTHORIZED_TEXT); } else { setResponseData(request, HTTP_PROXY_UNAUTHORIZED_CODE, HTTP_PROXY_UNAUTHORIZED_TEXT); } setAuthenticationData(authenticationScheme, authenticationRealm, authenticationNonce, authenticationOpaque, NULL, authEntity); } // This method is needed to cover the symetrical situation which is // specific to SIP authorization (i.e. authentication and authorize // fields may be in either requests or responses UtlBoolean SipMessage::verifyMd5Authorization(const char* userId, const char* password, const char* nonce, const char* realm, const char* uri, enum HttpEndpointEnum authEntity) const { UtlString uriString; UtlString method; if(isResponse()) { int seqNum; // What is the correct URI for a response Authorization if(uri) { uriString.append(uri); } getCSeqField(&seqNum, &method); } else { // If the uri (should be Auth header uri parameter) is // passed in use it. if(uri) { uriString.append(uri); } // Otherwise dig out the request URI. Note: it is not a good // idea to use the request uri to validate the digest hash as // it may not exactly match the Auth header uri parameter (in // which the validation will fail). else { getRequestUri(&uriString); OsSysLog::add(FAC_SIP,PRI_DEBUG, "SipMessage::verifyMd5Authorization using request URI: %s instead of Auth header uri parameter for digest\n", uriString.data()); } getRequestMethod(&method); } #ifdef TEST OsSysLog::add(FAC_SIP,PRI_DEBUG, "SipMessage::verifyMd5Authorization - " "userId='%s', password='%s', nonce='%s', realm='%s', uri='%s', method='%s' \n", userId, password, nonce, realm, uriString.data(), method.data()); #endif UtlBoolean isAllowed = FALSE; isAllowed = HttpMessage::verifyMd5Authorization(userId, password, nonce, realm, method.data(), uriString.data(), authEntity); return isAllowed; } void SipMessage::setResponseData(const SipMessage* request, int responseCode, const char* responseText, const char* localContact) { setTransportInfo(request) ; UtlString fromField; UtlString toField; UtlString callId; int sequenceNum; UtlString sequenceMethod; request->getFromField(&fromField); request->getToField(&toField); request->getCallIdField(&callId); request->getCSeqField(&sequenceNum, &sequenceMethod); setResponseData(responseCode, responseText, fromField.data(), toField.data(), callId, sequenceNum, sequenceMethod.data(), localContact) ; setViaFromRequest(request); } void SipMessage::setAckData(const char* uri, const char* fromField, const char* toField, const char* callId, int sequenceNumber) { setRequestData(SIP_ACK_METHOD, uri, fromField, toField, callId, sequenceNumber); } void SipMessage::setAckData(const SipMessage* inviteResponse, const SipMessage* inviteRequest, const char* contact, int sessionTimerExpires) { setTransportInfo(inviteResponse) ; UtlString fromField; UtlString toField; UtlString uri; UtlString callId; int sequenceNum; int responseCode ; UtlString sequenceMethod; UtlString requestContact; UtlBoolean SetDNSParameters = FALSE; inviteResponse->getFromField(&fromField); inviteResponse->getToField(&toField); responseCode = inviteResponse->getResponseStatusCode(); // SDUA //Set URI //Only for 2xx responses check the record route and contact field of response if ( responseCode >= SIP_OK_CODE && responseCode < SIP_MULTI_CHOICE_CODE) { // Set route field if recordRoute was set. UtlString routeField; UtlString requestToField; if(inviteResponse->buildRouteField(&routeField)) { setRouteField(routeField.data()); } // Loose_route always put contact in URI inviteResponse->getContactUri( 0 , &uri); if (uri.isNull()) { if(inviteRequest) inviteRequest->getRequestUri(&uri); else uri.append(toField.data()); } //if no record route and no contact filed which is a problem of the //other side because they should have a contact field //We should be more tolerant and use the request uri of INVITE //or the to field if(uri.isNull()) { if(inviteRequest) { inviteRequest->getRequestUri(&uri); } else { uri.append(toField.data()); } } } else { //set uri from request if no contact field in the response UtlString routeField; if (inviteRequest) { inviteRequest->getRequestUri(&uri); OsSysLog::add(FAC_SIP, (uri.data()[0] == '<') ? PRI_ERR : PRI_DEBUG, "SipMessage::setAckData inviteRequest->getRequestUri() = '%s'", uri.data()); inviteRequest->getRouteField(&routeField); setRouteField(routeField); } else uri.append(toField.data()); SetDNSParameters = TRUE; } //set senders contact if(contact && *contact) { setContactField(contact); } else if ( inviteRequest) { if( inviteRequest->getContactUri(0, &requestContact)) { // TODO: I think this is incorrect. requestContact I think can be a name-addr Url contactUrl(requestContact, true) ; contactUrl.includeAngleBrackets() ; contactUrl.toString(requestContact) ; setContactField(requestContact); } } //if no record route or contact add sticky DNS if ( SetDNSParameters) { // set the DNS fields UtlString protocol; UtlString address; UtlString port; if ( inviteResponse->getDNSField(&protocol , &address , &port)) { setDNSField(protocol , address , port); } } inviteResponse->getCallIdField(&callId); inviteResponse->getCSeqField(&sequenceNum, &sequenceMethod); setAckData(uri.data(), fromField.data(), toField.data(), callId, sequenceNum); if(sessionTimerExpires > 0) setSessionExpires(sessionTimerExpires); } void SipMessage::setAckErrorData(const SipMessage* byeRequest) { setResponseData(byeRequest, SIP_BAD_REQUEST_CODE, SIP_BAD_REQUEST_TEXT); } void SipMessage::setByeData(const char* uri, const char* fromField, const char* toField, const char* callId, const char* localContact, int sequenceNumber) { setRequestData(SIP_BYE_METHOD, uri, fromField, toField, callId, sequenceNumber, localContact); } void SipMessage::setByeData(const SipMessage* inviteRequest, const char* remoteContact, UtlBoolean byeToCallee, int localCSequenceNumber, const char* routeField, const char* alsoInviteUri, const char* localContact) { UtlString fromField; UtlString toField; UtlString uri; UtlString callId; int dummySequenceNum; UtlString sequenceMethod; UtlString remoteContactString; setTransportInfo(inviteRequest) ; if (remoteContact) remoteContactString.append(remoteContact); inviteRequest->getFromField(&fromField); inviteRequest->getToField(&toField); inviteRequest->getCallIdField(&callId); inviteRequest->getCSeqField(&dummySequenceNum, &sequenceMethod); setRouteField(routeField); if (!remoteContactString.isNull()) { uri.append(remoteContactString); } // Use the route uri if set if(!uri.isNull()) { } // Use the original uri from the INVITE if the INVITE is from // this side. else if(byeToCallee) { inviteRequest->getRequestUri(&uri); } // Use contact if present else if(inviteRequest->getContactUri(0, &uri) && !uri.isNull()) { } else { uri.append(fromField.data()); } if(byeToCallee) { setByeData(uri.data(), fromField.data(), toField.data(), callId, localContact, localCSequenceNumber); } else { setByeData(uri.data(), toField.data(), fromField.data(), callId, localContact, localCSequenceNumber); } if(alsoInviteUri && *alsoInviteUri) { if(!isRequireExtensionSet(SIP_CALL_CONTROL_EXTENSION)) { addRequireExtension(SIP_CALL_CONTROL_EXTENSION); } addAlsoUri(alsoInviteUri); } } void SipMessage::setReferData(const SipMessage* inviteRequest, UtlBoolean referToCallee, int localCSequenceNumber, const char* routeField, const char* contactUrl, const char* remoteContactUrl, const char* transferTargetAddress, const char* targetCallId) { UtlString fromField; UtlString toField; UtlString uri; UtlString callId; int dummySequenceNum; UtlString sequenceMethod; setTransportInfo(inviteRequest) ; inviteRequest->getFromField(&fromField); inviteRequest->getToField(&toField); inviteRequest->getCallIdField(&callId); inviteRequest->getCSeqField(&dummySequenceNum, &sequenceMethod); setRouteField(routeField); if(remoteContactUrl) { uri = remoteContactUrl; } // Use the route uri if set else if(!referToCallee) { inviteRequest->getContactUri(0, &uri); } // Use the original uri from the INVITE if the INVITE is from // this side. else if(referToCallee) { inviteRequest->getRequestUri(&uri); } // Use contact if present else if(inviteRequest->getContactUri(0, &uri) && !uri.isNull()) { } else { uri.append(fromField.data()); } UtlString referredByField; if(referToCallee) { setRequestData(SIP_REFER_METHOD, uri.data(), fromField.data(), toField.data(), callId, localCSequenceNumber, contactUrl); Url referToUrl(fromField); referToUrl.removeFieldParameters(); referToUrl.includeAngleBrackets(); referToUrl.toString(referredByField); } else { setRequestData(SIP_REFER_METHOD, uri.data(), toField.data(), fromField.data(), callId, localCSequenceNumber, contactUrl); Url referToUrl(toField); referToUrl.removeFieldParameters(); referToUrl.includeAngleBrackets(); referToUrl.toString(referredByField); } //referredByField.append("; "); if(transferTargetAddress && *transferTargetAddress) { UtlString targetAddress(transferTargetAddress); Url targetUrl(targetAddress); UtlString referTo; if(targetCallId && *targetCallId) { //targetAddress.append("?Call-ID="); //targetAddress.append(targetCallId); targetUrl.setHeaderParameter(SIP_CALLID_FIELD, targetCallId); } // Include angle brackets on the Refer-To header. We don't // need to do this, but it is the friendly thing to do. targetUrl.includeAngleBrackets(); targetUrl.toString(referTo); // This stuff went away in the Transfer-05/Refer-02 drafts // We need angle brackets for the refer to url in the referred-by //targetUrl.includeAngleBrackets(); //targetUrl.toString(targetAddress); //referredByField.append("ref="); //referredByField.append(targetAddress); setReferredByField(referredByField.data()); setReferToField(referTo.data()); } } void SipMessage::setReferOkData(const SipMessage* referRequest) { setResponseData(referRequest, SIP_OK_CODE, SIP_OK_TEXT); } void SipMessage::setReferDeclinedData(const SipMessage* referRequest) { setResponseData(referRequest, SIP_DECLINE_CODE, SIP_DECLINE_TEXT); } void SipMessage::setReferFailedData(const SipMessage* referRequest) { setResponseData(referRequest, SIP_SERVICE_UNAVAILABLE_CODE, SIP_SERVICE_UNAVAILABLE_TEXT); } void SipMessage::setOptionsData(const SipMessage* inviteRequest, const char* remoteContact, UtlBoolean optionsToCallee, int localCSequenceNumber, const char* routeField, const char* localContact) { UtlString fromField; UtlString toField; UtlString uri; UtlString callId; int dummySequenceNum; UtlString sequenceMethod; setTransportInfo(inviteRequest) ; inviteRequest->getFromField(&fromField); inviteRequest->getToField(&toField); inviteRequest->getCallIdField(&callId); inviteRequest->getCSeqField(&dummySequenceNum, &sequenceMethod); setRouteField(routeField); //set the uri to the contact uri returned in the last response from the other side if (remoteContact && *remoteContact) { uri.append(remoteContact); } // Use the remoteContact uri if set if(!uri.isNull()) { } // Use the original uri from the INVITE if the INVITE is from // this side. else if(optionsToCallee) { inviteRequest->getRequestUri(&uri); } // Use contact if present else if(inviteRequest->getContactUri(0, &uri) && !uri.isNull()) { } else { uri.append(fromField.data()); } UtlString referredByField; if(optionsToCallee) { setRequestData(SIP_OPTIONS_METHOD, uri.data(), fromField.data(), toField.data(), callId, localCSequenceNumber, localContact); referredByField = fromField; } else { setRequestData(SIP_OPTIONS_METHOD, uri.data(), toField.data(), fromField.data(), callId, localCSequenceNumber, localContact); referredByField = toField; } } void SipMessage::setByeErrorData(const SipMessage* byeRequest) { setResponseData(byeRequest, SIP_BAD_REQUEST_CODE, SIP_BAD_REQUEST_TEXT); } void SipMessage::setCancelData(const char* fromField, const char* toField, const char* callId, int sequenceNumber, const char* localContact) { setRequestData(SIP_CANCEL_METHOD, toField, fromField, toField, callId, sequenceNumber, localContact); } void SipMessage::setCancelData(const SipMessage* inviteRequest, const char* localContact) { UtlString uri; UtlString fromField; UtlString toField; UtlString callId; int sequenceNum; UtlString sequenceMethod; setTransportInfo(inviteRequest) ; inviteRequest->getFromField(&fromField); inviteRequest->getToField(&toField); inviteRequest->getCallIdField(&callId); inviteRequest->getCSeqField(&sequenceNum, &sequenceMethod); inviteRequest->getRequestUri(&uri); setRequestData(SIP_CANCEL_METHOD, uri, fromField, toField, callId, sequenceNum, localContact); } void SipMessage::setPublishData(const char* uri, const char* fromField, const char* toField, const char* callId, int cseq, const char* eventField, const char* id, const char* sipIfMatchField, int expiresInSeconds, const char* contact) { setRequestData(SIP_PUBLISH_METHOD, uri, fromField, toField, callId, cseq, contact); // Set the event type if( eventField && *eventField ) { UtlString eventHeaderValue(eventField); if (id && *id) { eventHeaderValue.append(";id="); eventHeaderValue.append(id); } setEventField(eventHeaderValue.data()); setHeaderValue(SIP_EVENT_FIELD, eventHeaderValue, 0); } // Set the SipIfMatch field if( sipIfMatchField && *sipIfMatchField ) { setSipIfMatchField(sipIfMatchField); } // setExpires setExpiresField(expiresInSeconds); } void SipMessage::applyTargetUriHeaderParams() { UtlString uriWithHeaderParams; getRequestUri(&uriWithHeaderParams); Url requestUri(uriWithHeaderParams, TRUE); int header; UtlString hdrName; UtlString hdrValue; for (header=0; requestUri.getHeaderParameter(header, hdrName, hdrValue); header++ ) { // If the header is allowed in a header parameter? if(isUrlHeaderAllowed(hdrName.data())) { if (0 == hdrName.compareTo(SIP_FROM_FIELD, UtlString::ignoreCase)) { /* * The From header requires special handling * - we need to preserve the tag, if any, from the original header */ UtlString originalFromHeader; getFromField(&originalFromHeader); Url originalFromUrl(originalFromHeader); UtlString originalFromTag; originalFromUrl.getFieldParameter("tag", originalFromTag); Url newFromUrl(hdrValue.data()); newFromUrl.removeFieldParameter("tag"); // specifying a tag is a no-no if ( !originalFromTag.isNull() ) { newFromUrl.setFieldParameter("tag", originalFromTag.data()); } UtlString newFromFieldValue; newFromUrl.toString(newFromFieldValue); setRawFromField(newFromFieldValue.data()); // I suspect that this really should be adding a History-Info element of some kind addHeaderField("X-Original-From", originalFromHeader); } else if (0 == hdrName.compareTo(SIP_ROUTE_FIELD, UtlString::ignoreCase)) { /* * The Route header requires special handling * Examine each redirected route and ensure that it is a loose route */ OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipMessage::applyTargetUriHeaderParams found route header '%s'", hdrValue.data() ); UtlString routeParams; int route; UtlString thisRoute; for (route=0; UtlNameValueTokenizer::getSubField(hdrValue.data(), route, SIP_MULTIFIELD_SEPARATOR, &thisRoute); thisRoute.remove(0), route++ ) { Url newRouteUrl(thisRoute.data()); UtlString unusedValue; if ( ! newRouteUrl.getUrlParameter("lr", unusedValue, 0)) { newRouteUrl.setUrlParameter("lr",NULL); // force a loose route } UtlString newRoute; newRouteUrl.toString(newRoute); if (!routeParams.isNull()) { routeParams.append(SIP_MULTIFIELD_SEPARATOR); } routeParams.append(newRoute); } // If we found any routes, push them onto the route set if (!routeParams.isNull()) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipMessage::applyTargetUriHeaderParams adding route(s) '%s'", routeParams.data() ); addRouteUri(routeParams.data()); } } else if (isUrlHeaderUnique(hdrName.data())) { // If the field exists, change it, // if does not exist, create it. setHeaderValue(hdrName.data(), hdrValue.data(), 0); } else { addHeaderField(hdrName.data(), hdrValue.data()); } } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "URL header disallowed: %s: %s", hdrName.data(), hdrValue.data()); } } if (header) { // Remove the header fields from the URL as they // have been added to the message UtlString uriWithoutHeaderParams; requestUri.removeHeaderParameters(); // Use getUri to get the addr-spec formmat, not the name-addr // format, because uriWithoutHeaderParams will be used as the // request URI of the request. requestUri.getUri(uriWithoutHeaderParams); changeRequestUri(uriWithoutHeaderParams); } } void SipMessage::addVia(const char* domainName, int port, const char* protocol, const char* branchId, const bool bIncludeRport, const char* customRouteId) { UtlString viaField(SIP_PROTOCOL_VERSION); char portString[MAXIMUM_INTEGER_STRING_LENGTH + 1]; bool bCustomRouteId = (customRouteId && strlen(customRouteId)) ; viaField.append("/"); if(protocol && strlen(protocol)) { viaField.append(protocol); } // Default the protocol if not set else { viaField.append(SIP_TRANSPORT_TCP); } viaField.append(" "); if (bCustomRouteId) { viaField.append(customRouteId); } else { viaField.append(domainName); if(portIsValid(port)) { sprintf(portString, ":%d", port); viaField.append(portString); } } if(branchId && *branchId) { viaField.append(';'); viaField.append("branch"); viaField.append('='); viaField.append(branchId); } if (bIncludeRport && !bCustomRouteId) { viaField.append(';'); viaField.append("rport"); } addViaField(viaField.data()); } void SipMessage::addViaField(const char* viaField, UtlBoolean afterOtherVias) { mHeaderCacheClean = FALSE; NameValuePair* nv = new NameValuePair(SIP_VIA_FIELD, viaField); // Look for other via fields size_t fieldIndex = mNameValues.index(nv); //osPrintf("SipMessage::addViaField via: %s after: %s fieldIndex: %d headername: %s\n", // viaField, afterOtherVias ? "true" : "false", fieldIndex, // SIP_VIA_FIELD); if(fieldIndex == UTL_NOT_FOUND) { #ifdef TEST_PRINT UtlDListIterator iterator(mNameValues); //remove whole line NameValuePair* nv = NULL; while(nv = (NameValuePair*) iterator()) { osPrintf("\tName: %s\n", nv->data()); } #endif } mHeaderCacheClean = FALSE; if(fieldIndex == UTL_NOT_FOUND || !afterOtherVias) { mNameValues.insert(nv); } else { mNameValues.insertAt(fieldIndex, nv); } } void SipMessage::setLastViaTag(const char* tagValue, const char* tagName) { UtlString lastVia; //get last via field and remove it getViaFieldSubField(&lastVia, 0); removeLastVia(); //update the last via and add the updated field //setUriParameter(&lastVia, tagName, receivedFromIpAddress); //parse all name=value pairs into a collectable object UtlSList list; parseViaParameters(lastVia,list); //create an iterator to walk the list UtlSListIterator iterator(list); NameValuePair* nvPair; UtlString newVia; UtlBoolean bFoundTag = FALSE; UtlString value; while ((nvPair = (NameValuePair*) iterator())) { value.remove(0); //only if we have something in our newVia string do we add a semicolon if (newVia.length()) newVia.append(";"); //always append the name part of the value pair newVia.append(nvPair->data()); UtlString strPairName = nvPair->data(); UtlString strTagName = tagName; //convert both to upper strPairName.toUpper(); strTagName.toUpper(); //if the value we are looking for is found, then we are going to replace the value with this value if (strTagName == strPairName) { if (tagValue) value = tagValue; else //the value could come in as NULL. In this case make it be an empty string value = ""; bFoundTag = TRUE; } else //ok we didn't find the one we are looking for value = nvPair->getValue(); //if the value has a length then append it if (value.length()) { newVia.append("="); newVia.append(value); } } //if we didn't find the tag we are looking for after looping, then //we should add the name and value pair at the end if (!bFoundTag) { //add a semicolon before our new name value pair is added newVia.append(";"); newVia.append(tagName); //only if it is non-NULL and has a length do we add the equal and value //So, if the value is "" we will only put the name (without equal) if (tagValue && strlen(tagValue)) { newVia.append("="); newVia.append(tagValue); } } addViaField(newVia); list.destroyAll(); } void SipMessage::setViaFromRequest(const SipMessage* request) { UtlString viaSubField; int subFieldindex = 0; while(request->getViaFieldSubField(&viaSubField, subFieldindex )) { #ifdef TEST osPrintf("Adding via field: %s\n", viaSubField.data()); #endif addViaField(viaSubField.data(), FALSE); subFieldindex++; } } void SipMessage::setReceivedViaParams(const UtlString& fromIpAddress, int fromPort ) { UtlString lastAddress; UtlString lastProtocol; int lastPort; int receivedPort; UtlBoolean receivedSet; UtlBoolean maddrSet; UtlBoolean receivedPortSet; // Check that the via is set to the address from whence // this message came getLastVia(&lastAddress, &lastPort, &lastProtocol, &receivedPort, &receivedSet, &maddrSet, &receivedPortSet); // The via address is different from that of the sockets if(lastAddress.compareTo(fromIpAddress) != 0) { // Add a receive from tag setLastViaTag(fromIpAddress.data()); } // If the rport tag is present the sender wants to // know what port this message was received from int tempLastPort = lastPort; if (!portIsValid(lastPort)) { tempLastPort = 5060; } if (receivedPortSet) { char portString[20]; sprintf(portString, "%d", fromPort); setLastViaTag(portString, "rport"); } } void SipMessage::setCallIdField(const char* callId) { setHeaderValue(SIP_CALLID_FIELD, callId); } void SipMessage::setCSeqField(int sequenceNumber, const char* method) { UtlString value; char numString[HTTP_LONG_INT_CHARS]; sprintf(numString, "%d", sequenceNumber); value.append(numString); value.append(SIP_SUBFIELD_SEPARATOR); value.append(method); setHeaderValue(SIP_CSEQ_FIELD, value.data()); } void SipMessage::incrementCSeqNumber() { int seqNum; UtlString seqMethod; if(!getCSeqField(&seqNum, &seqMethod)) { seqNum = 1; seqMethod.append("UNKNOWN"); } seqNum++; setCSeqField(seqNum, seqMethod.data()); } void SipMessage::buildSipUrl(UtlString* url, const char* address, int port, const char* protocol, const char* user, const char* userLabel, const char* tag) { char portString[MAXIMUM_INTEGER_STRING_LENGTH + 1]; url->remove(0); UtlString tmpAddress(address); tmpAddress.toUpper(); if(userLabel && strlen(userLabel)) { url->append(userLabel); url->append("<"); } // If the SIP url type label is not already in the address int sipLabelIndex = tmpAddress.index(SIP_URL_TYPE); //osPrintf("Found \"%s\" in \"%s\" at index: %d\n", // SIP_URL_TYPE, tmpAddress.data(), // sipLabelIndex); if(sipLabelIndex < 0 && !tmpAddress.isNull()) { // Use lower case for more likely interoperablity UtlString sipLabel(SIP_URL_TYPE); sipLabel.toLower(); url->append(sipLabel.data()); } //else //{ // osPrintf("SIP: not added index: %d\n", sipLabelIndex); //} if(!strstr(address, "@") && user && strlen(user)) { url->append(user); url->append('@'); } url->append(address); if (portIsValid(port)) { sprintf(portString, ":%d", port); url->append(portString); } if(protocol && strlen(protocol) > 0) { url->append(";transport="); url->append(protocol); } if(userLabel && strlen(userLabel)) { url->append(">"); } if(tag && strlen(tag)) { url->append(";tag="); url->append(tag); } tmpAddress.remove(0); } void SipMessage::setFromField(const char* url) { UtlString value; UtlString address; UtlString protocol; UtlString user; UtlString userLabel; int port; parseAddressFromUri(url, &address, &port, &protocol, &user, &userLabel); buildSipUrl(&value, address.data(), port, protocol.data(), user.data(), userLabel.data()); // If the field exists change it, if does not exist create it. setHeaderValue(SIP_FROM_FIELD, value.data(), 0); } void SipMessage::setFromField(const char* address, int port, const char* protocol, const char* user, const char* userLabel) { UtlString url; buildSipUrl(&url, address, port, protocol, user, userLabel); // If the field exists change it, if does not exist create it setHeaderValue(SIP_FROM_FIELD, url.data(), 0); } void SipMessage::setRawToField(const char* url) { setHeaderValue(SIP_TO_FIELD, url, 0); } void SipMessage::setRawFromField(const char* url) { // If the field exists change it, if does not exist create it setHeaderValue(SIP_FROM_FIELD, url, 0); } void SipMessage::setToField(const char* address, int port, const char* protocol, const char* user, const char* userLabel) { UtlString url; buildSipUrl(&url, address, port, protocol, user, userLabel); // If the field exists change it, if does not exist create it setHeaderValue(SIP_TO_FIELD, url.data(), 0); } void SipMessage::setExpiresField(int expiresInSeconds) { if (expiresInSeconds >= 0) { char secondsString[MAXIMUM_INTEGER_STRING_LENGTH]; sprintf(secondsString, "%d", expiresInSeconds); // If the field exists change it, if does not exist create it setHeaderValue(SIP_EXPIRES_FIELD, secondsString, 0); } } void SipMessage::setMinExpiresField(int minimumExpiresInSeconds) { char secondsString[MAXIMUM_INTEGER_STRING_LENGTH]; sprintf(secondsString, "%d", minimumExpiresInSeconds); // If the field exists change it, if does not exist create it setHeaderValue(SIP_MIN_EXPIRES_FIELD, secondsString, 0); } void SipMessage::setContactField(const char* contactField, int index) { // If the field exists change it. If it does not exist, create it. setHeaderValue(SIP_CONTACT_FIELD, contactField, index); } void SipMessage::setRequestDispositionField(const char* dispositionField) { // If the field exists change it, if does not exist create it setHeaderValue(SIP_REQUEST_DISPOSITION_FIELD, dispositionField, 0); } void SipMessage::addRequestDisposition(const char* dispositionToken) { // Append to the field value already there, if it exists UtlString field; getRequestDispositionField(&field); if(!field.isNull()) { field.append(' '); } field.append(dispositionToken); setRequestDispositionField(field.data()); } void SipMessage::setWarningField(int code, const char* hostname, const char* text) { UtlString warningContent; size_t sizeNeeded = 3 /* warning code size */ + strlen(hostname) + strlen(text) + 3 /* blanks & null */; size_t allocated = warningContent.capacity(sizeNeeded); if (allocated >= sizeNeeded) { sprintf((char*)warningContent.data(), "%3d %s %s", code, hostname, text); setHeaderValue(SIP_WARNING_FIELD, warningContent.data()); } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipMessage::setWarningField value too large (max %"PRIuPTR") host '%s' text '%s'", allocated, hostname, text); } } void SipMessage::changeUri(const char* newUri) { UtlString uriString; // Remove the stuff that should not be in a URI Url cleanUri(newUri); cleanUri.getUri(uriString); changeRequestUri(uriString.data()); } UtlBoolean SipMessage::getMaxForwards(int& maxForwards) const { const char* value = getHeaderValue(0, SIP_MAX_FORWARDS_FIELD); if(value) { maxForwards = atoi(value); } return(value != NULL); } void SipMessage::setMaxForwards(int maxForwards) { char buf[64]; sprintf(buf, "%d", maxForwards); setHeaderValue(SIP_MAX_FORWARDS_FIELD,buf, 0); } void SipMessage::decrementMaxForwards() { int maxForwards; if(!getMaxForwards(maxForwards)) { maxForwards = SIP_DEFAULT_MAX_FORWARDS; } maxForwards--; setMaxForwards(maxForwards); } void SipMessage::getFromField(UtlString* field) const { const char* value = getHeaderValue(0, SIP_FROM_FIELD); if(value) { *field = value; } else { field->remove(0); } } void SipMessage::getToField(UtlString* field) const { const char* value = getHeaderValue(0, SIP_TO_FIELD); if(value) { *field = value; } else { field->remove(0); } } void SipMessage::getToUrl(Url& toUrl) const { //UtlString toField; //getToField(&toField); const char* toField = getHeaderValue(0, SIP_TO_FIELD); toUrl = toField ? toField : ""; } void SipMessage::getFromUrl(Url& fromUrl) const { //UtlString fromField; //getFromField(&fromField); const char* fromField = getHeaderValue(0, SIP_FROM_FIELD); fromUrl = fromField ? fromField : ""; } void SipMessage::getFromLabel(UtlString* label) const { UtlString field; int labelEnd; getFromField(&field); label->remove(0); if(!field.isNull()) { labelEnd = field.index(" <"); if(labelEnd < 0) // seen without space too { labelEnd = field.index("<"); } if(labelEnd >= 0) { label->append(field.data()); label->remove(labelEnd); } } } UtlBoolean SipMessage::getPAssertedIdentityField(UtlString& identity, int index) const { UtlBoolean fieldExists = getFieldSubfield(SIP_P_ASSERTED_IDENTITY_FIELD, index, &identity); identity.strip(UtlString::both); return(fieldExists && !identity.isNull()); } void SipMessage::removePAssertedIdentityFields() { while(removeHeader(SIP_P_ASSERTED_IDENTITY_FIELD, 0)) { } } void SipMessage::addPAssertedIdentityField(const UtlString& identity) { // Order does not matter so just get the first occurance and // add a field seperator and the new identity value UtlString firstValue; const char* value = getHeaderValue(0, SIP_P_ASSERTED_IDENTITY_FIELD); if(value) { firstValue = value; firstValue.append(SIP_MULTIFIELD_SEPARATOR); firstValue.append(' '); } firstValue.append(identity); setHeaderValue(SIP_P_ASSERTED_IDENTITY_FIELD, firstValue, 0); } void SipMessage::getToLabel(UtlString* label) const { UtlString field; int labelEnd; getToField(&field); label->remove(0); if(!field.isNull()) { labelEnd = field.index(" <"); if(labelEnd < 0) // seen without space too { labelEnd = field.index("<"); } if(labelEnd >= 0) { label->append(field.data()); label->remove(labelEnd); } } } UtlBoolean SipMessage::parseParameterFromUri(const char* uri, const char* parameterName, UtlString* parameterValue) { UtlString parameterString(parameterName); UtlString uriString(uri); parameterString.append("="); // This may need to be changed to be make case insensative int parameterStart = uriString.index(parameterString.data()); // 0, UtlString::ignoreCase); parameterValue->remove(0); //osPrintf("SipMessage::parseParameterFromUri uri: %s parameter: %s index: %d\n", // uriString.data(), parameterString.data(), parameterStart); if(parameterStart >= 0) { parameterStart += parameterString.length(); uriString.remove(0, parameterStart); uriString.strip(UtlString::leading); //osPrintf("SipMessage::parseParameterFromUri uriString: %s index: %d\n", // uriString.data(), parameterStart); UtlNameValueTokenizer::getSubField(uriString.data(), 0, " \t;>", parameterValue); } return(parameterStart >= 0); } void SipMessage::parseAddressFromUri(const char* uri, UtlString* address, int* port, UtlString* protocol, UtlString* user, UtlString* userLabel, UtlString* tag) { // A SIP url looks like the following: // "user label ;tag=nnnn" Url parsedUri(uri); if (address) { parsedUri.getHostAddress(*address); } if (port) { *port = parsedUri.getHostPort(); } if (protocol) { parsedUri.getUrlParameter("transport",*protocol); } if (user) { parsedUri.getUserId(*user); } if (userLabel) { parsedUri.getDisplayName(*userLabel); } if (tag) { parsedUri.getFieldParameter("tag", *tag); } } void SipMessage::setUriParameter(UtlString* uri, const char* parameterName, const char* parameterValue) { UtlString parameterString(parameterName); //only append the '=' if not null and has a length if (parameterValue && *parameterValue != '\0') parameterString.append('='); int tagIndex = uri->index(parameterString.data()); // Tag already exists, replace it if(tagIndex >= 0) { //osPrintf("Found tag at index: %d\n", tagIndex); // Minimally start after the tag name & equal sign tagIndex+= parameterString.length(); int tagSpace = uri->index(' ', tagIndex); int tagTab = uri->index('\t', tagIndex); int tagSemi = uri->index(';', tagIndex); int tagEnd = tagSpace; if(tagTab >= tagIndex && (tagTab < tagEnd || tagEnd < tagIndex)) { tagEnd = tagTab; } if(tagSemi >= tagIndex && (tagSemi < tagEnd || tagEnd < tagIndex)) { tagEnd = tagSemi; } // Remove up to the separator if(tagEnd >= tagIndex) { uri->remove(tagIndex, tagEnd - tagIndex); } // Remove to the end, no separator found else { uri->remove(tagIndex); } //only insert the value if not null and has a length if (parameterValue && *parameterValue != '\0') uri->insert(tagIndex, parameterValue); } // Tag does not exist append it else { //osPrintf("Found no tag appending to the end\n"); uri->append(";"); uri->append(parameterString.data()); //only add the value if not null and has a length if (parameterValue && *parameterValue != '\0') uri->append(parameterValue); } } void SipMessage::setToFieldTag(const char* tagValue) { UtlString toField; getToField(&toField); //osPrintf("To field before: \"%s\"\n", toField.data()); setUriTag(&toField, tagValue); //osPrintf("To field after: \"%s\"\n", toField.data()); setRawToField(toField.data()); } void SipMessage::setToFieldTag(int tagValue) { char tagString[MAXIMUM_INTEGER_STRING_LENGTH]; sprintf(tagString, "%d", tagValue); setToFieldTag(tagString); } void SipMessage::removeToFieldTag() { UtlString toField; getToField(&toField); Url toUrl(toField); toUrl.removeFieldParameter("tag"); setRawToField(toUrl.toString()); } void SipMessage::setUriTag(UtlString* uri, const char* tagValue) { setUriParameter(uri, "tag", tagValue); } void SipMessage::getUri(UtlString* address, int* port, UtlString* protocol, UtlString* user) const { UtlString uriField; getRequestUri(&uriField); if( !uriField.isNull()) { //Uri field will only have URL parameters . So add angle backets around the //whole string. else the url parameters will be trated as field and header parameters Url uriUrl(uriField, TRUE); // is addrSpec if(address) { uriUrl.getHostAddress(*address); } if(protocol) { uriUrl.getUrlParameter("transport", *protocol); } if(port) { *port = uriUrl.getHostPort(); } if(user) { uriUrl.getUserId(*user); } } // parseAddressFromUri(uriField.data(), address, port, protocol, user); } void SipMessage::getFromAddress(UtlString* address, int* port, UtlString* protocol, UtlString* user, UtlString* userLabel, UtlString* tag) const { UtlString uri; getFromField(&uri); parseAddressFromUri(uri.data(), address, port, protocol, user, userLabel, tag); } void SipMessage::getToAddress(UtlString* address, int* port, UtlString* protocol, UtlString* user, UtlString* userLabel, UtlString* tag) const { UtlString uri; getToField(&uri); parseAddressFromUri(uri.data(), address, port, protocol, user, userLabel, tag); } void SipMessage::getFromUri(UtlString* uri) const { UtlString field; int labelEnd; getFromField(&field); uri->remove(0); if(!field.isNull()) { labelEnd = field.index("<"); // Look for a label terminator if(labelEnd >= 0) { // Remove the label and terminator labelEnd += 1; field.remove(0, labelEnd); // Find the URI terminator size_t uriEnd = field.index(">"); // No URI terminator found, assume the whole thing if(uriEnd == UTL_NOT_FOUND) { uri->append(field.data()); } // Remove the terminator else { field.remove(uriEnd); uri->append(field.data()); } } // There is no label take the whole thing as the URI else { uri->append(field.data()); } } } UtlBoolean SipMessage::getResponseSendAddress(UtlString& address, int& port, UtlString& protocol) const { int receivedPort; UtlBoolean receivedSet; UtlBoolean maddrSet; UtlBoolean receivedPortSet; // use the via as the place to send the response getLastVia(&address, &port, &protocol, &receivedPort, &receivedSet, &maddrSet, &receivedPortSet); // If the sender of the request indicated support of // rport (i.e. received port) send this response back to // the same port it came from if(receivedPortSet && portIsValid(receivedPort)) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipMessage::getResponseSendAddress response to receivedPort %s:%d not %d\n", address.data(), receivedPort, port); port = receivedPort; } // No via, use the from if(address.isNull()) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipMessage::getResponseSendAddress No VIA address, using From address\n"); getFromAddress(&address, &port, &protocol); } return(!address.isNull()); } void SipMessage::convertProtocolStringToEnum(const char* protocolString, OsSocket::IpProtocolSocketType& protocolEnum) { if(strcasecmp(protocolString, SIP_TRANSPORT_UDP) == 0) { protocolEnum = OsSocket::UDP; } else if(strcasecmp(protocolString, SIP_TRANSPORT_TCP) == 0) { protocolEnum = OsSocket::TCP; } else if(strcasecmp(protocolString, SIP_TRANSPORT_TLS) == 0) { protocolEnum = OsSocket::SSL_SOCKET; } else { protocolEnum = OsSocket::UNKNOWN; } } void SipMessage::convertProtocolEnumToString(OsSocket::IpProtocolSocketType protocolEnum, UtlString& protocolString) { protocolString = OsSocket::ipProtocolString(protocolEnum); } void SipMessage::getToUri(UtlString* uri) const { UtlString field; int labelEnd; getToField(&field); int uriEnd; uri->remove(0); if(!field.isNull()) { labelEnd = field.index("<"); // Look for a label terminator if(labelEnd >= 0) { // Remove the label and terminator labelEnd += 1; field.remove(0, labelEnd); // Find the URI terminator uriEnd = field.index(">", labelEnd); // No URI terminator found, assume the whole thing if(uriEnd < 0) { uri->append(field.data()); } // Remove the terminator else { field.remove(uriEnd); uri->append(field.data()); } } // There is no label take the whole thing as the URI else { uri->append(field.data()); } } } UtlBoolean SipMessage::getWarningCode(int* warningCode, int index) const { const char* value = getHeaderValue(index, SIP_WARNING_FIELD); UtlString warningField; int endOfCode; *warningCode = 0; if(value) { warningField.append(value); endOfCode = warningField.index(SIP_SUBFIELD_SEPARATOR); if(endOfCode > 0) { warningField.remove(endOfCode); *warningCode = atoi(warningField.data()); } } return(value != NULL); } UtlBoolean SipMessage::removeLastVia() { //do not remove the whole via header line . Remove only the first subfield UtlBoolean fieldFound = FALSE; UtlString NewViaHeader; UtlString viaField; if ( getViaField( &viaField , 0)) { size_t posSubField = viaField.first(SIP_MULTIFIELD_SEPARATOR); if (posSubField != UTL_NOT_FOUND) { viaField.remove(0, posSubField + strlen(SIP_MULTIFIELD_SEPARATOR)); NewViaHeader = viaField.strip(UtlString::both , ' '); } } NameValuePair viaHeaderField(SIP_VIA_FIELD); //remove whole line NameValuePair* nv = (NameValuePair*) mNameValues.find(&viaHeaderField); if(nv) { mHeaderCacheClean = FALSE; mNameValues.destroy(nv); nv = NULL; fieldFound = TRUE; } //add updated line if ( !NewViaHeader.isNull()) { addViaField( NewViaHeader); } return(fieldFound); } UtlBoolean SipMessage::getViaField(UtlString* viaField, int index) const { const char* value = getHeaderValue(index, SIP_VIA_FIELD); viaField->remove(0); if(value) { viaField->append(value); } return(value != NULL); } UtlBoolean SipMessage::getViaFieldSubField(UtlString* viaSubField, int subFieldIndex) const { UtlBoolean retVal = FALSE; UtlString Via; if (getFieldSubfield(SIP_VIA_FIELD, subFieldIndex, &Via) ) { viaSubField->remove(0); if(!Via.isNull()) { viaSubField->append(Via); retVal = TRUE; } } return retVal; } void SipMessage::getLastVia(UtlString* address, int* port, UtlString* protocol, int* receivedPort, UtlBoolean* receivedSet, UtlBoolean* maddrSet, UtlBoolean* receivedPortSet) const { UtlString Via; UtlString sipProtocol; UtlString url; UtlString receivedAddress; UtlString receivedPortString; UtlString maddr; int index; address->remove(0); *port = PORT_NONE; protocol->remove(0); if (port) { *port = 0; } if (address) { address->remove(0); } if (protocol) { protocol->remove(0); } if (receivedSet) { *receivedSet = FALSE; } if (maddrSet) { *maddrSet = FALSE; } if (receivedPortSet) { *receivedPortSet = FALSE; } // Get the first (most recent) Via value, which is the one that tells // how to send the response. if (getFieldSubfield(SIP_VIA_FIELD, 0, &Via)) { UtlNameValueTokenizer::getSubField(Via, 0, SIP_SUBFIELD_SEPARATORS, &sipProtocol); UtlNameValueTokenizer::getSubField(Via, 1, SIP_SUBFIELD_SEPARATORS, &url); index = sipProtocol.index('/'); if(index >= 0) { sipProtocol.remove(0, index + 1); index = sipProtocol.index('/'); } if(index >= 0) { sipProtocol.remove(0, index + 1); } if (protocol) { protocol->append(sipProtocol.data()); } Url viaParam(url,TRUE); if (address) { viaParam.getHostAddress(*address); } if (port) { *port = viaParam.getHostPort(); } UtlBoolean receivedFound = viaParam.getUrlParameter("received", receivedAddress); UtlBoolean maddrFound = viaParam.getUrlParameter("maddr", maddr); UtlBoolean receivedPortFound = viaParam.getUrlParameter("rport", receivedPortString); // The maddr takes precedence over the received-by address if(address && !maddr.isNull()) { *address = maddr; } // The received address takes precedence over the sent-by address else if(address && !receivedAddress.isNull()) { address->remove(0); address->append(receivedAddress.data()); } if(receivedPort && !receivedPortString.isNull()) { *receivedPort = atoi(receivedPortString.data()); } else if(receivedPort) { *receivedPort = PORT_NONE; } if(receivedSet) { *receivedSet = receivedFound; } if(maddrSet) { *maddrSet = maddrFound; } if(receivedPortSet) { *receivedPortSet = receivedPortFound; } } } UtlBoolean SipMessage::getViaTag(const char* viaField, const char* tagName, UtlString& tagValue) { UtlString strNameValuePair; UtlBoolean tagFound = FALSE; UtlHashBag viaParameters; parseViaParameters(viaField,viaParameters); UtlString nameMatch(tagName); NameValuePair *pair = (NameValuePair *)viaParameters.find(&nameMatch); if (pair) { tagValue = pair->getValue(); tagFound = TRUE; } else tagValue.remove(0); viaParameters.destroyAll(); return(tagFound); } void SipMessage::getCallIdField(UtlString* callId) const { const char* value = getHeaderValue(0, SIP_CALLID_FIELD); if(value) { *callId = value; } else { callId->remove(0); } } void SipMessage::getDialogHandle(UtlString& dialogHandle) const { getCallIdField(&dialogHandle); // Separator dialogHandle.append(','); Url messageFromUrl; getFromUrl(messageFromUrl); UtlString fromTag; messageFromUrl.getFieldParameter("tag", fromTag); dialogHandle.append(fromTag); // Separator dialogHandle.append(','); Url messageToUrl; getToUrl(messageToUrl); UtlString toTag; messageToUrl.getFieldParameter("tag", toTag); dialogHandle.append(toTag); } UtlBoolean SipMessage::getCSeqField(int* sequenceNum, UtlString* sequenceMethod) const { const char* value = getHeaderValue(0, SIP_CSEQ_FIELD); if(value) { // Too slow: /*UtlString sequenceNumString; UtlNameValueTokenizer::getSubField(value, 0, SIP_SUBFIELD_SEPARATORS, &sequenceNumString); *sequenceNum = atoi(sequenceNumString.data()); UtlNameValueTokenizer::getSubField(value, 1, SIP_SUBFIELD_SEPARATORS, sequenceMethod);*/ // Ignore white space in the begining int valueStart = strspn(value, SIP_SUBFIELD_SEPARATORS); // Find the end of the sequence number int numStringLen = strcspn(&value[valueStart], SIP_SUBFIELD_SEPARATORS) - valueStart; // Get the method if(sequenceMethod) { *sequenceMethod = &value[numStringLen + valueStart]; sequenceMethod->strip(UtlString::both); } if(numStringLen > MAXIMUM_INTEGER_STRING_LENGTH) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipMessage::getCSeqField " "CSeq field '%.*s' contains %d digits, which exceeds " "MAXIMUM_INTEGER_STRING_LENGTH (%d). Truncated.\n", numStringLen, &value[valueStart], numStringLen, MAXIMUM_INTEGER_STRING_LENGTH); numStringLen = MAXIMUM_INTEGER_STRING_LENGTH; } if(sequenceNum) { // Convert the sequence number char numBuf[MAXIMUM_INTEGER_STRING_LENGTH + 1]; memcpy(numBuf, &value[valueStart], numStringLen); numBuf[numStringLen] = '\0'; *sequenceNum = atoi(numBuf); } } else { if(sequenceNum) { *sequenceNum = -1; } if(sequenceMethod) { sequenceMethod->remove(0); } } return(value != NULL); } UtlBoolean SipMessage::getContactUri(int addressIndex, UtlString* uri) const { UtlBoolean uriFound = getContactEntry(addressIndex, uri); if(uriFound) { int trimIndex = uri->index('<'); if(trimIndex >= 0) uri->remove(0, trimIndex + 1); trimIndex = uri->index('>'); if(trimIndex > 0) uri->remove(trimIndex); } return(uriFound); } UtlBoolean SipMessage::getContactField(int addressIndex, UtlString& contactField) const { const char* value = getHeaderValue(addressIndex, SIP_CONTACT_FIELD); contactField = value ? value : ""; return(value != NULL); } // Make sure that the getContactEntry does the right thing for UtlBoolean SipMessage::getContactEntry(int addressIndex, UtlString* uriAndParameters) const { // return(getFieldSubfield(SIP_CONTACT_FIELD, addressIndex, uriAndParameters)); UtlBoolean contactFound = FALSE; int currentHeaderFieldValue = 0; int currentEntryValue = 0; const char* value = NULL; while ( (value = getHeaderValue(currentHeaderFieldValue, SIP_CONTACT_FIELD)) && (currentEntryValue <= addressIndex) ) { uriAndParameters->remove(0); if(value) { #ifdef TEST_PRINT osPrintf("SipMessage::getContactEntry addressIndex: %d\n", addressIndex); #endif //UtlNameValueTokenizer::getSubField(value, addressIndex, ",", // uriAndParameters); int addressStart = 0; int addressCount = 0; int charIndex = 0; int doubleQuoteCount = 0; while(1) { if(value[charIndex] == '"') { doubleQuoteCount++; #ifdef TEST_PRINT osPrintf("SipMessage::getContactEntry doubleQuoteCount parity:%d", doubleQuoteCount % 2); #endif } // We found a comma that is not in the middle of a quoted string if( (value[charIndex] == ',' || value[charIndex] == '\0') && !(doubleQuoteCount % 2) ) { if(currentEntryValue == addressIndex) { uriAndParameters->append(&value[addressStart], charIndex - addressStart); #ifdef TEST_PRINT osPrintf("SipMessage::getContactEntry found contact[%d] starting: %d ending: %d \"%s\"\n", addressIndex, addressStart, charIndex, uriAndParameters->data()); #endif currentEntryValue ++; contactFound = TRUE; break; } currentEntryValue ++; addressStart = charIndex + 1; addressCount++; } if(value[charIndex] == '\0') break; charIndex++; } } currentHeaderFieldValue++; } return(contactFound); } UtlBoolean SipMessage::getContactAddress(int addressIndex, UtlString* contactAddress, int* contactPort, UtlString* protocol, UtlString* user, UtlString* userLabel) const { UtlString uri; UtlBoolean foundUri = getContactUri(addressIndex, &uri); if(foundUri) parseAddressFromUri(uri.data(), contactAddress, contactPort, protocol, user, userLabel); return(foundUri); } UtlBoolean SipMessage::getRequireExtension(int extensionIndex, UtlString* extension) const { return(getFieldSubfield(SIP_REQUIRE_FIELD, extensionIndex, extension)); } UtlBoolean SipMessage::getProxyRequireExtension(int extensionIndex, UtlString* extension) const { return(getFieldSubfield(SIP_PROXY_REQUIRE_FIELD, extensionIndex, extension)); } void SipMessage::addRequireExtension(const char* extension) { addHeaderField(SIP_REQUIRE_FIELD, extension); } /// Retrieve the event type, id, and other params from the Event Header UtlBoolean SipMessage::getEventField(UtlString* eventType, UtlString* eventId, //< set to the 'id' parameter value if not NULL UtlHashMap* params //< holds parameter name/value pairs if not NULL ) const { UtlString eventField; UtlBoolean gotHeader = getEventField(eventField); if (NULL != eventId) { eventId->remove(0); } if (gotHeader) { UtlNameValueTokenizer::getSubField(eventField, 0, ";", eventType); eventType->strip(UtlString::both); UtlString eventParam; for (int param_idx = 1; UtlNameValueTokenizer::getSubField(eventField.data(), param_idx, ";", &eventParam); param_idx++ ) { UtlString name; UtlString value; UtlNameValueTokenizer paramPair(eventParam); if (paramPair.getNextPair('=',&name,&value)) { if (0==name.compareTo("id",UtlString::ignoreCase) && NULL != eventId) { *eventId=value; } else if (NULL != params) { UtlString* returnedName = new UtlString(name); UtlString* returnedValue = new UtlString(value); params->insertKeyAndValue( returnedName, returnedValue ); } } else { OsSysLog::add(FAC_SIP,PRI_WARNING,"invalid event parameter '%s'", eventParam.data()); } } } return gotHeader; } UtlBoolean SipMessage::getEventField(UtlString& eventField) const { const char* value = getHeaderValue(0, SIP_EVENT_FIELD); eventField.remove(0); if(value) { eventField.append(value); } return(value != NULL); } void SipMessage::setEventField(const char* eventField) { setHeaderValue(SIP_EVENT_FIELD, eventField, 0); } UtlBoolean SipMessage::getExpiresField(int* expiresInSeconds) const { const char* fieldValue = getHeaderValue(0, SIP_EXPIRES_FIELD); if(fieldValue) { UtlString subfieldText; UtlNameValueTokenizer::getSubField(fieldValue, 1, " \t:;,", &subfieldText); // if(subfieldText.isNull()) { *expiresInSeconds = atoi(fieldValue); } // If there is more than one token assume it is a text date else { long dateExpires = OsDateTime::convertHttpDateToEpoch(fieldValue); long dateSent = 0; // If the date was not set in the message if(!getDateField(&dateSent)) { #ifdef TEST osPrintf("Date field not set\n"); #endif // Assume date sent is now dateSent = OsDateTime::getSecsSinceEpoch(); } #ifdef TEST_PRINT osPrintf("Expires date: %ld\n", dateExpires); osPrintf("Current time: %ld\n", dateSent); #endif *expiresInSeconds = dateExpires - dateSent; } } else { *expiresInSeconds = -1; } return(fieldValue != NULL); } UtlBoolean SipMessage::getRequestDispositionField(UtlString* dispositionField) const { const char* value = getHeaderValue(0, SIP_REQUEST_DISPOSITION_FIELD); dispositionField->remove(0); if(value) { dispositionField->append(value); } return(value != NULL); } UtlBoolean SipMessage::getRequestDisposition(int tokenIndex, UtlString* dispositionToken) const { return(getFieldSubfield(SIP_REQUEST_DISPOSITION_FIELD, tokenIndex, dispositionToken)); } UtlBoolean SipMessage::getRecordRouteField(int index, UtlString* recordRouteField) const { const char* fieldValue = getHeaderValue(index, SIP_RECORD_ROUTE_FIELD); recordRouteField->remove(0); if(fieldValue) recordRouteField->append(fieldValue); return(fieldValue != NULL); } UtlBoolean SipMessage::getRecordRouteUri(int index, UtlString* recordRouteUri) const { //UtlString recordRouteField; //UtlBoolean fieldExists = getRecordRouteField(&recordRouteField); //UtlNameValueTokenizer::getSubField(recordRouteField.data(), index, // ",", recordRouteUri); UtlBoolean fieldExists = getFieldSubfield(SIP_RECORD_ROUTE_FIELD, index, recordRouteUri); recordRouteUri->strip(UtlString::both); return(fieldExists && !recordRouteUri->isNull()); } void SipMessage::setRecordRouteField(const char* recordRouteField, int index) { setHeaderValue(SIP_RECORD_ROUTE_FIELD, recordRouteField, index); } void SipMessage::addRecordRouteUri(const char* recordRouteUri) { UtlString recordRouteField; UtlString recordRouteUriString; /*int recordRouteIndex = 0; while(getRecordRouteField(recordRouteIndex, &recordRouteField)) { recordRouteIndex++; } // Try to format the same as it came in either all the record route // URLs on the same line or a different field for each if(recordRouteIndex == 1) { recordRouteIndex--; getRecordRouteField(recordRouteIndex, &recordRouteField); } if(recordRouteUri && !recordRouteField.isNull()) { recordRouteField.insert(0, ','); }*/ if(recordRouteUri && strchr(recordRouteUri, '<') == NULL) { recordRouteUriString.append('<'); recordRouteUriString.append(recordRouteUri); recordRouteUriString.append('>'); } else if(recordRouteUri) { recordRouteUriString.append(recordRouteUri); } recordRouteField.insert(0, recordRouteUriString); //setRecordRouteField(recordRouteField.data(), recordRouteIndex); // Record route is always added on the top NameValuePair* headerField = new NameValuePair(SIP_RECORD_ROUTE_FIELD, recordRouteUriString.data()); mHeaderCacheClean = FALSE; mNameValues.insertAt(0, headerField); } // isClientMsgStrictRouted returns whether or not a message // is set up such that it requires strict routing. // This is appropriate only when acting as a UAC UtlBoolean SipMessage::isClientMsgStrictRouted() const { UtlBoolean result; UtlString routeUriString; // If this message was loose routed, the first route must contain the lr parameter. // Get the first route if(getRouteUri(0, &routeUriString)) { //OsSysLog::add(FAC_SIP, PRI_DEBUG, // "SipMessage::isClientMsgStrictRouted got first route: \"%s\"", // routeUriString.data()); Url routeUrl(routeUriString, FALSE); UtlString valueIgnored; // there is a route header, so see if it is loose routed or not result = ! routeUrl.getUrlParameter("lr", valueIgnored); } else { result = FALSE; } return result; } UtlBoolean SipMessage::getRouteField(UtlString* routeField) const { const char* fieldValue = getHeaderValue(0, SIP_ROUTE_FIELD); routeField->remove(0); if(fieldValue) routeField->append(fieldValue); return(fieldValue != NULL); } void SipMessage::addRouteUri(const char* routeUri) { UtlString routeField; UtlString routeParameter; const char* bracketPtr = strchr(routeUri, '<'); if(bracketPtr == NULL) { routeParameter.append('<'); } routeParameter.append(routeUri); bracketPtr = strchr(routeUri, '>'); if(bracketPtr == NULL) { routeParameter.append('>'); } // If there is already a route header if(getRouteField( &routeField)) { routeParameter.append(SIP_MULTIFIELD_SEPARATOR); // Remove the entire header removeHeader(SIP_ROUTE_FIELD, 0); } //add the updated header routeField.insert(0,routeParameter); setRouteField(routeField); } void SipMessage::addLastRouteUri(const char* routeUri) { if(routeUri && *routeUri) { // THis is the cheap brut force way to do this int index = 0; const char* routeField = NULL; while ((routeField = getHeaderValue(index, SIP_ROUTE_FIELD))) { index++; } UtlString routeString(routeField ? routeField : ""); if(routeField) { // Add a field separator routeString.append(SIP_MULTIFIELD_SEPARATOR); } // Make sure the route is in name-addr format if(strstr(routeUri,"<") <= 0) { routeString.append("<"); } routeString.append(routeUri); if(strstr(routeUri, ">") <= 0) { routeString.append(">"); } setHeaderValue(SIP_ROUTE_FIELD, routeString.data(), index); } } UtlBoolean SipMessage::getLastRouteUri(UtlString& routeUri, int& lastIndex) { int index = 0; UtlString tempRoute; while(getFieldSubfield(SIP_ROUTE_FIELD, index, &tempRoute)) { index++; routeUri = tempRoute; } index--; lastIndex = index; return(!routeUri.isNull()); } UtlBoolean SipMessage::getRouteUri(int index, UtlString* routeUri) const { UtlString routeField; UtlBoolean fieldExists = getFieldSubfield(SIP_ROUTE_FIELD, index, routeUri); return(fieldExists && !routeUri->isNull()); } UtlBoolean SipMessage::removeRouteUri(int index, UtlString* routeUri) { UtlString newRouteField; UtlString aRouteUri; UtlBoolean uriFound = FALSE; int uriIndex = 0; while(getFieldSubfield(SIP_ROUTE_FIELD, uriIndex, &aRouteUri)) { #ifdef TEST_PRINT osPrintf("removeRouteUri::routeUri[%d]: %s\n", uriIndex, newRouteField.data()); #endif if(uriIndex == index) { *routeUri = aRouteUri; uriFound = TRUE; } else { if(!newRouteField.isNull()) { newRouteField.append(','); } int routeUriIndex = aRouteUri.index('<'); if(routeUriIndex < 0) { aRouteUri.insert(0, '<'); aRouteUri.append('>'); } newRouteField.append(aRouteUri.data()); } #ifdef TEST_PRINT osPrintf("removeRouteUri::newRouteField: %s\n", newRouteField.data()); #endif uriIndex++; } // Remove all the old route headers. while(removeHeader(SIP_ROUTE_FIELD, 0)) { } // Set the route field to contain the uri list with the indicated // uri removed. if(!newRouteField.isNull()) { insertHeaderField(SIP_ROUTE_FIELD, newRouteField.data()); } return(uriFound); } void SipMessage::setRouteField(const char* routeField) { #ifdef TEST_PRINT osPrintf("setRouteField: %s\n", routeField); #endif if (routeField && strlen(routeField)) { setHeaderValue(SIP_ROUTE_FIELD, routeField, 0); } } UtlBoolean SipMessage::buildRouteField(UtlString* routeFld) const { UtlBoolean recordRouteFound = FALSE; UtlString contactUri; UtlString routeField; // If request build from recordRoute verbatum if(!isResponse()) { #ifdef TEST_PRINT osPrintf("SipMessage::buildRouteField recordRoute verbatum\n"); #endif //recordRouteFound = getRecordRouteField(routeField); int recordRouteIndex = 0; UtlString recordRouteUri; while(getRecordRouteUri(recordRouteIndex, &recordRouteUri)) { if(!routeField.isNull()) { routeField.append(','); } routeField.append(recordRouteUri.data()); #ifdef TEST_PRINT osPrintf("SipMessage::buildRouteField recordRouteUri[%d] %s\n", recordRouteIndex, recordRouteUri.data()); #endif recordRouteIndex++; } if(recordRouteIndex) recordRouteFound = TRUE; } // If response build from recordeRoute in reverse order else { #ifdef TEST_PRINT osPrintf("SipMessage::buildRouteField recordRoute reverse\n"); #endif UtlString recordRouteUri; routeField.remove(0); int index = 0; int recordRouteUriIndex; while(getRecordRouteUri(index, &recordRouteUri)) { recordRouteFound = TRUE; if(index > 0) { routeField.insert(0, ", "); } recordRouteUriIndex = recordRouteUri.index('<'); if(recordRouteUriIndex < 0) { recordRouteUri.insert(0, '<'); recordRouteUri.append('>'); } #ifdef TEST_PRINT osPrintf("SipMessage::buildRouteField recordRouteUri[%d] %s\n", index, recordRouteUri.data()); #endif routeField.insert(0, recordRouteUri.data()); index++; } } #ifdef LOOSE_ROUTE // In either case if contact is present add to the end of the route list. if(recordRouteFound && getContactUri(0, &contactUri)) { routeField.append(", "); int contactUriIndex = contactUri.index('<'); if(contactUriIndex < 0) { contactUri.insert(0, '<'); contactUri.append('>'); } routeField.append(contactUri.data()); } #endif #ifdef TEST_PRINT osPrintf("buildRouteField: %s\n", routeField.data()); #endif if (recordRouteFound) { //clear the previous recourd route field and set it to the new one routeFld->remove(0); routeFld->append(routeField); } return(recordRouteFound); } void SipMessage::buildReplacesField(UtlString& replacesField, const char* callId, const char* fromField, const char* toField) { replacesField = callId; replacesField.append(";to-tag="); Url toUrl(toField); UtlString toTag; toUrl.getFieldParameter("tag", toTag); replacesField.append(toTag); replacesField.append(";from-tag="); Url fromUrl(fromField); UtlString fromTag; fromUrl.getFieldParameter("tag", fromTag); replacesField.append(fromTag); } UtlBoolean SipMessage::getFieldSubfield(const char* fieldName, int addressIndex, UtlString* uri) const { UtlBoolean uriFound = FALSE; UtlString url; int fieldIndex = 0; int subFieldIndex = 0; int index = 0; const char* value = getHeaderValue(fieldIndex, fieldName); uri->remove(0); while(value && index <= addressIndex) { subFieldIndex = 0; UtlNameValueTokenizer::getSubField(value, subFieldIndex, SIP_MULTIFIELD_SEPARATOR, &url); #ifdef TEST osPrintf("Got field: \"%s\" subfield[%d]: %s\n", fieldName, fieldIndex, url.data()); #endif while(!url.isNull() && index < addressIndex) { subFieldIndex++; index++; UtlNameValueTokenizer::getSubField(value, subFieldIndex, SIP_MULTIFIELD_SEPARATOR, &url); #ifdef TEST osPrintf("Got field: \"%s\" subfield[%d]: %s\n", fieldName, fieldIndex, url.data()); #endif } if(index == addressIndex && !url.isNull()) { uri->append(url.data()); uriFound = TRUE; break; } else if(index > addressIndex) { break; } fieldIndex++; value = getHeaderValue(fieldIndex, fieldName); } return(uriFound); } /*UtlBoolean SipMessage::setFieldSubfield(const char* fieldName, int addressIndex, const char* subFieldValue) const { UtlBoolean uriFound = FALSE; UtlString url; int fieldIndex = 0; int subFieldIndex = 0; int index = 0; const char* value = getHeaderValue(fieldIndex, fieldName); uri->remove(0); while(value && index <= addressIndex) { subFieldIndex = 0; UtlNameValueTokenizer::getSubField(value, subFieldIndex, SIP_MULTIFIELD_SEPARATOR, &url); #ifdef TEST osPrintf("Got field: \"%s\" subfield[%d]: %s\n", fieldName, fieldIndex, url.data()); #endif while(!url.isNull() && index < addressIndex) { subFieldIndex++; index++; UtlNameValueTokenizer::getSubField(value, subFieldIndex, SIP_MULTIFIELD_SEPARATOR, &url); #ifdef TEST osPrintf("Got field: \"%s\" subfield[%d]: %s\n", fieldName, fieldIndex, url.data()); #endif } if(index == addressIndex && !url.isNull()) { url.remove(0); url.append(subFieldValue.data()); uriFound = TRUE; break; } else if(index > addressIndex) { break; } fieldIndex++; value = getHeaderValue(fieldIndex, fieldName); } return(uriFound); } */ UtlBoolean SipMessage::getContentEncodingField(UtlString* contentEncodingField) const { const char* value = getHeaderValue(0, SIP_CONTENT_ENCODING_FIELD); contentEncodingField->remove(0); if(value) { contentEncodingField->append(value); } return(value != NULL); } UtlBoolean SipMessage::getSessionExpires(int* sessionExpiresSeconds, UtlString* refresher) const { const char* value = getHeaderValue(0, SIP_SESSION_EXPIRES_FIELD); if (value) { *sessionExpiresSeconds = atoi(value); UtlString expiresParams(value) ; size_t iIndex = expiresParams.first(';') ; if (iIndex != UTL_NOT_FOUND) { expiresParams.remove(0, iIndex+1) ; UtlNameValueTokenizer tokenizer(expiresParams.data()) ; UtlString name ; UtlString value ; while (tokenizer.getNextPair('=', &name, &value)) { if (name.compareTo("refresher", UtlString::ignoreCase) == 0) { *refresher = value ; break ; } } } } else { *sessionExpiresSeconds = 0; refresher->remove(0) ; } return(value != NULL); } void SipMessage::setSessionExpires(int sessionExpiresSeconds, const char* refresher) { UtlString fieldValue; if(refresher && *refresher) { fieldValue.appendFormat("%d;refresher=%s", sessionExpiresSeconds, refresher); } else { fieldValue.appendFormat("%d", sessionExpiresSeconds); } setHeaderValue(SIP_SESSION_EXPIRES_FIELD, fieldValue); } bool SipMessage::hasSelfHeader() const { UtlString value; getUserAgentField(&value); if (value.isNull()) { getServerField(&value); } return ! value.isNull(); } void SipMessage::getServerField(UtlString* serverFieldValue) const { const char* server = getHeaderValue(0, SIP_SERVER_FIELD); serverFieldValue->remove(0); if(server) { serverFieldValue->append(server); } } void SipMessage::setServerField(const char* serverField) { setHeaderValue(SIP_SERVER_FIELD, serverField); } UtlBoolean SipMessage::getSupportedField(UtlString& supportedField) const { return(getFieldSubfield(SIP_SUPPORTED_FIELD, 0, &supportedField)); } void SipMessage::setSupportedField(const char* supportedField) { setHeaderValue(SIP_SUPPORTED_FIELD, supportedField); } UtlBoolean SipMessage::isInSupportedField(const char* token) const { UtlBoolean tokenFound = FALSE; UtlString url; int fieldIndex = 0; int subFieldIndex = 0; const char* value = getHeaderValue(fieldIndex, SIP_SUPPORTED_FIELD); while (value && !tokenFound) { subFieldIndex = 0; UtlNameValueTokenizer::getSubField(value, subFieldIndex, SIP_MULTIFIELD_SEPARATOR, &url); #ifdef TEST OsSysLog::add(FAC_SIP, PRI_DEBUG, "Got field: \"%s\" subfield[%d]: %s\n", value, fieldIndex, url.data()); #endif url.strip(UtlString::both); if (url.compareTo(token, UtlString::ignoreCase) == 0) { tokenFound = TRUE; } while (!url.isNull() && !tokenFound) { subFieldIndex++; UtlNameValueTokenizer::getSubField(value, subFieldIndex, SIP_MULTIFIELD_SEPARATOR, &url); url.strip(UtlString::both); #ifdef TEST OsSysLog::add(FAC_SIP, PRI_DEBUG, "Got field: \"%s\" subfield[%d]: %s\n", SIP_SUPPORTED_FIELD, fieldIndex, url.data()); #endif if (url.compareTo(token, UtlString::ignoreCase) == 0) { tokenFound = TRUE; } } fieldIndex++; value = getHeaderValue(fieldIndex, SIP_SUPPORTED_FIELD); } return(tokenFound); } // Call control accessors UtlBoolean SipMessage::getAlsoUri(int index, UtlString* alsoUri) const { return(getFieldSubfield(SIP_ALSO_FIELD, index, alsoUri)); } UtlBoolean SipMessage::getAlsoField(UtlString* alsoField) const { const char* value = getHeaderValue(0, SIP_ALSO_FIELD); alsoField->remove(0); if(value) alsoField->append(value); return(value != NULL); } void SipMessage::setAlsoField(const char* alsoField) { setHeaderValue(SIP_ALSO_FIELD, alsoField); } void SipMessage::addAlsoUri(const char* alsoUri) { // Append to the field value already there, if it exists UtlString field; if(getAlsoField(&field) && !field.isNull()) { field.append(SIP_MULTIFIELD_SEPARATOR); field.append(SIP_SINGLE_SPACE); } if(!strchr(alsoUri, '<')) field.append('<'); field.append(alsoUri); if(!strchr(alsoUri, '>')) field.append('>'); setAlsoField(field.data()); } void SipMessage::setRequestedByField(const char* requestedByUri) { setHeaderValue(SIP_REQUESTED_BY_FIELD, requestedByUri); } UtlBoolean SipMessage::getRequestedByField(UtlString& requestedByField) const { const char* value = getHeaderValue(0, SIP_REQUESTED_BY_FIELD); requestedByField.remove(0); if(value) requestedByField.append(value); return(value != NULL); } void SipMessage::setReferToField(const char* referToField) { setHeaderValue(SIP_REFER_TO_FIELD, referToField); } UtlBoolean SipMessage::getReferToField(UtlString& referToField) const { const char* value = getHeaderValue(0, SIP_REFER_TO_FIELD); referToField.remove(0); if(value) referToField.append(value); return(value != NULL); } void SipMessage::setReferredByField(const char* referredByField) { setHeaderValue(SIP_REFERRED_BY_FIELD, referredByField); } UtlBoolean SipMessage::getReferredByField(UtlString& referredByField) const { const char* value = getHeaderValue(0, SIP_REFERRED_BY_FIELD); referredByField.remove(0); if(value) referredByField.append(value); return(value != NULL); } UtlBoolean SipMessage::getReferredByUrls(UtlString* referrerUrl, UtlString* referredToUrl) const { if(referrerUrl) referrerUrl->remove(0); if(referredToUrl) referredToUrl->remove(0); const char* value = getHeaderValue(0, SIP_REFERRED_BY_FIELD); if(value) { // The first element is the referrer URL if(referrerUrl) UtlNameValueTokenizer::getSubField(value, 0, ";", referrerUrl); // The second element is the referred to URL if(referredToUrl) UtlNameValueTokenizer::getSubField(value, 1, ";", referredToUrl); } return(value != NULL); } UtlBoolean SipMessage::getReplacesData(UtlString& callId, UtlString& toTag, UtlString& fromTag) const { const char* replacesField = getHeaderValue(0, SIP_REPLACES_FIELD); UtlString parameter; UtlString name; UtlString value(""); int parameterIndex = 1; if (replacesField) { // Get the callId UtlNameValueTokenizer::getSubField(replacesField, 0, ";", &callId); callId.strip(UtlString::both); // Look through the rest of the parameters do { // Get a name value pair UtlNameValueTokenizer::getSubField(replacesField, parameterIndex, ";", ¶meter); // Parse out the parameter name UtlNameValueTokenizer::getSubField(parameter.data(), 0, "=", &name); name.toLower(); name.strip(UtlString::both); // Parse out the parameter value UtlNameValueTokenizer::getSubField(parameter.data(), 1, "=", &value); value.strip(UtlString::both); // Set the to and from tags when we find them if(name.compareTo("to-tag") == 0) { toTag = value; } else if(name.compareTo("from-tag") == 0) { fromTag = value; } parameterIndex++; } while(!parameter.isNull()); } return (replacesField != NULL) ; } void SipMessage::setAllowField(const char* allowField) { setHeaderValue(SIP_ALLOW_FIELD, allowField); } UtlBoolean SipMessage::getAllowField(UtlString& allowField) const { const char* value; int allowIndex = 0; allowField.remove(0); while ((value = getHeaderValue(allowIndex, SIP_ALLOW_FIELD))) { if(value && *value) { if(!allowField.isNull()) allowField.append(", "); allowField.append(value); } allowIndex++; } return(value != NULL); } ///// RFC 3326 /// void SipMessage::setReasonField(const char* reasonField) { if(NULL != reasonField) { setHeaderValue(SIP_REASON_FIELD, reasonField); } } UtlBoolean SipMessage::getReasonField(UtlString& reasonField) const { const char* value; reasonField.remove(0); value = getHeaderValue(0, SIP_REASON_FIELD); if(value && *value) { reasonField.append(value); reasonField.strip(UtlString::both); } return(value != NULL); } //////////////////////////////// // for Diversion-header void SipMessage::addDiversionField(const char* addr, const char* reasonParam, UtlBoolean afterOtherDiversions) { if (NULL == addr || NULL == reasonParam) { return; } char diversionString[255]; sprintf(diversionString,"%s;reason=%s",addr,reasonParam); addDiversionField(diversionString,afterOtherDiversions); } void SipMessage::addDiversionField(const char* diversionField, UtlBoolean afterOtherDiversions) { if(NULL != diversionField) { mHeaderCacheClean = FALSE; NameValuePair* nv = new NameValuePair(SIP_DIVERSION_FIELD, diversionField); // Look for other diversion fields size_t fieldIndex = mNameValues.index(nv); # ifdef TEST_PRINT if(fieldIndex == UTL_NOT_FOUND) { UtlDListIterator iterator(nameValues); // remove whole line NameValuePair* nv = NULL; while(nv = (NameValuePair*) iterator()) { osPrintf("\tName: %s\n", nv->data()); } } # endif mHeaderCacheClean = FALSE; if(fieldIndex == UTL_NOT_FOUND || afterOtherDiversions) { mNameValues.insert(nv); } else { mNameValues.insertAt(fieldIndex, nv); } } } UtlBoolean SipMessage::getLastDiversionField(UtlString& diversionField, int& lastIndex) { int index = 0; UtlString tempDiversion; while(getFieldSubfield(SIP_DIVERSION_FIELD, index, &tempDiversion)) { index++; diversionField = tempDiversion; } index--; lastIndex = index; return(!diversionField.isNull()); } UtlBoolean SipMessage::getDiversionField(int index, UtlString& diversionField) { diversionField.remove(0); return getFieldSubfield(SIP_DIVERSION_FIELD,index,&diversionField); } UtlBoolean SipMessage::getDiversionField(int index, UtlString& addr, UtlString& reasonParam) { UtlString divString; addr.remove(0); reasonParam.remove(0); if (getFieldSubfield(SIP_DIVERSION_FIELD,index,&divString)) { // Parse addr int parameterIndex = divString.index(";"); if(parameterIndex > 0) { addr.append(divString); addr.remove(parameterIndex); addr.strip(UtlString::both); // Parse reason int reasonIndex = divString.index("reason=", 0, UtlString::ignoreCase); if(reasonIndex > parameterIndex) { reasonParam.append(&((divString.data())[reasonIndex + 7])); int endIndex = reasonParam.length()-1; int semicolonIndex = reasonParam.index(";"); if (endIndex > semicolonIndex && semicolonIndex > 0) { endIndex = semicolonIndex; reasonParam.remove(endIndex); reasonParam.strip(UtlString::both); } } } else if(parameterIndex) { addr.append(divString); addr.strip(UtlString::both); } else { return FALSE; } return TRUE; } return(FALSE); } /* ============================ INQUIRY =================================== */ UtlBoolean SipMessage::isResponse() const { UtlBoolean responseType = FALSE; //UtlString firstHeaderField; //getFirstHeaderLinePart(0, &firstHeaderField); if(mFirstHeaderLine.index(SIP_PROTOCOL_VERSION) == 0) { responseType = TRUE; } return(responseType); } UtlBoolean SipMessage::isServerTransaction(UtlBoolean isOutgoing) const { UtlBoolean returnCode; if(isResponse()) { if(isOutgoing) { returnCode = TRUE; } else { returnCode = FALSE; } } else { if(isOutgoing) { returnCode = FALSE; } else { returnCode = TRUE; } } return(returnCode); } UtlBoolean SipMessage::isSameMessage(const SipMessage* message, UtlBoolean responseCodesMustMatch) const { UtlBoolean isSame = FALSE; UtlString thisMethod, thatMethod; int thisSequenceNum, thatSequenceNum; UtlString thisSequenceMethod, thatSequenceMethod; if(message) { // Compare the method, To, From, CallId, Sequence number and // sequence method UtlBoolean thatIsResponse = message->isResponse(); UtlBoolean thisIsResponse = isResponse(); int thisResponseCode = 38743; int thatResponseCode = 49276; // Both are responses or requests if(thatIsResponse == thisIsResponse) { if(!thisIsResponse) { getRequestMethod(&thisMethod); message->getRequestMethod(&thatMethod); } else { thisResponseCode = getResponseStatusCode(); thatResponseCode = message->getResponseStatusCode(); } if( (thisIsResponse && !responseCodesMustMatch) || (thisIsResponse && responseCodesMustMatch && thisResponseCode == thatResponseCode) || (!thisIsResponse && thisMethod.compareTo(thatMethod) == 0)) { if(isSameSession(message)) { getCSeqField(&thisSequenceNum, &thisSequenceMethod); message->getCSeqField(&thatSequenceNum, &thatSequenceMethod); if(thisSequenceNum == thatSequenceNum && thisSequenceMethod.compareTo(thatSequenceMethod) == 0) { isSame = TRUE; } } } } } return(isSame); } UtlBoolean SipMessage::isSameSession(const SipMessage* message) const { UtlBoolean isSame = FALSE; UtlBoolean isSameFrom = FALSE; UtlString thisTo, thatTo; UtlString thisFrom, thatFrom; UtlString thisCallId, thatCallId; // Messages from the same session have the same To, From and CallId if(message) { getCallIdField(&thisCallId); message->getCallIdField(&thatCallId); if(thisCallId.compareTo(thatCallId) == 0) { getFromField(&thisFrom); message->getFromField(&thatFrom); if(thisFrom.compareTo(thatFrom) == 0) { isSameFrom = TRUE; } else { UtlString thisAddress; UtlString thatAddress; int thisPort; int thatPort; UtlString thisProtocol; UtlString thatProtocol; UtlString thisUser; UtlString thatUser; UtlString thisUserLabel; UtlString thatUserLabel; UtlString thisTag; UtlString thatTag; getFromAddress(&thisAddress, &thisPort, &thisProtocol, &thisUser, &thisUserLabel, &thisTag); message->getFromAddress(&thatAddress, &thatPort, &thatProtocol, &thatUser, &thatUserLabel, &thatTag); if (thisAddress.compareTo(thatAddress) == 0 && (thisPort == thatPort || (thisPort == PORT_NONE && thatPort == SIP_PORT) || (thisPort == SIP_PORT && thatPort == PORT_NONE)) && thisProtocol.compareTo(thatProtocol) == 0 && thisUser.compareTo(thatUser) == 0 && (thisTag.compareTo(thatTag, UtlString::ignoreCase) == 0 || (thisTag.isNull() && !isResponse()) || (thatTag.isNull() && !message->isResponse()))) { isSameFrom = TRUE; } else { #ifdef TEST_PRINT osPrintf("ERROR: From field did not match: \nAddr: (%s!=%s)\nPort: %d!=%d\nUser: (%s!=%s)\nTag: (%s!=%s)\n", thisAddress.data(), thatAddress.data(), thisPort, thatPort, thisUser.data(), thatUser.data(), thisTag.data(), thatTag.data()); #endif } } getToField(&thisTo); message->getToField(&thatTo); if(isSameFrom && thisTo.compareTo(thatTo ) == 0) { isSame = TRUE; } // Check for tag else if(isSameFrom) { UtlString thisAddress; UtlString thatAddress; int thisPort; int thatPort; UtlString thisProtocol; UtlString thatProtocol; UtlString thisUser; UtlString thatUser; UtlString thisUserLabel; UtlString thatUserLabel; UtlString thisTag; UtlString thatTag; getToAddress(&thisAddress, &thisPort, &thisProtocol, &thisUser, &thisUserLabel, &thisTag); message->getToAddress(&thatAddress, &thatPort, &thatProtocol, &thatUser, &thatUserLabel, &thatTag); // Everything must match with the exception that the // request may not have the tag set. if (thisAddress.compareTo(thatAddress) == 0 && (thisPort == thatPort || (thisPort == PORT_NONE && thatPort == SIP_PORT) || (thisPort == SIP_PORT && thatPort == PORT_NONE)) && thisProtocol.compareTo(thatProtocol) == 0 && thisUser.compareTo(thatUser) == 0 && (thisTag.compareTo(thatTag , UtlString::ignoreCase) == 0 || (thisTag.isNull() && !isResponse()) || (thatTag.isNull() && !message->isResponse()))) { isSame = TRUE; } else { #ifdef TEST_PRINT osPrintf("ERROR: To field did not match:\n: (%s!=%s)\nPort: %d!=%d\nUser: (%s!=%s)\nTag: (%s!=%s)\n", thisAddress.data(), thatAddress.data(), thisPort, thatPort, thisUser.data(), thatUser.data(), thisTag.data(), thatTag.data()); #endif } } } } return(isSame); } UtlBoolean SipMessage::isSameSession(Url& oldUrl, Url& newUrl) { UtlBoolean isSame = FALSE; UtlString thisAddress; UtlString thatAddress; int thisPort; int thatPort; UtlString thisProtocol; UtlString thatProtocol; UtlString thisUser; UtlString thatUser; UtlString thisTag; UtlString thatTag; oldUrl.getHostAddress(thisAddress); newUrl.getHostAddress(thatAddress); thisPort = oldUrl.getHostPort(); thatPort = newUrl.getHostPort(); oldUrl.getUserId(thisUser); newUrl.getUserId(thatUser); oldUrl.getUrlParameter("transport", thisProtocol); newUrl.getUrlParameter("transport", thatProtocol); oldUrl.getFieldParameter("tag", thisTag); newUrl.getFieldParameter("tag", thatTag); if(thisAddress.compareTo(thatAddress) == 0 && (thisPort == thatPort || (thisPort == 0 && thatPort == SIP_PORT) || (thisPort == SIP_PORT && thatPort == 0)) && thisProtocol.compareTo(thatProtocol) == 0 && thisUser.compareTo(thatUser) == 0 && (thisTag.compareTo(thatTag , UtlString::ignoreCase) == 0 || thisTag.isNull())) // Allow the old tag to be NULL // We do not allow only the new tag to be NULL as // this will cause some false matches. Both may be NULL.*/ { isSame = TRUE; } else { #ifdef TEST_PRINT osPrintf("SipMessage::isSameSession Url did not match: \nAddr: (%s!=%s)\nPort: %d!=%d\nUser: (%s!=%s)\nTag: (%s!=%s)\n", thisAddress.data(), thatAddress.data(), thisPort, thatPort, thisUser.data(), thatUser.data(), thisTag.data(), thatTag.data()); #endif } return(isSame); } UtlBoolean SipMessage::isResponseTo(const SipMessage* request) const { UtlBoolean isPair = FALSE; UtlString thisMethod, thatMethod; int thisSequenceNum, thatSequenceNum; UtlString thisSequenceMethod, thatSequenceMethod; // If this is a response and request is a request if(request && !request->isResponse() && isResponse()) { // Compare the To, From, CallId, Sequence number and // sequence method if(isSameSession(request)) { getCSeqField(&thisSequenceNum, &thisSequenceMethod); request->getCSeqField(&thatSequenceNum, &thatSequenceMethod); if(thisSequenceNum == thatSequenceNum && thisSequenceMethod.compareTo(thatSequenceMethod) == 0) { isPair = TRUE; } } } return(isPair); } UtlBoolean SipMessage::isAckFor(const SipMessage* inviteResponse) const { UtlBoolean isPair = FALSE; UtlString thisMethod; int thisSequenceNum, thatSequenceNum; UtlString thisSequenceMethod, thatSequenceMethod; // If this is an ACK request and that is an INVITE response if(inviteResponse && inviteResponse->isResponse() && !isResponse()) { getRequestMethod(&thisMethod); // Compare the To, From, CallId, Sequence number and sequence method if(thisMethod.compareTo(SIP_ACK_METHOD) == 0 && isSameSession(inviteResponse)) { getCSeqField(&thisSequenceNum, &thisSequenceMethod); inviteResponse->getCSeqField(&thatSequenceNum, &thatSequenceMethod); if(thisSequenceNum == thatSequenceNum && thatSequenceMethod.compareTo(SIP_INVITE_METHOD) == 0) { isPair = TRUE; } } } return(isPair); } //SDUA UtlBoolean SipMessage::isInviteFor(const SipMessage* cancelRequest) const { UtlBoolean isPair = FALSE; UtlString thisMethod; // If this is an CANCEL request and that is an INVITE response if(cancelRequest && !isResponse()) { getRequestMethod(&thisMethod); // Compare the To, From, CallId, Sequence number and sequence method if(thisMethod.compareTo( SIP_INVITE_METHOD) == 0 && isSameTransaction(cancelRequest)) isPair = TRUE; } return(isPair); } UtlBoolean SipMessage::isSameTransaction(const SipMessage* message) const { // Compare the To, From, CallId, Sequence number and sequence method UtlBoolean isPair = FALSE; int thisSequenceNum, thatSequenceNum; UtlString thisSequenceMethod, thatSequenceMethod; if( isSameSession(message)) { getCSeqField(&thisSequenceNum, &thisSequenceMethod); message->getCSeqField(&thatSequenceNum, &thatSequenceMethod); if(thisSequenceNum == thatSequenceNum ) { isPair = TRUE; } } return(isPair); } UtlBoolean SipMessage::isRequestDispositionSet(const char* dispositionToken) const { UtlString field; int tokenIndex = 0; UtlBoolean matchFound = FALSE; while(getRequestDisposition(tokenIndex, &field)) { field.toUpper(); if(field.compareTo(dispositionToken) == 0) { matchFound = TRUE; break; } } return(matchFound); } UtlBoolean SipMessage::isRequireExtensionSet(const char* extension) const { UtlString extensionString; UtlBoolean alreadySet = FALSE; int extensionIndex = 0; while(getRequireExtension(extensionIndex, &extensionString)) { extensionString.toLower(); if(extensionString.compareTo(extension) == 0) { alreadySet = TRUE; } } return(alreadySet); } UtlBoolean SipMessage::isUrlHeaderAllowed(const char* headerFieldName) { UtlString name(headerFieldName); name.toUpper(); return (!sSipMessageFieldProps.mDisallowedUrlHeaders.contains(&name)); } UtlBoolean SipMessage::isUrlHeaderUnique(const char* headerFieldName) { UtlString name(headerFieldName); name.toUpper(); return (sSipMessageFieldProps.mUniqueUrlHeaders.contains(&name)); } //SDUA UtlBoolean SipMessage::getDNSField( UtlString * Protocol , UtlString * Address, UtlString * Port) const { //protocol can be empty by default if( !m_dnsAddress.isNull() && !m_dnsPort.isNull()) { Protocol->remove(0); Address->remove(0); Port->remove(0); Protocol->append(m_dnsProtocol); Address->append(m_dnsAddress); Port->append(m_dnsPort); return (true); } else { return (false); } } void SipMessage::setDNSField( const char* Protocol , const char* Address, const char* Port) { m_dnsProtocol.remove(0); m_dnsAddress.remove(0); m_dnsPort.remove(0); m_dnsProtocol.append(Protocol); m_dnsAddress.append(Address); m_dnsPort.append(Port); } void SipMessage::clearDNSField() { m_dnsProtocol.remove(0); m_dnsAddress.remove(0); m_dnsPort.remove(0); } void SipMessage::setTransaction(SipTransaction* transaction) { mpSipTransaction = transaction; } SipTransaction* SipMessage::getSipTransaction() const { return(mpSipTransaction); } const UtlString SipMessage::getTransportName(bool& bCustom) const { UtlString transport; UtlString toField; getToField(&toField); Url toUrl(toField); UtlString topRoute ; getRouteUri(0, &topRoute) ; Url route(topRoute) ; route.getUrlParameter("transport", transport); if (transport.isNull()) { toUrl.getUrlParameter("transport", transport); if (transport.isNull()) { bCustom = false; } } if ("UDP" == transport || "TCP" == transport || "TLS" == transport) { bCustom = false; } else { bCustom = true; } return transport; } void SipMessage::ParseContactFields(const SipMessage *registerResponse, const SipMessage *SipRequest, const UtlString &subField, int& subFieldRetVal) { //get the request contact value ...so that we can find out the expires subfield value // for this contact from the list of contacts returned byt the Rgister server UtlString RequestContactValue; SipRequest->getContactEntry(0 , &RequestContactValue); UtlString contactField; int indexContactField = 0; while (registerResponse->getContactEntry(indexContactField , &contactField)) { if ( strstr(contactField, RequestContactValue ) != NULL) { UtlString subfieldText; int subfieldIndex = 0; UtlString subfieldName; UtlString subfieldValue; UtlNameValueTokenizer::getSubField(contactField.data(), subfieldIndex, ";", &subfieldText); while(!subfieldText.isNull()) { UtlNameValueTokenizer::getSubField(subfieldText.data(), 0, "=", &subfieldName); UtlNameValueTokenizer::getSubField(subfieldText.data(), 1, "=", &subfieldValue); # ifdef TEST_PRINT osPrintf("ipMessage::ParseContactFields found contact parameter[%d]: \"%s\" value: \"%s\"\n", subfieldIndex, subfieldName.data(), subfieldValue.data()); # endif subfieldName.toUpper(); if(subfieldName.compareTo(subField, UtlString::ignoreCase) == 0 && subField.compareTo(SIP_EXPIRES_FIELD, UtlString::ignoreCase)== 0) { //see if more than one token in the expire value UtlNameValueTokenizer::getSubField(subfieldValue, 1, " \t:;,", &subfieldText); // if not ...time is in seconds if(subfieldText.isNull()) { subFieldRetVal = atoi(subfieldValue); } // If there is more than one token assume it is a text date else { // Get the expiration date long dateExpires = OsDateTime::convertHttpDateToEpoch(subfieldValue); long dateSent = 0; // If the date was not set in the message if(!registerResponse->getDateField(&dateSent)) { #ifdef TEST_PRINT osPrintf("Date field not set\n"); #endif // Assume date sent is now dateSent = OsDateTime::getSecsSinceEpoch(); } #ifdef TEST_PRINT osPrintf("Contact expires date: %ld\n", dateExpires); osPrintf("Current time: %ld\n", dateSent); #endif subFieldRetVal = dateExpires - dateSent; } break; }//any other field else if(subfieldName.compareTo(subField, UtlString::ignoreCase) == 0) { subFieldRetVal = atoi(subfieldValue); } subfieldIndex++; UtlNameValueTokenizer::getSubField(contactField.data(), subfieldIndex, ";", &subfieldText); } } indexContactField ++; } return ; } const UtlString& SipMessage::getLocalIp() const { return mLocalIp; } void SipMessage::setLocalIp(const UtlString& localIp) { mLocalIp = localIp; } void SipMessage::setTransportInfo(const SipMessage* pMsg) { assert(pMsg != NULL) ; if (pMsg) { setLocalIp(pMsg->getLocalIp()) ; } } /// Get the name/value pairs for a Via field /// /// void SipMessage::parseViaParameters( const char* viaField ,UtlContainer& viaParamList ) { const char* pairSeparator = ";"; const char* namValueSeparator = "="; const char* nameAndValuePtr; int nameAndValueLength; const char* namePtr; int nameLength; int nameValueIndex = 0; UtlString value; int lastCharIndex = 0; int relativeIndex; int nameValueRelativeIndex; int viaFieldLength = strlen(viaField); do { # ifdef TEST_PRINT osPrintf("SipMessage::parseViaParameters: \"%s\" lastCharIndex: %d", &(viaField[lastCharIndex]), lastCharIndex); # endif // Pull out a name value pair UtlNameValueTokenizer::getSubField(&(viaField[lastCharIndex]), viaFieldLength - lastCharIndex, 0, pairSeparator, nameAndValuePtr, nameAndValueLength, &relativeIndex); lastCharIndex += relativeIndex; if(nameAndValuePtr && nameAndValueLength > 0) { // Separate the name and value UtlNameValueTokenizer::getSubField(nameAndValuePtr, nameAndValueLength, 0, namValueSeparator, namePtr, nameLength, &nameValueRelativeIndex); // Get rid of leading white space in the name while(nameLength > 0 && (*namePtr == ' ' || *namePtr == '\t')) { nameLength--; namePtr++; } if(nameLength > 0) { int valueSeparatorOffset = strspn(&(namePtr[nameLength]), namValueSeparator); const char* valuePtr = &(namePtr[nameLength]) + valueSeparatorOffset; int valueLength = nameAndValueLength - (valuePtr - nameAndValuePtr); // If there is a value if(valueSeparatorOffset <= 0 || *valuePtr == '\0' || valueLength <= 0) { valuePtr = NULL; valueLength = 0; } NameValuePair* newNvPair = new NameValuePair(""); newNvPair->append(namePtr, nameLength); if(valuePtr) { value.remove(0); value.append(valuePtr, valueLength); value.strip(UtlString::both); newNvPair->setValue(value); } else { newNvPair->setValue(""); } newNvPair->strip(UtlString::both); // Add a name, value pair to the list viaParamList.insert(newNvPair); nameValueIndex++; } } } while( nameAndValuePtr && nameAndValueLength > 0 && viaField[lastCharIndex] != '\0' ); } void SipMessage::setSipIfMatchField(const char* sipIfMatchField) { setHeaderValue(SIP_IF_MATCH_FIELD, sipIfMatchField, 0); } UtlBoolean SipMessage::getSipIfMatchField(UtlString& sipIfMatchField) const { const char* fieldValue = getHeaderValue(0, SIP_IF_MATCH_FIELD); sipIfMatchField.remove(0); if(fieldValue) sipIfMatchField.append(fieldValue); return(fieldValue != NULL); } void SipMessage::setSipETagField(const char* sipETagField) { setHeaderValue(SIP_ETAG_FIELD, sipETagField, 0); } UtlBoolean SipMessage::getSipETagField(UtlString& sipETagField) const { const char* fieldValue = getHeaderValue(0, SIP_ETAG_FIELD); sipETagField.remove(0); if(fieldValue) sipETagField.append(fieldValue); return(fieldValue != NULL); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ SipMessage::SipMessageFieldProps::SipMessageFieldProps() { // Call the initializer functions. initNames(); initDisallowedUrlHeaders(); initUniqueUrlHeaders(); } SipMessage::SipMessageFieldProps::~SipMessageFieldProps() { mLongFieldNames.destroyAll(); mShortFieldNames.destroyAll(); mDisallowedUrlHeaders.destroyAll(); mUniqueUrlHeaders.destroyAll(); } void SipMessage::SipMessageFieldProps::initNames() { // Load the table to translate long header names to short names. mLongFieldNames.insert(new NameValuePair(SIP_CONTENT_TYPE_FIELD, SIP_SHORT_CONTENT_TYPE_FIELD)); mLongFieldNames.insert(new NameValuePair(SIP_CONTENT_ENCODING_FIELD, SIP_SHORT_CONTENT_ENCODING_FIELD)); mLongFieldNames.insert(new NameValuePair(SIP_FROM_FIELD, SIP_SHORT_FROM_FIELD)); mLongFieldNames.insert(new NameValuePair(SIP_CALLID_FIELD, SIP_SHORT_CALLID_FIELD)); mLongFieldNames.insert(new NameValuePair(SIP_CONTACT_FIELD, SIP_SHORT_CONTACT_FIELD)); mLongFieldNames.insert(new NameValuePair(SIP_CONTENT_LENGTH_FIELD, SIP_SHORT_CONTENT_LENGTH_FIELD)); mLongFieldNames.insert(new NameValuePair(SIP_REFERRED_BY_FIELD, SIP_SHORT_REFERRED_BY_FIELD)); mLongFieldNames.insert(new NameValuePair(SIP_REFER_TO_FIELD, SIP_SHORT_REFER_TO_FIELD)); mLongFieldNames.insert(new NameValuePair(SIP_SUBJECT_FIELD, SIP_SHORT_SUBJECT_FIELD)); mLongFieldNames.insert(new NameValuePair(SIP_SUPPORTED_FIELD, SIP_SHORT_SUPPORTED_FIELD)); mLongFieldNames.insert(new NameValuePair(SIP_TO_FIELD, SIP_SHORT_TO_FIELD)); mLongFieldNames.insert(new NameValuePair(SIP_VIA_FIELD, SIP_SHORT_VIA_FIELD)); mLongFieldNames.insert(new NameValuePair(SIP_EVENT_FIELD, SIP_SHORT_EVENT_FIELD)); // Reverse the pairs to load the table to translate short header names to // long ones. UtlHashBagIterator iterator(mLongFieldNames); NameValuePair* nvPair; while ((nvPair = (NameValuePair*) iterator())) { mShortFieldNames.insert(new NameValuePair(nvPair->getValue(), nvPair->data())); } } void SipMessage::SipMessageFieldProps::initDisallowedUrlHeaders() { // These headers may NOT be passed through in a URL to // be set in a message mDisallowedUrlHeaders.insert(new UtlString(SIP_CONTACT_FIELD)); mDisallowedUrlHeaders.insert(new UtlString(SIP_SHORT_CONTACT_FIELD)); mDisallowedUrlHeaders.insert(new UtlString(SIP_CONTENT_LENGTH_FIELD)); mDisallowedUrlHeaders.insert(new UtlString(SIP_SHORT_CONTENT_LENGTH_FIELD)); mDisallowedUrlHeaders.insert(new UtlString(SIP_CONTENT_TYPE_FIELD)); mDisallowedUrlHeaders.insert(new UtlString(SIP_SHORT_CONTENT_TYPE_FIELD)); mDisallowedUrlHeaders.insert(new UtlString(SIP_CONTENT_ENCODING_FIELD)); mDisallowedUrlHeaders.insert(new UtlString(SIP_SHORT_CONTENT_ENCODING_FIELD)); mDisallowedUrlHeaders.insert(new UtlString(SIP_CSEQ_FIELD)); mDisallowedUrlHeaders.insert(new UtlString(SIP_RECORD_ROUTE_FIELD)); mDisallowedUrlHeaders.insert(new UtlString(SIP_REFER_TO_FIELD)); mDisallowedUrlHeaders.insert(new UtlString(SIP_REFERRED_BY_FIELD)); mDisallowedUrlHeaders.insert(new UtlString(SIP_TO_FIELD)); mDisallowedUrlHeaders.insert(new UtlString(SIP_SHORT_TO_FIELD)); mDisallowedUrlHeaders.insert(new UtlString(SIP_USER_AGENT_FIELD)); mDisallowedUrlHeaders.insert(new UtlString(SIP_VIA_FIELD)); mDisallowedUrlHeaders.insert(new UtlString(SIP_SHORT_VIA_FIELD)); } void SipMessage::SipMessageFieldProps::initUniqueUrlHeaders() { // These headers may occur only once in a message, so a URI header // parameter overrides the existing header in the message. mUniqueUrlHeaders.insert(new UtlString(SIP_EXPIRES_FIELD)); mUniqueUrlHeaders.insert(new UtlString(SIP_ROUTE_FIELD)); } bool SipMessage::smimeEncryptSdp(const void *pEventData) { if (pEventData) { mpEventData = (void*)pEventData; } const HttpBody* pOriginalBody = NULL; bool bRet = false; if (mpSecurity && getSdpBody(mpSecurity) != NULL) { UtlString bodyBytes; int bodyLength; pOriginalBody = getBody() ; if (pOriginalBody) { pOriginalBody->getBytes(&bodyBytes, &bodyLength); SdpBody* pSdpBodyCopy = new SdpBody(bodyBytes, bodyLength); // this should be destroyed by // the smime destructor, // so, we wont destroy it here SIPXTACK_SECURITY_ATTRIBUTES* pSecurityAttrib = (SIPXTACK_SECURITY_ATTRIBUTES*)mpSecurity; if (pSdpBodyCopy && pSecurityAttrib->getSecurityLevel() > 0) { SmimeBody* newlyEncryptedBody = new SmimeBody(NULL, 0, NULL); UtlString der(pSecurityAttrib->getSmimeKey(), pSecurityAttrib->getSmimeKeyLength()); const char* derPublicKeyCert[1]; int certLength[1]; derPublicKeyCert[0] = der.data(); certLength[0] = der.length(); if (newlyEncryptedBody->encrypt(pSdpBodyCopy, 1, derPublicKeyCert, certLength, mpSecurity->szMyCertNickname, mpSecurity->szCertDbPassword, this) ) { setBody(newlyEncryptedBody); setContentType(CONTENT_SMIME_PKCS7); setContentLength(newlyEncryptedBody->getLength()); bRet = true; } } } } else { OnError(SECURITY_ENCRYPT, SECURITY_CAUSE_ENCRYPT_FAILURE_INVALID_PARAMETER); } return bRet; } bool SipMessage::fireSecurityEvent(const void* pEventData, const enum SIPX_SECURITY_EVENT event, const enum SIPX_SECURITY_CAUSE cause, SIPXTACK_SECURITY_ATTRIBUTES* const pSecurity, void* pCert, char* szSubjectAltName) const { SIPX_SECURITY_INFO info; memset(&info, 0, sizeof(SIPX_SECURITY_INFO)); info.nSize = sizeof(SIPX_SECURITY_INFO); info.event = event; info.cause = cause; UtlString callId; getCallIdField(&callId); if (pSecurity) { info.nCertificateSize = pSecurity->getSmimeKeyLength(); info.callId = (char*)callId.data(); // determine if the remoteAddress is the ToField or the FromField Url urlIdentity; UtlString identity; if (mbFromThisSide && !isResponse()) { if (!isResponse()) { getToUrl(urlIdentity); } else { getFromUrl(urlIdentity); } } else { if (!isResponse()) { getFromUrl(urlIdentity); } else { getToUrl(urlIdentity); } } identity = urlIdentity.toString(); if (pCert) { info.pCertificate = pCert; info.szSubjAltName = szSubjectAltName; } else { info.pCertificate = (void*)pSecurity->getSmimeKey(); } info.remoteAddress = (char*)identity.data(); info.szSRTPkey = (char*)pSecurity->getSrtpKey(); } return TapiMgr::getInstance().fireEvent(pEventData ? pEventData : mpEventData, EVENT_CATEGORY_SECURITY, &info); } void SipMessage::OnError(SIPX_SECURITY_EVENT event, SIPX_SECURITY_CAUSE cause) { fireSecurityEvent(mpEventData, event, cause, mpSecurity); } bool SipMessage::OnSignature(void* pCert, char* szSubjAltName) { return fireSecurityEvent(mpEventData, SECURITY_DECRYPT, SECURITY_CAUSE_SIGNATURE_NOTIFY, mpSecurity, pCert, szSubjAltName); } void SipMessage::normalizeProxyRoutes(const SipUserAgent* sipUA, Url& requestUri, UtlSList* removedRoutes ) { UtlString requestUriString; Url topRouteUrl; UtlString topRouteValue; /* * Check the request URI and the topmost route * - Detect and correct for any strict router upstream * as specified by RFC 3261 section 16.4 Route Information Preprocessing: * * The proxy MUST inspect the Request-URI of the request. If the * Request-URI of the request contains a value this proxy previously * placed into a Record-Route header field (see Section 16.6 item 4), * the proxy MUST replace the Request-URI in the request with the last * value from the Route header field, and remove that value from the * Route header field. The proxy MUST then proceed as if it received * this modified request. * * - Pop off the topmost route until it is not me * * Note that this loop always executes at least once, and that: * - it leaves requestUri set correctly */ bool doneNormalizingRouteSet = false; while (! doneNormalizingRouteSet) { // Check the request URI. // If it has 'lr' parameter that is me, then the sender was a // strict router (it didn't recognize the loose route indication) getRequestUri(&requestUriString); requestUri.fromString(requestUriString, TRUE /* is a request uri */); UtlString noValue; if ( requestUri.getUrlParameter("lr", noValue, 0) && sipUA->isMyHostAlias(requestUri) ) { /* * We need to fix it (convert it back to a loose route).. * - pop the last route and put it in the request URI * see RFC 3261 section 16.4 * * For example: * INVITE sip:mydomain.com;lr SIP/2.0 * Route: , * becomes: * INVITE sip:user@elsewhere.example.com SIP/2.0 * Route: */ UtlString lastRouteValue; int lastRouteIndex; if ( getLastRouteUri(lastRouteValue, lastRouteIndex) ) { removeRouteUri(lastRouteIndex, &lastRouteValue); // Put the last route in as the request URI changeUri(lastRouteValue); // this strips appropriately OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipMessage::normalizeProxyRoutes " "strict route '%s' replaced with uri from '%s'", requestUriString.data(), lastRouteValue.data()); if (removedRoutes) { // save a copy of the route we're removing for the caller. // this looks just like this was properly loose routed. // use the output from Url::toString so that all are normalized. UtlString* removedRoute = new UtlString; requestUri.toString(*removedRoute); removedRoutes->append(removedRoute); // caller is responsible for deleting the savedRoute } } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipMessage::normalizeProxyRoutes " "found 'lr' in Request-URI with no Route; stripped 'lr'" ); requestUri.removeUrlParameter("lr"); UtlString newUri; requestUri.toString(newUri); changeRequestUri(newUri); // this strips appropriately } // note: we've changed the request uri and the route set, // but not set doneNormalizingRouteSet, so we go around again... } else // topmost route was not a loose route uri we put there... { if ( getRouteUri(0, &topRouteValue) ) { /* * There is a Route header... if it is a route to this proxy, pop it off. * For example: * INVITE sip:user@elsewhere.example.com SIP/2.0 * Route: , * becomes: * INVITE sip:user@elsewhere.example.com SIP/2.0 * Route: */ topRouteUrl.fromString(topRouteValue,FALSE /* not a request uri */); if ( sipUA->isMyHostAlias(topRouteUrl) ) { if (removedRoutes) { // save a copy of the route we're removing for the caller. // use the output from Url::toString so that all are normalized. UtlString* savedRoute = new UtlString(); topRouteUrl.toString(*savedRoute); removedRoutes->append(savedRoute); // caller is responsible for deleting the savedRoute } UtlString removedRoute; removeRouteUri(0, &removedRoute); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipMessage::normalizeProxyRoutes popped route to self '%s'", removedRoute.data() ); } else // topmost route is someone else { doneNormalizingRouteSet = true; } } else // no more routes { doneNormalizingRouteSet = true; } } } // while ! doneNormalizingRouteSet } sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipMessageEvent.cpp0000644000175000017500000000474512205613256024752 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipMessageEvent::SipMessageEvent(SipMessage* message, int status) : OsMsg(OsMsg::PHONE_APP, SipMessage::NET_SIP_MESSAGE) { messageStatus = status; sipMessage = message; } // Destructor SipMessageEvent::~SipMessageEvent() { if(sipMessage) { delete sipMessage; sipMessage = NULL; } } OsMsg* SipMessageEvent::createCopy() const { // Ineffient but easy coding way to copy message SipMessage* sipMsg = NULL; if(sipMessage) { sipMsg = new SipMessage(*sipMessage); } return(new SipMessageEvent(sipMsg, messageStatus)); } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipMessageEvent& SipMessageEvent::operator=(const SipMessageEvent& rhs) { if (this == &rhs) // handle the assignment to self case return *this; OsMsg::operator=(rhs); messageStatus = rhs.messageStatus; if(sipMessage) { delete sipMessage; sipMessage = NULL; } if(rhs.sipMessage) { sipMessage = new SipMessage(*(rhs.sipMessage)); } return *this; } /* ============================ ACCESSORS ================================= */ const SipMessage* SipMessageEvent::getMessage() { return(sipMessage); } void SipMessageEvent::setMessageStatus(int status) { messageStatus = status; } int SipMessageEvent::getMessageStatus() const { return(messageStatus); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipMessageList.cpp0000644000175000017500000002703612205613256024602 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS //#define TEST_PRINT /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipMessageList::SipMessageList() { } // Copy constructor SipMessageList::SipMessageList(const SipMessageList& rSipMessageList) { } // Destructor SipMessageList::~SipMessageList() { while (SipMessage* pMsg = (SipMessage*) messageList.pop()) { delete pMsg ; } } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipMessageList& SipMessageList::operator=(const SipMessageList& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } /* ============================ ACCESSORS ================================= */ SipMessage* SipMessageList::getResponseFor(SipMessage* request) { int iteratorHandle = messageList.getIteratorHandle(); SipMessage* message; while ((message = (SipMessage*) messageList.next(iteratorHandle))) { if(message->isResponseTo(request)) { break; } } messageList.releaseIteratorHandle(iteratorHandle); return(message); } SipMessage* SipMessageList::getRequestFor(SipMessage* response) { int iteratorHandle = messageList.getIteratorHandle(); SipMessage* message; while ((message = (SipMessage*) messageList.next(iteratorHandle))) { if(response->isResponseTo(message)) { break; } } messageList.releaseIteratorHandle(iteratorHandle); return(message); } SipMessage* SipMessageList::getDuplicate(SipMessage* message, UtlBoolean responseCodesMustMatch) { int iteratorHandle = messageList.getIteratorHandle(); SipMessage* listMessage; while ((listMessage = (SipMessage*) messageList.next(iteratorHandle))) { if(listMessage->isSameMessage(message, responseCodesMustMatch)) { break; } } messageList.releaseIteratorHandle(iteratorHandle); return(listMessage); } SipMessage* SipMessageList::getAckFor(SipMessage* inviteResponse) { int iteratorHandle = messageList.getIteratorHandle(); SipMessage* listMessage; while ((listMessage = (SipMessage*) messageList.next(iteratorHandle))) { if(listMessage->isAckFor(inviteResponse)) { break; } } messageList.releaseIteratorHandle(iteratorHandle); return(listMessage); } //SDUA SipMessage* SipMessageList::getInviteFor(SipMessage* cancelRequest) { int iteratorHandle = messageList.getIteratorHandle(); SipMessage* listMessage; while ((listMessage = (SipMessage*) messageList.next(iteratorHandle))) { if(listMessage->isInviteFor(cancelRequest)) { break; } } messageList.releaseIteratorHandle(iteratorHandle); return(listMessage); } int SipMessageList::getListSize() { return messageList.getCount(); } int SipMessageList::getIterator() { return messageList.getIteratorHandle(); } SipMessage* SipMessageList::getSipMessageForIndex( int iteratorHandle ) { return (SipMessage*) messageList.next(iteratorHandle); } void SipMessageList::releaseIterator(int iteratorHandle) { messageList.releaseIteratorHandle(iteratorHandle); } SipMessage* SipMessageList::isSameFrom( const Url& fromUrl ) { int iteratorHandle = messageList.getIteratorHandle(); SipMessage* listMessage = NULL; // @JC More efficient this was in the main loop int newPort; UtlString newAddress, newProtocol, newUser; SipMessage::parseAddressFromUri( fromUrl.toString(), &newAddress, &newPort, &newProtocol, &newUser); // Iterate through the list of SipMessages, extracting the from field // fields from each of the messages and compare them to the // one passed in, if same returns pointer to match in the list while ((listMessage = (SipMessage*) messageList.next(iteratorHandle))) { UtlString from; listMessage->getFromField(&from); if(!from.isNull()) { int port; UtlString address, protocol, user; SipMessage::parseAddressFromUri( from, &address, &port, &protocol, &user); if ( address.compareTo(newAddress) == 0 && protocol.compareTo(newProtocol) == 0 && user.compareTo(newUser) == 0 && port == newPort) { break; } } } messageList.releaseIteratorHandle( iteratorHandle ); return(listMessage); } SipMessage* SipMessageList::isSameTo( const Url& toUrl ) { int iteratorHandle = messageList.getIteratorHandle(); SipMessage* listMessage = NULL; UtlString newTo = toUrl.toString(); // @JC Moved here from inner loop int newPort; UtlString newAddress, newProtocol, newUser; SipMessage::parseAddressFromUri( newTo, &newAddress, &newPort, &newProtocol, &newUser); // Iterate through the list of SipMessages, extracting the 'to' field // fields from each of the messages and compare them to the // one passed in, if same returns pointer to match in the list while ((listMessage = (SipMessage*) messageList.next(iteratorHandle))) { UtlString to; listMessage->getToField(&to); if(!to.isNull()) { int port; UtlString address, protocol, user; SipMessage::parseAddressFromUri( to, &address , &port, &protocol, &user); if ( address.compareTo(newAddress) == 0 && protocol.compareTo(newProtocol) == 0 && user.compareTo(newUser) == 0 && port == newPort) { break; } } } messageList.releaseIteratorHandle(iteratorHandle); return(listMessage); } SipMessage* SipMessageList::isSameCallId( const UtlString& newCallId ) { int iteratorHandle = messageList.getIteratorHandle(); SipMessage* listMessage = NULL; while ((listMessage = (SipMessage*) messageList.next(iteratorHandle))) { UtlString callId; listMessage->getCallIdField(&callId); if(!callId.isNull()) { if ( newCallId.compareTo(callId) == 0) { break; } } } messageList.releaseIteratorHandle(iteratorHandle); return(listMessage); } UtlBoolean SipMessageList::remove( SipMessage* message ) { int iteratorHandle = messageList.getIteratorHandle(); SipMessage* listMessage; while ((listMessage = (SipMessage*) messageList.next(iteratorHandle))) { #ifdef TEST_PRINT UtlString listMessageStr; int listMessageLen; listMessage->getBytes(&listMessageStr, &listMessageLen); osPrintf("\n-------\nSipMessageList::remove List message %s \n++++++\n",listMessageStr.data()); UtlString MessageStr; int MessageLen; message->getBytes(&MessageStr, &MessageLen); osPrintf("\nSipMessageList::remove parameter Message %s \n-------\n",MessageStr.data()); #endif if(listMessage == message) { #ifdef TEST_PRINT osPrintf("SipMessageList::remove removing message\n"); #endif messageList.remove(iteratorHandle); break; } } messageList.releaseIteratorHandle(iteratorHandle); return(listMessage != NULL); } void SipMessageList::add(SipMessage* message) { messageList.push(message); } void SipMessageList::remove(int iteratorHandle) { messageList.remove(iteratorHandle); } void SipMessageList::removeOldMessages(long oldTime, UtlBoolean deleteMessages) { int iteratorHandle = messageList.getIteratorHandle(); SipMessage* message; // osPrintf("**********************************\n"); // osPrintf("SipMessageList::removeOldMessages\n"); // osPrintf("**********************************\n"); while ((message = (SipMessage*) messageList.next(iteratorHandle))) { if(message->getTransportTime() < oldTime) { #ifdef TEST_PRINT osPrintf("SipMessageList::removeOldMessages removing message dated: %d before: %d\n", message->getTransportTime(), oldTime); #endif messageList.remove(iteratorHandle); if(deleteMessages) { // osPrintf("**********************************\n"); // osPrintf("SipMessageList::removeOldMessages REMOVED: %X\n",message); // osPrintf("**********************************\n"); delete message; message = NULL; } } } messageList.releaseIteratorHandle(iteratorHandle); } void SipMessageList::toString(UtlString& listDumpString) { int iteratorHandle = messageList.getIteratorHandle(); listDumpString.remove(0); SipMessage* listMessage; UtlString listMessageBytes; int msgLen; while ((listMessage = (SipMessage*) messageList.next(iteratorHandle))) { listMessageBytes.remove(0); listMessage->getBytes(&listMessageBytes, &msgLen); listDumpString.append("?????????????????????????????\n"); listDumpString.append(listMessageBytes); } listDumpString.append("End ?????????????????????????????\n"); messageList.releaseIteratorHandle(iteratorHandle); listMessageBytes.remove(0); } #define DBG_TBL_MAX_URI 30 #define DBG_TBL_MAX_FIELD 10 #define DBG_TBL_FORMAT_STR "%-30s %-30s %-10s %-10d %s\n" void SipMessageList::printDebugTable() { SipMessage* pMsg ; int iteratorHandle = messageList.getIteratorHandle(); osPrintf("\nDump of SipMessageList (instance %8p)\n", this) ; osPrintf("To CallId Method CSeq Request\n") ; osPrintf("------------------------------ ------------------------------ ---------- ---------- ----------\n") ; while ((pMsg = (SipMessage*) messageList.next(iteratorHandle))) { UtlString toURI ; UtlString callId ; int iCseq ; UtlString method ; UtlBoolean bIsResponse ; pMsg->getToUri(&toURI) ; pMsg->getCallIdField(&callId) ; pMsg->getCSeqField(&iCseq, &method); bIsResponse = pMsg->isResponse() ; // Shorten fields if necessary if (toURI.length() > DBG_TBL_MAX_URI) toURI.remove(DBG_TBL_MAX_URI) ; if (callId.length() > DBG_TBL_MAX_URI) callId.remove(DBG_TBL_MAX_URI) ; if (method.length() > DBG_TBL_MAX_FIELD) method.remove(DBG_TBL_MAX_FIELD) ; osPrintf(DBG_TBL_FORMAT_STR, toURI.data(), callId.data(), method.data(), iCseq, bIsResponse ? "FALSE" : "TRUE") ; } osPrintf("\n") ; messageList.releaseIteratorHandle(iteratorHandle); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipNonceDb.cpp0000644000175000017500000001575112205613256023673 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include "os/OsLock.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // :TBD: replace this with a cluster-specific secret #define NONCE_SIGNATURE_INNER_SECRET "66287423e9e289fc9d78a3bd04475b06" // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipNonceDb::SipNonceDb() { mNonceSignatureSecret = NONCE_SIGNATURE_INNER_SECRET; // :TBD: append some configuration-specific value here } // Copy constructor SipNonceDb::SipNonceDb(const SipNonceDb& rSipNonceDb) { } // Destructor SipNonceDb::~SipNonceDb() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipNonceDb& SipNonceDb::operator=(const SipNonceDb& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } // ********************************************************** // Sip Nonce construction // // We want our servers to be able to use a common algorithm // to construct the authentication nonce values so that they // can create authenticated requests to each other without // sending an unauthenticated request to get the challenge. // At the same time, it must not be possible for any other party // to produce a valid nonce or predict what any future valid // nonce would be, since that would undermine the security // of Digest authentication. // // We accomplish this by constructing the nonce value as: // := // := (decimal seconds since the epoch) // := H() // := // := NONCE_SIGNATURE_INNER_SECRET // // H(x) is the hexadecimal encoding of MD5(x) // // Using the call parameters incorporates them into the // integrity protection of the authentication response, // while allowing the nonce to be usefull for any request // within the call. // // The timestamp allows us to detect that an unacceptably old // nonce is being used, and ensures that the inputs to the hash // are changed by something not in the control of the requestor. // // NB: The timestamp creates the requirement that all servers // have clocks that are roughly syncronized (the expiration // time is set by the caller requesting validation of a nonce, // at present to 5 minutes) void SipNonceDb::createNewNonce(const UtlString& callId, //input const UtlString& fromTag, // input const UtlString& uri, // :TBD: no longer used const UtlString& realm, // input UtlString& nonce) // output { long now = OsDateTime::getSecsSinceEpoch(); char dateString[20]; UtlString nonceSignature; // create the timestamp, which will be in the clear sprintf(dateString, "%ld", now); nonce = SipNonceDb::nonceSignature(callId,fromTag,uri,realm,dateString); nonce.append(dateString); } void SipNonceDb::removeOldNonces(long oldTime) { } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ UtlBoolean SipNonceDb::isNonceValid(const UtlString& nonce, const UtlString& callId, const UtlString& fromTag, const UtlString& uri, //:TBD: no longer used const UtlString& realm, const long expiredTime) { UtlBoolean valid = FALSE; if (nonce.length() > MD5_SIZE) { UtlString timestamp = nonce(MD5_SIZE,nonce.length()-MD5_SIZE); UtlString rcvdSignature = nonce(0,MD5_SIZE); if (0 == rcvdSignature.compareTo(nonceSignature(callId, fromTag, uri, realm, timestamp))) { // check for expiration int nonceCreated = atoi(timestamp.data()); long now = OsDateTime::getSecsSinceEpoch(); if ( nonceCreated+expiredTime >= now ) { valid = TRUE; } else { OsSysLog::add(FAC_SIP,PRI_INFO, "SipNonceDB::isNonceValid expired nonce: created %d+%ld < %ld" ,nonceCreated, expiredTime, now ); } } else { OsSysLog::add(FAC_SIP,PRI_ERR, "SipNonceDB::isNonceValid nonce signature check failed" ); } } else { OsSysLog::add(FAC_SIP,PRI_ERR, "SipNonceDb::isNonceValid invalid nonce format \"%s\"\n", nonce.data()); } return(valid); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ TESTING =================================== */ /* ============================ FUNCTIONS ================================= */ UtlString SipNonceDb::nonceSignature(const UtlString& callId, const UtlString& fromTag, const UtlString& uri, // :TBD: no longer used const UtlString& realm, const UtlString& timestamp) { UtlString signature; UtlString nonceSigningData(timestamp); OsSysLog::add(FAC_SIP, PRI_DEBUG, "nonceSignature: callId='%s' fromTag='%s' realm='%s' timestamp='%s'", callId.data(), fromTag.data(), realm.data(), timestamp.data() ); // create the signature value by hashing the timestamp with // the callId, fromTag, the realm, and a secret nonceSigningData.append(callId); nonceSigningData.append(fromTag); nonceSigningData.append(mNonceSignatureSecret); nonceSigningData.append(realm); NetMd5Codec::encode(nonceSigningData.data(), signature); return signature; } OsBSem* SharedNonceDb::spLock = new OsBSem(OsBSem::Q_PRIORITY, OsBSem::FULL); SipNonceDb* SharedNonceDb::spSipNonceDb = NULL; SipNonceDb* SharedNonceDb::get() { // critical region to ensure that only one shared ssl context is created OsLock lock(*spLock); if (!spSipNonceDb) { spSipNonceDb = new SipNonceDb(); } return spSipNonceDb; } sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipNotifyStateTask.cpp0000644000175000017500000007157712205613256025467 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie (dpetrie AT SIPez DOT com) // SYSTEM INCLUDES #include #include #include #ifdef __pingtel_on_posix__ #include #endif // APPLICATION INCLUDES #include "net/SipNotifyStateTask.h" #include "net/SipUserAgent.h" #include "net/HttpBody.h" #include "utl/UtlNameValueTokenizer.h" #include "os/OsTimer.h" #include "os/OsQueuedEvent.h" #include "os/OsEventMsg.h" #include "os/OsSysLog.h" #include "os/OsDefs.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define RUN_SCRIPT_BUSY_DELAY 60 // When the phone is busy, this is the // amount of time the phone will wait // before retrying. // STATIC VARIABLE INITIALIZATIONS // STRUCTURES struct tagRunScriptInfo { UtlString* pContent ; } ; // Used to package data through the OsEvent/queue mechanism /* //////////////////////////// PUBLIC //////////////////////////////////// */ void SipNotifyStateTask::defaultReboot() { osPrintf("SipNotifyStateTask::defaultReboot request to reboot\n"); } void SipNotifyStateTask::defaultBinaryMessageWaiting(const char* toUrl, UtlBoolean newMessages) { osPrintf("SipNotifyStateTask::defaultBinaryMessageWaiting Message status for: %s\n%snew messages available\n", toUrl, newMessages ? "" : "NO "); } void SipNotifyStateTask::defaultDetailMessageWaiting(const char* toUrl, const char* messageMediaType, UtlBoolean absoluteValues, int totalNewMessages, int totalOldMessages, int totalUntouchedMessages, int urgentUntouchedMessages, int totalSkippedMessages, int urgentSkippedMessages, int totalFlaggedMessages, int urgentFlaggedMessages, int totalReadMessages, int urgentReadMessages, int totalAnsweredMessages, int urgentAnsweredMessages, int totalDeletedMessages, int urgentDeletedMessages) { osPrintf("SipNotifyStateTask::defaultDetailMessageWaiting\n\ Messages status for URL: %s\n\ Message media type: %s\n\ %s\n\ %d new messages\n\ %d old messages\n\ Status\t\tTotal\tUrgent\n\ Untouched\t%d\t%d\n\ Skipped\t\t%d\t%d\n\ Flagged\t\t%d\t%d\n\ Read\t\t%d\t%d\n\ Answered\t%d\t%d\n\ Deleted\t\t%d\t%d\n", toUrl, messageMediaType, absoluteValues ? "Absolute counts:" : "Message deltas:", totalNewMessages, totalOldMessages, totalUntouchedMessages, urgentUntouchedMessages, totalSkippedMessages, urgentSkippedMessages, totalFlaggedMessages, urgentFlaggedMessages, totalReadMessages, urgentReadMessages, totalAnsweredMessages, urgentAnsweredMessages, totalDeletedMessages, urgentDeletedMessages); } /* ============================ CREATORS ================================== */ // Constructor SipNotifyStateTask::SipNotifyStateTask(const UtlString& checkSyncPolicy, SipUserAgent* pSipUserAgent) : OsServerTask("SipNotifyStateTask-%d"), mCheckSyncPolicy(checkSyncPolicy) { mpSipUserAgent = pSipUserAgent; mpRebootFunction = NULL; mpBinaryMessageWaitingFunction = NULL; mpDetailedMessageWaitingFunction = NULL; mpRunScriptTimer = NULL ; mpRunScriptEvent = NULL ; } // Copy constructor SipNotifyStateTask::SipNotifyStateTask(const SipNotifyStateTask& rSipNotifyStateTask) { } // Destructor SipNotifyStateTask::~SipNotifyStateTask() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipNotifyStateTask& SipNotifyStateTask::operator=(const SipNotifyStateTask& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } UtlBoolean SipNotifyStateTask::handleMessage(OsMsg& eventMessage) { int msgType = eventMessage.getMsgType(); int msgSubType = eventMessage.getMsgSubType(); // SIP message if(msgType == OsMsg::PHONE_APP && msgSubType == SipMessage::NET_SIP_MESSAGE) { const SipMessage* sipMessage = ((SipMessageEvent&)eventMessage).getMessage(); // If this is a NOTIFY request UtlString method; if(sipMessage) sipMessage->getRequestMethod(&method); method.toUpper(); if(sipMessage && method.compareTo(SIP_NOTIFY_METHOD) == 0 && !sipMessage->isResponse()) { osPrintf("SipNotifyStateTask::handleMessage got NOTIFY message\n"); // Loop through the event fields int eventIndex = 0; const char* eventFieldCharValue = NULL; UtlString eventField; if ((eventFieldCharValue = sipMessage->getHeaderValue(eventIndex, SIP_EVENT_FIELD))) { eventField = eventFieldCharValue; eventField.toLower(); // Need to get the body to if it is text base. // We are only going to support text format for now. UtlString contentType; sipMessage->getContentType(&contentType); contentType.toLower(); const HttpBody* httpBody; // If this is a message waiting indication // Looking for header: "Event: message-summary" // This is for the draft-mahy-sip-message-waiting-00.txt version // of the draft. if(eventField.index(SIP_EVENT_MESSAGE_SUMMARY, 0, UtlString::ignoreCase) == 0 && (contentType.index(CONTENT_TYPE_TEXT_PLAIN, 0, UtlString::ignoreCase) == 0 && (httpBody = sipMessage->getBody()) != NULL)) { osPrintf("SipNotifyStateTask::handleMessage found message-summary event ContentType plain/text\n"); UtlDList bodyHeaderNameValues; const char* bodyBytes; int bodyLength; httpBody->getBytes(&bodyBytes, &bodyLength); HttpMessage::parseHeaders(bodyBytes, bodyLength, bodyHeaderNameValues); UtlString toField; sipMessage->getToField(&toField); // Loop through the body header nameValue pairs UtlDListIterator iterator(bodyHeaderNameValues); NameValuePair* nv; while ((nv = (NameValuePair*) iterator())) { HttpMessage::cannonizeToken(*nv); // if binary message waiting status osPrintf("SipNotifyStateTask::handleMessage body field name: %s value: %s\n", nv->data(), nv->getValue()); // Check for either a "Messages-Waiting" or a "Message-Waiting" field. // "Messages-Waiting" is what's specified in the Internet draft; // "Message-Waiting" is needed for backward compatibility. if((strcmp(nv->data(), "Messages-Waiting") == 0) || (strcmp(nv->data(), "Message-Waiting") == 0)) { if(mpBinaryMessageWaitingFunction) { UtlString binaryStatus = nv->getValue(); binaryStatus.toLower(); UtlBoolean newMessages = FALSE; if(binaryStatus.compareTo("yes") == 0) newMessages = TRUE; mpBinaryMessageWaitingFunction(toField.data(), newMessages); binaryStatus.remove(0); } } // if detailed, media specific message status else if(mpDetailedMessageWaitingFunction) { UtlString status = nv->getValue(); // The name of the header is the message media type // parse the message counts out // The format is generically: // : [: [/]] ... // Where there may be 0 or more flags int newMessages = -1; int oldMessages = -1; int totalUntouched = -1; int urgentUntouched = -1; int totalSkipped = -1; int urgentSkipped = -1; int totalFlagged = -1; int urgentFlagged = -1; int totalRead = -1; int urgentRead = -1; int totalAnswered = -1; int urgentAnswered = -1; int totalDeleted = -1; int urgentDeleted = -1; // Get the number of new messages UtlString numberString; UtlBoolean absoluteValues = TRUE; UtlNameValueTokenizer::getSubField(status.data(), 0, " \t/;", &numberString); // If there is a + or - the numbers are in delta values if(numberString.data()[0] == '+' || numberString.data()[0] == '-') { absoluteValues = FALSE; oldMessages = 0; totalUntouched = 0; urgentUntouched = 0; totalSkipped = 0; urgentSkipped = 0; totalFlagged = 0; urgentFlagged = 0; totalRead = 0; urgentRead = 0; totalAnswered = 0; urgentAnswered = 0; totalDeleted = 0; urgentDeleted = 0; } if(!numberString.isNull()) { newMessages = atoi(numberString.data()); } // Get the number of old messages UtlNameValueTokenizer::getSubField(status.data(), 1, " \t/;", &numberString); if(!numberString.isNull()) oldMessages = atoi(numberString.data()); int parameterIndex = 2; UtlString flag; UtlNameValueTokenizer::getSubField(status.data(), parameterIndex, " \t/:;", &flag); flag.toLower(); // Loop through the flags do { osPrintf("SipNotifyStateTask::handleMessage flag=\'%s\'\n", flag.data()); switch(flag.data()[0]) { case 'u': parameterIndex += getStatusTotalUrgent(status, absoluteValues, parameterIndex + 1, totalUntouched, urgentUntouched); break; case 's': parameterIndex += getStatusTotalUrgent(status, absoluteValues, parameterIndex + 1, totalSkipped, urgentSkipped); break; case 'f': parameterIndex += getStatusTotalUrgent(status, absoluteValues, parameterIndex + 1, totalFlagged, urgentFlagged); break; case 'r': parameterIndex += getStatusTotalUrgent(status, absoluteValues, parameterIndex + 1, totalRead, urgentRead); break; case 'a': parameterIndex += getStatusTotalUrgent(status, absoluteValues, parameterIndex + 1, totalAnswered, urgentAnswered); break; case 'd': parameterIndex += getStatusTotalUrgent(status, absoluteValues, parameterIndex + 1, totalDeleted, urgentDeleted); break; default: break; } parameterIndex+=2; UtlNameValueTokenizer::getSubField(status.data(), parameterIndex, " \t/:;", &flag); } while(!flag.isNull()); // Make the MWI call back for the detailed status mpDetailedMessageWaitingFunction(toField.data(), nv->data(), // message media type absoluteValues, newMessages, oldMessages, totalUntouched, urgentUntouched, totalSkipped, urgentSkipped, totalFlagged, urgentFlagged, totalRead, urgentRead, totalAnswered, urgentAnswered, totalDeleted, urgentDeleted); status.remove(0); numberString.remove(0); flag.remove(0); } delete nv; } // Send a 200 OK response if(mpSipUserAgent) { SipMessage notifyOkResponse; notifyOkResponse.setOkResponseData(sipMessage); mpSipUserAgent->send(notifyOkResponse); } } // If this is a message waiting indication // Looking for header: "Event: simple-message-summary" // This is for the draft-mahy-sip-message-waiting-01.txt version of the draft. else if(((eventField.index(SIP_EVENT_SIMPLE_MESSAGE_SUMMARY, 0, UtlString::ignoreCase) == 0) || (eventField.index(SIP_EVENT_MESSAGE_SUMMARY, 0, UtlString::ignoreCase) == 0)) && (contentType.index(CONTENT_TYPE_SIMPLE_MESSAGE_SUMMARY, 0, UtlString::ignoreCase) == 0 && (httpBody = sipMessage->getBody()) != NULL)) { osPrintf("SipNotifyStateTask::handleMessage found simple-message-summary or message-summary event\n"); osPrintf("SipNotifyStateTask::handleMessage got application/simple-message-summary body\n"); UtlDList bodyHeaderNameValues; const char* bodyBytes; int bodyLength; httpBody->getBytes(&bodyBytes, &bodyLength); HttpMessage::parseHeaders(bodyBytes, bodyLength, bodyHeaderNameValues); UtlBoolean bBinaryNotification = true ; UtlBoolean bNewMessages = false ; UtlString strMediaType ; int iNewMessages = 0 ; int iOldMessages = 0 ; UtlString toField; sipMessage->getToField(&toField); // Loop through the body header nameValue pairs UtlDListIterator iterator(bodyHeaderNameValues); NameValuePair* nv; while ((nv = (NameValuePair*) iterator())) { HttpMessage::cannonizeToken(*nv); // if binary message waiting status osPrintf("SipNotifyStateTask::handleMessage body field name: %s value: %s\n", nv->data(), nv->getValue()); // Check for either a "Messages-Waiting" or a "Message-Waiting" field. // "Messages-Waiting" is what's specified in the Internet draft; // "Message-Waiting" is needed for backward compatibility. if((strcmp(nv->data(), "Messages-Waiting") == 0) || (strcmp(nv->data(), "Message-Waiting") == 0)) { UtlString binaryStatus = nv->getValue(); binaryStatus.toLower(); if (binaryStatus.compareTo("yes") == 0) bNewMessages = TRUE ; continue ; } if(strcmp(nv->data(), "Voice-Message") == 0) { UtlString numberString ; UtlString status = nv->getValue() ; status.toLower() ; // Parse number of new messages UtlNameValueTokenizer::getSubField(status.data(), 0, " \t/;()", &numberString); iNewMessages = atoi(numberString.data()); // Parse number of old messages UtlNameValueTokenizer::getSubField(status.data(), 1, " \t/;()", &numberString); iOldMessages = atoi(numberString.data()); strMediaType = nv->data() ; bBinaryNotification = false ; continue ; } } // If binary, notifiy the binary listener, otherwise // notify either binary or detailed if (bBinaryNotification) { // Notify Binary Listener if (mpBinaryMessageWaitingFunction != NULL) { mpBinaryMessageWaitingFunction(toField.data(), bNewMessages) ; } } else { if (mpDetailedMessageWaitingFunction != NULL) { mpDetailedMessageWaitingFunction(toField.data(), strMediaType.data(), true, iNewMessages, iOldMessages, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } } // Send a 200 OK response if(mpSipUserAgent) { SipMessage notifyOkResponse; notifyOkResponse.setOkResponseData(sipMessage); mpSipUserAgent->send(notifyOkResponse); } } // If this is a resync notification // Looking for header: "Event: check-sync" else if (eventField.index(SIP_EVENT_CHECK_SYNC) == 0) { handleCheckSyncEvent(sipMessage) ; } else { osPrintf("Unhandled NOTIFY event type: %s\n", eventField.data()) ; syslog(FAC_SIP, PRI_WARNING, "Unhandled NOTIFY event type: %s", eventField.data()) ; } eventIndex++; eventField.remove(0); } } method.remove(0); } else if (eventMessage.getMsgType() == OsMsg::OS_EVENT) { OsEventMsg* pEventMsg = (OsEventMsg*) &eventMessage; intptr_t userData ; intptr_t eventData ; pEventMsg->getEventData(eventData); pEventMsg->getUserData(userData); if (eventData == ((intptr_t) mpRunScriptTimer)) { // Restart Event: handle the event and clean up the temp data struct tagRunScriptInfo* pInfo = (struct tagRunScriptInfo*) userData ; if (pInfo != NULL) { // Ideally remove this dependency on phone library assert("OPENDEV PORT: Unexpected code path for softphone"); delete pInfo ; } } } return(TRUE); } /* ============================ ACCESSORS ================================= */ void SipNotifyStateTask::setRebootFunction(void (*rebootNotifyFunction)()) { mpRebootFunction = rebootNotifyFunction; } void SipNotifyStateTask::setBinaryMessageWaitingFunction(void (*binaryMessageWaitingFunc)(const char* toUrl, UtlBoolean newMessages)) { mpBinaryMessageWaitingFunction = binaryMessageWaitingFunc; } void SipNotifyStateTask::setDetailMessageWaitingFunction(void (*detailMessageWaitingFunction)( const char* toUrl, const char* messageMediaType, UtlBoolean absoluteValues, int totalNewMessages, int totalOldMessages, int totalUntouchedMessages, int urgentUntouchedMessages, int totalSkippedMessages, int urgentSkippedMessages, int totalFlaggedMessages, int urgentFlaggedMessages, int totalReadMessages, int urgentReadMessages, int totalAnsweredMessages, int urgentAnsweredMessages, int totalDeletedMessages, int urgentDeletedMessages)) { mpDetailedMessageWaitingFunction = detailMessageWaitingFunction; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ OsStatus SipNotifyStateTask::handleCheckSyncEvent(const SipMessage* source) { OsStatus status = OS_SUCCESS ; // Regardless of our success, we processed the event UtlString *pContent = NULL ; // First and foremost; send an ack back to the requestor if(mpSipUserAgent) { SipMessage notifyOkResponse; notifyOkResponse.setOkResponseData(source); mpSipUserAgent->send(notifyOkResponse); } // Figure out if a valid script file was included const HttpBody* body = source->getBody() ; if (body != NULL) { if (strcasecmp(body->getContentType(), CONTENT_TYPE_XPRESSA_SCRIPT) == 0) { pContent = new UtlString() ; int length = 0 ; body->getBytes(pContent, &length) ; if (pContent->isNull()) { delete pContent ; pContent = NULL ; } } } // Execute according to policy if ((mCheckSyncPolicy.compareTo("SCRIPT", UtlString::ignoreCase) == 0) && (pContent != NULL)) { #ifdef _VXWORKS pContent = NULL ; // null out pContent so that we don't delete it now. #endif } else if ( (mCheckSyncPolicy.compareTo("ENABLE", UtlString::ignoreCase) == 0) || (mCheckSyncPolicy.compareTo("REBOOT", UtlString::ignoreCase) == 0) || (mCheckSyncPolicy.compareTo("SCRIPT", UtlString::ignoreCase) == 0)) { // // Perform a simple reboot // syslog(FAC_UPGRADE, PRI_NOTICE, "Rebooting in response to a check-sync event") ; if (mpRebootFunction != NULL) { // Call the reboot handler mpRebootFunction() ; } } else { syslog(FAC_UPGRADE, PRI_NOTICE, "Ignoring check-sync; Setting not enabled") ; // // Do nothing; check-sync is disabled. // } if (pContent != NULL) { delete pContent ; pContent = NULL ; } return status ; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ UtlBoolean SipNotifyStateTask::getStatusTotalUrgent(const char* status, UtlBoolean absoluteValues, int parameterIndex, int& total, int& urgent) { UtlString numberString; UtlBoolean urgentFound = FALSE; // Get the total for this type of status UtlNameValueTokenizer::getSubField(status, parameterIndex, " \t/;:", &numberString); if(!numberString.isNull()) { total = atoi(numberString.data()); // Get the total for this type of status UtlNameValueTokenizer::getSubField(status, parameterIndex + 1, " \t/;:", &numberString); if(!numberString.isNull() && (isdigit(numberString.data()[0]) || numberString.data()[0] == '+' || numberString.data()[0] == '-')) { urgent = atoi(numberString.data()); urgentFound = TRUE; } // It is not a digit so it must be a flag else if(absoluteValues) urgent = -1; else urgent = 0; } else if(absoluteValues) { total = -1; urgent = -1; } else { total = 0; urgent = 0; } numberString.remove(0); // true/false the urgent count was set return(urgentFound); } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipObserverCriteria.cpp0000644000175000017500000000651412205613256025632 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipObserverCriteria::SipObserverCriteria(void* observerData, OsMsgQ* messageQueue, const char* sipMethod, UtlBoolean wantRequests, UtlBoolean wantResponses, UtlBoolean wantIncoming, UtlBoolean wantOutGoing, const char* eventName, SipSession* pSession ) : UtlString(sipMethod ? sipMethod : "") { mObserverData = observerData; mpMessageObserverQueue = messageQueue; mWantsRequests = wantRequests; mWantsResponses = wantResponses; mWantsIncoming = wantIncoming; mWantsOutGoing = wantOutGoing; mEventName = eventName ? eventName : ""; // Make a copy of the session if (pSession != NULL) mpSession = new SipSession(*pSession) ; else mpSession = NULL ; } // Copy constructor SipObserverCriteria::SipObserverCriteria(const SipObserverCriteria& rSipObserverCriteria) { } // Destructor SipObserverCriteria::~SipObserverCriteria() { if (mpSession != NULL) { delete mpSession ; mpSession = NULL ; } } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipObserverCriteria& SipObserverCriteria::operator=(const SipObserverCriteria& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } /* ============================ ACCESSORS ================================= */ OsMsgQ* SipObserverCriteria::getObserverQueue() { return(mpMessageObserverQueue); } void* SipObserverCriteria::getObserverData() { return(mObserverData); } void SipObserverCriteria::getEventName(UtlString& eventName) { eventName = mEventName; } SipSession* SipObserverCriteria::getSession() { return (mpSession); } /* ============================ INQUIRY =================================== */ UtlBoolean SipObserverCriteria::wantsRequests() { return(mWantsRequests); } UtlBoolean SipObserverCriteria::wantsResponses() { return(mWantsResponses); } UtlBoolean SipObserverCriteria::wantsIncoming() { return(mWantsIncoming); } UtlBoolean SipObserverCriteria::wantsOutGoing() { return(mWantsOutGoing); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipPimClient.cpp0000644000175000017500000002736212205613256024250 0ustar00danieldaniel00000000000000// // Copyright (C) 2005 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Daniel Petrie // dpetrie AT SIPez DOT com ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipPimClient::SipPimClient(SipUserAgent& userAgent, Url& presentityAor): mpTextHandlerFunction(NULL), mpTextHandlerUserData(NULL) { mCallIdIndex = 0; presentityAor.toString(mFromField); mPresentityAor = presentityAor; mpUserAgent = &userAgent; // Register to get incoming MESSAGE requests OsMsgQ* myQueue = getMessageQueue(); userAgent.addMessageObserver(*myQueue, SIP_MESSAGE_METHOD, TRUE, // requests FALSE, // responces TRUE, // incoming FALSE); // outgoing } // Copy constructor SipPimClient::SipPimClient(const SipPimClient& rSipPimClient): mpTextHandlerFunction(NULL) { } // Destructor SipPimClient::~SipPimClient() { mpUserAgent->removeMessageObserver(*getMessageQueue()); } /* ============================ MANIPULATORS ============================== */ void SipPimClient::setLocalKeyCert(const char* localPkcs12DerKeyCert, int localPkcs12DerKeyCertLength, const char* sPkcs12Password) { mPkcs12KeyCertContainer.remove(0); if(localPkcs12DerKeyCert && *localPkcs12DerKeyCert && localPkcs12DerKeyCertLength > 0) { mPkcs12KeyCertContainer.append(localPkcs12DerKeyCert, localPkcs12DerKeyCertLength); } if(sPkcs12Password && *sPkcs12Password) { mPkcs12Password = sPkcs12Password; } else { sPkcs12Password = ""; } } // Assignment operator SipPimClient& SipPimClient::operator=(const SipPimClient& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } //! Send a pager style instant message to the given destination UtlBoolean SipPimClient::sendPagerMessage(Url& destinationAor, const char* messageText, const char* subject, int& responseCode, UtlString& responseCodeText) { UtlBoolean returnCode = FALSE; responseCode = -1; responseCodeText.remove(0); if(messageText && *messageText) { // Construct the text body HttpBody* textBody = new HttpBody(messageText, strlen(messageText), CONTENT_TYPE_TEXT_PLAIN); // Construct the MESSAGE request UtlString toAddress = destinationAor.toString(); UtlString requestUri; destinationAor.getUri(requestUri); UtlString callId; getNextCallId(callId); SipMessage messageRequest; messageRequest.setRequestData(SIP_MESSAGE_METHOD, requestUri, mFromField, toAddress, callId, 1, // sequenceNumber NULL); // contactUrl if (NULL != subject && 0 != strlen(subject)) messageRequest.setHeaderValue("Subject", subject); // Attache the body messageRequest.setBody(textBody); messageRequest.setContentType(CONTENT_TYPE_TEXT_PLAIN); // Set the queue to which the response will be deposited // for this specific request. OsMsgQ responseQueue; messageRequest.setResponseListenerQueue(&responseQueue); // Send the request returnCode = mpUserAgent->send(messageRequest); // wait for the response OsMsg* qMessage = NULL; // For now we will block forever. Theoretically this should // always get a response (e.g. worst case a 408 timed out). // If we do not wait forever, we need to be sure to wait the // the maximum transaction timeout period so that the qMessage // exists when the SipUserAgent queues the response. // counter to make sure we don't get stuck in the following // loop forever int loopCounter = 0; do { responseQueue.receive(qMessage); // If we got a response, get the response status code and text if(qMessage) { int msgType = qMessage->getMsgType(); int msgSubType = qMessage->getMsgSubType(); // SIP message if(msgType == OsMsg::PHONE_APP && msgSubType == SipMessage::NET_SIP_MESSAGE) { const SipMessage* messageResponse = ((SipMessageEvent*)qMessage)->getMessage(); if(messageResponse && messageResponse->isResponse()) { responseCode = messageResponse->getResponseStatusCode(); messageResponse->getResponseStatusText(&responseCodeText); } } } } while (responseCode == 407 && ++loopCounter < 2); } return(returnCode); } void SipPimClient::setIncomingImTextHandler(MessageCallback textHandler, void* userData) { mpTextHandlerFunction = textHandler; mpTextHandlerUserData = userData; } //! Update the presence state of the presentity indicate UtlBoolean SipPimClient::updatePresenceState(SipxRpidStates newState) { UtlBoolean returnCode = FALSE; return(returnCode); } UtlBoolean SipPimClient::handleMessage(OsMsg& eventMessage) { int msgType = eventMessage.getMsgType(); int msgSubType = eventMessage.getMsgSubType(); // SIP message if(msgType == OsMsg::PHONE_APP && msgSubType == SipMessage::NET_SIP_MESSAGE) { const SipMessage* sipMessage = ((SipMessageEvent&)eventMessage).getMessage(); // If this is a MESSAGE request UtlString method; if(sipMessage) sipMessage->getRequestMethod(&method); method.toUpper(); UtlBoolean responseSent = FALSE; if(sipMessage && method.compareTo(SIP_MESSAGE_METHOD) == 0 && !sipMessage->isResponse()) { const HttpBody* messageBody = sipMessage->getBody(); UtlString contentType = messageBody->getContentType(); // We have a text body and a callback handler function if(messageBody && mpTextHandlerFunction && contentType.index(CONTENT_TYPE_TEXT_PLAIN, 0, UtlString::ignoreCase) == 0) { const char* bodyBytes; int bodyLength; messageBody->getBytes(&bodyBytes, &bodyLength); UtlString fromField; sipMessage->getFromField(&fromField); const char* subj = sipMessage->getHeaderValue(0, "Subject"); if (NULL == subj) subj = ""; // Send back a 200 response SipMessage response; response.setResponseData(sipMessage, SIP_OK_CODE, SIP_OK_TEXT); mpUserAgent->send(response); responseSent = TRUE; // Invoke the call back with the info mpTextHandlerFunction(mpTextHandlerUserData, fromField, bodyBytes, bodyLength, subj, *sipMessage); } #ifdef SMIME // S/MIME else if(messageBody && mpTextHandlerFunction && contentType.index(CONTENT_SMIME_PKCS7, 0, UtlString::ignoreCase) == 0 && mPkcs12KeyCertContainer.length() > 0) { SmimeBody* smimeBody = (SmimeBody*) messageBody; UtlBoolean decryptedOk = smimeBody->decrypt(mPkcs12KeyCertContainer.data(), mPkcs12KeyCertContainer.length(), mPkcs12Password); const HttpBody* decryptedBody = NULL; UtlString decryptedContentType; if(decryptedOk) { decryptedBody = smimeBody->getDecyptedBody(); if(decryptedBody) { decryptedContentType = decryptedBody->getContentType(); if(decryptedContentType.index(CONTENT_TYPE_TEXT_PLAIN, UtlString::ignoreCase) == 0) { const char* bodyBytes; int bodyLength; messageBody->getBytes(&bodyBytes, &bodyLength); UtlString fromField; sipMessage->getFromField(&fromField); // Send back a 200 response SipMessage response; response.setResponseData(sipMessage, SIP_OK_CODE, SIP_OK_TEXT); mpUserAgent->send(response); responseSent = TRUE; // Invoke the call back with the info mpTextHandlerFunction(fromField, bodyBytes, bodyLength, *sipMessage); } } } else { UtlString localUri = mPresentityAor.toString(); OsSysLog::add(FAC_SIP, PRI_WARNING, "Unable to decrypt S/MIME MESSAGE Remote: %s Local: %s", mFromField.data(), localUri.data()); } } #endif if(!responseSent) { // Send an error as we do not accept the content type SipMessage badContentResponse; badContentResponse.setResponseData(sipMessage, SIP_BAD_MEDIA_CODE, SIP_BAD_MEDIA_TEXT); mpUserAgent->send(badContentResponse); } } } return(TRUE); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ void SipPimClient::getNextCallId(UtlString& callId) { UtlString callIdSeed; mpUserAgent->getContactUri(&callIdSeed); char num[20]; int epochTime = OsDateTime::getSecsSinceEpoch(); sprintf(num, "%d", epochTime); callIdSeed.append(num); mCallIdIndex++; sprintf(num, "%d", mCallIdIndex); callIdSeed.append(num); callIdSeed.append(mFromField); NetMd5Codec::encode(callIdSeed, callId); callId.append("-pimc"); callId.append(num); } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ TESTING =================================== */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipPresenceEvent.cpp0000644000175000017500000002332512205613256025125 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define DOUBLE_QUOTE "\"" #define END_BRACKET ">" #define END_LINE ">\n" // STATIC VARIABLE INITIALIZATIONS const UtlContainableType Tuple::TYPE = "Tuple"; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor Tuple::Tuple(const char* tupleId) { mId = tupleId; } // Destructor Tuple::~Tuple() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator Tuple& Tuple::operator=(const Tuple& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } // Copy constructor Tuple::Tuple(const Tuple& rTuple) { mId = rTuple.mId; } /* ============================ ACCESSORS ================================= */ void Tuple::setTupleId(const char* tupleId) { mId = tupleId; } void Tuple::getTupleId(UtlString& tupleId) const { tupleId = mId; } void Tuple::setStatus(const char* status) { mStatus = status; } void Tuple::getStatus(UtlString& status) const { status = mStatus; } void Tuple::setContact(const char* contactUrl, const float priority) { mContactUrl = contactUrl; mPriority = priority; } void Tuple::getContact(UtlString& contactUrl, float& priority) const { contactUrl = mContactUrl; priority = mPriority; } int Tuple::compareTo(const UtlContainable *b) const { return mId.compareTo(((Tuple *)b)->mId); } unsigned int Tuple::hash() const { return mId.hash(); } const UtlContainableType Tuple::getContainableType() const { return TYPE; } /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipPresenceEvent::SipPresenceEvent(const char* entity, const char*bodyBytes) : mLock(OsBSem::Q_PRIORITY, OsBSem::FULL) { remove(0); append(PRESENCE_EVENT_CONTENT_TYPE); mEntity = entity; if(bodyBytes) { bodyLength = strlen(bodyBytes); parseBody(bodyBytes); ((SipPresenceEvent*)this)->mBody = bodyBytes; } } // Destructor SipPresenceEvent::~SipPresenceEvent() { // Clean up all the tuple elements if (!mTuples.isEmpty()) { mTuples.destroyAll(); } } /* ============================ MANIPULATORS ============================== */ void SipPresenceEvent::parseBody(const char* bodyBytes) { if(bodyBytes) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipPresenceEvent::parseBody incoming package = %s\n", bodyBytes); TiXmlDocument doc("PresenceEvent.xml"); if (doc.Parse(bodyBytes)) { TiXmlNode * rootNode = doc.FirstChild ("presence"); TiXmlElement* ucElement = 0; if (rootNode != NULL) { ucElement = rootNode->ToElement(); if (ucElement) { mEntity = ucElement->Attribute("entity"); } // Parse each tuple for (TiXmlNode *groupNode = rootNode->FirstChild("tuple"); groupNode; groupNode = groupNode->NextSibling("tuple")) { UtlString tupleId; // Get the attributes in tuple ucElement = groupNode->ToElement(); if (ucElement) { tupleId = ucElement->Attribute("id"); } Tuple* pTuple = new Tuple(tupleId); // Get the status element UtlString status; status = ((groupNode->FirstChild("status"))->FirstChild("basic"))->FirstChild()->Value(); pTuple->setStatus(status); // Get the contact element UtlString contact, priority; TiXmlNode *subNode = groupNode->FirstChild("contact"); if (subNode) { contact = subNode->FirstChild()->Value(); ucElement = subNode->ToElement(); if (ucElement) { priority = ucElement->Attribute("priority"); } pTuple->setContact(contact, (float)atof(priority)); } // Insert it into the list insertTuple(pTuple); } } } } } // Assignment operator SipPresenceEvent& SipPresenceEvent::operator=(const SipPresenceEvent& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } /* ============================ ACCESSORS ================================= */ void SipPresenceEvent::insertTuple(Tuple* tuple) { mLock.acquire(); if (mTuples.insert(tuple) != NULL) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipPresenceEvent::insertTuple Tuple = %p succeeded", tuple); } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipPresenceEvent::insertTuple Tuple = %p failed", tuple); } mLock.release(); } Tuple* SipPresenceEvent::removeTuple(Tuple* tuple) { mLock.acquire(); UtlContainable *foundValue; foundValue = mTuples.remove(tuple); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipPresenceEvent::removeTuple Tuple = %p", foundValue); mLock.release(); return (Tuple *) foundValue; } Tuple* SipPresenceEvent::getTuple(UtlString& tupleId) { mLock.acquire(); UtlHashMapIterator tupleIterator(mTuples); Tuple* pTuple; UtlString foundValue; while ((pTuple = (Tuple *) tupleIterator())) { pTuple->getTupleId(foundValue); if (foundValue.compareTo(tupleId) == 0) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipPresenceEvent::getTuple found Tuple = %p for tupleId %s", pTuple, tupleId.data()); mLock.release(); return pTuple; } } OsSysLog::add(FAC_SIP, PRI_WARNING, "SipPresenceEvent::getTuple could not found the Tuple for tupleId = %s", tupleId.data()); mLock.release(); return NULL; } UtlBoolean SipPresenceEvent::isEmpty() { return (mTuples.isEmpty()); } int SipPresenceEvent::getLength() const { int length; UtlString tempBody; getBytes(&tempBody, &length); return length; } void SipPresenceEvent::buildBody() const { UtlString PresenceEvent; UtlString singleLine; // Construct the xml document of Tuple event PresenceEvent = UtlString(XML_VERSION_1_0); // Presence Structure PresenceEvent.append(BEGIN_PRESENCE); PresenceEvent.append(PRESENTITY_EQUAL); singleLine = DOUBLE_QUOTE + mEntity + DOUBLE_QUOTE; PresenceEvent += singleLine; PresenceEvent.append(END_LINE); // Tuple elements ((SipPresenceEvent*)this)->mLock.acquire(); UtlHashMapIterator tupleIterator(mTuples); Tuple* pTuple; while ((pTuple = (Tuple *) tupleIterator())) { UtlString tupleId; pTuple->getTupleId(tupleId); PresenceEvent.append(BEGIN_TUPLE); singleLine = DOUBLE_QUOTE + tupleId + DOUBLE_QUOTE; PresenceEvent += singleLine; PresenceEvent.append(END_LINE); // Status element UtlString status; pTuple->getStatus(status); PresenceEvent.append(BEGIN_STATUS); singleLine = BEGIN_BASIC + status + END_BASIC; PresenceEvent += singleLine; PresenceEvent.append(END_STATUS); // Contact element UtlString contact; float priority; pTuple->getContact(contact, priority); if (!contact.isNull()) { singleLine = BEGIN_CONTACT + contact + END_CONTACT; PresenceEvent += singleLine; } // End of Tuple element PresenceEvent.append(END_TUPLE); } // End of presence structure PresenceEvent.append(END_PRESENCE); ((SipPresenceEvent*)this)->mLock.release(); ((SipPresenceEvent*)this)->mBody = PresenceEvent; ((SipPresenceEvent*)this)->bodyLength = PresenceEvent.length(); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTupleEvent::getBytes Tuple content = \n%s", PresenceEvent.data()); } void SipPresenceEvent::getBytes(const char** bytes, int* length) const { UtlString tempBody; getBytes(&tempBody, length); ((SipPresenceEvent*)this)->mBody = tempBody.data(); *bytes = mBody.data(); } void SipPresenceEvent::getBytes(UtlString* bytes, int* length) const { buildBody(); *bytes = ((SipPresenceEvent*)this)->mBody; *length = ((SipPresenceEvent*)this)->bodyLength; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipProtocolServerBase.cpp0000644000175000017500000005664212205617431026151 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include // APPLICATION INCLUDES #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS //#define TEST_PRINT // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipProtocolServerBase::SipProtocolServerBase(SipUserAgent* userAgent, const char* protocolString, const char* taskName) : OsTask(taskName), mClientLock(OsMutex::Q_FIFO) { mSipUserAgent = userAgent; mProtocolString = protocolString; mDefaultPort = SIP_PORT; } // Copy constructor SipProtocolServerBase::SipProtocolServerBase(const SipProtocolServerBase& rSipProtocolServerBase) : mClientLock(OsMutex::Q_FIFO) { } // Destructor SipProtocolServerBase::~SipProtocolServerBase() { mDataGuard.acquire(); mClientLock.acquireWrite(); waitUntilShutDown(); int iteratorHandle = mClientList.getIteratorHandle(); SipClient* client = NULL; while ((client = (SipClient*)mClientList.next(iteratorHandle))) { mClientList.remove(iteratorHandle); delete client; } mClientList.releaseIteratorHandle(iteratorHandle); mClientLock.releaseWrite(); mDataGuard.release(); } /* ============================ MANIPULATORS ============================== */ UtlBoolean SipProtocolServerBase::send(SipMessage* message, const char* hostAddress, int hostPort) { UtlBoolean sendOk = FALSE; UtlString localIp(message->getLocalIp()); if (localIp.length() < 1) { localIp = mDefaultIp; } SipClient* client = createClient(hostAddress, hostPort, localIp); if(client) { int isBusy = client->isInUseForWrite(); UtlString clientNames; client->getClientNames(clientNames); OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServerBase::send %p isInUseForWrite %d, client info\n %s", mProtocolString.data(), client, isBusy, clientNames.data()); sendOk = client->sendTo(*message, hostAddress, hostPort); if(!sendOk) { OsTask* pCallingTask = OsTask::getCurrentTask(); OsTaskId_t callingTaskId = -1; OsTaskId_t clientTaskId = -1; if ( pCallingTask ) { pCallingTask->id(callingTaskId); } client->id(clientTaskId); if (clientTaskId != callingTaskId) { // Do not need to clientLock.acquireWrite(); // as deleteClient uses the locking list lock // which is all that is needed as the client is // already marked as busy when we called // createClient above. deleteClient(client); client = NULL; } } } if(client) { releaseClient(client); } return(sendOk); } void SipProtocolServerBase::releaseClient(SipClient* client) { mClientLock.acquireWrite(); if(client && clientExists(client)) { if(client->isInUseForWrite()) { client->markAvailbleForWrite(); } else { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipProtocolServerBase::releaseClient releasing %s client not locked: %p", mProtocolString.data(), client); } } else { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipProtocolServerBase::releaseClient releasing %s client not in list: %p", mProtocolString.data(), client); } mClientLock.releaseWrite(); } UtlBoolean SipProtocolServerBase::startListener() { # ifdef TEST_PRINT osPrintf("SIP Server binding to port %d\n", serverPort); # endif UtlHashMapIterator iter(mServerSocketMap); UtlVoidPtr* pSocketContainer = NULL; UtlString* pKey; while ((pKey =(UtlString*)iter())) { OsSocket* pSocket = NULL; SipClient* pServer = NULL; UtlVoidPtr* pServerContainer = NULL; UtlString localIp = *pKey; pSocketContainer = (UtlVoidPtr*)iter.value(); if (pSocketContainer) { pSocket = (OsSocket*)pSocketContainer->getValue(); } pServerContainer = (UtlVoidPtr*)mServers.findValue(&localIp); if (!pServerContainer) { pServer = new SipClient(pSocket); // This used to be done at the end of this else statement // however there is a race and the userAgent must be set before // starting this client. I think the race occurs if there is // immediately an incoming message on the socket. if(mSipUserAgent) { if (pServer) { pServer->setUserAgent(mSipUserAgent); } } this->mServers.insertKeyAndValue(new UtlString(localIp), new UtlVoidPtr((void*)pServer)); pServer->start(); } else { pServer = (SipClient*) pServerContainer->getValue(); if(mSipUserAgent) { if (pServer) { pServer->setUserAgent(mSipUserAgent); } } } } return(TRUE); } SipClient* SipProtocolServerBase::createClient(const char* hostAddress, int hostPort, const char* localIp) { UtlString remoteHostAddr; UtlBoolean clientStarted = FALSE; mClientLock.acquireWrite(); SipClient* client = getClient(hostAddress, hostPort, localIp); if(! client) { # if TEST_CLIENT_CREATION OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipProtocolServerBase::createClient( %s, %d )", hostAddress, hostPort); # endif if(!portIsValid(hostPort)) { hostPort = mDefaultPort; # if TEST_CLIENT_CREATION OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipProtocolServerBase::createClient port defaulting to %d", hostPort); # endif } OsTime time; OsDateTime::getCurTimeSinceBoot(time); long beforeSecs = time.seconds(); OsSocket* clientSocket = buildClientSocket(hostPort, hostAddress, localIp); OsDateTime::getCurTimeSinceBoot(time); long afterSecs = time.seconds(); if(afterSecs - beforeSecs > 1) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SIP %s socket create for %s:%d took %d seconds", mProtocolString.data(), hostAddress, hostPort, (int)(afterSecs - beforeSecs)); } UtlBoolean isOk = clientSocket->isOk(); int writeWait = 3000; // mSec UtlBoolean isReadyToWrite = clientSocket->isReadyToWrite(writeWait); if(!isReadyToWrite) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SIP %s socket %s:%d not ready for writing after %d seconds", mProtocolString.data(), hostAddress, hostPort, (int) (writeWait/1000)); } if(isOk && isReadyToWrite) { #ifdef TEST osPrintf("Socket OK, creating client\n"); #endif client = new SipClient(clientSocket) ; if (client && mSipUserAgent->getUseRport() && clientSocket->getIpProtocol() == OsSocket::UDP) { client->setSharedSocket(TRUE) ; } #ifdef TEST osPrintf("Created client\n"); #endif if(mSipUserAgent) { client->setUserAgent(mSipUserAgent); } if (clientSocket->getIpProtocol() != OsSocket::UDP) { //osPrintf("starting client\n"); clientStarted = client->start(); if(!clientStarted) { osPrintf("SIP %s client failed to start\n", mProtocolString.data()); } } OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServer::createClient client: %p %s -> %s:%d", mProtocolString.data(), client, localIp, hostAddress, hostPort); mClientList.push(client); } // The socket failed to be connected else { if(clientSocket) { if (!mSipUserAgent->getUseRport() || (clientSocket->getIpProtocol() == OsSocket::TCP)) { delete clientSocket; } clientSocket = NULL; } OsSysLog::add(FAC_SIP, PRI_WARNING, "Sip%sServer::createClient client %p Failed to create socket %s -> %s:%d", mProtocolString.data(), this, localIp, hostAddress, hostPort); } } int isBusy = FALSE; if(client) { isBusy = client->isInUseForWrite(); if(!isBusy) client->markInUseForWrite(); } mClientLock.releaseWrite(); if(client && isBusy) { if(!waitForClientToWrite(client)) client = NULL; } return(client); } UtlBoolean SipProtocolServerBase::isOk() { UtlBoolean bRet = true; SipClient* pServer = NULL; UtlHashMapIterator iterator(mServers); UtlVoidPtr* pServerContainer = NULL; UtlString* pKey = NULL; while ((pKey = (UtlString*)iterator())) { pServerContainer = (UtlVoidPtr*)iterator.value(); if (pServerContainer) { pServer = (SipClient*)pServerContainer->getValue(); } if (pServer) { bRet = bRet && pServer->isOk(); } } return bRet; } UtlBoolean SipProtocolServerBase::waitForClientToWrite(SipClient* client) { UtlBoolean exists; UtlBoolean busy = FALSE; int numTries = 0; do { numTries++; mClientLock.acquireWrite(); exists = clientExists(client); if(exists) { busy = client->isInUseForWrite(); if(!busy) { client->markInUseForWrite(); mClientLock.releaseWrite(); if(numTries > 1) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServerBase::waitForClientToWrite %p locked after %d tries", mProtocolString.data(), client, numTries); } } else { // We set an event to be signaled when a // transaction is released. OsEvent* waitEvent = new OsEvent(); client->notifyWhenAvailableForWrite(*waitEvent); // Must unlock while we wait or there is a dead lock mClientLock.releaseWrite(); #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServerBase::waitForClientToWrite %p " "waiting on: %p after %d tries", mProtocolString.data(), client, waitEvent, numTries); #endif // Do not block forever OsTime maxWaitTime(0, 500000); // If the other side signaled if(waitEvent->wait(maxWaitTime) == OS_SUCCESS) { // The other side is no longer referencing // the event. This side must clean it up delete waitEvent; waitEvent = NULL; } // A timeout occurred and the other side did not signal yet else { // Signal the other side to indicate we are done // with the event. If already signaled, we lost // a race and the other side was done first. if(waitEvent->signal(0) == OS_ALREADY_SIGNALED) { delete waitEvent; waitEvent = NULL; } } #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServerBase::waitForClientToWrite %p done waiting after %d tries", mProtocolString.data(), client, numTries); #endif } } else { mClientLock.releaseWrite(); OsSysLog::add(FAC_SIP, PRI_ERR, "Sip%sServerBase::waitForClientToWrite %p gone after %d tries", mProtocolString.data(), client, numTries); } } while(exists && busy); return(exists && !busy); } SipClient* SipProtocolServerBase::getClient(const char* hostAddress, int hostPort, const char* localIp) { UtlBoolean isSameHost = FALSE; UtlString hostAddressString(hostAddress ? hostAddress : ""); int iteratorHandle = mClientList.getIteratorHandle(); SipClient* client = NULL; # if TEST_CLIENT_CREATION OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipProtocolServerBase::getClient( %s, %d )", hostAddress, hostPort); # endif while ((client = (SipClient*)mClientList.next(iteratorHandle))) { // Are these the same host? isSameHost = client->isConnectedTo(hostAddressString, hostPort); if(isSameHost && client->isOk() && 0 == strcmp(client->getLocalIp(), localIp)) { break; } else if(isSameHost) { if(!client->isOk()) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "%s Client matches but is not OK", mProtocolString.data()); } } } mClientList.releaseIteratorHandle(iteratorHandle); # ifdef TEST_CLIENT_CREATION if (!client) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipProtocolServerBase::getClient( %s, %d ) NOT FOUND", hostAddress, hostPort); } # endif return(client); } void SipProtocolServerBase::deleteClient(SipClient* sipClient) { // Find the client in the list of clients and shut it down int iteratorHandle = mClientList.getIteratorHandle(); SipClient* client = NULL; #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServer::deleteClient(%p)", mProtocolString.data(), sipClient); #endif while ((client = (SipClient*)mClientList.next(iteratorHandle))) { // Remove this bad client // This used to be a little over zealous and delete any // SipClient that was not ok. It was not checking if // the SipClient was busy or not so bad things could // happen. This is now on the conservative side and // deleting only the thing it is supposed to. if(client == sipClient) { #ifdef TEST_PRINT UtlString clientNames; client->getClientNames(clientNames); OsSysLog::add(FAC_SIP, PRI_DEBUG, "Removing %s client %p names:\n%s", mProtocolString.data(), this, clientNames.data()); #endif mClientList.remove(iteratorHandle); break; } } mClientList.releaseIteratorHandle(iteratorHandle); // Delete the client outside the lock on the list as // it can create a deadlock. If the client is doing // an operation that requires the locking list, the // client gets blocked from shutting down. We then // block here trying to delete the client forever. if(client) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServer::deleteClient(%p) done", mProtocolString.data(), sipClient); delete client; client = NULL; } #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServer::deleteClient(%p) done", mProtocolString.data(), sipClient); #endif } void SipProtocolServerBase::removeOldClients(long oldTime) { mClientLock.acquireWrite(); // Find the old clients in the list and shut them down int iteratorHandle = mClientList.getIteratorHandle(); SipClient* client; int numClients = mClientList.getCount(); int numDelete = 0; int numBusy = 0; SipClient** deleteClientArray = NULL; UtlString clientNames; while ((client = (SipClient*)mClientList.next(iteratorHandle))) { if(client->isInUseForWrite()) numBusy++; // Remove any client with a bad socket // With TCP clients let them stay around if they are still // good as the may stay open for the session // The clients opened from this side for sending requests // get closed by the server (i.e. other side). The clients // opened as servers for requests from the remote side are // explicitly closed on this side when the final response is // sent. if( ! client->isInUseForWrite() // can't remove it if writing to it... && ( ! client->isOk() // socket is bad || client->getLastTouchedTime() < oldTime // idle for long enough ) ) { client->getClientNames(clientNames); #ifdef TEST_PRINT osPrintf("Removing %s client names:\n%s\r\n", mProtocolString.data(), clientNames.data()); #endif OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServer::Removing old client %p:\n%s\r", mProtocolString.data(), client, clientNames.data()); mClientList.remove(iteratorHandle); // Delete the clients after releasing the lock if(!deleteClientArray) deleteClientArray = new SipClient*[numClients]; deleteClientArray[numDelete] = client; numDelete++; client = NULL; } else { # ifdef TEST_PRINT UtlString names; client->getClientNames(names); OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServer::removeOldClients leaving client:\n%s", mProtocolString.data(), names.data()); # endif } } mClientList.releaseIteratorHandle(iteratorHandle); mClientLock.releaseWrite(); if ( numDelete || numBusy ) // get rid of lots of 'doing nothing when nothing to do' messages in the log { OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServer::removeOldClients deleting %d of %d SipClients (%d busy)", mProtocolString.data(), numDelete, numClients, numBusy); } // These have been removed from the list so delete them // after releasing the locks for(int clientIndex = 0; clientIndex < numDelete; clientIndex++) { delete deleteClientArray[clientIndex]; } if(deleteClientArray) { delete[] deleteClientArray; deleteClientArray = NULL; } } // Assignment operator SipProtocolServerBase& SipProtocolServerBase::operator=(const SipProtocolServerBase& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } void SipProtocolServerBase::startClients() { int iteratorHandle = mClientList.getIteratorHandle(); SipClient* client = NULL; while ((client = (SipClient*)mClientList.next(iteratorHandle))) { client->start(); } mClientList.releaseIteratorHandle(iteratorHandle); } void SipProtocolServerBase::shutdownClients() { // For each client request shutdown int iteratorHandle = mClientList.getIteratorHandle(); SipClient* client = NULL; while ((client = (SipClient*)mClientList.next(iteratorHandle))) { client->requestShutdown(); } mClientList.releaseIteratorHandle(iteratorHandle); } /* ============================ ACCESSORS ================================= */ int SipProtocolServerBase::getClientCount() { return(mClientList.getCount()); } void SipProtocolServerBase::addClient(SipClient* client) { if(client) { mClientList.push(client); } } UtlBoolean SipProtocolServerBase::clientExists(SipClient* client) { SipClient* listClient; UtlBoolean found = FALSE; int iteratorHandle = mClientList.getIteratorHandle(); while ((listClient = (SipClient*)mClientList.next(iteratorHandle))) { if(client == listClient) { found = TRUE; break; } } mClientList.releaseIteratorHandle(iteratorHandle); return(found); } void SipProtocolServerBase::printStatus() { int numClients = mClientList.getCount(); int iteratorHandle = mClientList.getIteratorHandle(); OsTime time; OsDateTime::getCurTimeSinceBoot(time); long currentTime = time.seconds(); //long currentTime = OsDateTime::getSecsSinceEpoch(); SipClient* client; UtlString clientNames; long clientTouchedTime; UtlBoolean clientOk; osPrintf("%s %d clients in list at: %ld\n", mProtocolString.data(), numClients, currentTime); while ((client = (SipClient*)mClientList.next(iteratorHandle))) { // Remove this or any other bad client clientTouchedTime = client->getLastTouchedTime(); clientOk = client->isOk(); client->getClientNames(clientNames); osPrintf("%s client %p last used: %ld ok: %d names:\n%s\n", mProtocolString.data(), this, clientTouchedTime, clientOk, clientNames.data()); } mClientList.releaseIteratorHandle(iteratorHandle); } /* ============================ INQUIRY =================================== */ #ifdef LOOKING_FOR_T220_COMPILER_BUG /* [ */ int SipProtocolServerBase::dumpLayout(void *Ths) { SipProtocolServerBase* THIS = (SipProtocolServerBase*) Ths; printf("SipProtocolServerBase: size = %d bytes\n", sizeof(*THIS)); printf(" offset(startOfSipProtocolServerBase) = %d\n", (((int) &(THIS->startOfSipProtocolServerBase)) - ((int) THIS))); printf(" offset(mProtocolString) = %d\n", (((int) &(THIS->mProtocolString)) - ((int) THIS))); printf(" offset(mDefaultPort) = %d\n", (((int) &(THIS->mDefaultPort)) - ((int) THIS))); printf(" offset(mSipUserAgent) = %d\n", (((int) &(THIS->mSipUserAgent)) - ((int) THIS))); printf(" offset(mClientLock) = %d\n", (((int) &(THIS->mClientLock)) - ((int) THIS))); printf(" offset(mClientList) = %d\n", (((int) &(THIS->mClientList)) - ((int) THIS))); printf(" offset(endOfSipProtocolServerBase) = %d\n", (((int) &(THIS->endOfSipProtocolServerBase)) - ((int) THIS))); OsLockingList::dumpLayout(Ths); return sizeof(*THIS); } #endif /* LOOKING_FOR_T220_COMPILER_BUG ] */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipPublishContentMgr.cpp0000644000175000017500000005343512205613256025773 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2010 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2005 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie (dpetrie AT SIPez DOT com) //#define TEST_PRINT // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include // Private class to contain callback for eventTypeKey class PublishCallbackContainer : public UtlString { public: PublishCallbackContainer(); virtual ~PublishCallbackContainer(); // Parent UtlString contains the SIP event Type token (not the eventTypeKey) void* mpApplicationData; SipPublishContentMgr::SipPublisherContentChangeCallback mpCallback; private: //! DISALLOWED accidental copying PublishCallbackContainer(const PublishCallbackContainer& rPublishCallbackContainer); PublishCallbackContainer& operator=(const PublishCallbackContainer& rhs); }; // Private class to contain event content for eventTypeKey class PublishContentContainer : public UtlString { public: PublishContentContainer(); virtual ~PublishContentContainer(); // parent UtlString contains the resourceId and eventTypeKey UtlSList mEventContent; private: //! DISALLOWED accendental copying PublishContentContainer(const PublishContentContainer& rPublishContentContainer); PublishContentContainer& operator=(const PublishContentContainer& rhs); }; // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ PublishCallbackContainer::PublishCallbackContainer() : mpApplicationData(NULL), mpCallback(NULL) { } PublishCallbackContainer::~PublishCallbackContainer() { } PublishContentContainer::PublishContentContainer() { } PublishContentContainer::~PublishContentContainer() { } // Constructor SipPublishContentMgr::SipPublishContentMgr() : mPublishMgrMutex(OsMutex::Q_FIFO) { } // Copy constructor NOT IMPLEMENTED SipPublishContentMgr::SipPublishContentMgr(const SipPublishContentMgr& rSipPublishContentMgr) : mPublishMgrMutex(OsMutex::Q_FIFO) { } // Destructor SipPublishContentMgr::~SipPublishContentMgr() { // Delete the stored information. mContentEntries.destroyAll(); mDefaultContentEntries.destroyAll(); mDefaultContentConstructors.destroyAll(); mEventContentCallbacks.destroyAll(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipPublishContentMgr& SipPublishContentMgr::operator=(const SipPublishContentMgr& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } void SipPublishContentMgr::publish(const char* resourceId, const char* eventTypeKey, const char* eventType, int numContentTypes, HttpBody* eventContent[], UtlBoolean noNotify) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipPublishContentMgr::publish resourceId '%s', eventTypeKey '%s', eventType '%s', numContentTypes %d", resourceId, eventTypeKey, eventType, numContentTypes); #ifdef TEST_PRINT osPrintf("SipPublishContentMgr::publish(%s, %s, %s, %d, [%p], ...)\n", resourceId, eventTypeKey, eventType, numContentTypes, eventContent[0]); #endif UtlBoolean resourceIdProvided = resourceId && *resourceId; // Construct the key to look up. UtlString key; if(resourceIdProvided) { key = resourceId; } if(eventTypeKey) { key.append(eventTypeKey); } lock(); // Look up the key in the specific or default entries, as appropriate. PublishContentContainer* container = static_cast ((resourceIdProvided ? mContentEntries : mDefaultContentEntries).find(&key)); // If not found, create a container. if(container == NULL) { container = new PublishContentContainer(); *((UtlString*) container) = key; // Save the container in the appropriate hash. (resourceIdProvided ? mContentEntries : mDefaultContentEntries).insert(container); } // The content for this event type already existed else { // Remove the old content container->mEventContent.destroyAll(); } // Add the new content for(int index = 0; index < numContentTypes; index++) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipPublishContentMgr::publish eventContent[%d] = %p", index, eventContent[index]); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipPublishContentMgr::publish eventContent[%d]->getBytes() = %p", index, eventContent[index]->getBytes()); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipPublishContentMgr::publish eventContent[%d] = '%s'", index, eventContent[index]->getBytes()); container->mEventContent.append(eventContent[index]); } // Don't call the observers if noNotify is set. if (!noNotify) { // Call the observer for the content change, if any. UtlString eventTypeString(eventType); PublishCallbackContainer* callbackContainer = static_cast (mEventContentCallbacks.find(&eventTypeString)); if(callbackContainer && callbackContainer->mpCallback) { (callbackContainer->mpCallback)(callbackContainer->mpApplicationData, resourceId, eventTypeKey, eventTypeString, !resourceIdProvided); } } unlock(); } void SipPublishContentMgr::publishDefault(const char* eventTypeKey, const char* eventType, int numContentTypes, HttpBody* eventContent[]) { publish(NULL, eventTypeKey, eventType, numContentTypes, eventContent); } void SipPublishContentMgr::publishDefault(const char* eventTypeKey, const char* eventType, SipPublishContentMgrDefaultConstructor* defaultConstructor) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipPublishContentMgr::publishDefault eventTypeKey '%s', eventType '%s', defaultConstructor %p", eventTypeKey, eventType, defaultConstructor); // Construct the key to look up. UtlString key; if(eventTypeKey) { key.append(eventTypeKey); } lock(); // Add the default constructor. if (defaultConstructor) { // Remove any old value first. mDefaultContentConstructors.destroy(&key); UtlString* key_heap = new UtlString(key); mDefaultContentConstructors.insertKeyAndValue(key_heap, defaultConstructor); } // Call the observer for the content change, if any. UtlString eventTypeString(eventType); PublishCallbackContainer* callbackContainer = static_cast (mEventContentCallbacks.find(&eventTypeString)); if(callbackContainer && callbackContainer->mpCallback) { (callbackContainer->mpCallback)(callbackContainer->mpApplicationData, NULL, eventTypeKey, eventTypeString, TRUE); } unlock(); } void SipPublishContentMgr::unpublish(const char* resourceId, const char* eventTypeKey, const char* eventType) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipPublishContentMgr::unpublish resourceId '%s', eventTypeKey '%s', eventType '%s'", resourceId, eventTypeKey, eventType); UtlBoolean resourceIdProvided = resourceId && *resourceId; // Construct the key to look up. UtlString key; if(resourceIdProvided) { key = resourceId; } if(eventTypeKey) { key.append(eventTypeKey); } lock(); // Look up the key in the specific or default entries, as appropriate. PublishContentContainer* container = static_cast ((resourceIdProvided ? mContentEntries : mDefaultContentEntries).find(&key)); // If a container was found, delete it and its contents. if (container) { container->mEventContent.destroyAll(); (resourceIdProvided ? mContentEntries : mDefaultContentEntries).destroy(container); } // Remove any default constructor. if (!resourceIdProvided) { mDefaultContentConstructors.destroy(&key); } // Call the observer for the content change, if any. UtlString eventTypeString(eventType); PublishCallbackContainer* callbackContainer = static_cast (mEventContentCallbacks.find(&eventTypeString)); if(callbackContainer && callbackContainer->mpCallback) { (callbackContainer->mpCallback)(callbackContainer->mpApplicationData, resourceId, eventTypeKey, eventTypeString, !resourceIdProvided); } unlock(); } void SipPublishContentMgr::unpublishDefault(const char* eventTypeKey, const char* eventType) { unpublish(NULL, eventTypeKey, eventType); } UtlBoolean SipPublishContentMgr::setContentChangeObserver(const char* eventType, void* applicationData, SipPublisherContentChangeCallback callbackFunction) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipPublishContentMgr::setContentChangeObserver eventType '%s', callbackFunction %p", eventType, callbackFunction); UtlBoolean callbackSet = FALSE; UtlString eventTypeString(eventType); lock(); // eventTypeKey and eventType must be defined if(eventType == NULL || *eventType == 0) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipPublishContentMgr::setContentChangeObserver ignored, event type not set."); } // There should not be a callback set, need to unset first else if((mEventContentCallbacks.find(&eventTypeString))) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipPublishContentMgr::setContentChangeObserver ignored, callback already exists for event: %s", eventType ? eventType : ""); } else { callbackSet = TRUE; PublishCallbackContainer* callbackEntry = new PublishCallbackContainer(); *((UtlString*)callbackEntry) = eventType; callbackEntry->mpApplicationData = applicationData; callbackEntry->mpCallback = callbackFunction; mEventContentCallbacks.insert(callbackEntry); } unlock(); return(callbackSet); } UtlBoolean SipPublishContentMgr::removeContentChangeObserver(const char* eventType, void*& applicationData, SipPublisherContentChangeCallback& callbackFunction) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipPublishContentMgr::removeContentChangeObserver eventType '%s', callbackFunction %p", eventType, callbackFunction); UtlBoolean callbackRemoved = FALSE; UtlString eventTypeString(eventType); PublishCallbackContainer* callbackEntry = NULL; lock(); // eventType must be defined if(eventType == NULL || *eventType == 0) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipPublishContentMgr::setContentChangeObserver ignored, event type not set."); } // There should not be a callback set, need to unset first else if((callbackEntry = (PublishCallbackContainer*) mEventContentCallbacks.remove(&eventTypeString))) { callbackRemoved = TRUE; callbackFunction = callbackEntry->mpCallback; applicationData = callbackEntry->mpApplicationData; delete callbackEntry; callbackEntry = NULL; } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipPublishContentMgr::setContentChangeObserver ignored, no callback exists for event: %s", eventType ? eventType : ""); } unlock(); return(callbackRemoved); } /* ============================ ACCESSORS ================================= */ UtlBoolean SipPublishContentMgr::getContent(const char* resourceId, const char* eventTypeKey, const char* eventType, const char* acceptHeaderValue, HttpBody*& content, UtlBoolean& isDefaultContent) { #ifdef TEST_PRINT osPrintf("SipPublishContentMgr::getContent(%s, %s, %s, ...)\n", resourceId, eventTypeKey, acceptHeaderValue); #endif UtlBoolean foundContent = FALSE; UtlString key(resourceId); key.append(eventTypeKey); PublishContentContainer* container = NULL; UtlHashMap contentTypes; isDefaultContent = FALSE; UtlBoolean acceptedTypesGiven = buildContentTypesContainer(acceptHeaderValue, contentTypes); lock(); // See if resource specific content exists container = static_cast (mContentEntries.find(&key)); // There is no resource specific content. Check if the default // constructor exists. if(container == NULL) { // Construct the key for the default data. UtlString default_key(eventTypeKey); // Look up the constructor. SipPublishContentMgrDefaultConstructor* constructor = static_cast (mDefaultContentConstructors.findValue(&default_key)); // If it exists, call it to publish content for this resource/event. if (constructor) { constructor->generateDefaultContent(this, resourceId, eventTypeKey, eventType); } // See if resource specific content exists now. container = static_cast (mContentEntries.find(&key)); // If content was found, still mark it as default content. if(container) { isDefaultContent = TRUE; } // If still no content was found, check if the default exists. else { container = static_cast (mDefaultContentEntries.find(&default_key)); if(container) { isDefaultContent = TRUE; } } } if(container) { HttpBody* bodyPtr = NULL; UtlSListIterator contentIterator(container->mEventContent); while((bodyPtr = (HttpBody*)contentIterator())) { // No MIME types specified, take the first one if(!acceptedTypesGiven) { content = HttpBody::copyBody(*bodyPtr); foundContent = TRUE; break; } // Find the first match. The container has the bodies // in the server's preferred order. if(contentTypes.find(bodyPtr)) { content = HttpBody::copyBody(*bodyPtr); foundContent = TRUE; break; } } } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipPublishContentMgr::getContent no container is found for acceptHeaderValue '%s', resourceId '%s', eventTypeKey ='%s', eventType '%s'", acceptHeaderValue ? acceptHeaderValue : "[none]", resourceId ? resourceId : "[none]", eventTypeKey, eventType); } unlock(); contentTypes.destroyAll(); return(foundContent); } void SipPublishContentMgr::getStats(int& numDefaultContent, int& numDefaultConstructor, int& numResourceSpecificContent, int& numCallbacksRegistered) { lock(); numDefaultContent = mDefaultContentEntries.entries(); numDefaultConstructor = mDefaultContentConstructors.entries(); numResourceSpecificContent = mContentEntries.entries(); numCallbacksRegistered = mEventContentCallbacks.entries(); unlock(); } UtlBoolean SipPublishContentMgr::getPublished(const char* resourceId, const char* eventTypeKey, int maxContentTypes, int& numContentTypes, HttpBody* eventContent[], SipPublishContentMgrDefaultConstructor** pDefaultConstructor) { UtlBoolean contentReturned = FALSE; UtlBoolean resourceIdProvided = resourceId && *resourceId; // Construct the key to look up. UtlString key; if(resourceIdProvided) { key = resourceId; } if(eventTypeKey) { key.append(eventTypeKey); } lock(); // Look up the key in the specific or default entries, as appropriate. PublishContentContainer* container = static_cast ((resourceIdProvided ? mContentEntries : mDefaultContentEntries).find(&key)); // If not found, return zero versions. if (container == NULL) { contentReturned = TRUE; numContentTypes = 0; } // The content for this event type exists. else { int num = container->mEventContent.entries(); if(num <= maxContentTypes) { contentReturned = TRUE; numContentTypes = num; // Copy the contents into the array. for (int index = 0; index < num; index++) { eventContent[index] = new HttpBody(*static_cast (container->mEventContent.at(index))); } } } // Return the default constructor, if any. if (pDefaultConstructor) { UtlContainable* defaultConstructor = mDefaultContentConstructors.findValue(&key); *pDefaultConstructor = // Is there a default constructor? defaultConstructor ? // If so, make a copy of the constructor and return pointer to it. (static_cast (defaultConstructor))->copy() : // Otherwise, return NULL. NULL; } unlock(); return contentReturned; } int SipPublishContentMgr::dumpContents(UtlString& dumpString) { int contentCount = 0; dumpString=""; dumpString.appendFormat("Elements: %d\n", mContentEntries.entries()); lock(); UtlString* key = NULL; PublishContentContainer* contentPtr = NULL; UtlHashMapIterator iterator(mContentEntries); while((key = (UtlString*) iterator())) { contentCount++; contentPtr = (PublishContentContainer*) mContentEntries.findValue(key); dumpString.append(*key); dumpString.append("="); if(contentPtr) { dumpString.append(*contentPtr); } dumpString.append('\n'); } unlock(); return(contentCount); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ UtlBoolean SipPublishContentMgr::buildContentTypesContainer(const char* acceptHeaderValue, UtlHashMap& contentTypes) { // TODO: need to parse the comma delimited mime types UtlBoolean containsMimetypes = FALSE; // Parse the accept header value and add a string for each mime type // For each mime type //while(mimeType = parsed from acceptHeaderValue) //{ // Add a string to the list to contain the MIME type // contentTypes.insert(new UtlString(mimeType)); // containsMimetypes = TRUE; //} return(containsMimetypes); } void SipPublishContentMgr::lock() { mPublishMgrMutex.acquire(); } void SipPublishContentMgr::unlock() { mPublishMgrMutex.release(); } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipPublishServer.cpp0000644000175000017500000003730212205613256025154 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include #include // Private class to contain event type and event specific utilities class PublishServerEventData : public UtlString { public: PublishServerEventData(); virtual ~PublishServerEventData(); // Parent UtlString contains the eventType SipPublishServerEventStateCompositor* mpEventSpecificStateCompositor; SipUserAgent* mpEventSpecificUserAgent; SipPublishServerEventStateMgr* mpEventSpecificStateMgr; private: //! DISALLOWED accidental copying PublishServerEventData(const PublishServerEventData& rPublishServerEventData); PublishServerEventData& operator=(const PublishServerEventData& rhs); }; PublishServerEventData::PublishServerEventData() { mpEventSpecificStateCompositor = NULL; mpEventSpecificUserAgent = NULL; mpEventSpecificStateMgr = NULL; } PublishServerEventData::~PublishServerEventData() { } // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ SipPublishServer* SipPublishServer::buildBasicServer(SipUserAgent& userAgent, const char* eventType) { SipPublishServer* newServer = NULL; // Create a default event state compositor SipPublishServerEventStateCompositor* eventStateCompositor = new SipPublishServerEventStateCompositor(); // Create a default event state manager SipPublishServerEventStateMgr* eventStateMgr = new SipPublishServerEventStateMgr(); newServer = new SipPublishServer(userAgent, *eventStateMgr, *eventStateCompositor); // Enable the server to accept the given SIP event package newServer->enableEventType(eventType, &userAgent, eventStateMgr, eventStateCompositor); return(newServer); } // Constructor SipPublishServer::SipPublishServer(SipUserAgent& defaultUserAgent, SipPublishServerEventStateMgr& defaultEventStateMgr, SipPublishServerEventStateCompositor& defaultEventStateCompositor) : mPublishServerMutex(OsMutex::Q_FIFO) { mpDefaultUserAgent = &defaultUserAgent; mpDefaultEventStateMgr = &defaultEventStateMgr; mpDefaultCompositor = &defaultEventStateCompositor; } // Copy constructor NOT IMPLEMENTED SipPublishServer::SipPublishServer(const SipPublishServer& rSipPublishServer) : mPublishServerMutex(OsMutex::Q_FIFO) { } // Destructor SipPublishServer::~SipPublishServer() { // Iterate through and delete all the event data // TODO: } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipPublishServer& SipPublishServer::operator=(const SipPublishServer& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } UtlBoolean SipPublishServer::enableEventType(const char* eventTypeToken, SipUserAgent* userAgent, SipPublishServerEventStateMgr* eventStateMgr, SipPublishServerEventStateCompositor* eventStateCompositor) { UtlBoolean addedEvent = FALSE; UtlString eventName(eventTypeToken ? eventTypeToken : ""); lockForWrite(); // Only add the event support if it does not already exist; PublishServerEventData* eventData = (PublishServerEventData*) mEventDefinitions.find(&eventName); if(!eventData) { addedEvent = TRUE; eventData = new PublishServerEventData(); *((UtlString*)eventData) = eventName; eventData->mpEventSpecificUserAgent = userAgent ? userAgent : mpDefaultUserAgent; eventData->mpEventSpecificStateCompositor = eventStateCompositor ? eventStateCompositor : mpDefaultCompositor; eventData->mpEventSpecificStateMgr = eventStateMgr ? eventStateMgr : mpDefaultEventStateMgr; mEventDefinitions.insert(eventData); // Register an interest in PUBLISH requests for this event type eventData->mpEventSpecificUserAgent->addMessageObserver(*(getMessageQueue()), SIP_PUBLISH_METHOD, TRUE, // requests FALSE, // not reponses TRUE, // incoming FALSE, // no outgoing eventName, NULL, NULL); } unlockForWrite(); return(addedEvent); } UtlBoolean SipPublishServer::disableEventType(const char* eventTypeToken, SipUserAgent*& userAgent, SipPublishServerEventStateMgr*& eventStateMgr, SipPublishServerEventStateCompositor*& eventStateCompositor) { UtlBoolean removedEvent = FALSE; UtlString eventName(eventTypeToken ? eventTypeToken : ""); lockForWrite(); // Only add the event support if it does not already exist; PublishServerEventData* eventData = (PublishServerEventData*) mEventDefinitions.remove(&eventName); if(eventData) { removedEvent = TRUE; userAgent = eventData->mpEventSpecificUserAgent == mpDefaultUserAgent ? NULL : eventData->mpEventSpecificUserAgent; eventStateCompositor = eventData->mpEventSpecificStateCompositor == mpDefaultCompositor ? NULL : eventData->mpEventSpecificStateCompositor; eventStateMgr = eventData->mpEventSpecificStateMgr == mpDefaultEventStateMgr ? NULL : eventData->mpEventSpecificStateMgr; // Unregister interest in PUBLISH requests for this event type eventData->mpEventSpecificUserAgent->removeMessageObserver(*(getMessageQueue())); delete eventData; eventData = NULL; } else { userAgent = NULL; eventStateCompositor = NULL; eventStateMgr = NULL; } unlockForWrite(); return(removedEvent); } UtlBoolean SipPublishServer::handleMessage(OsMsg &eventMessage) { int msgType = eventMessage.getMsgType(); int msgSubType = eventMessage.getMsgSubType(); // SIP message if(msgType == OsMsg::PHONE_APP && msgSubType == SipMessage::NET_SIP_MESSAGE) { const SipMessage* sipMessage = ((SipMessageEvent&)eventMessage).getMessage(); UtlString method; if(sipMessage) { sipMessage->getCSeqField(NULL, &method); } // PUBLISH requests if(sipMessage && !sipMessage->isResponse() && method.compareTo(SIP_PUBLISH_METHOD) == 0) { handlePublish(*sipMessage); } } return(TRUE); } /* ============================ ACCESSORS ================================= */ SipPublishServerEventStateCompositor* SipPublishServer::getEventStateCompositor(const UtlString& eventType) { SipPublishServerEventStateCompositor* eventStateCompositor = NULL; lockForRead(); PublishServerEventData* eventData = (PublishServerEventData*) mEventDefinitions.find(&eventType); if(eventData) { eventStateCompositor = eventData->mpEventSpecificStateCompositor; } else { eventStateCompositor = mpDefaultCompositor; } unlockForRead(); return(eventStateCompositor); } SipPublishServerEventStateMgr* SipPublishServer::getEventStateMgr(const UtlString& eventType) { SipPublishServerEventStateMgr* eventStateMgr = NULL; lockForRead(); PublishServerEventData* eventData = (PublishServerEventData*) mEventDefinitions.find(&eventType); if(eventData) { eventStateMgr = eventData->mpEventSpecificStateMgr; } else { eventStateMgr = mpDefaultEventStateMgr; } unlockForRead(); return(eventStateMgr); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ UtlBoolean SipPublishServer::handlePublish(const SipMessage& publishRequest) { UtlBoolean handledPublish = FALSE; UtlString eventName; publishRequest.getEventField(&eventName, NULL); // Not modifying the PublishServerEventData, just reading it lockForRead(); // Get the event specific handler and information PublishServerEventData* eventPackageInfo = (PublishServerEventData*) mEventDefinitions.find(&eventName); // We handle this event type if(eventPackageInfo) { handledPublish = TRUE; UtlString resourceId; UtlString eventTypeKey; SipPublishServerEventStateCompositor* compositor = eventPackageInfo->mpEventSpecificStateCompositor; // Get the keys used to identify the event state content compositor->getKeys(publishRequest, resourceId, eventTypeKey); SipMessage publishResponse; // Check if authenticated (or if it needs to be authenticated) if(compositor->isAuthenticated(publishRequest, resourceId, eventTypeKey, publishResponse)) { // Check if authorized (or if authorization is required) if(compositor->isAuthorized(publishRequest, resourceId, eventTypeKey, publishResponse)) { // The publication is allowed, so process the PUBLISH request // Modify the expiration if neccessary int expiration; if (publishRequest.getExpiresField(&expiration)) { // Check whether the expiration is too brief if (!eventPackageInfo->mpEventSpecificStateMgr->checkExpiration(&expiration)) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipPublishServer::handlePublish interval too brief"); publishResponse.setResponseData(&publishRequest, SIP_TOO_BRIEF_CODE, SIP_TOO_BRIEF_TEXT); publishResponse.setMinExpiresField(expiration); mpDefaultUserAgent->send(publishResponse); unlockForRead(); return(handledPublish); } } // Generate a new entity tag UtlString entity; eventPackageInfo->mpEventSpecificStateMgr->generateETag(entity); UtlString sipIfMatchField; if (publishRequest.getSipIfMatchField(sipIfMatchField)) { // Check whether the SIP-If-Match header matches with an existing one if (eventPackageInfo->mpEventSpecificStateMgr->publishExists(sipIfMatchField)) { if (expiration == 0) { // Remove the publication eventPackageInfo->mpEventSpecificStateMgr->removePublish(sipIfMatchField); } else { // Update the publication eventPackageInfo->mpEventSpecificStateMgr->updatePublish(sipIfMatchField, entity, resourceId, eventTypeKey, expiration); } } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipPublishServer::handlePublish interval too brief"); publishResponse.setResponseData(&publishRequest, SIP_CONDITIONAL_REQUEST_FAILED_CODE, SIP_CONDITIONAL_REQUEST_FAILED_TEXT); mpDefaultUserAgent->send(publishResponse); unlockForRead(); return(handledPublish); } } else { // Initial publish eventPackageInfo->mpEventSpecificStateMgr->addPublish(entity, resourceId, eventTypeKey, expiration); } publishResponse.setResponseData(&publishRequest, SIP_ACCEPTED_CODE, SIP_ACCEPTED_TEXT); publishResponse.setExpiresField(expiration); // Send the response ASAP to minimize resend handling of request eventPackageInfo->mpEventSpecificUserAgent->send(publishResponse); } // Not authorized else { // Send the response eventPackageInfo->mpEventSpecificUserAgent->send(publishResponse); } } // Not authenticated else { // Send the response eventPackageInfo->mpEventSpecificUserAgent->send(publishResponse); } } // We should not have received SUBSCRIBE requests for this event type // This event type has not been enabled in this SubscribeServer else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipPublishServer::handlePublish event type: %s not enabled", eventName.data()); SipMessage eventTypeNotHandled; eventTypeNotHandled.setResponseData(&publishRequest, SIP_BAD_EVENT_CODE, SIP_BAD_EVENT_TEXT); mpDefaultUserAgent->send(eventTypeNotHandled); } unlockForRead(); return(handledPublish); } void SipPublishServer::lockForRead() { mPublishServerMutex.acquireRead(); } void SipPublishServer::unlockForRead() { mPublishServerMutex.releaseRead(); } void SipPublishServer::lockForWrite() { mPublishServerMutex.acquireWrite(); } void SipPublishServer::unlockForWrite() { mPublishServerMutex.releaseWrite(); } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipPublishServerEventStateCompositor.cpp0000644000175000017500000000611712205613256031236 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include // Constructor SipPublishServerEventStateCompositor::SipPublishServerEventStateCompositor() { } // Copy constructor NOT IMPLEMENTED SipPublishServerEventStateCompositor::SipPublishServerEventStateCompositor(const SipPublishServerEventStateCompositor& rSipPublishServerEventStateCompositor) { } // Destructor SipPublishServerEventStateCompositor::~SipPublishServerEventStateCompositor() { // Iterate through and delete all the dialogs // TODO: } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipPublishServerEventStateCompositor& SipPublishServerEventStateCompositor::operator=(const SipPublishServerEventStateCompositor& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } UtlBoolean SipPublishServerEventStateCompositor::getKeys(const SipMessage& publishRequest, UtlString& resourceId, UtlString& eventTypeKey) { // default resourceId is the identity UtlString uriString; publishRequest.getRequestUri(&uriString); Url uri(uriString); uri.getIdentity(resourceId); // Default event key is the event type with no parameters publishRequest.getEventField(&eventTypeKey, NULL); return(TRUE); } UtlBoolean SipPublishServerEventStateCompositor::isAuthenticated(const SipMessage& publishRequest, const UtlString& resourceId, const UtlString& eventTypeKey, SipMessage& subscribeResponse) { // By default no authentication required return(TRUE); } UtlBoolean SipPublishServerEventStateCompositor::isAuthorized(const SipMessage& publishRequest, const UtlString& resourceId, const UtlString& eventTypeKey, SipMessage& subscribeResponse) { // By default no authorization required return(TRUE); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipPublishServerEventStateMgr.cpp0000644000175000017500000001414312205613256027623 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include #include // Private class to contain callback for eventTypeKey class PublishServerEventState : public UtlString { public: PublishServerEventState(); virtual ~PublishServerEventState(); // Parent UtlString contains the dialog handle UtlString mResourceId; UtlString mEventTypeKey; UtlString mEntityTagValue; long mExpirationDate; // epoch time OsTimer* mpExpirationTimer; private: //! DISALLOWED accidental copying PublishServerEventState(const PublishServerEventState& rPublishServerEventState); PublishServerEventState& operator=(const PublishServerEventState& rhs); }; // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ PublishServerEventState::PublishServerEventState() { mExpirationDate = -1; mEntityTagValue = NULL; mpExpirationTimer = NULL; } PublishServerEventState::~PublishServerEventState() { if(mpExpirationTimer) { // Timer should have been stopped and the the task upon // which the fired timer queues its message need to have // synchronized to make sure it does not get touched after // it is deleted here. delete mpExpirationTimer; mpExpirationTimer = NULL; } } // Constructor SipPublishServerEventStateMgr::SipPublishServerEventStateMgr() : mEventStateMgrMutex(OsMutex::Q_FIFO) { mMinExpiration = 32; mDefaultExpiration = 3600; mMaxExpiration = 86400; } // Copy constructor NOT IMPLEMENTED SipPublishServerEventStateMgr::SipPublishServerEventStateMgr(const SipPublishServerEventStateMgr& rSipPublishServerEventStateMgr) : mEventStateMgrMutex(OsMutex::Q_FIFO) { } // Destructor SipPublishServerEventStateMgr::~SipPublishServerEventStateMgr() { // Iterate through and delete all the dialogs // TODO: } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipPublishServerEventStateMgr& SipPublishServerEventStateMgr::operator=(const SipPublishServerEventStateMgr& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } void SipPublishServerEventStateMgr::generateETag(UtlString& entity) { } void SipPublishServerEventStateMgr::addPublish(UtlString& entity, UtlString& resourceId, UtlString& eventTypeKey, int expiration) { } void SipPublishServerEventStateMgr::updatePublish(UtlString& oldEntity, UtlString& entity, UtlString& resourceId, UtlString& eventTypeKey, int expiration) { } void SipPublishServerEventStateMgr::removePublish(UtlString& entity) { } void SipPublishServerEventStateMgr::removeOldPublication(long oldEpochTimeSeconds) { lock(); #if 0 UtlHashBagIterator iterator(mSubscriptionStateResourceIndex); PublishServerEventStateIndex* stateIndex = NULL; while((stateIndex = (PublishServerEventStateIndex*) iterator())) { if(stateIndex->mpState) { if(stateIndex->mpState->mExpirationDate < oldEpochTimeSeconds) { mpDialogMgr->deleteDialog(*(stateIndex->mpState)); mSubscriptionStatesByDialogHandle.removeReference(stateIndex->mpState); delete stateIndex->mpState; stateIndex->mpState = NULL; mSubscriptionStateResourceIndex.removeReference(stateIndex); delete stateIndex; } } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipPublishServerEventStateMgr::removeOldSubscriptions PublishServerEventStateIndex with NULL mpState, deleting"); mSubscriptionStateResourceIndex.removeReference(stateIndex); delete stateIndex; } } #endif unlock(); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ UtlBoolean SipPublishServerEventStateMgr::publishExists(UtlString& entityTag) { UtlBoolean publishFound = FALSE; lock(); PublishServerEventState* state = (PublishServerEventState*) mEventStatesByEntityTag.find(&entityTag); if(state) { publishFound = TRUE; } unlock(); return(publishFound); } UtlBoolean SipPublishServerEventStateMgr::isExpired(UtlString& entityTag) { UtlBoolean publishExpired = TRUE; lock(); PublishServerEventState* state = (PublishServerEventState*) mEventStatesByEntityTag.find(&entityTag); if(state) { long now = OsDateTime::getSecsSinceEpoch(); if(now <= state->mExpirationDate) { publishExpired = FALSE; } } unlock(); return(publishExpired); } UtlBoolean SipPublishServerEventStateMgr::checkExpiration(int* expiration) { return 0; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ void SipPublishServerEventStateMgr::lock() { mEventStateMgrMutex.acquire(); } void SipPublishServerEventStateMgr::unlock() { mEventStateMgrMutex.release(); } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipRefreshMgr.cpp0000644000175000017500000022342112205613256024422 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #if defined(_VXWORKS) #include #include #endif #include #include "os/OsStatus.h" #include "os/OsConfigDb.h" #include "os/OsEventMsg.h" #include "os/OsLock.h" #include "os/OsDateTime.h" #include "os/OsQueuedEvent.h" #include "os/OsTimer.h" #include "os/OsRWMutex.h" #include "os/OsReadLock.h" #include "os/OsWriteLock.h" #include "net/SipLine.h" #include "net/SipLineMgr.h" #include "net/SipRefreshMgr.h" #include "net/SipMessageEvent.h" #include "utl/UtlNameValueTokenizer.h" #include "net/SipObserverCriteria.h" #include "net/Url.h" #include "net/SipUserAgent.h" #include "utl/UtlTokenizer.h" #include "net/TapiMgr.h" #define UNREGISTER_CSEQ_NUMBER 2146483648 // 2^31 - 1,000,000 #define MIN_REFRESH_TIME_SECS 20 // Floor for re-subscribes/re-registers //#define REMOVE_TO_TAG_IN_REREGISTER // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // #define TEST_PRINT 1 ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// SipRefreshMgr::SipRefreshMgr(): OsServerTask("SipRefreshMgr-%d"), mpLineMgr(NULL), mpLastLineEventMap(NULL), mRegisterListMutexR(OsRWMutex::Q_FIFO), mRegisterListMutexW(OsRWMutex::Q_FIFO), mSubscribeListMutexR(OsRWMutex::Q_FIFO), mSubscribeListMutexW(OsRWMutex::Q_FIFO), mIsStarted(FALSE), mObserverMutex(OsRWMutex::Q_FIFO), mUAReadyMutex(OsRWMutex::Q_FIFO), mMyUserAgent(NULL) { } SipRefreshMgr::~SipRefreshMgr() { waitUntilShutDown(); if (mpLastLineEventMap) { mpLastLineEventMap->destroyAll() ; delete mpLastLineEventMap ; } UtlHashBagIterator itor(mMessageObservers) ; while (SipObserverCriteria* pObserver = (SipObserverCriteria*) itor()) { mMessageObservers.remove(pObserver) ; delete pObserver ; } // delete all unfired timers and their SipMessages UtlHashBagIterator timerIterator(mTimerBag) ; while (OsTimer* pTimer = (OsTimer*) timerIterator()) { OsQueuedEvent *pEvent = (OsQueuedEvent*)pTimer->getNotifier(); intptr_t userData; pEvent->getUserData(userData); SipMessage *pMessage = (SipMessage *)userData; // get rid of them delete pMessage; delete pTimer; } mTimerBag.removeAll(); } /*===================================================================*/ //INITIALIZED /*===================================================================*/ UtlBoolean SipRefreshMgr::init( SipUserAgent *ptrToMyAgent, int sipTcpPort, int sipUdpPort, const char* defaultUser, const char* publicAddress, const char* defaultAddress, const char* sipDirectoryServers, const char* sipRegistryServers, int defaultRegistryTimeout, int defaultSubscribeTimeout, int restartCount, const char* macAddress ) { if ( ptrToMyAgent != NULL ) { mMyUserAgent = ptrToMyAgent; //set default paremeters mTcpPort = sipTcpPort; mUdpPort = sipUdpPort; if ( defaultAddress ) mDefaultSipAddress.append( defaultAddress ); if ( publicAddress && *publicAddress ) mSipIpAddress.append( publicAddress ); else OsSocket::getHostIp( &mSipIpAddress ); if ( sipRegistryServers ) mRegistryServer.append(sipRegistryServers); if ( defaultUser && *defaultUser ) mDefaultUser.append(defaultUser); if ( macAddress && *macAddress ) mMacAddress.append(macAddress); // defaultRegistryTimeout is 1 hr if ( defaultRegistryTimeout <= 0 ) mDefaultRegistryPeriod = 3600; else mDefaultRegistryPeriod = defaultRegistryTimeout; // defaultSubscribeTimeout is 24 hr if ( defaultSubscribeTimeout <= 0 ) mDefaultSubscribePeriod = 60*60*24; else mDefaultSubscribePeriod = defaultSubscribeTimeout; mRestartCount = restartCount; char strCount[64]; sprintf( strCount, "%d", mRestartCount ); mRestartCountStr.append( strCount ); return true; } else { osPrintf("ERROR:SipRefreshMgr::Init: NULL SipUserAgent\n"); return false; } } void SipRefreshMgr::StartRefreshMgr() { if ( !isStarted() ) { // start the thread start(); } OsMsg StartMsg( OsMsg::REFRESH_MSG, SipRefreshMgr::START_REFRESH_MGR ); postMessage(StartMsg); #ifdef TEST_PRINT osPrintf("SipRefreshMgr: End of constructor\n"); #endif } void SipRefreshMgr::waitForUA() { #ifdef TEST_PRINT osPrintf("SipRefreshMgr::waitForUA - Start\n"); #endif OsLock lock( mUAReadyMutex ); // wait for the UA to start and get the NAT address mMyUserAgent->waitUntilReady(); // Bob 2/10/03: Ideally, we would only listen for requests and responses, // but not incoming messages. // // However, we don't seem to receive transport errors caused by no // udp/tcp user agent at the target (nobody home). So, we need to // add an incoming messages listener. // // NOTE: Not adding a response listener doesn't work either. It seems // that we miss some auth events. // mMyUserAgent->addMessageObserver( *(this->getMessageQueue()), SIP_REGISTER_METHOD, TRUE, // want to get requests TRUE, // want to get responses TRUE, // Incoming messages FALSE); // Don't want to see out going messages mMyUserAgent->addMessageObserver( *(this->getMessageQueue()), SIP_SUBSCRIBE_METHOD, TRUE, // want to get requests TRUE, // want to get responses TRUE, // Incoming messages FALSE); // Don't want to see out going messages // register all lines reRegisterAll(); // subscribe to all subscriptions, MWI, CONFIG SERVER etc. reSubscribeAll(); mIsStarted = TRUE; #ifdef TEST_PRINT osPrintf("SipRefreshMgr::waitForUA - End\n"); #endif } UtlBoolean SipRefreshMgr::isUAStarted() { OsLock lock(mUAReadyMutex); return(mIsStarted); } void SipRefreshMgr::addMessageConsumer( OsServerTask* messageEventListener ) { // Need to do the real thing by keeping a list of consumers // and putting a mutex around the add to list //if(messageListener) //{ // osPrintf("WARNING: message consumer is NOT a LIST\n"); //} //messageListener = messageEventListener; if ( messageEventListener ) { addMessageObserver( *(messageEventListener->getMessageQueue())); } } void SipRefreshMgr::addMessageObserver ( OsMsgQ& messageQueue, const char* sipMethod, UtlBoolean wantRequests, UtlBoolean wantResponses, UtlBoolean wantIncoming, UtlBoolean wantOutGoing, const char* eventName, void* observerData) { SipObserverCriteria* observer = new SipObserverCriteria( observerData, &messageQueue, sipMethod, wantRequests, wantResponses, wantIncoming, wantOutGoing, eventName ); { // Add the observer and its filter criteria to the list lock scope OsWriteLock lock(mObserverMutex); mMessageObservers.insert(observer); } } /*===================================================================*/ //REGISTER /*===================================================================*/ UtlBoolean SipRefreshMgr::newRegisterMsg( const Url& fromUrl, const UtlString& lineId, int registryPeriodSeconds, Url* pPreferredContactUri) { if ( !isDuplicateRegister( fromUrl ) ) { syslog(FAC_REFRESH_MGR, PRI_DEBUG, "adding registration:\nurl=%s\nlineid=%s\nperiod=%d", fromUrl.toString().data(), lineId.data(), registryPeriodSeconds) ; Url uri = fromUrl; uri.setDisplayName(""); uri.setUserId(""); //generate Call Id UtlString registerCallId; generateCallId( fromUrl.toString(), SIP_REGISTER_METHOD, registerCallId ); UtlString contactField; getContactField( fromUrl, contactField, lineId, pPreferredContactUri); registerUrl(fromUrl.toString(), // from fromUrl.toString(), // to uri.toString(), contactField.data(), registerCallId, registryPeriodSeconds); return true; } else { syslog(FAC_REFRESH_MGR, PRI_ERR, "unable to add new registration (dup):\nurl=%s\nlineid=%s\nperiod=%d", fromUrl.toString().data(), lineId.data(), registryPeriodSeconds) ; } return false; } /*---------------------------------------------------*/ void SipRefreshMgr::getFromAddress( UtlString* address, int* port, UtlString* protocol ) { UtlTokenizer tokenizer(mRegistryServer); UtlString regServer; tokenizer.next(regServer, ","); SipMessage::parseAddressFromUri(regServer.data(), address, port, protocol); if ( address->isNull() ) { protocol->remove(0); // TCP only if ( portIsValid(mTcpPort) && !portIsValid(mUdpPort) ) { protocol->append(SIP_TRANSPORT_TCP); *port = mTcpPort; } // UDP only else if ( portIsValid(mUdpPort) && !portIsValid(mTcpPort) ) { protocol->append(SIP_TRANSPORT_UDP); *port = mUdpPort; } // TCP & UDP on non-standard port else if ( mTcpPort != SIP_PORT ) { *port = mTcpPort; } // TCP & UDP on standard port else { *port = PORT_NONE; } // If there is an address configured use it UtlNameValueTokenizer::getSubField(mDefaultSipAddress.data(), 0, ", \t", address); // else use the local host ip address if ( address->isNull() ) { address->append(mSipIpAddress); } } }/*---------------------------------------------------*/ void SipRefreshMgr::reRegisterAll() { SipMessageList tempList; SipMessage* listMessage; int iteratorHandle; #ifdef TEST_PRINT osPrintf("SipRefreshMgr::reRegisterAll start \n"); #endif //scope the locks { OsReadLock readlock(mRegisterListMutexR); OsWriteLock writeLock(mRegisterListMutexW); iteratorHandle = mRegisterList.getIterator(); while ((listMessage = (SipMessage*) mRegisterList.getSipMessageForIndex(iteratorHandle))) { //somehow stop the old timer - will get not cause harm because will not be able to find corresponding request. tempList.add(listMessage); } mRegisterList.releaseIterator(iteratorHandle); } iteratorHandle = tempList.getIterator(); while ((listMessage = (SipMessage*) tempList.getSipMessageForIndex(iteratorHandle))) { rescheduleRequest(listMessage, 1 , SIP_REGISTER_METHOD, DEFAULT_PERCENTAGE_TIMEOUT, TRUE); } tempList.releaseIterator(iteratorHandle); // We need to empty the list before the Implicit destructor deletes // the "members" and the list. // iteratorHandle = tempList.getIterator(); while (tempList.getSipMessageForIndex(iteratorHandle)) { tempList.remove(iteratorHandle); } tempList.releaseIterator(iteratorHandle); } /*---------------------------------------------------*/ void SipRefreshMgr::reRegister( const Url& fromUrl) { SipMessage *oldMsg = mRegisterList.isSameFrom( fromUrl); if ( oldMsg ) { SipMessage newMsg(*oldMsg); newMsg.incrementCSeqNumber(); // Clear the DNS field, so that we retry DNS-SRV before resending. // This should be performed for all failure cases, except for // auth challenges newMsg.clearDNSField() ; newMsg.resetTransport() ; addToRegisterList(&newMsg); if (sendRequest(newMsg , SIP_REGISTER_METHOD) != OS_SUCCESS) { removeFromRegisterList(&newMsg); } } } /*---------------------------------------------------*/ void SipRefreshMgr::unRegisterUser ( const Url& fromUrl, const UtlBoolean& onStartup, const UtlString& lineId ) { if ( onStartup ) { Url Uri = fromUrl; Uri.setDisplayName(""); Uri.setUserId(""); //generate Call Id UtlString registerCallId; generateCallId(fromUrl.toString(),SIP_REGISTER_METHOD, registerCallId, TRUE); SipMessage* regMessage = new SipMessage(); UtlString contactField; getContactField( fromUrl, contactField, lineId ); UtlString fromField(fromUrl.toString()); UtlString toField(fromField); //add Tag to from field UtlString tagNamevaluePair ; createTagNameValuePair(tagNamevaluePair); fromField.append(";"); fromField.append(tagNamevaluePair); Url contact(contactField); contact.setFieldParameter(SIP_EXPIRES_FIELD,"0"); regMessage->setRegisterData(fromField.data(), // from toField.data(), // to Uri.toString(), // uri contact.toString().data(), // contact registerCallId.data(), UNREGISTER_CSEQ_NUMBER, 0); regMessage->removeHeader(SIP_EXPIRES_FIELD,0); if (sendRequest(*regMessage , SIP_REGISTER_METHOD) != OS_SUCCESS) { removeFromRegisterList(regMessage); // delete regMessage; - wdn - fix leaks later !!! } } else { SipMessage sipMsg; if ( isDuplicateRegister(fromUrl, sipMsg) ) { Url Uri = fromUrl; //dont set a common expires - then you need to send * in contact field //sipMsg.setExpiresField(0); UtlString contactField; sipMsg.getContactField(0,contactField); Url contact(contactField); contact.setFieldParameter(SIP_EXPIRES_FIELD,"0"); sipMsg.setContactField(contact.toString()); sipMsg.removeHeader(SIP_EXPIRES_FIELD,0); UtlString localIp; int localPort; SIPX_TRANSPORT_TYPE protocol = TRANSPORT_UDP; UtlString fromString; fromUrl.toString(fromString); if (fromString.contains("sips:") || fromString.contains("transport=tls")) { protocol = TRANSPORT_TLS; } else if (fromString.contains("transport=tcp")) { protocol = TRANSPORT_TCP; } mMyUserAgent->getLocalAddress(&localIp, &localPort, protocol); sipMsg.setLocalIp(localIp); fireSipXLineEvent(Uri, lineId.data(), LINESTATE_UNREGISTERING, LINESTATE_UNREGISTERING_NORMAL); // clear out any pending register requests removeAllFromRequestList(&sipMsg); sendRequest(sipMsg, SIP_REGISTER_METHOD); addToRegisterList(&sipMsg); } } } UtlBoolean SipRefreshMgr::isDuplicateRegister ( const Url& fromUrl, SipMessage &oldMsg ) { OsReadLock readlock(mRegisterListMutexR); OsWriteLock writeLock(mRegisterListMutexW); // call copy constructor on the oldMsg SipMessage* pduplicate = mRegisterList.isSameFrom(fromUrl); if ( pduplicate != NULL ) { oldMsg = *pduplicate; return true; } return false; } UtlBoolean SipRefreshMgr::isDuplicateRegister( const Url& fromUrl ) { OsReadLock readlock( mRegisterListMutexR ); OsWriteLock writeLock( mRegisterListMutexW ); SipMessage* oldMsg = mRegisterList.isSameFrom( fromUrl ); if ( oldMsg != NULL ) return true; return false; } OsStatus SipRefreshMgr::sendRequest ( SipMessage& request, const char* method ) { OsStatus retval = OS_UNSPECIFIED ; // Sucess of operation UtlString methodName(method) ; // Method name fo request int refreshPeriod = -1 ; // Refresh period used when resubscribing UtlBoolean bIsUnregOrUnsub ; // Is this an unregister or unsubscribe? // Reset the transport data and the via fields #ifdef REMOVE_TO_TAG_IN_REREGISTER UtlString requestMethod; request.getRequestMethod(&requestMethod); if(requestMethod.compareTo(SIP_REGISTER_METHOD) == 0) { request.removeToFieldTag(); } #endif request.resetTransport(); request.removeLastVia(); request.setDateField(); bIsUnregOrUnsub = isExpiresZero(&request) ; #ifdef TEST_PRINT { UtlString method2 ; int cseq ; UtlString callId ; request.getCSeqField(&cseq, &method2) ; request.getCallIdField(&callId) ; if ( method2.compareTo(SIP_REGISTER_METHOD) == 0 ) { osPrintf("** sendRequest cseq=%d, method=%s, callId=%s\n", cseq, method2.data(), callId.data()) ; mRegisterList.printDebugTable() ; } } #endif // Keep a copy for reschedule UtlString localIp; int localPort; SIPX_TRANSPORT_TYPE protocol = TRANSPORT_UDP; UtlString toField; request.getToField(&toField); if (toField.contains("sips:") || toField.contains("transport=tls")) { protocol = TRANSPORT_TLS; } if (toField.contains("transport=tcp")) { protocol = TRANSPORT_TCP; } mMyUserAgent->getLocalAddress(&localIp, &localPort, protocol); request.setLocalIp(localIp); if ( !mMyUserAgent->send( request, getMessageQueue() ) ) { UtlString toField ; request.getToField(&toField) ; syslog(FAC_REFRESH_MGR, PRI_ERR, "unable to send %s message (send failed):\nto: %s", method, toField.data()) ; UtlString tmpMethod; Url url; UtlString lineId; request.getToUrl(url); url.getIdentity(lineId); lineId = "sip:" + lineId; if ( methodName.compareTo(SIP_REGISTER_METHOD) == 0 && !isExpiresZero(&request)) { if (getLineMgr()) { mpLineMgr->setStateForLine(url, SipLine::LINE_STATE_FAILED); } fireSipXLineEvent(url, lineId.data(), LINESTATE_REGISTER_FAILED, LINESTATE_REGISTER_FAILED_COULD_NOT_CONNECT); rescheduleAfterTime(&request, FAILED_PERCENTAGE_TIMEOUT); } else if ( methodName.compareTo(SIP_REGISTER_METHOD) == 0 && isExpiresZero(&request)) { fireSipXLineEvent(url, lineId.data(), LINESTATE_UNREGISTER_FAILED, LINESTATE_UNREGISTER_FAILED_COULD_NOT_CONNECT); } // @JC Added Comments: create a message on the queue with a quarter // lease period timeout if the timer triggers and we've not received // a good response from the server within FAILED_PERCENTAGE_TIMEOUT // secs resubscribe SipMessage* message = new SipMessage( request ); if (!message) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipRefreshMgr::sendRequest failed to allocate new SipMessage"); OsSysLog::flush(); assert(0); } if ( request.getResponseListenerData() ) { message->setResponseListenerData( request.getResponseListenerData() ); } // Report error to observers SipMessageEvent eventMsg( message ); eventMsg.setMessageStatus( SipMessageEvent::TRANSPORT_ERROR ); message = NULL; sendToObservers( eventMsg, &request ); } else { int sequenceNum = 0; UtlString tmpMethod; request.getCSeqField(&sequenceNum, &tmpMethod); Url url; UtlString lineId; request.getToUrl(url); url.getIdentity(lineId); lineId = "sip:" + lineId; if ( methodName.compareTo(SIP_REGISTER_METHOD) == 0 && !isExpiresZero(&request)) { fireSipXLineEvent(url, lineId.data(), LINESTATE_REGISTERING, LINESTATE_REGISTERING_NORMAL); } else if ( methodName.compareTo(SIP_REGISTER_METHOD) == 0 && isExpiresZero(&request)) { } retval = OS_SUCCESS; } return retval; } void SipRefreshMgr::rescheduleRequest( SipMessage* request, int secondsFromNow, const char *method, int percentage, UtlBoolean sendImmediate) { UtlString seqMethod; SipMessage* listMessage = NULL; UtlString methodStr(method); int defaultTime = -1; //set according to the requested method to default UtlString lineId; // Log reschedule attempt syslog(FAC_REFRESH_MGR, PRI_DEBUG, "rescheduling %s request:\nsecs=%d\npercent=%d\nsendNow=%d", method, secondsFromNow, percentage, sendImmediate) ; if (!request) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipRefreshMgr::rescheduleRequest null request"); OsSysLog::flush(); assert(0); } if ( methodStr.compareTo(SIP_REGISTER_METHOD) == 0 ) { OsReadLock readlock(mRegisterListMutexR); listMessage = mRegisterList.getDuplicate(request); // May not have a To tag set in the list because it was sent the first time if ( !listMessage ) { UtlString fromUri; request->getFromUri(&fromUri); Url uri(fromUri); uri.removeAngleBrackets(); if ( !fromUri.isNull() ) { SipMessage sipMsg; if ( isDuplicateRegister(uri, sipMsg) ) { listMessage = mRegisterList.getDuplicate(&sipMsg); } } } defaultTime = mDefaultRegistryPeriod; } else // Subscribe { OsReadLock readlock(mSubscribeListMutexR); listMessage = mSubscribeList.getDuplicate(request); // May not have a To tag set in the list because it was sent the first time if ( !listMessage ) { UtlString fromUri; request->getFromUri(&fromUri); Url uri(fromUri); uri.removeAngleBrackets(); if ( !fromUri.isNull() ) { SipMessage sipMsg; if ( isDuplicateSubscribe(uri, sipMsg) ) { listMessage = mSubscribeList.getDuplicate(&sipMsg); } } } defaultTime = mDefaultSubscribePeriod; } // if it is an immediate send then it is either a re-register or unregister // The Request has already incremented CSEQ number is that case so don't // increment, but increase the number only to the message that is added // to the list because that will be used for next timer register in case // of re-register in case of unregister, the message will be deleted from // the list upon getting a response if ( !sendImmediate ) { request->incrementCSeqNumber(); // Clear the DNS field, so that we retry DNS-SRV before resending. // This should be performed for all failure cases, except for // auth challenges request->clearDNSField() ; request->resetTransport() ; } // Remove the old list message and add the new one if ( methodStr.compareTo(SIP_REGISTER_METHOD) == 0 ) addToRegisterList(request); else addToSubscribeList(request); // There will always be a copy - if there is no copy then don't reschedule // because reregister may have removed the copy deliberately. if ( secondsFromNow > 0 ) { request->setSendProtocol(OsSocket::UNKNOWN); request->setTimesSent(0); // add the request back to the list UtlString contact; request->getContactEntry(0,&contact); if ( contact.isNull() ) { UtlString toField; UtlString contactStr; request->getToField(&toField); Url toFieldTmp(toField); getContactField(toFieldTmp, contactStr, lineId); request->setContactField(contactStr.data()); } // empty the via headers while ( request->removeHeader(SIP_VIA_FIELD, 0) ) {} // Make a copy for the timer SipMessage* timerRegisterMessage = new SipMessage(*request); OsTimer* timer = new OsTimer(&mIncomingQ, (intptr_t)timerRegisterMessage); mTimerBag.insert(timer); int maxSipTransactionTimeSecs = (mMyUserAgent->getSipStateTransactionTimeout()/1000); secondsFromNow = (secondsFromNow * percentage)/100; // ensure that the time that the transaction times out // is at least the max transaction time (preventing duplicate // retransmits if ( secondsFromNow < MIN_REFRESH_TIME_SECS ) secondsFromNow = MIN_REFRESH_TIME_SECS; // check for minumum and maximum values. if ( !sendImmediate ) { //mseconds to seconds if ( secondsFromNow < MIN_REFRESH_TIME_SECS ) { secondsFromNow = MIN_REFRESH_TIME_SECS; } else if ( secondsFromNow > defaultTime ) { secondsFromNow = (defaultTime * percentage)/100; } } // Log reschedule attempt syslog(FAC_REFRESH_MGR, PRI_DEBUG, "rescheduled %s in %d second(s)", method, secondsFromNow) ; OsTime timerTime(secondsFromNow, 0); timer->oneshotAfter(timerTime); } return; } void SipRefreshMgr::processResponse( const OsMsg& eventMessage, SipMessage *request) { SipMessage* response = (SipMessage*)((SipMessageEvent&)eventMessage).getMessage(); SipMessage* requestCopy = mRegisterList.getRequestFor(response); if (requestCopy) { requestCopy = new SipMessage(*requestCopy); } SipMessage* responseCopy = new SipMessage(*response); UtlBoolean sendEventToUpperlayer = FALSE; if (!request) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipRefreshMgr::processResponse null request"); OsSysLog::flush(); assert(0); } UtlString method; requestCopy->getRequestMethod( &method) ; // ensure that this is a response first if ( responseCopy->isResponse() ) { int responseCode = responseCopy->getResponseStatusCode(); if ( request && responseCode < SIP_2XX_CLASS_CODE ) { // provisional response codes sendEventToUpperlayer = TRUE; } else if ( ( (responseCode >= SIP_2XX_CLASS_CODE) && (responseCode < SIP_3XX_CLASS_CODE) ) ) { // Success Class response 2XX removeAllFromRequestList(response); processOKResponse(responseCopy, requestCopy ); } else // failure case { removeAllFromRequestList(response); // unregister/unsubscribe? if ( isExpiresZero(requestCopy) ) { // reschedule only if expires value id not zero otherwise // it means we just did an unregister if ( method.compareTo(SIP_REGISTER_METHOD) == 0 ) { Url url; UtlString lineId; requestCopy->getToUrl(url); url.getIdentity(lineId); lineId = "sip:" + lineId; if (responseCode == 401 || responseCode == 403 || responseCode == 407) { fireSipXLineEvent(url, lineId.data(), LINESTATE_UNREGISTER_FAILED, LINESTATE_UNREGISTER_FAILED_NOT_AUTHORIZED); } else if (responseCode == 408) { fireSipXLineEvent(url, lineId.data(), LINESTATE_UNREGISTER_FAILED, LINESTATE_UNREGISTER_FAILED_TIMEOUT); } else { fireSipXLineEvent(url, lineId.data(), LINESTATE_UNREGISTER_FAILED, LINESTATE_CAUSE_UNKNOWN); } } sendEventToUpperlayer = TRUE; } else // it is a register or subscribe { if ( method.compareTo(SIP_REGISTER_METHOD) == 0 ) { Url url; UtlString lineId; requestCopy->getToUrl(url); url.getIdentity(lineId); if (getLineMgr()) { mpLineMgr->setStateForLine(url, SipLine::LINE_STATE_FAILED); } lineId = "sip:" + lineId; if (responseCode == 401 || responseCode == 403 || responseCode == 407) { fireSipXLineEvent(url, lineId.data(), LINESTATE_REGISTER_FAILED, LINESTATE_REGISTER_FAILED_NOT_AUTHORIZED); } else if (responseCode == 408) { fireSipXLineEvent(url, lineId.data(), LINESTATE_REGISTER_FAILED, LINESTATE_REGISTER_FAILED_TIMEOUT); rescheduleAfterTime(requestCopy, FAILED_PERCENTAGE_TIMEOUT ); } else { fireSipXLineEvent(url, lineId.data(), LINESTATE_REGISTER_FAILED, LINESTATE_CAUSE_UNKNOWN); // Reschedule in case of failure rescheduleAfterTime(requestCopy, FAILED_PERCENTAGE_TIMEOUT ); } } } } } else { if (getLineMgr()) { Url url; UtlString lineId; requestCopy->getToUrl(url); url.getIdentity(lineId); mpLineMgr->setStateForLine(url, SipLine::LINE_STATE_FAILED); } Url url; UtlString lineId; requestCopy->getToUrl(url); url.getIdentity(lineId); lineId = "sip:" + lineId; fireSipXLineEvent(url, lineId.data(), LINESTATE_REGISTER_FAILED, LINESTATE_CAUSE_UNKNOWN); } if ( sendEventToUpperlayer ) { sendToObservers(eventMessage, requestCopy); } delete responseCopy; delete requestCopy; } void SipRefreshMgr::processOKResponse( SipMessage* response, SipMessage* request ) { int responseRefreshPeriod = -1; if (!request) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipRefreshMgr::processOKResponse null request"); OsSysLog::flush(); assert(0); } // Check response for Expires header or field if no header if ( !response->getExpiresField(&responseRefreshPeriod) ) { // this method looks at the request/response pair // the response may have multiple contacts so it searched // for the expires header corresponding to the request parseContactFields( response, request, responseRefreshPeriod ); } // Check request for Expires header or field if no header int requestRefreshPeriod = -1; if ( !request->getExpiresField(&requestRefreshPeriod) ) { // to get expires value @JC whi request 2 times parseContactFields( request, request, requestRefreshPeriod ); } OsSysLog::add(FAC_REFRESH_MGR, PRI_DEBUG, "SipRefreshMgr::processOKResponse requestRefreshPeriod: %d responseRefreshPeriod: %d", requestRefreshPeriod, responseRefreshPeriod); //get to To Tag from the 200 ok response and add it to the request UtlString toAddr; UtlString toProto; int toPort; UtlString toTag; response->getToAddress(&toAddr, &toPort, &toProto, NULL, NULL, &toTag); UtlString method; request->getRequestMethod( &method) ; if ( method.compareTo(SIP_REGISTER_METHOD) == 0 ) { //reschedule only if expires value != 0, otherwise it means we just did an unregister if ( requestRefreshPeriod == 0 ) { // if its an unregister, remove all related messasges // from the appropriate request list response->setCSeqField(-1, method); // TODO - should also destroy the timer now Url url; UtlString lineId; request->getToUrl(url); url.getIdentity(lineId); lineId = "sip:" + lineId; fireSipXLineEvent(url, lineId.data(), LINESTATE_UNREGISTERED, LINESTATE_UNREGISTERED_NORMAL); } else { // copying from response (this is why we set the To Field if ( !toTag.isNull() ) { request->setToFieldTag(toTag); } Url url; UtlString lineId; request->getToUrl(url); url.getIdentity(lineId); lineId = "sip:" + lineId; // extract the Message body and pass to apps const char *bodyBytes = NULL; int nBodySize = 0; const HttpBody *body = response->getBody(); if (body) { body->getBytes( &bodyBytes, &nBodySize ); } fireSipXLineEvent(url, lineId.data(), LINESTATE_REGISTERED, LINESTATE_REGISTERED_NORMAL, bodyBytes ); if (responseRefreshPeriod > 0) { rescheduleRequest(request, responseRefreshPeriod, SIP_REGISTER_METHOD); } else { // could not find expires in 200 ok response , reschedule after default time rescheduleAfterTime(request); } } } else // subscribe { // reschedule according to expires value if ( requestRefreshPeriod == 0 ) { // if its an unregister, remove all related messasges // from the appropriate request list response->setCSeqField(-1, method); removeAllFromRequestList(response); // TODO - should also destroy the timer now } else if ( responseRefreshPeriod > 0 ) { if ( !toTag.isNull() ) { request->setToFieldTag(toTag); } rescheduleRequest( request, responseRefreshPeriod, SIP_SUBSCRIBE_METHOD); } else { // could not find expires in 200 ok response , reschedule after default time // copying from response (this is why we set the To Field request->setToFieldTag(toTag); rescheduleAfterTime(request); } } return; } void SipRefreshMgr::parseContactFields( SipMessage* registerResponse, SipMessage* requestMessage, int &serverRegPeriod) { // get the request contact uri ...so that we can find out // the expires subfield value for this contact from the list // of contacts returned by the registration server UtlString requestContactEntry; requestMessage->getContactEntry(0 , &requestContactEntry); Url requestContactUrl(requestContactEntry); UtlString requestContactIdentity; requestContactUrl.getIdentity(requestContactIdentity); UtlString requestContactLineId; requestContactUrl.getUrlParameter(SIP_LINE_LINEID, requestContactLineId); UtlString contactField; int indexContactField = 0; while ( registerResponse->getContactEntry(indexContactField , &contactField) ) { Url returnedContact(contactField); UtlString returnedIdentity; returnedContact.getIdentity(returnedIdentity); UtlString responseContactLineId; returnedContact.getUrlParameter(SIP_LINE_LINEID, responseContactLineId); #ifdef TEST_PRINT OsSysLog::add(FAC_REFRESH_MGR, PRI_DEBUG, "SipRefreshMgr::parseContactFields response returnedIdentity: %s lineId: %s, request requestContactIdentity: %s lineId: %s", returnedIdentity.data(), responseContactLineId.data(), requestContactIdentity.data(), requestContactLineId.data()); #endif if ( returnedIdentity.compareTo(requestContactIdentity) == 0 || responseContactLineId.compareTo(requestContactLineId) == 0) { UtlString subfieldText; int subfieldIndex = 0; UtlString subfieldName; UtlString subfieldValue; UtlNameValueTokenizer::getSubField(contactField.data(), subfieldIndex, ";", &subfieldText); while ( !subfieldText.isNull() ) { UtlNameValueTokenizer::getSubField(subfieldText.data(), 0, "=", &subfieldName); UtlNameValueTokenizer::getSubField(subfieldText.data(), 1, "=", &subfieldValue); #ifdef TEST_PRINT OsSysLog::add(FAC_REFRESH_MGR, PRI_DEBUG, "SipUserAgent::processRegisterResponce found contact parameter[%d]: \"%s\" value: \"%s\"\n", subfieldIndex, subfieldName.data(), subfieldValue.data()); #endif subfieldName.toUpper(); if ( subfieldName.compareTo(SIP_EXPIRES_FIELD) == 0 ) { //see if more than one token in the expire value UtlNameValueTokenizer::getSubField( subfieldValue, 1, " \t:;,", &subfieldText); // if not ...time is in seconds if ( subfieldText.isNull() ) { serverRegPeriod = atoi(subfieldValue); } // If there is more than one token assume it is a text date else { // Get the expiration date long dateExpires = OsDateTime::convertHttpDateToEpoch(subfieldValue); long dateSent = 0; // If the date was not set in the message if ( !registerResponse->getDateField(&dateSent) ) { #ifdef TEST_PRINT osPrintf("Date field not set\n"); #endif // Assume date sent is now dateSent = OsDateTime::getSecsSinceEpoch(); } #ifdef TEST_PRINT osPrintf("Contact expires date: %ld\n", dateExpires); osPrintf("Current time: %ld\n", dateSent); #endif serverRegPeriod = dateExpires - dateSent; } break; } subfieldIndex++; UtlNameValueTokenizer::getSubField(contactField.data(), subfieldIndex, ";", &subfieldText); } } indexContactField ++; } return ; } void SipRefreshMgr::sendToObservers ( const OsMsg& eventMessage, SipMessage *request ) { SipMessage* Response = (SipMessage*)((SipMessageEvent&)eventMessage).getMessage(); int messageType = ((SipMessageEvent&)eventMessage).getMessageStatus(); if (!request) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipRefreshMgr::sendToObservers null request"); OsSysLog::flush(); assert(0); } // Create a new message event SipMessage * message = new SipMessage(*Response); SipMessageEvent event(message); event.setMessageStatus(messageType); UtlString method; request->getRequestMethod( &method) ; // Find all of the observers which are interested in // this method and post the message if ( method.compareTo(SIP_REGISTER_METHOD) == 0 ) { queueMessageToObservers(event, SIP_REGISTER_METHOD); } else { queueMessageToObservers(event, SIP_SUBSCRIBE_METHOD); } // send it to those with no method descrimination as well queueMessageToObservers(event, ""); // Do not delete the message it gets deleted with the event } void SipRefreshMgr::registerUrl( const char* registerFromAddress, const char* registerToAddress, const char* registerUri, const char* contactUrl, const UtlString& registerCallId, int registerPeriod) { SipMessage* regMessage = new SipMessage(); int startSequence = 101; UtlString fromField(registerFromAddress); // add Tag to from field UtlString tagNamevaluePair ; createTagNameValuePair(tagNamevaluePair); fromField.append(";"); fromField.append(tagNamevaluePair); regMessage->setRegisterData ( fromField.data(), // from registerToAddress, // to registerUri, // uri contactUrl, // contact registerCallId.data(), // callid startSequence, registerPeriod >= 0 ? registerPeriod : mDefaultRegistryPeriod ); // Add to the register list addToRegisterList(regMessage); // If the user agent is not started, then queue it. Once the // UA is started, it will kick off those registrations. if ( isUAStarted() ) { UtlString localIp; int localPort; SIPX_TRANSPORT_TYPE protocol = TRANSPORT_UDP; UtlString uri(registerUri); if (uri.contains("sips:") || uri.contains("transport=tls")) { protocol = TRANSPORT_TLS; } if (uri.contains("transport=tcp")) { protocol = TRANSPORT_TCP; } mMyUserAgent->getLocalAddress(&localIp, &localPort, protocol); regMessage->setLocalIp(localIp); if (sendRequest(*regMessage , SIP_REGISTER_METHOD) != OS_SUCCESS) { // if we couldn't send, go ahead and remove the register request from the list removeFromRegisterList(regMessage); regMessage = 0; } } else { regMessage->setContactField("") ; // BA: Why are we clearing the contact field ?!? syslog(FAC_REFRESH_MGR, PRI_DEBUG, "queueing register until the SIP UA is ready:\nfrom=%s\nto=%s\nuri=%s\ncontact=%s\ncallid=%s", fromField.data(), registerToAddress, registerUri, contactUrl, registerCallId.data()) ; } delete regMessage; } UtlBoolean SipRefreshMgr::handleMessage( OsMsg& eventMessage ) { UtlBoolean messageProcessed = FALSE; int msgType = eventMessage.getMsgType(); int msgSubType = eventMessage.getMsgSubType(); UtlString method; if ( msgType == OsMsg::REFRESH_MSG && msgSubType == SipRefreshMgr::START_REFRESH_MGR ) { waitForUA(); messageProcessed = TRUE; } if ( msgType == OsMsg::PHONE_APP ) { SipMessage* sipMsg = (SipMessage*)((SipMessageEvent&)eventMessage).getMessage(); int messageType = ((SipMessageEvent&)eventMessage).getMessageStatus(); #ifdef TEST_PRINT OsSysLog::add(FAC_REFRESH_MGR, PRI_DEBUG, "SipRefreshMgr::handleMessage messageType: %d", messageType); #endif UtlString callid; int cseq; sipMsg->getCallIdField(&callid); sipMsg->getCSeqField(&cseq, &method); // if transport error and no response from remote machine. Unable to send to remote host if ( !sipMsg->isResponse() && messageType == SipMessageEvent::TRANSPORT_ERROR ) { SipMessage * msgInList = NULL; // Log Failures syslog(FAC_REFRESH_MGR, PRI_ERR, "unable to send %s (transport):\ncallid=%s", method.data(), callid.data()) ; //reschedule only if expires value is not zero otherwise it means we just did an unregister if ( !isExpiresZero(sipMsg) ) { if (msgInList) { sendToObservers(eventMessage, msgInList); // try again after default time out rescheduleAfterTime(msgInList, FAILED_PERCENTAGE_TIMEOUT); } else { // It is possible to have msgInList=NULL if removed by another task+ICMP // osPrintf("SipRefreshMgr::handleMessage-L1274: msgInList=NULL; why ??*********"); // do nothing here. ; } } messageProcessed = TRUE; } // If this is a response, else if ( sipMsg->isResponse() ) { SipMessage *request = NULL; SipMessage *requestFound = NULL; // Is this a register msg? { OsReadLock readlock(mRegisterListMutexR); // Find the request which goes with this response requestFound = mRegisterList.getRequestFor(sipMsg); //make a dupe if ( requestFound ) request = new SipMessage(*requestFound); } // IS this a subscribe msg? if ( !request ) { OsReadLock readlock(mSubscribeListMutexR); // Find the request which goes with this response requestFound = mSubscribeList.getRequestFor(sipMsg); if (requestFound) request = new SipMessage(*requestFound); } if ( request ) { UtlBoolean retryWithAuthentication = FALSE; request->getRequestMethod( &method) ; if ( messageType == SipMessageEvent::AUTHENTICATION_RETRY ) { syslog(FAC_REFRESH_MGR, PRI_INFO, "authentication requested for %s request:\ncallid=%s", method.data(), callid.data()) ; if ( strcmp(method.data(), SIP_REGISTER_METHOD) == 0 ) { // Find the request which goes with this response SipMessage* request = mRegisterList.getRequestFor(sipMsg); // increment the CSeq number in the stored request if ( request ) { request->incrementCSeqNumber(); addToRegisterList(request); retryWithAuthentication = TRUE; } } else if ( strcmp(method.data(), SIP_SUBSCRIBE_METHOD) == 0 ) { // Find the request which goes with this response SipMessage* request = mSubscribeList.getRequestFor(sipMsg); //increment the CSeq number in the stored request request->incrementCSeqNumber(); addToSubscribeList(request); retryWithAuthentication = TRUE; } } if ( request && retryWithAuthentication == FALSE ) { processResponse(eventMessage, request); } } else { // Bob 2/10/03 Do not complain if we cannot find the // message. Because we add observers for both requests // and incoming messages, we *WILL* receive duplicate // responses- and yes, we won't find them here. /* // Report that we were unable to find this request UtlString response ; int respLen ; UtlString msgContents ; // Log Failure sipMsg->getBytes(&response, &respLen) ; dumpMessageLists(msgContents) ; syslog(FAC_REFRESH_MGR, PRI_ERR, "unable to find request for %s response:\ncallid=%s\nResponse:\n%s\nLists:\n%s", method.data(), callid.data(), response.data(), msgContents.data()) ; */ } if ( request ) { delete request; request = NULL; } }//end if isresponse messageProcessed = TRUE; } else if ( (msgType == OsMsg::OS_EVENT) && (msgSubType == OsEventMsg::NOTIFY) ) { // A timer expired SipMessage* sipMessage; OsTimer* timer; int protocolType; ((OsEventMsg&)eventMessage).getUserData((intptr_t&)sipMessage); ((OsEventMsg&)eventMessage).getEventData((intptr_t&)timer); if ( timer ) { // remove timer from mTimerBag mTimerBag.removeReference(timer); delete timer; timer = NULL; } if ( sipMessage ) { UtlString callId; protocolType = sipMessage->getSendProtocol(); sipMessage->getCallIdField(&callId); sipMessage->getRequestMethod(&method); // Log Timeout syslog(FAC_REFRESH_MGR, PRI_DEBUG, "timeout for %s:\ncallid=%s", method.data(), callId.data()) ; #ifdef TEST_PRINT int len = 0 ; UtlString bytes ; sipMessage->getBytes(&bytes, &len) ; osPrintf("%s\n", bytes.data()) ; #endif // check if a duplicate request is in the list, // if not then it means that it was unregistered // before the timer expired UtlString fromUri; sipMessage->getFromUri(&fromUri); Url uri(fromUri); uri.removeAngleBrackets(); SipMessage sipMsg; if ( !fromUri.isNull() ) { int num; UtlString method; sipMessage->getCSeqField(&num , &method); if ( method.compareTo(SIP_REGISTER_METHOD) == 0 ) { if ( isDuplicateRegister(uri, sipMsg) ) { int listNum; UtlString listMethod; sipMsg.getCSeqField(&listNum , &listMethod); // check if CSeq is less than what is in the list ..if less, then it is because // reregister must have incremented it and this rescheduling from the previous // msg if ( num >= listNum ) { if (sendRequest(*sipMessage, SIP_REGISTER_METHOD) != OS_SUCCESS) { removeFromRegisterList(sipMessage); } } } else { syslog(FAC_REFRESH_MGR, PRI_ERR, "unable to refresh %s (not found):\ncallid=%s", method.data(), callId.data()) ; } } else { if ( isDuplicateSubscribe(uri, sipMsg) ) { int listNum; UtlString listMethod; sipMsg.getCSeqField(&listNum , &listMethod); // check if CSeq is less than what is in the list ..if less, then it is because // reregister must have incremented it and this rescheduling from the previous // msg if ( num >= listNum ) { if (sendRequest(*sipMessage, SIP_SUBSCRIBE_METHOD) != OS_SUCCESS) { removeFromSubscribeList(sipMessage); } } } else { syslog(FAC_REFRESH_MGR, PRI_ERR, "unable to refresh %s (not found):\ncallid=%s", method.data(), callId.data()) ; } } } // The timer made its own copy of this message.Delete it now that we are done with it. delete sipMessage; sipMessage = NULL; messageProcessed = TRUE; } } return (messageProcessed); } // Get the nat mapped address (if available) UtlBoolean SipRefreshMgr::getNatMappedAddress(UtlString* pIpAddress, int* pPort) { UtlBoolean bRC = FALSE ; if (mMyUserAgent) { bRC = mMyUserAgent->getNatMappedAddress(pIpAddress, pPort) ; } return bRC ; } void SipRefreshMgr::queueMessageToObservers( SipMessageEvent& event, const char* method ) { const SipMessage* message = event.getMessage(); // Find all of the observers which are interested in this method and post the message UtlString messageEventName; if ( message ) message->getEventField(messageEventName); UtlString observerMatchingMethod(method); SipObserverCriteria* observerCriteria = NULL; OsReadLock lock(mObserverMutex); UtlHashBagIterator observerIterator(mMessageObservers, &observerMatchingMethod); do { observerCriteria = (SipObserverCriteria*) observerIterator(); // If this message matches the filter criteria //wants responses if ( observerCriteria && observerCriteria->wantsIncoming() && (message->isResponse() && observerCriteria->wantsResponses()) ) { OsMsgQ* observerQueue = observerCriteria->getObserverQueue(); void* observerData = observerCriteria->getObserverData(); // Cheat a little and set the observer data to be passed back ((SipMessage*) message)->setResponseListenerData(observerData); // Put the message in the observers queue observerQueue->send(event); } //wants requests if ( observerCriteria && observerCriteria->wantsIncoming() && !message->isResponse() ) { OsMsgQ* observerQueue = observerCriteria->getObserverQueue(); void* observerData = observerCriteria->getObserverData(); // Cheat a little and set the observer data to be passed back ((SipMessage*) message)->setResponseListenerData(observerData); // Put the message in the observers queue observerQueue->send(event); } } while ( observerCriteria != NULL ); } /*===================================================================*/ // SUBSCRIBE /*===================================================================*/ void SipRefreshMgr::reSubscribeAll() { SipMessageList tempList; SipMessage* listMessage; int iteratorHandle; {//scope the locks OsReadLock readlock(mSubscribeListMutexR); OsWriteLock writeLock(mSubscribeListMutexW); iteratorHandle = mSubscribeList.getIterator(); while ((listMessage = (SipMessage*) mSubscribeList.getSipMessageForIndex(iteratorHandle))) { //somehow stop the old timer - will get not cause harm because will not be able to find corresponding request. tempList.add(listMessage); } mSubscribeList.releaseIterator(iteratorHandle); } iteratorHandle = tempList.getIterator(); while ((listMessage = (SipMessage*) tempList.getSipMessageForIndex(iteratorHandle))) { rescheduleRequest(listMessage, 1 , SIP_SUBSCRIBE_METHOD, DEFAULT_PERCENTAGE_TIMEOUT ,TRUE); } tempList.releaseIterator(iteratorHandle); } void SipRefreshMgr::unSubscribeAll() { SipMessage* listMessage; int iteratorHandle; {//scope the locks OsReadLock readlock(mSubscribeListMutexR); OsWriteLock writeLock(mSubscribeListMutexW); iteratorHandle = mSubscribeList.getIterator(); while ((listMessage = (SipMessage*) mSubscribeList.getSipMessageForIndex(iteratorHandle))) { listMessage->setExpiresField(0); listMessage->incrementCSeqNumber(); // Clear the DNS field, so that we retry DNS-SRV before resending. // This should be performed for all failure cases, except for // auth challenges listMessage->clearDNSField() ; listMessage->resetTransport() ; UtlString localIp; int localPort; SIPX_TRANSPORT_TYPE protocol = TRANSPORT_UDP; UtlString url; listMessage->getToField(&url); if (url.contains("sips:") || url.contains("transport=tls")) { protocol = TRANSPORT_TLS; } if (url.contains("transport=tcp")) { protocol = TRANSPORT_TCP; } mMyUserAgent->getLocalAddress(&localIp, &localPort, protocol); listMessage->setLocalIp(localIp); mMyUserAgent->send(*listMessage); mSubscribeList.remove(iteratorHandle); delete listMessage; } mSubscribeList.releaseIterator(iteratorHandle); } } UtlBoolean SipRefreshMgr::newSubscribeMsg( SipMessage& sipMessage ) { UtlString to; UtlString method; UtlString eventType; // Assume failed unless proven otherwise UtlBoolean result = false; sipMessage.getRequestMethod( &method ); sipMessage.getToField( &to ); sipMessage.getEventField( eventType ); // ensure that this is a subscribe request if ( strcmp( method.data(), SIP_SUBSCRIBE_METHOD ) == 0 ) { if ( !isDuplicateSubscribe( to.data() ) ) { syslog(FAC_REFRESH_MGR, PRI_DEBUG, "adding registration:\nurl=%s\nevent-type=%s", to.data(), eventType.data()) ; // lazy create the from tag Url fromUrl; sipMessage.getFromUrl( fromUrl ); UtlString tagValue; if ( !fromUrl.getFieldParameter( "tag", tagValue ) ) { // tag has not been set so set it here UtlString tagNameValuePair; createTagNameValuePair( tagNameValuePair ); // Tokenize out the tag=value part UtlTokenizer next (tagNameValuePair); UtlString junk; next.next(junk, "="); UtlString tagValue; next.next(tagValue, "="); fromUrl.setFieldParameter("tag", tagValue); sipMessage.setRawFromField( fromUrl.toString().data() ); } // lazy create the callid UtlString subscribeCallId; sipMessage.getCallIdField(&subscribeCallId); if ( subscribeCallId.isNull() ) { UtlString from; sipMessage.getFromField( &from ); // Generate Call Id UtlString subscribeCallId; generateCallId ( from, SIP_SUBSCRIBE_METHOD, subscribeCallId ); sipMessage.setCallIdField( subscribeCallId.data()); } // Add to subscription list addToSubscribeList( &sipMessage ); if (isUAStarted()) { if (sendRequest( sipMessage, SIP_SUBSCRIBE_METHOD ) != OS_SUCCESS) { removeFromSubscribeList(&sipMessage); } } else { syslog(FAC_REFRESH_MGR, PRI_ERR, "unable to add registration (queue):\nurl=%s\nevent-type=%s", to.data(), eventType.data()) ; } result = true; } else { syslog(FAC_REFRESH_MGR, PRI_ERR, "unable to add new registration (dup):\nurl=%s\nevent-type=%s", to.data(), eventType.data()) ; } } else { osPrintf("ERROR SipRefreshMgr::newSubscribeMsg - " "Not a SIP_SUBSCRIBE_METHOD request\n"); } return result; } // Appends the message contents of both the mRegisterList and mSubscribeList. void SipRefreshMgr::dumpMessageLists(UtlString& results) { UtlString temp ; // Dump Register List results.append("\nRegister List:\n\n") ; mRegisterList.remove(0) ; mRegisterList.toString(temp) ; results.append(temp) ; // Dump Subscribe List results.append("\nSubscribe List:\n\n") ; mSubscribeList.remove(0) ; mSubscribeList.toString(temp) ; results.append(temp) ; } void SipRefreshMgr::generateCallId( const UtlString& fromUrl, const UtlString& method, UtlString& callId, UtlBoolean onStartup) { Url temp(fromUrl); UtlString identity; temp.getIdentity(identity); if ( method.compareTo(SIP_REGISTER_METHOD) == 0 ) { if ( onStartup ) { int previousCount = mRestartCount -1; char strCount[64]; sprintf(strCount, "%d", previousCount); //use previous restart count to get the previous call id HttpMessage::buildMd5UserPasswordDigest(mMacAddress, strCount, identity, callId); } else { // TEMP - mdc // call id is a hash of fromUrl, ipaddress+rnd, method int randomInt = mRandomNumGenerator.rand(); char randomString[60]; sprintf (randomString, "-%d", randomInt); UtlString randomizedHostIP; OsSocket::getHostIp( &randomizedHostIP ); randomizedHostIP.append (randomString); HttpMessage::buildMd5UserPasswordDigest( fromUrl, randomizedHostIP, method, callId ); //HttpMessage::buildMd5UserPasswordDigest(mMacAddress, mRestartCountStr, identity, callId); } } else // subscribe method { // call id is a hash of fromUrl, ipaddress+rnd, method int randomInt = mRandomNumGenerator.rand(); char randomString[60]; sprintf (randomString, "-%d", randomInt); UtlString randomizedHostIP; OsSocket::getHostIp( &randomizedHostIP ); randomizedHostIP.append (randomString); HttpMessage::buildMd5UserPasswordDigest( fromUrl, randomizedHostIP, method, callId ); } } UtlBoolean SipRefreshMgr::removeFromRegisterList(SipMessage* message) { UtlBoolean bRemovedOk = FALSE; OsReadLock readlock(mRegisterListMutexR); OsWriteLock writeLock(mRegisterListMutexW); #ifdef TEST_PRINT osPrintf("**********************************************\n"); osPrintf("Removing message from register list: %X\n",message); osPrintf("**********************************************\n"); #endif if ( mRegisterList.remove(message) == FALSE ) { #ifdef TEST_PRINT osPrintf("**********************************************\n"); osPrintf("Cannot Find message to register list: %X\n",message); osPrintf("**********************************************\n"); #endif } else bRemovedOk = TRUE; #ifdef TEST_PRINT osPrintf("Exit removeFromRegisterList: bRemovedOk=%d", bRemovedOk); mRegisterList.printDebugTable() ; #endif return bRemovedOk; } void SipRefreshMgr::addToRegisterList(SipMessage *message) { OsReadLock readlock(mRegisterListMutexR); OsWriteLock writeLock(mRegisterListMutexW); if (mRegisterList.getDuplicate( message, TRUE )) { // osPrintf("****We already have the message in mRegisterList[]"); } else { SipMessage *msg = new SipMessage (*message); // Remove the To tag so that does not interfer with the matching msg->removeToFieldTag(); #ifdef TEST_PRINT osPrintf("**********************************************\n"); osPrintf("Adding message to register list: orig: %X new: %X\n",message, msg); osPrintf("**********************************************\n"); #endif mRegisterList.add(msg); } #ifdef TEST_PRINT osPrintf("Exit addToRegisterList:"); mRegisterList.printDebugTable() ; // dumpMessageLists( mRegisterList ); #endif } UtlBoolean SipRefreshMgr::removeFromSubscribeList(SipMessage* message) { UtlBoolean bRemovedOk = FALSE; OsReadLock readlock(mSubscribeListMutexR); OsWriteLock writeLock(mSubscribeListMutexW); #ifdef TEST_PRINT osPrintf("**********************************************\n"); osPrintf("Removing message from subscribe list: %X\n",message); osPrintf("**********************************************\n"); #endif if (mSubscribeList.remove(message) == FALSE) { #ifdef TEST_PRINT osPrintf("**********************************************\n"); osPrintf("Cannot Find message to subscribe list: %X\n",message); osPrintf("**********************************************\n"); #endif } else bRemovedOk = TRUE; return bRemovedOk; } void SipRefreshMgr::addToSubscribeList(SipMessage *message) { OsReadLock readlock(mSubscribeListMutexR); OsWriteLock writeLock(mSubscribeListMutexW); mSubscribeList.add(new SipMessage (*message)); } UtlBoolean SipRefreshMgr::isDuplicateSubscribe ( const Url& toUrl ) { OsReadLock readlock(mSubscribeListMutexR); OsWriteLock writeLock(mSubscribeListMutexW); SipMessage * oldMsg = mSubscribeList.isSameTo(toUrl); if ( oldMsg ) { return true; } return false; } UtlBoolean SipRefreshMgr::isDuplicateSubscribe ( const Url& fromUrl, SipMessage &oldMsg ) { OsReadLock readlock(mSubscribeListMutexR); OsWriteLock writeLock(mSubscribeListMutexW); // call copy constructor on the oldMsg SipMessage* pduplicate = mSubscribeList.isSameFrom(fromUrl); if ( pduplicate != NULL ) { oldMsg = *pduplicate; return true; } return false; } void SipRefreshMgr::rescheduleAfterTime( SipMessage *request, int percentage ) { int iOriginalExpiration ; UtlString method ; int dummy; request->getCSeqField(&dummy, &method); if (!request) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipRefreshMgr::rescheduleAfterTime null request"); OsSysLog::flush(); assert(0); } if (request) request->getRequestMethod(&method); // Figure out expiration if (request && !request->getExpiresField(&iOriginalExpiration)) { if ( method.compareTo(SIP_REGISTER_METHOD) == 0 ) { iOriginalExpiration = mDefaultRegistryPeriod ; } else { iOriginalExpiration = mDefaultSubscribePeriod ; } } if (request) { rescheduleRequest( request, iOriginalExpiration, method.data(), percentage); } } void SipRefreshMgr::createTagNameValuePair( UtlString& tagNamevaluePair ) { // Build a from tag char fromTagBuffer[24]; sprintf(fromTagBuffer, "%0x%0x", mRandomNumGenerator.rand(), mRandomNumGenerator.rand()); tagNamevaluePair = "tag=" ; tagNamevaluePair.append(fromTagBuffer); } void SipRefreshMgr::getContactField( const Url& registerToField, UtlString& contact, const UtlString& lineId, Url* pPreferredContactUri) { contact.remove(0); UtlString tempContact; UtlString displayName; UtlString userId; // First look at the passed contact uri if (pPreferredContactUri) { UtlString host ; int port ; pPreferredContactUri->getHostAddress(host) ; port = pPreferredContactUri->getHostPort() ; if (host.length() > 0) { tempContact = host ; // Only include port number if non-standard if ((port != 5060) && (port != PORT_NONE)) { char cPort[32] ; sprintf(cPort, "%d", port) ; tempContact.append(':') ; tempContact.append(cPort) ; } } } // Use default contact from SipUserAgent if preferred is not supplied if (tempContact.length() == 0) { mMyUserAgent->getContactUri(&tempContact); } // The contact URI does not have the correct urserId information in it ... // Get the user ID and display name from To field and stick it in Url contactUrl(tempContact); registerToField.getDisplayName(displayName); registerToField.getUserId(userId); contactUrl.setDisplayName(displayName); contactUrl.setUserId(userId); if ( !lineId.isNull() ) { contactUrl.setUrlParameter(SIP_LINE_IDENTIFIER, lineId); contactUrl.includeAngleBrackets(); } int index = 0; UtlString paramName; UtlString paramValue; while ( ((Url&)(registerToField)).getFieldParameter( index, paramName , paramValue ) ) { if ( paramName.compareTo(SIP_Q_FIELD, UtlString::ignoreCase) == 0 ) { contactUrl.setFieldParameter(SIP_Q_FIELD, paramValue); } index ++; } contact.append(contactUrl.toString().data()); } // Is the expire field set to zero for the specified request? UtlBoolean SipRefreshMgr::isExpiresZero(SipMessage* pRequest) { UtlBoolean bRC = FALSE ; // Is the expire field zero? if ((pRequest != NULL) && !pRequest->isResponse()) { int iExpires = -1; if (!pRequest->getExpiresField(&iExpires)) { parseContactFields(pRequest, pRequest, iExpires) ; } if (iExpires == 0) bRC = TRUE ; } return bRC ; } void SipRefreshMgr::setRegistryPeriod(const int periodInSeconds) { mDefaultRegistryPeriod = periodInSeconds; } void SipRefreshMgr::setSubscribeTimeout(const int periodInSeconds) { mDefaultSubscribePeriod = periodInSeconds; } const int SipRefreshMgr::getSubscribeTimeout() { return mDefaultSubscribePeriod; } void SipRefreshMgr::fireSipXLineEvent(const Url& url, const UtlString& lineId, const SIPX_LINESTATE_EVENT event, const SIPX_LINESTATE_CAUSE cause, const char *bodyBytes ) { // Avoid sending duplicate events if (event != getLastLineEvent(lineId)) { if (event == LINESTATE_REGISTERED) { if (getLineMgr()) { mpLineMgr->setStateForLine(url, SipLine::LINE_STATE_REGISTERED); } } else if (event == LINESTATE_UNREGISTERED) { if (getLineMgr()) { mpLineMgr->setStateForLine(url, SipLine::LINE_STATE_DISABLED); } } setLastLineEvent(lineId.data(), event); // TapiMgr::getInstance().fireLineEvent(this, lineId.data(), event, cause, bodyBytes ); if (event == LINESTATE_UNREGISTERED) { if (getLineMgr()) { mpLineMgr->lineHasBeenUnregistered(url); } } TapiMgr::getInstance().fireLineEvent(this, lineId.data(), event, cause, bodyBytes ); } } SIPX_LINESTATE_EVENT SipRefreshMgr::getLastLineEvent(const UtlString& lineId) { SIPX_LINESTATE_EVENT lastLineEvent = LINESTATE_UNKNOWN; UtlInt* lastEvent = NULL; if (!mpLastLineEventMap) { mpLastLineEventMap = new UtlHashMap(); } lastEvent = static_cast(mpLastLineEventMap->find(&lineId)); if (lastEvent) { lastLineEvent = (SIPX_LINESTATE_EVENT)lastEvent->getValue(); } return lastLineEvent; } void SipRefreshMgr::setLastLineEvent(const UtlString& lineId, const SIPX_LINESTATE_EVENT eMajor) { if (!mpLastLineEventMap) { mpLastLineEventMap = new UtlHashMap(); } UtlString* newId = new UtlString(lineId); UtlString* exisitingId; if((exisitingId = static_cast(mpLastLineEventMap->find(newId)))) { OsSysLog::add(FAC_REFRESH_MGR, PRI_DEBUG, "SipRefreshMgr::setLastLineEvent: LineId found, being destroyed ??" ); mpLastLineEventMap->destroy(exisitingId); } mpLastLineEventMap->insertKeyAndValue(newId, new UtlInt(eMajor)); } void SipRefreshMgr::removeAllFromRequestList(SipMessage* response) { OsReadLock readlock(mRegisterListMutexR); OsWriteLock writeLock(mRegisterListMutexW); UtlString methodName; int seqNum = 0; response->getCSeqField(&seqNum, &methodName); if (methodName.compareTo(SIP_REGISTER_METHOD) == 0) { removeAllFromRequestList(response, &mRegisterList); } else if (methodName.compareTo(SIP_SUBSCRIBE_METHOD) == 0) { removeAllFromRequestList(response, &mSubscribeList); } #ifdef TEST_PRINT osPrintf("** removeFromRegisterList\n") ; mRegisterList.printDebugTable() ; #endif } void SipRefreshMgr::removeAllFromRequestList(SipMessage* response, SipMessageList* pRequestList) { SipMessage* listMessage = NULL; int iteratorHandle = pRequestList->getIterator(); UtlString methodName; int seqNum = 0; response->getCSeqField(&seqNum, &methodName); while ((listMessage = (SipMessage*) pRequestList->getSipMessageForIndex(iteratorHandle))) { int requestSeqNum = 0; UtlString dummy; listMessage->getCSeqField(&requestSeqNum, &dummy); if (response->isSameSession(listMessage) && (seqNum == -1 || requestSeqNum <= seqNum) ) { mRegisterList.releaseIterator(iteratorHandle); mRegisterList.remove(listMessage); delete listMessage; listMessage = NULL; iteratorHandle = pRequestList->getIterator(); } } pRequestList->releaseIterator(iteratorHandle); } void SipRefreshMgr::setLineMgr(SipLineMgr* const lineMgr) { mpLineMgr = lineMgr; return; } SipLineMgr* const SipRefreshMgr::getLineMgr() const { return mpLineMgr; } sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipRefreshManager.cpp0000644000175000017500000012627012205613256025253 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie (dpetrie AT SIPez DOT com) // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // Private class to contain subscription client states class RefreshDialogState : public UtlString { public: RefreshDialogState(); virtual ~RefreshDialogState(); void toString(UtlString& dumpString); // UtlString::data contains the Dialog Handle; void* mpApplicationData; SipRefreshManager::RefreshStateCallback mpStateCallback; int mExpirationPeriodSeconds; // original expiration long mPendingStartTime; // epoch time in seconds long mExpiration; // epoch time in seconds SipMessage* mpLastRequest; SipRefreshManager::RefreshRequestState mRequestState; int mFailedResponseCode; UtlString mFailedResponseText; OsTimer* mpRefreshTimer; // Fires when it is time to resend private: //! DISALLOWED accendental copying RefreshDialogState(const RefreshDialogState& rRefreshDialogState); RefreshDialogState& operator=(const RefreshDialogState& rhs); }; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ RefreshDialogState::RefreshDialogState() { mpApplicationData = NULL; mpStateCallback = NULL; mExpirationPeriodSeconds = -1; mPendingStartTime = -1; mExpiration = -1; mpLastRequest = NULL; mRequestState = SipRefreshManager::REFRESH_REQUEST_UNKNOWN; mFailedResponseCode = -1; mpRefreshTimer = NULL; } void RefreshDialogState::toString(UtlString& dumpString) { dumpString = "RefreshDialogState:\n\tmpData: "; dumpString.append(*this); dumpString.append("\n\tmpApplicationData: "); char numBuf[20]; sprintf(numBuf, "%p", mpApplicationData); dumpString.append(numBuf); dumpString.append("\n\tmpStateCallback: "); sprintf(numBuf, "%p", mpStateCallback); dumpString.append(numBuf); dumpString.append("\n\tmExpirationPeriodSeconds: "); sprintf(numBuf, "%d", mExpirationPeriodSeconds); dumpString.append(numBuf); dumpString.append("\n\tmPendingStartTime: "); sprintf(numBuf, "%ld", mPendingStartTime); dumpString.append(numBuf); dumpString.append("\n\tmExpiration: "); sprintf(numBuf, "%ld", mExpiration); dumpString.append(numBuf); dumpString.append("\n\tmpLastRequest: "); sprintf(numBuf, "%p", mpLastRequest); dumpString.append(numBuf); dumpString.append("\n\tmRequestState: "); UtlString stateString; SipRefreshManager::refreshState2String(mRequestState, stateString); dumpString.append(stateString); dumpString.append("\n\tmFailedResponseCode: "); sprintf(numBuf, "%d", mFailedResponseCode); dumpString.append(numBuf); dumpString.append("\n\tmFailedResponseText: "); dumpString.append(mFailedResponseText ? mFailedResponseText : ""); dumpString.append("\n\tmpRefreshTimer: "); sprintf(numBuf, "%p", mpRefreshTimer); dumpString.append(numBuf); } // Copy constructor NOT ALLOWED RefreshDialogState::RefreshDialogState(const RefreshDialogState& rRefreshDialogState) { } RefreshDialogState::~RefreshDialogState() { } //Assignment operator NOT ALLOWED RefreshDialogState& RefreshDialogState::operator=(const RefreshDialogState& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } // Constructor SipRefreshManager::SipRefreshManager(SipUserAgent& userAgent, SipDialogMgr& dialogMgr) : OsServerTask("SipRefreshManager-%d") , mRefreshMgrMutex(OsMutex::Q_FIFO) { mpUserAgent = &userAgent; mpDialogMgr = &dialogMgr; mReceivingRegisterResponses = FALSE; mDefaultExpiration = 3600; } // Copy constructor SipRefreshManager::SipRefreshManager(const SipRefreshManager& rSipRefreshManager) : mRefreshMgrMutex(OsMutex::Q_FIFO) { // NOT ALLOWED } // Destructor SipRefreshManager::~SipRefreshManager() { // Do not delete mpUserAgent ,mpDialogMgr. They // may be used else where and need to be deleted outside the // SipRefreshManager. // Stop receiving SUBSCRIBE responses mpUserAgent->removeMessageObserver(*(getMessageQueue())); // Wait until this OsServerTask has stopped or handleMethod // might access something we are about to delete here. waitUntilShutDown(); // Delete the event type strings mEventTypes.destroyAll(); // Unsubscribe to anything that is in the list stopAllRefreshes(); // mRefreshes should now be empty } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipRefreshManager& SipRefreshManager::operator=(const SipRefreshManager& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } UtlBoolean SipRefreshManager::initiateRefresh(SipMessage& subscribeOrRegisterRequest, void* applicationData, const RefreshStateCallback refreshStateCallback, UtlString& earlyDialogHandle) { UtlBoolean intitialRequestSent = FALSE; // Make sure we do not have an existing dialog or refresh session state // going for the given message UtlString messageDialogHandle; subscribeOrRegisterRequest.getDialogHandle(messageDialogHandle); UtlBoolean existingRefreshState = FALSE; UtlBoolean existingDialogState = FALSE; if(!SipDialog::isEarlyDialog(messageDialogHandle)) { existingDialogState = TRUE; OsSysLog::add(FAC_SIP, PRI_ERR, "SipRefreshManager::initiateRefresh called with established dialog handle: %s", messageDialogHandle.data()); } else { OsLock localLock(mRefreshMgrMutex); // See if there is an early or established dialog for this message if(getAnyDialog(messageDialogHandle)) { existingRefreshState = TRUE; intitialRequestSent = FALSE; OsSysLog::add(FAC_SIP, PRI_ERR, "SipRefreshManager::initiateRefresh called with pre-existing refresh state: %s", messageDialogHandle.data()); } // The dialog should not exist either else if(mpDialogMgr->dialogExists(messageDialogHandle) || mpDialogMgr->earlyDialogExistsFor(messageDialogHandle)) { existingDialogState = TRUE; OsSysLog::add(FAC_SIP, PRI_ERR, "SipRefreshManager::initiateRefresh called with pre-existing dialog: %s", messageDialogHandle.data()); } } // Should not be any existing refresh or dialog states // for this message if(!existingRefreshState && !existingDialogState) { // Make sure we are registered to receive responses // for the message we are about to send UtlString method; subscribeOrRegisterRequest.getRequestMethod(&method); if(method.compareTo(SIP_REGISTER_METHOD) == 0) { lock(); if(!mReceivingRegisterResponses) { mReceivingRegisterResponses = TRUE; // receive REGISTER responses mpUserAgent->addMessageObserver(*(getMessageQueue()), SIP_REGISTER_METHOD, FALSE, // yes requests TRUE, // no responses TRUE, // incoming, FALSE, // outgoing NULL); } unlock(); } else if(method.compareTo(SIP_SUBSCRIBE_METHOD) == 0) { UtlString eventType; subscribeOrRegisterRequest.getEventField(&eventType, NULL); // Check to see if we have already registered to // receive the event type lock(); if(mEventTypes.find(&eventType) == NULL) { mEventTypes.insert(new UtlString(eventType)); // receive SUBSCRIBE responses for this event type mpUserAgent->addMessageObserver(*(getMessageQueue()), SIP_SUBSCRIBE_METHOD, FALSE, // no requests TRUE, // yes responses TRUE, // incoming, FALSE, // outgoing eventType); } unlock(); } // Create a new refresh state int requestedExpiration = 0; // returned from following call RefreshDialogState* state = createNewRefreshState(subscribeOrRegisterRequest, messageDialogHandle, applicationData, refreshStateCallback, requestedExpiration); // create a new dialog mpDialogMgr->createDialog(subscribeOrRegisterRequest, TRUE, // message from this side messageDialogHandle); // Keep track of when we send this request to be refreshed long now = OsDateTime::getSecsSinceEpoch(); state->mPendingStartTime = now; state->mRequestState = REFRESH_REQUEST_PENDING; // Set a timer at which to resend the next refresh based upon the // assumption that the request will succeed. When we receive a // failed response, we will cancel the timer and reschedule // a new timer based upon a smaller fraction of the requested // expiration period setRefreshTimer(*state, TRUE); // Resend with successful timeout OsTimer* resendTimer = state->mpRefreshTimer; OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipRefreshManager::initiateRefresh refreshTimer just being set."); // Mark the refresh state as having an outstanding request // and make a copy of the request. The copy needs to be // attached to the state before the send incase the response // comes back before we return from the send. state->mRequestState = REFRESH_REQUEST_PENDING; state->mpLastRequest = new SipMessage(subscribeOrRegisterRequest); // Add the state to the container of refresh states // No need to lock this refreshMgr earlier as this is a new // state and no one can touch it until it is in the list. lock(); mRefreshes.insert(state); unlock(); // NOTE: at this point is is no longer safe to touch the state // without locking it again. Avoid locking this refresh mgr // when something can block (e.g. like calling SipUserAgent ::send) // Send the request // Is the correct? Should we send the request first and only set // a timer if the request succeeds?? intitialRequestSent = mpUserAgent->send(subscribeOrRegisterRequest); // We do not clean up the state even if the send fails. // The application must end the refresh as the refresh // manager should retry the send if it failed if(!intitialRequestSent) { // Need to lock this refresh mgr and make sure the state // still exists. It could have been deleted while this // was unlocked above. lock(); if(stateExists(state)) { // It is now safe to touch the state again // Mark the state of the last request as having // failed, so we know to resend when the timer // fires state->mRequestState = REFRESH_REQUEST_FAILED; // The expiration should still be set to zero // the initial send failed, cancel the timer and // fire the notification. The handleMessage method // will see that the subscription or registration // has never succeeded and reshedule the timer for // a failure timeout. We cannot reschedule the // timer here as there is a race condition between // deleting the timer here (in the applications context) // and in handleMessage in this refresh manager's // context. // If the timer has not changed assume it is still safe // to touch it if(state->mpRefreshTimer == resendTimer) { stopTimerForFailureReschedule(state->mpRefreshTimer); } // Do not notify the application that the request failed // when it occurs on the first invokation. The application // will know by the return. } unlock(); } } return(intitialRequestSent); } UtlBoolean SipRefreshManager::stopRefresh(const char* dialogHandle) { UtlBoolean stateFound = FALSE; lock(); // Find the refresh state UtlString dialogHandleString(dialogHandle); RefreshDialogState* state = getAnyDialog(dialogHandleString); // Remove the state so we can release the lock if(state) { mRefreshes.removeReference(state); } unlock(); // If a matching state exists if(state) { // If the subscription or registration has not expired // or there is a pending request long now = OsDateTime::getSecsSinceEpoch(); if(state->mExpiration > now || state->mRequestState == REFRESH_REQUEST_PENDING) { if(state->mpLastRequest) { // Reset the request with a zero expiration setForResend(*state, TRUE); // expire now // Don't really need to set this stuff as we are // going to delete the state anyway state->mRequestState = REFRESH_REQUEST_PENDING; state->mPendingStartTime = now; state->mExpirationPeriodSeconds = 0; mpUserAgent->send(*(state->mpLastRequest)); // Invoke the refresh state call back to indicate // the refresh has been expired UtlBoolean stateKeyIsEarlyDialog = SipDialog::isEarlyDialog(*state); (state->mpStateCallback)(state->mRequestState, stateKeyIsEarlyDialog ? state->data() : NULL, stateKeyIsEarlyDialog ? NULL : state->data(), state->mpApplicationData, -1, // responseCode NULL, // responseText, 0, // zero means expires now NULL); // response } // No prior request for some reason else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipRefreshManager::stopRefresh state with NULL mpLastRequest"); } } // Stop and delete the refresh timer state->mpRefreshTimer->stop(); deleteTimerAndEvent(state->mpRefreshTimer); // Get rid of the dialog mpDialogMgr->deleteDialog(*state); // Fire and forget delete state; state = NULL; stateFound = TRUE; } return(stateFound); } void SipRefreshManager::stopAllRefreshes() { // Not sure if it is safe to take the lock on this // and keep it while we unsubscribe and unregister // everything. There are some locking issues related // to handling incoming messages that might be a // problem. RefreshDialogState* dialogKey = NULL; lock(); UtlHashMapIterator iterator(mRefreshes); while((dialogKey = (RefreshDialogState*) iterator())) { // Unsubscribe or unregister. // This also deletes RefreshDialogState object, so it should not // be touched afterwards. stopRefresh(*dialogKey); } unlock(); } UtlBoolean SipRefreshManager::handleMessage(OsMsg &eventMessage) { int msgType = eventMessage.getMsgType(); int msgSubType = eventMessage.getMsgSubType(); // Timer fired if(msgType == OsMsg::OS_EVENT && msgSubType == OsEventMsg::NOTIFY) { intptr_t eventData = 0; RefreshDialogState* state = NULL; ((OsEventMsg&)eventMessage).getUserData((intptr_t&)state); ((OsEventMsg&)eventMessage).getEventData(eventData); lock(); // If the state is not still in the list we cannot // touch it. It may have been deleted. if(state && stateExists(state)) { // Refresh request failed, need to clean up and // schedule a refresh in a short/failed time period if(eventData == OS_INTERRUPTED) { // Clean up the timer and notifier deleteTimerAndEvent(state->mpRefreshTimer); state->mpRefreshTimer = NULL; // Create and set a new timer for the failed time out period setRefreshTimer(*state, FALSE); // Resend with failure timeout OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipRefreshManager::handleMessage refreshTimer just being set for the failed timeout."); } // Normal timer fire, time to refresh else if(eventData != 0 || ((OsTimer*)eventData) == state->mpRefreshTimer) { // Clean up the timer and notifier deleteTimerAndEvent(state->mpRefreshTimer); state->mpRefreshTimer = NULL; // Legitimate states to reSUBSCRIBE or reREGISTER if(state->mRequestState == REFRESH_REQUEST_FAILED || state->mRequestState == REFRESH_REQUEST_SUCCEEDED) { // Create and set a new timer for resending assuming // the resend is successful. If it fails we will // cancel the timer and set a shorter timeout setRefreshTimer(*state, TRUE); // Resend with successful timeout OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipRefreshManager::handleMessage refreshTimer just being set for the normal timeout."); // reset the message for resend setForResend(*state, FALSE); // do not expire now // Keep track of when this refresh is sent so we know // when the new expiration is relative to. state->mPendingStartTime = OsDateTime::getSecsSinceEpoch(); // Do not want to keep the lock while we send the // message as it could block. Presumably it is better // to incure the cost of copying the message???? SipMessage tempRequest(*(state->mpLastRequest)); UtlString lastRequest; int length; state->mpLastRequest->getBytes(&lastRequest, &length); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipRefreshManager::handleMessage last request = \n%s", lastRequest.data()); unlock(); mpUserAgent->send(tempRequest); // do not need the lock any more, but this gives us // clean locking symmetry. DO NOT TOUCH state or // any of its members BEYOND this point as it may // have been deleted lock(); } // This should not happen else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipRefreshManager::handleMessage timer fired for state: %d", state->mRequestState); if(state->mRequestState == REFRESH_REQUEST_PENDING) { // Try again later if it was pending setRefreshTimer(*state, FALSE); // Resend with failed timeout OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipRefreshManager::handleMessage refreshTimer just being resent for the failed timeout."); } } } // Bad do not know what happened else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipRefreshManager::handleMessage timer: %"PRIxPTR" does not match states timer: %p", eventData, state->mpRefreshTimer); } } unlock(); } // SIP message else if(msgType == OsMsg::PHONE_APP && msgSubType == SipMessage::NET_SIP_MESSAGE) { const SipMessage* sipMessage = ((SipMessageEvent&)eventMessage).getMessage(); int messageType = ((SipMessageEvent&)eventMessage).getMessageStatus(); // messageType can be: // SipMessageEvent::TRANSPORT_ERROR for requests that do not get sent // but we would have to register with the SipUserAgent to // receive requests. // SipMessageEvent::AUTHENTICATION_RETRY for 401 or 407 responses // that are resent with credentials. We ge this message so // that we can keep the dialog info. up to date. // SipMessageEvent::APPLICATION normal messages // For now we will treat the APPLICATION and AUTHENTICATION_RETRY // identically. // If this is a SUBSCRIBE or REGISTER response UtlString method; int cseq; if(sipMessage) sipMessage->getCSeqField(&cseq, &method); if(sipMessage && sipMessage->isResponse() && (method.compareTo(SIP_SUBSCRIBE_METHOD) == 0 || method.compareTo(SIP_REGISTER_METHOD) == 0)) { UtlString eventField; sipMessage->getEventField(&eventField, NULL); // We could validate that the event field is // set and is the right event type, but mostly // we should not care as we know the event type // from the subscription. We can be tolerant of // missing or malformed event headers in the // NOTIFY request. The event header is not // required in the subscribe response. UtlString dialogHandle; UtlString earlyDialogHandle; sipMessage->getDialogHandle(dialogHandle); UtlBoolean foundDialog = mpDialogMgr->dialogExists(dialogHandle); UtlBoolean foundEarlyDialog = FALSE; UtlBoolean matchesLastLocalTransaction = FALSE; if(foundDialog) { matchesLastLocalTransaction = mpDialogMgr->isLastLocalTransaction(*sipMessage, dialogHandle); } else { foundEarlyDialog = mpDialogMgr->getEarlyDialogHandleFor(dialogHandle, earlyDialogHandle); if(foundEarlyDialog) { matchesLastLocalTransaction = mpDialogMgr->isLastLocalTransaction(*sipMessage, earlyDialogHandle); } } #ifdef TEST_PRINT osPrintf("Looking for refresh state with dialog handle: %s\n", dialogHandle.data()); UtlString refreshStateDump; dumpRefreshStates(refreshStateDump); osPrintf("SipRefreshManager::handleMessage state dump:\n%s\n", refreshStateDump.data()); #endif lock(); // Find the refresh state for this response RefreshDialogState* state = NULL; if(foundDialog && matchesLastLocalTransaction) { state = (RefreshDialogState*) mRefreshes.find(&dialogHandle); // Check if the key has the tags reversed if(state == NULL) { UtlString reversedDialogHandle; SipDialog::reverseTags(dialogHandle, reversedDialogHandle); state = (RefreshDialogState*) mRefreshes.find(&reversedDialogHandle); } } else if(foundEarlyDialog && matchesLastLocalTransaction) { state = (RefreshDialogState*) mRefreshes.remove(&earlyDialogHandle); // See if the key has the tags reversed if(state == NULL) { UtlString reversedEarlyDialogHandle; SipDialog::reverseTags(earlyDialogHandle, reversedEarlyDialogHandle); state = (RefreshDialogState*) mRefreshes.remove(&reversedEarlyDialogHandle); } if(state) { #ifdef TEST_PRINT osPrintf("Removed refresh state with dialog handle: %s\n", state->data()); osPrintf("Inserting refresh state with dialog handle: %s\n", dialogHandle.data()); #endif // Fix the state handle and put it back in the list *((UtlString*) state) = dialogHandle; mRefreshes.insert(state); } } if(state) { // Need to check for error responses or 2xx class responses int responseCode = sipMessage->getResponseStatusCode(); UtlString responseText; sipMessage->getResponseStatusText(&responseText); // Update the expiration members int expirationPeriod = 0; if(responseCode >= SIP_2XX_CLASS_CODE && responseCode < SIP_3XX_CLASS_CODE) { // Should we tolerate no Expires header in response? // Currently assume that if Expires header is not // set that we got what we asked for if(!getAcceptedExpiration(state, *sipMessage, expirationPeriod)) { expirationPeriod = state->mExpirationPeriodSeconds; } // SUBSCRIBE or REGISTER gave us expiration seconds // from when the request was sent. if(expirationPeriod > 0) { state->mExpiration = state->mPendingStartTime + expirationPeriod; } // UnSUBSCRIBE or unREGISTER else { state->mExpiration = 0; } // The request succeeded state->mRequestState = REFRESH_REQUEST_SUCCEEDED; } // Provisional response, do nothing else if(responseCode < SIP_2XX_CLASS_CODE) { } // There was a resend with credentials for this // failed response (should be a 401 or 407 auth. // challenge. else if(messageType == SipMessageEvent::AUTHENTICATION_RETRY) { // Do not stop the timer and do not change the // state from PENDING to FAILED } // a non-success response code, don't care what // type of error. It is the applications job // to care. If the credentials are wrong, the // application needs to fix it. We will just keep // on trying, hoping that the credentials get fixed on //this side or on the server side else { state->mFailedResponseCode = responseCode; state->mFailedResponseText = responseText; state->mRequestState = REFRESH_REQUEST_FAILED; // Do not change the expiration date, it // is what ever it was before the response was // sent. // Kill the timer and have it fire now and // reschedule with the error timeout. We // cannot delete the timer or notifier here // as there is a race condition where the // timer might fire before we delete it. Then // it would be deleted twice (i.e. bad). stopTimerForFailureReschedule(state->mpRefreshTimer); } //updateState(state, sipMessage); mpDialogMgr->updateDialog(*sipMessage); // Invoke the callback to let the application // know that the state changed if(state->mpStateCallback) { (state->mpStateCallback)(state->mRequestState, earlyDialogHandle, dialogHandle, state->mpApplicationData, responseCode, // responseCode responseText, // responseText, state->mExpiration, // zero means expires now sipMessage); // response } } unlock(); } // endif SUBSCRIBE or REGISTER response } // endif SipMessage event return(TRUE); } /* ============================ ACCESSORS ================================= */ void SipRefreshManager::refreshState2String(RefreshRequestState state, UtlString& stateString) { switch(state) { case REFRESH_REQUEST_UNKNOWN: stateString = "REFRESH_REQUEST_UNKNOWN"; break; case REFRESH_REQUEST_PENDING: stateString = "REFRESH_REQUEST_PENDING"; break; case REFRESH_REQUEST_FAILED: stateString = "REFRESH_REQUEST_FAILED"; break; case REFRESH_REQUEST_SUCCEEDED: stateString = "REFRESH_REQUEST_SUCCEEDED"; break; default: { stateString = "unknown: "; char numBuf[20]; sprintf(numBuf, "%d", state); stateString.append(numBuf); } break; } } int SipRefreshManager::dumpRefreshStates(UtlString& dumpString) { int count = 0; dumpString.remove(0); lock(); UtlHashMapIterator iterator(mRefreshes); RefreshDialogState* state = NULL; UtlString oneStateDump; while((state = (RefreshDialogState*) iterator())) { state->toString(oneStateDump); dumpString.append(oneStateDump); count++; } unlock(); return(count); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ void SipRefreshManager::lock() { mRefreshMgrMutex.acquire(); } void SipRefreshManager::unlock() { mRefreshMgrMutex.release(); } /* //////////////////////////// PRIVATE /////////////////////////////////// */ RefreshDialogState* SipRefreshManager::getAnyDialog(UtlString& messageDialogHandle) { RefreshDialogState* state = (RefreshDialogState*) mRefreshes.find(&messageDialogHandle); if(state == NULL) { UtlString reversedHandle; SipDialog::reverseTags(messageDialogHandle, reversedHandle); state = (RefreshDialogState*) mRefreshes.find(&reversedHandle); } // It did not match if(state == NULL) { // If this is an early dialog handle find out what the // established dialog is UtlString establishedDialogHandle; if(mpDialogMgr->getEstablishedDialogHandleFor(messageDialogHandle, establishedDialogHandle)) { state = (RefreshDialogState*) mRefreshes.find(&establishedDialogHandle); if(state == NULL) { UtlString reversedEstablishedDialogHandle; SipDialog::reverseTags(establishedDialogHandle, reversedEstablishedDialogHandle); state = (RefreshDialogState*) mRefreshes.find(&reversedEstablishedDialogHandle); } } // If this is an established dialog, find out what the // early dialog handle was and see if we can find it else { UtlString earlyDialogHandle; mpDialogMgr->getEarlyDialogHandleFor(messageDialogHandle, earlyDialogHandle); state = (RefreshDialogState*) mRefreshes.find(&earlyDialogHandle); if(state == NULL) { UtlString reversedEarlyDialogHandle; SipDialog::reverseTags(earlyDialogHandle, reversedEarlyDialogHandle); state = (RefreshDialogState*) mRefreshes.find(&reversedEarlyDialogHandle); } } } return(state); } UtlBoolean SipRefreshManager::stateExists(RefreshDialogState* statePtr) { // Assume we already have the lock // Does not seem to be a method to test if the reference // exists. If this end up being a performance problem // should probably add a method to UtlHashBag RefreshDialogState* state = (RefreshDialogState*) mRefreshes.removeReference(statePtr); if(state) { mRefreshes.insert(state); } return(state != NULL); } RefreshDialogState* SipRefreshManager::createNewRefreshState(SipMessage& subscribeOrRegisterRequest, UtlString& messageDialogHandle, void* applicationData, const RefreshStateCallback refreshStateCallback, int& requestedExpiration) { RefreshDialogState* state = new RefreshDialogState(); *((UtlString*) state) = messageDialogHandle; state->mpApplicationData = applicationData; state->mpStateCallback = refreshStateCallback; if(!getInitialExpiration(subscribeOrRegisterRequest, state->mExpirationPeriodSeconds)) // original expiration { state->mExpirationPeriodSeconds = mDefaultExpiration; subscribeOrRegisterRequest.setExpiresField(mDefaultExpiration); } requestedExpiration = state->mExpirationPeriodSeconds; state->mPendingStartTime = 0; state->mExpiration = 0; state->mRequestState = REFRESH_REQUEST_UNKNOWN; state->mFailedResponseCode = 0; state->mFailedResponseText = NULL; state->mpRefreshTimer = NULL; state->mpLastRequest = NULL; return(state); } void SipRefreshManager::setRefreshTimer(RefreshDialogState& state, UtlBoolean isSuccessfulReschedule) { // Create and set a new timer for the failed time out period int nextResendSeconds = calculateResendTime(state.mExpirationPeriodSeconds, isSuccessfulReschedule); // If a signficant amount of time has passed since the prior // request was sent, decrease the error timeout a bit. // This is only a problem with the error case as in the // successful case we set the timer before sending the // request. if(!isSuccessfulReschedule) { long now = OsDateTime::getSecsSinceEpoch(); if(state.mPendingStartTime > 0 && now - state.mPendingStartTime > 5) { nextResendSeconds = nextResendSeconds - now + state.mPendingStartTime; if(nextResendSeconds < 30) { nextResendSeconds = 30; } } } OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipRefreshManager::setRefreshTimer setting resend timeout in %d seconds\n", nextResendSeconds); OsMsgQ* incomingQ = getMessageQueue(); OsTimer* resendTimer = new OsTimer(incomingQ, (intptr_t)&state); state.mpRefreshTimer = resendTimer; OsTime timerTime(nextResendSeconds, 0); resendTimer->oneshotAfter(timerTime); } int SipRefreshManager::calculateResendTime(int requestedExpiration, UtlBoolean isSuccessfulResend) { int expiration; if(isSuccessfulResend) { expiration = (int)(0.55 * requestedExpiration); } else { expiration = (int)(0.1 * requestedExpiration); } // Clamp it to a minimum of a transaction timeout int minRefresh = (mpUserAgent->getSipStateTransactionTimeout())/1000; if(expiration < minRefresh) { expiration = minRefresh; } return(expiration); } void SipRefreshManager::stopTimerForFailureReschedule(OsTimer* resendTimer) { if(resendTimer) { resendTimer->stop(); OsQueuedEvent* queuedEvent = (OsQueuedEvent*) resendTimer->getNotifier(); // If the queued event exists fire it now with an error status // to indicate that it should be resheduled with the (shorter) // error timeout. Normally the timer is scheduled with the // timeout assuming that the reSUBSCRIBE or reREGISTER will // succeed. if(queuedEvent) { // Effectively make the timer fire now queuedEvent->signal(OS_INTERRUPTED); // CANCELED } } } void SipRefreshManager::deleteTimerAndEvent(OsTimer* timer) { if(timer) { delete timer; timer = NULL; } } void SipRefreshManager::setForResend(RefreshDialogState& state, UtlBoolean expireNow) { if(state.mpLastRequest) { UtlString lastRequest; int length; state.mpLastRequest->getBytes(&lastRequest, &length); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipRefreshManager::setForResend last request = \n%s", lastRequest.data()); // Remove old vias state.mpLastRequest->removeLastVia(); // Remove old routes UtlString route; while(state.mpLastRequest->removeRouteUri(0, &route)) { } // Remove any credentials while(state.mpLastRequest->removeHeader(HTTP_AUTHORIZATION_FIELD, 0)) { } while(state.mpLastRequest->removeHeader(HTTP_PROXY_AUTHORIZATION_FIELD, 0)) { } // Remove transport state info state.mpLastRequest->resetTransport(); // Set the dialog info and cseq mpDialogMgr->setNextLocalTransactionInfo(*(state.mpLastRequest)); // Set the expiration if (expireNow) { state.mpLastRequest->setExpiresField(0); } else { state.mpLastRequest->setDateField(); } } } UtlBoolean SipRefreshManager::getInitialExpiration(const SipMessage& sipRequest, int& expirationPeriod) { UtlString method; UtlBoolean foundExpiration = FALSE; sipRequest.getRequestMethod(&method); if(method.compareTo(SIP_REGISTER_METHOD) == 0) { // Register could have it in the Contact header UtlString requestContactValue; if(sipRequest.getContactEntry(0 , &requestContactValue)) { // Get the expires parameter for the contact if it exists Url contactUri(requestContactValue); UtlString contactExpiresParameter; if(contactUri.getFieldParameter(SIP_EXPIRES_FIELD, contactExpiresParameter) && !contactExpiresParameter.isNull()) { foundExpiration = TRUE; // Convert to int expirationPeriod = atoi(contactExpiresParameter); } } } if(!foundExpiration) { // Not sure if we care if this is a request or response foundExpiration = sipRequest.getExpiresField(&expirationPeriod); } return(foundExpiration); } UtlBoolean SipRefreshManager::getAcceptedExpiration(RefreshDialogState* state, const SipMessage& sipResponse, int& expirationPeriod) { UtlString method; UtlBoolean foundExpiration = FALSE; int cseq; sipResponse.getCSeqField(&cseq, &method); if(method.compareTo(SIP_REGISTER_METHOD) == 0) { // Get the presumably first contact in the REGISTER request // so that we can find the same contact in the response and // find out what the expiration is UtlString requestContact; Url requestContactUri; if(state && state->mpLastRequest && state->mpLastRequest->getContactEntry(0, &requestContact)) { requestContactUri = requestContact; } // Register could have it in the Contact header UtlString responseContactValue; int contactIndex = 0; while(sipResponse.getContactEntry(contactIndex , &responseContactValue)) { // Get the expires parameter for the contact if it exists Url contactUri(responseContactValue); if(requestContactUri.isUserHostPortEqual(contactUri)) { UtlString contactExpiresParameter; if(contactUri.getFieldParameter(SIP_EXPIRES_FIELD, contactExpiresParameter) && !contactExpiresParameter.isNull()) { foundExpiration = TRUE; // Convert to int expirationPeriod = atoi(contactExpiresParameter); } } contactIndex++; } } if(!foundExpiration) { // Not sure if we care if this is a request or response foundExpiration = sipResponse.getExpiresField(&expirationPeriod); } return(foundExpiration); } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipRequestContext.cpp0000644000175000017500000001314212205613256025350 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS const char* SipRequestContext::sAUTH_USER = "AUTH_USER"; const char* SipRequestContext::sAUTH_REALM = "AUTH_REALM"; const char* SipRequestContext::sREQUEST_METHOD = "REQUEST_METHOD"; const char* SipRequestContext::sSERVER_DOMAIN = "SERVER_DOMAIN"; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipRequestContext::SipRequestContext(const char* requestMethod) { if(requestMethod) { addVariable(sREQUEST_METHOD, requestMethod); } } // Copy constructor SipRequestContext::SipRequestContext(const SipRequestContext& rSipRequestContext) { // delete the old values in the UtlDList if(!mVariableList.isEmpty()) { mVariableList.destroyAll(); } //copy mVariableList memebers individually UtlDListIterator iterator((UtlDList&)rSipRequestContext.mVariableList); NameValuePair* nameValuePair = NULL; UtlString value; UtlString name; int index = 0; do { nameValuePair = (NameValuePair*)iterator(); if(nameValuePair) { name.append(*nameValuePair); value.append(nameValuePair->getValue()); NameValuePair* newNvPair = new NameValuePair(name, value); mVariableList.insertAt(index, newNvPair); index ++; name.remove(0); value.remove(0); } } while (nameValuePair != NULL); } // Destructor SipRequestContext::~SipRequestContext() { mVariableList.destroyAll(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipRequestContext& SipRequestContext::operator=(const SipRequestContext& rhs) { if (this == &rhs) // handle the assignment to self case return *this; else { // delete the old values in the UtlDList if(!mVariableList.isEmpty()) { mVariableList.destroyAll(); } //copy mVariableList members individually UtlDListIterator iterator((UtlDList&)rhs.mVariableList); NameValuePair* nameValuePair = NULL; UtlString value; UtlString name; int index = 0; do { nameValuePair = (NameValuePair*)iterator(); if(nameValuePair) { name.append(*nameValuePair); value.append(nameValuePair->getValue()); NameValuePair* newNvPair = new NameValuePair(name, value); mVariableList.insertAt(index, newNvPair); index ++; value.remove(0); name.remove(0); } } while (nameValuePair != NULL); } return *this; } /* ============================ ACCESSORS ================================= */ UtlBoolean SipRequestContext::getVariable(const char* name, UtlString& value, int occurance) const { UtlDListIterator iterator((UtlDList&)mVariableList); NameValuePair* nameValuePair = NULL; int fieldIndex = 0; UtlString upperCaseName; UtlBoolean foundName = FALSE; value.remove(0); if(name) { upperCaseName.append(name); upperCaseName.toUpper(); } NameValuePair matchName(upperCaseName); // For each name value: while(fieldIndex <= occurance) { // Go to the next header field nameValuePair = (NameValuePair*) iterator.findNext(&matchName); if(!nameValuePair || fieldIndex == occurance) { break; } fieldIndex++; } if(fieldIndex == occurance && nameValuePair) { value.append(nameValuePair->getValue()); foundName = TRUE; } upperCaseName.remove(0); return(foundName); } int SipRequestContext::toString(UtlString& dumpString) { int count = 0; UtlString name; UtlString value; dumpString.remove(0); while(getVariable(count, name, value)) { dumpString.append(name); dumpString.append(": "); dumpString.append(value); dumpString.append("\n"); } return(count); } void SipRequestContext::addVariable(const char* name, const char* value) { NameValuePair* newNvPair = new NameValuePair(name, value); mVariableList.append(newNvPair); } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ UtlBoolean SipRequestContext::getVariable(int index, UtlString& name, UtlString& value) const { NameValuePair* nameValuePair = NULL; if((int)(mVariableList.entries()) > index && index >= 0) { nameValuePair = (NameValuePair*)mVariableList.at(index); if(nameValuePair) { name = *nameValuePair; value.remove(0); value.append(nameValuePair->getValue()); } else { name.remove(0); value.remove(0); } } return(nameValuePair != NULL); } /* //////////////////////////// PRIVATE /////////////////////////////////// */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipResourceList.cpp0000644000175000017500000002360112205613256024777 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const UtlContainableType TYPE = "ResourceList"; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor Resource::Resource(const char* uri) { mUri = uri; } // Destructor Resource::~Resource() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator Resource& Resource::operator=(const Resource& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } // Copy constructor Resource::Resource(const Resource& rResource) { mUri = rResource.mUri; } /* ============================ ACCESSORS ================================= */ void Resource::getResourceUri(UtlString& uri) const { uri = mUri; } void Resource::setName(const char* name) { mName = name; } void Resource::getName(UtlString& name) const { name = mName; } void Resource::setInstance(const char* id, const char* state) { mState = state; mId = id; } void Resource::getInstance(UtlString& id, UtlString& state) const { state = mState; id = mId; } int Resource::compareTo(const UtlContainable *b) const { return mUri.compareTo(((Resource *)b)->mUri); } unsigned int Resource::hash() const { return mUri.hash(); } const UtlContainableType Resource::getContainableType() const { return TYPE; } /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipResourceList::SipResourceList(const UtlBoolean state, const char* uri, const char* type) : mLock(OsBSem::Q_PRIORITY, OsBSem::FULL) { remove(0); append(RESOURCE_LIST_CONTENT_TYPE); mVersion = 0; if (state) { mFullState = "true"; } else { mFullState = "false"; } mListUri = uri; mEventType = type; } SipResourceList::SipResourceList(const char* bodyBytes, const char* type) : mLock(OsBSem::Q_PRIORITY, OsBSem::FULL) { remove(0); append(RESOURCE_LIST_CONTENT_TYPE); if(bodyBytes) { bodyLength = strlen(bodyBytes); parseBody(bodyBytes); } ((SipResourceList*)this)->mBody = bodyBytes; mEventType = type; } // Destructor SipResourceList::~SipResourceList() { // Clean up all the resource elements if (!mResources.isEmpty()) { mResources.destroyAll(); } // Clean up all the event elements if (!mEvents.isEmpty()) { mEvents.destroyAll(); } } /* ============================ MANIPULATORS ============================== */ void SipResourceList::parseBody(const char* bodyBytes) { if(bodyBytes) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipResourceList::parseBody incoming package = %s\n", bodyBytes); TiXmlDocument doc("ResourceList.xml"); if (doc.Parse(bodyBytes)) { TiXmlNode * rootNode = doc.FirstChild ("list"); TiXmlElement* ucElement = 0; } } } // Assignment operator SipResourceList& SipResourceList::operator=(const SipResourceList& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } /* ============================ ACCESSORS ================================= */ void SipResourceList::insertResource(Resource* resource) { mLock.acquire(); if (mResources.insert(resource) != NULL) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipResourceList::insertResource Resource = %p", resource); } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipResourceList::insertResource Resource = %p failed", resource); } mLock.release(); } Resource* SipResourceList::removeResource(Resource* resource) { mLock.acquire(); UtlContainable *foundValue; foundValue = mResources.remove(resource); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipResourceList::removeResource Resource = %p", foundValue); mLock.release(); return (Resource *) foundValue; } Resource* SipResourceList::getResource(UtlString& resourceUri) { mLock.acquire(); UtlHashMapIterator resourceIterator(mResources); Resource* pResource; UtlString foundValue; while ((pResource = (Resource *) resourceIterator())) { pResource->getResourceUri(foundValue); if (foundValue.compareTo(resourceUri) == 0) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipResourceList::getResource found Resource = %p for resourceUri %s", pResource, resourceUri.data()); mLock.release(); return pResource; } } OsSysLog::add(FAC_SIP, PRI_WARNING, "SipResourceList::getResource could not found the Resource for resourceUri = %s", resourceUri.data()); mLock.release(); return NULL; } UtlBoolean SipResourceList::isEmpty() { return (mResources.isEmpty()); } void SipResourceList::insertEvent(UtlContainable* event) { mLock.acquire(); if (mEvents.insert(event) != NULL) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipResourceList::insertEvent Event = %p", event); } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipResourceList::insertEvent Event = %p failed", event); } mLock.release(); } UtlContainable* SipResourceList::removeEvent(UtlContainable* event) { mLock.acquire(); UtlContainable *foundValue; foundValue = mEvents.remove(event); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipResourceList::removeEvent Event = %p", foundValue); mLock.release(); return foundValue; } void SipResourceList::getEventType(UtlString& type) const { type = mEventType; } void SipResourceList::getListUri(UtlString& uri) const { uri = mListUri; } int SipResourceList::getLength() const { int length; UtlString tempBody; getBytes(&tempBody, &length); return length; } void SipResourceList::buildBody() const { UtlString resourceList; UtlString singleLine; char version[20]; // Construct the xml document of resource list resourceList = UtlString(XML_VERSION_1_0); // Information Structure Url listUri(mListUri); resourceList.append(BEGIN_LIST); resourceList.append(URI_EQUAL); singleLine = DOUBLE_QUOTE + listUri.toString() + DOUBLE_QUOTE; resourceList += singleLine; sprintf(version, "%d", mVersion); resourceList.append(VERSION_EQUAL); singleLine = DOUBLE_QUOTE + UtlString(version) + DOUBLE_QUOTE; resourceList += singleLine; resourceList.append(FULL_STATE_EQUAL); singleLine = DOUBLE_QUOTE + mFullState + DOUBLE_QUOTE; resourceList += singleLine; resourceList.append(END_LINE); // Resource elements ((SipResourceList*)this)->mLock.acquire(); UtlHashMapIterator resourceIterator(mResources); Resource* pResource; while ((pResource = (Resource *) resourceIterator())) { UtlString uriStr; pResource->getResourceUri(uriStr); Url uri(uriStr); resourceList.append(BEGIN_RESOURCE); singleLine = DOUBLE_QUOTE + uri.toString() + DOUBLE_QUOTE; resourceList += singleLine; resourceList.append(END_LINE); // Name element UtlString name; pResource->getName(name); if (!name.isNull()) { singleLine = BEGIN_CONTACT + name + END_CONTACT; resourceList += singleLine; } UtlString id, state; pResource->getInstance(id, state); resourceList.append(BEGIN_INSTANCE); singleLine = DOUBLE_QUOTE + id + DOUBLE_QUOTE; resourceList += singleLine; resourceList.append(STATE_EQUAL); singleLine = DOUBLE_QUOTE + state + DOUBLE_QUOTE; resourceList += singleLine; resourceList.append(END_LINE); // End of resource element resourceList.append(END_RESOURCE); } // End of list element resourceList.append(END_LIST); ((SipResourceList*)this)->mLock.release(); ((SipResourceList*)this)->mBody = resourceList; ((SipResourceList*)this)->bodyLength = resourceList.length(); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipResourceList::getBytes Resource list content = \n%s", resourceList.data()); ((SipResourceList*)this)->mVersion++; } void SipResourceList::getBytes(const char** bytes, int* length) const { UtlString tempBody; getBytes(&tempBody, length); ((SipResourceList*)this)->mBody = tempBody.data(); *bytes = mBody.data(); } void SipResourceList::getBytes(UtlString* bytes, int* length) const { buildBody(); *bytes = ((SipResourceList*)this)->mBody; *length = ((SipResourceList*)this)->bodyLength; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipServerBroker.cpp0000644000175000017500000000360512205613256024771 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include "os/OsDefs.h" #include #include #include "os/OsTask.h" #include "os/OsPtrMsg.h" // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsTask.h" #include "os/OsServerTask.h" #include "os/OsConnectionSocket.h" #include "os/OsEvent.h" #include "os/OsNotification.h" #include "net/SipServerBroker.h" #include "os/OsServerSocket.h" #include "os/OsEventMsg.h" #include "net/SipTcpServer.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS SipServerBroker::SipServerBroker(OsServerTask* pTask, OsServerSocket* pSocket) : OsTask("SipServerBroker - %d"), mpSocket(pSocket), mpOwnerTask(pTask) { start(); } int SipServerBroker::run(void *pNotUsed) { OsConnectionSocket* clientSocket = NULL; while(mpSocket && !isShuttingDown() && mpSocket->isOk()) { clientSocket = mpSocket->accept(); // post a message, containing the the client socket, // to the owner if(!isShuttingDown() && mpSocket && clientSocket) { OsPtrMsg ptrMsg(OsMsg::OS_EVENT, SIP_SERVER_BROKER_NOTIFY, (void*)clientSocket); mpOwnerTask->postMessage(ptrMsg); } } return 0; } // Destructor SipServerBroker::~SipServerBroker() { requestShutdown(); if (mpSocket) { mpSocket->close(); } waitUntilShutDown(); delete mpSocket; mpSocket = NULL; } /************************************************************************/ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipServerBase.cpp0000644000175000017500000000331312205613256024413 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipServerBase::SipServerBase(SipUserAgent* sipUserAgent, const UtlString& defaultDomain) :mSipUserAgent(NULL) { mSipUserAgent = sipUserAgent; if(!defaultDomain.isNull()) { mDefaultDomain.remove(0); mDefaultDomain.append(defaultDomain); } } // Copy constructor SipServerBase::SipServerBase(const SipServerBase& rSipServerBase) { } // Destructor SipServerBase::~SipServerBase() { mSipUserAgent = NULL; } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipServerBase& SipServerBase::operator=(const SipServerBase& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipSession.cpp0000644000175000017500000002476412205613256024012 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipSession::SipSession(const SipMessage* initialMessage, UtlBoolean isFromLocal) { if(initialMessage) { UtlString callId; initialMessage->getCallIdField(&callId); append(callId); // The transaction was initiated from this side if((!initialMessage->isResponse() && isFromLocal) || (initialMessage->isResponse() && !isFromLocal)) { initialMessage->getFromUrl(mLocalUrl); initialMessage->getToUrl(mRemoteUrl); initialMessage->getCSeqField(&mInitialLocalCseq, &mInitialMethod); initialMessage->getRequestUri(&msLocalRequestUri); mLastFromCseq = mInitialLocalCseq; mLastToCseq = -1; } // The transaction was initiated from the other side else { initialMessage->getFromUrl(mRemoteUrl); initialMessage->getToUrl(mLocalUrl); initialMessage->getCSeqField(&mInitialRemoteCseq, &mInitialMethod); initialMessage->getRequestUri(&msRemoteRequestUri); mLastToCseq = mInitialRemoteCseq; mLastFromCseq = -1; mInitialLocalCseq = -1; } if(!initialMessage->isResponse()) { UtlString uri; initialMessage->getRequestUri(&uri); if(isFromLocal) { mRemoteContact = uri; } else { mLocalContact = uri; } } UtlString contact; initialMessage->getContactUri(0, &contact); if(isFromLocal) { mLocalContact = contact; } else { mRemoteContact = contact; } } else { mLastFromCseq = -1; mLastToCseq = -1; mInitialLocalCseq = -1; mInitialRemoteCseq = -1; } mSessionState = SESSION_UNKNOWN; } // Constructor SipSession::SipSession(const char* callId, const char* toUrl, const char* fromUrl) : UtlString(callId) { mRemoteUrl = Url(toUrl); mLocalUrl = Url(fromUrl); mInitialLocalCseq = -1; mInitialRemoteCseq = -1; mLastFromCseq = -1; mLastToCseq = -1; mSessionState = SESSION_UNKNOWN; } // Copy constructor SipSession::SipSession(const SipSession& rSipSession) : UtlString(rSipSession) { mLocalUrl = rSipSession.mLocalUrl; mRemoteUrl = rSipSession.mRemoteUrl; mLocalContact = rSipSession.mLocalContact; mRemoteContact = rSipSession.mRemoteContact; mInitialMethod = rSipSession.mInitialMethod; mInitialLocalCseq = rSipSession.mInitialLocalCseq; mInitialRemoteCseq = rSipSession.mInitialRemoteCseq; mLastFromCseq = rSipSession.mLastFromCseq; mLastToCseq = rSipSession.mLastToCseq; mSessionState = rSipSession.mSessionState; msLocalRequestUri = rSipSession.msLocalRequestUri; msRemoteRequestUri = rSipSession.msRemoteRequestUri; msContactUriStr = rSipSession.msContactUriStr; } // Destructor SipSession::~SipSession() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipSession& SipSession::operator=(const SipSession& rhs) { if (this == &rhs) // handle the assignment to self case return *this; UtlString::operator=(rhs); // assign fields for parent class mLocalUrl = rhs.mLocalUrl; mRemoteUrl = rhs.mRemoteUrl; mLocalContact = rhs.mLocalContact; mRemoteContact = rhs.mRemoteContact; mInitialMethod = rhs.mInitialMethod; mInitialLocalCseq = rhs.mInitialLocalCseq; mInitialRemoteCseq = rhs.mInitialRemoteCseq; mLastFromCseq = rhs.mLastFromCseq; mLastToCseq = rhs.mLastToCseq; mSessionState = rhs.mSessionState; msLocalRequestUri = rhs.msLocalRequestUri; msRemoteRequestUri = rhs.msRemoteRequestUri; msContactUriStr = rhs.msContactUriStr; return *this; } void SipSession::updateSessionData(SipMessage& message) { int cSeq; UtlString method; message.getCSeqField(&cSeq, &method); int responseCode = message.getResponseStatusCode(); // Figure out if the request is from the session initiator or // the destination if(isMessageFromInitiator(message)) { // This message is part of a transaction initiated by // the caller/initiator of the session if(cSeq > mLastFromCseq) { mLastFromCseq = cSeq; if(method.compareTo(SIP_BYE_METHOD) == 0) { mSessionState = SESSION_TERMINATED; } } if(cSeq == mInitialLocalCseq) { if(message.isResponse()) { if(method.compareTo(SIP_INVITE_METHOD) == 0) { if(responseCode >= SIP_OK_CODE && responseCode < SIP_3XX_CLASS_CODE) { mSessionState = SESSION_SETUP; // The tag gets set in the 2xx response // so we need to update the URL message.getToUrl(mRemoteUrl); } else if(responseCode > SIP_3XX_CLASS_CODE) { // The session failed to be setup mSessionState = SESSION_FAILED; } } } else { if(method.compareTo(SIP_INVITE_METHOD) == 0) { mSessionState = SESSION_INITIATED; } else if(method.compareTo(SIP_CANCEL_METHOD) == 0) { mSessionState = SESSION_FAILED; } } } } else if(isMessageFromDestination(message)) { // This message is part of a transaction initiated by // the callee/destination of the session if(cSeq > mLastToCseq) { mLastToCseq = cSeq; if(method.compareTo(SIP_BYE_METHOD) == 0) { mSessionState = SESSION_TERMINATED; } } } } /* ============================ ACCESSORS ================================= */ void SipSession::getCallId(UtlString& callId) { callId = data(); } void SipSession::setCallId(const char* callId) { remove(0); append(callId ? callId : ""); } void SipSession::getFromUrl(Url& fromUrl) { fromUrl = mLocalUrl; } void SipSession::setFromUrl(const Url& fromUrl) { mLocalUrl = fromUrl; } void SipSession::getToUrl(Url& toUrl) { toUrl = mRemoteUrl; } void SipSession::setToUrl(const Url& toUrl) { mRemoteUrl = toUrl; } void SipSession::getRemoteContact(Url& remoteContact) { remoteContact = mRemoteContact; } void SipSession::setRemoteContact(const Url& remoteContact) { mRemoteContact = remoteContact; } void SipSession::getLocalContact(Url& localContact) { localContact = mLocalContact; } void SipSession::setLocalContact(const Url& localContact) { mLocalContact = localContact; } void SipSession::getLocalRequestUri(UtlString& requestUri) { requestUri = msLocalRequestUri; } void SipSession::setLocalRequestUri(UtlString& requestUri) { msLocalRequestUri = requestUri; } void SipSession::getRemoteRequestUri(UtlString& requestUri) { requestUri = msRemoteRequestUri; } void SipSession::setRemoteRequestUri(UtlString& requestUri) { msRemoteRequestUri = requestUri; } void SipSession::getContactRequestUri(UtlString& requestContactUri) { requestContactUri = msContactUriStr; } void SipSession::setContactRequestUri(UtlString& requestContactUri) { msContactUriStr = requestContactUri; } void SipSession::getInitialMethod(UtlString& method) { method = mInitialMethod; } void SipSession::setInitialMethod(const char* method) { mInitialMethod = method; } int SipSession::getLastFromCseq() { return(mLastFromCseq); } void SipSession::setLastFromCseq(int lastFromCseq) { mLastFromCseq = lastFromCseq; } int SipSession::getLastToCseq() { return(mLastToCseq); } void SipSession::setLastToCseq(int lastToCseq) { mLastToCseq = lastToCseq; } int SipSession::getNextFromCseq() { mLastFromCseq++; return(mLastFromCseq); } /* ============================ INQUIRY =================================== */ UtlBoolean SipSession::isMessageFromInitiator(SipMessage& message) { Url messageFromUrl; Url messageToUrl; UtlString messageCallId; message.getFromUrl(messageFromUrl); message.getToUrl(messageToUrl); message.getCallIdField(&messageCallId); return(((message.isResponse() && SipMessage::isSameSession(mRemoteUrl, messageFromUrl) && SipMessage::isSameSession(mLocalUrl, messageToUrl)) || (!message.isResponse() && SipMessage::isSameSession(mRemoteUrl, messageToUrl) && SipMessage::isSameSession(mLocalUrl, messageFromUrl)))&& messageCallId.compareTo(*this) == 0); } UtlBoolean SipSession::isMessageFromDestination(SipMessage& message) { Url messageFromUrl; Url messageToUrl; UtlString messageCallId; message.getFromUrl(messageFromUrl); message.getToUrl(messageToUrl); message.getCallIdField(&messageCallId); return(((!message.isResponse() && SipMessage::isSameSession(mRemoteUrl, messageFromUrl) && SipMessage::isSameSession(mLocalUrl, messageToUrl)) || (message.isResponse() && SipMessage::isSameSession(mRemoteUrl, messageToUrl) && SipMessage::isSameSession(mLocalUrl, messageFromUrl)))&& messageCallId.compareTo(*this) == 0); } UtlBoolean SipSession::isSameSession(SipMessage& message) { return(isMessageFromInitiator(message) || isMessageFromDestination(message)); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipSrvLookup.cpp0000644000175000017500000010727512205613256024332 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Rewritten based on DomainSearch by Christian Zahl, and SipSrvLookup // by Henning Schulzrinne. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #if defined(_WIN32) # include "resparse/wnt/sysdep.h" # include # include # include # include extern "C" { # include "resparse/wnt/inet_aton.h" } #elif defined(_VXWORKS) # include # include # include # include /* Use local lnameser.h for info missing from VxWorks version --GAT */ /* lnameser.h is a subset of resparse/wnt/arpa/nameser.h */ # include # include /* Use local lresolv.h for info missing from VxWorks version --GAT */ /* lresolv.h is a subset of resparse/wnt/resolv/resolv.h */ # include # include /* #include used sockLib.h instead --GAT */ # include # include #elif defined(__pingtel_on_posix__) # include # include # include # include # include #else # error Unsupported target platform. #endif #ifndef __pingtel_on_posix__ extern struct __res_state _sip_res; #endif #ifdef WINCE # include #else # include #endif // Standard C includes. #include #include #include #include #include #include #include // Application includes. #include #include #include #include #include #include "resparse/rr.h" // The space allocated for returns from res_query. #define DNS_RESPONSE_SIZE 4096 // The initial value of OptionCodeCNAMELImit. #define DEFAULT_CNAME_LIMIT 5 // Forward references // All of these functions are made forward references here rather than // being protected methods in SipSrvLookup.h because some of them // require #include "resparse/rr.h", which ultimately includes // /usr/include/arpa/nameser_compat.h, which #defines STATUS, which is // used in other places in our code for other purposes. /** * @name Server List * * These methods maintain a list of servers and their properties that have * been found so far during the current search. * The list is a malloc'ed array of pointers to server_t's, and is * represented by a pointer to the array, a count of the allocated length * of the array, and a count of the number of entries in the array that * are used. */ ///@{ /// Initialize the variables pointing to the list of servers found thus far. static void server_list_initialize(server_t*& list, int& list_length_allocated, int& list_length_used); ///@} /// Insert records into the list for a server address. static void server_insert_addr( /// List control variables. server_t*& list, int& list_length_allocated, int& list_length_used, /// Components of the server_t. const char *host, ///< (copied) OsSocket::IpProtocolSocketType type, struct sockaddr_in sin, unsigned int priority, unsigned int weight); /**< * If type is UNKNOWN (meaning no higher-level process has specified * the transport to this server, server_insert_addr may insert two * records, one for UDP and one for TCP. */ /** * Add server_t to the end of a list of server addresses. * Calculates sorting score. */ static void server_insert( /// List control variables. server_t*& list, int& list_length_allocated, int& list_length_used, /// Components of the server_t. const char *host, ///< (copied) OsSocket::IpProtocolSocketType type, struct sockaddr_in sin, unsigned int priority, unsigned int weight); /** * Look up SRV records for a domain name, and from them find server * addresses to insert into the list of servers. */ static void lookup_SRV(server_t*& list, int& list_length_allocated, int& list_length_used, const char *domain, ///< domain name const char *service, ///< "sip" or "sips" const char *proto_string, ///< protocol string for DNS lookup OsSocket::IpProtocolSocketType proto_code, ///< protocol code for result list const char* srcIp ); /** * Look up A records for a domain name, and insert them into the list * of servers. */ static void lookup_A(server_t*& list, int& list_length_allocated, int& list_length_used, const char *domain, ///< domain name OsSocket::IpProtocolSocketType proto_code, /**< protocol code for result list * UNKNOWN means both UDP and TCP are acceptable * SSL must be set explicitly. */ res_response* in_response, ///< current DNS response, or NULL int port, ///< port unsigned int priority, ///< priority unsigned int weight ///< weight ); /**< * If in_response is non-NULL, use it as an initial source of A records. * * @returns TRUE if one or more addresses were added to the list. */ /** * Search for an RR with 'name' and 'type' in the answer and additional * sections of a DNS response. * * @return pointer to rdata structure for the first RR founr, or NULL. */ static union u_rdata* look_for(res_response* response, ///< response to look in const char* name, ///< domain name int type ///< RR type ); /// Function to compare two server entries. static int server_compare(const void* a, const void* b); /**< * Compares two server_t's which represent two servers. * Used by qsort to sort the list of server entries into preference * order. The sort rules are that the first (smallest) element is: * # Lowest priority * # Highest weighting score * Transport type (UDP, TCP, etc.) is ignored. * * @returns Integer comparison result as needed by qsort. */ static void sort_answers(res_response* response); static int rr_compare(const void* a, const void* b); /** * The array of option values. * * Set the initial values. */ int SipSrvLookup::options[OptionCodeLast+1] = { 0, // OptionCodeNone 0, // OptionCodeFirst 0, // OptionCodeIgnoreSRV 0, // OptionCodeIgnoreNAPTR 0, // OptionCodeSortAnswers 0, // OptionCodePrintAnswers DEFAULT_CNAME_LIMIT, // OptionCodeCNAMELimit 0, // OptionCodeNoDefaultTCP 0 // OptionCodeLast }; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /// Get the list of server entries for SIP domain name 'domain'. server_t* SipSrvLookup::servers(const char* domain, ///< SIP domain name or host name const char* service, ///< "sip" or "sips" OsSocket::IpProtocolSocketType socketType, ///< types of transport int port, ///< port number from URI, or PORT_NONE const char* srcIp ///< the outgoing interface ip to send the request on ) { server_t* list; int list_length_allocated; int list_length_used = 0; struct sockaddr_in in; OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSrvLookup::servers domain = '%s', service = '%s', " "socketType = %s, port = %d", domain, service, OsSocket::ipProtocolString(socketType), port); // Initialize the list of servers. server_list_initialize(list, list_length_allocated, list_length_used); // Seize the lock. OsLock lock(sMutex); // Case 0: Eliminate contradictory combinations of service and type. // While a sip: URI can be used with a socketType of SSL_SOCKET // (e.g., ), a sips: URI must // be used with TLS. if ((strcmp(service, "sips") == 0 && (socketType == OsSocket::TCP || socketType == OsSocket::UDP))) { OsSysLog::add(FAC_SIP, PRI_INFO, "SipSrvLookup::servers Incompatible service '%s' and " "socketType %d", service, socketType); /* Add no elements to the list. */ } else // Case 1: Domain name is a numeric IP address. if ( IS_INET_RETURN_OK( inet_aton((char *)domain, &in.sin_addr)) ) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSrvLookup::servers IP address ('%s') no DNS lookup", domain); in.sin_family = AF_INET; // Set up the port number. // If port was specified in the URI, that is the port to use. // Otherwise, if the service is sips, use 5061. Otherwise use 5060. in.sin_port = htons(portIsValid(port) ? port : ((strcmp(service, "sips") == 0) || (socketType == OsSocket::SSL_SOCKET)) ? 5061 : 5060); // Set the transport if it is not already set for SIPS. if (socketType == OsSocket::UNKNOWN && strcmp(service, "sips") == 0) { socketType = OsSocket::SSL_SOCKET; } server_insert_addr(list, list_length_allocated, list_length_used, domain, socketType, in, 0, 0); } else { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSrvLookup::servers DNS SRV lookup for address: '%s'", domain); // Case 2: SRV records exist for this domain. // (Only used if no port is specified in the URI.) if (port <= 0 && !options[OptionCodeIgnoreSRV]) { // If UDP transport is acceptable. if ((socketType == OsSocket::UNKNOWN || socketType == OsSocket::UDP) && strcmp(service, "sips") != 0) { lookup_SRV(list, list_length_allocated, list_length_used, domain, service, "udp", OsSocket::UDP, srcIp); } // If TCP transport is acceptable. if ((socketType == OsSocket::UNKNOWN || socketType == OsSocket::TCP) && strcmp(service, "sips") != 0) { lookup_SRV(list, list_length_allocated, list_length_used, domain, service, "tcp", OsSocket::TCP, srcIp); } // If TLS transport is acceptable. if (socketType == OsSocket::UNKNOWN || socketType == OsSocket::SSL_SOCKET) { lookup_SRV(list, list_length_allocated, list_length_used, domain, service, "tls", OsSocket::SSL_SOCKET, srcIp); } } // Case 3: Look for A records. // (Only used for non-numeric addresses for which SRV lookup did not // produce any addresses. This includes if an explicit port was given.) if (list_length_used == 0) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSrvLookup::servers DNS lookup A record for address: '%s'", domain); lookup_A(list, list_length_allocated, list_length_used, domain, // Default the transport for "sips". (socketType == OsSocket::UNKNOWN && strcmp(service, "sips") == 0) ? OsSocket::SSL_SOCKET : socketType, // must do a query. NULL, // Default the port if it is not already set. (portIsValid(port) ? port : ((strcmp(service, "sips") == 0) || (socketType == OsSocket::SSL_SOCKET)) ? 5061 : 5060), // Set the priority and weight to 0. 0, 0); } } // Sort the list of servers found by priority and score. qsort(list, list_length_used, sizeof (server_t), server_compare); // Add ending empty element to list (after sorting the real entries). memset(&in, 0, sizeof(in)) ; server_insert(list, list_length_allocated, list_length_used, NULL, OsSocket::UNKNOWN, in, 0, 0); // Return the list of servers. if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { // Debugging print of list of servers. for (int j = 0; j < list_length_used; j++) { if (list[j].isValidServerT()) { UtlString host; list[j].getHostNameFromServerT(host); UtlString ip_addr; list[j].getIpAddressFromServerT(ip_addr); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSrvLookup::servers host = '%s', IP addr = '%s', " "port = %d, weight = %u, score = %f, " "priority = %u, proto = %s", host.data(), ip_addr.data(), list[j].getPortFromServerT(), list[j].getWeightFromServerT(), list[j].getScoreFromServerT(), list[j].getPriorityFromServerT(), OsSocket::ipProtocolString(list[j].getProtocolFromServerT()) ); } } } return list; } /// Set an option value. void SipSrvLookup::setOption(OptionCode option, int value) { // Seize the lock, to ensure atomic effect. OsLock lock(sMutex); options[option] = value; } //! Sets the DNS SRV times. Defaults: timeout=5, retries=4 void SipSrvLookup::setDnsSrvTimeouts(int initialTimeoutInSecs, int retries) { OsSysLog::add(FAC_NET, PRI_DEBUG, "SipSrvLookup::setDnsSrvTimeouts(initialTimeoutInSecs=%d, retries=%d)", initialTimeoutInSecs, retries); #if defined(ANDROID) // Could not put code in here for Android due to header file errors/conflicts in C++ code android_res_setDnsSrvTimeouts(initialTimeoutInSecs, retries); #else if (initialTimeoutInSecs > 0) { # if defined(__pingtel_on_posix__) _res.retrans = initialTimeoutInSecs; # else _sip_res.retrans = initialTimeoutInSecs; # endif } if (retries > 0) { # if defined(__pingtel_on_posix__) _res.retry = retries; # else _sip_res.retry = retries; # endif } #endif /* non ANDROID */ } void SipSrvLookup::getDnsSrvTimeouts(int& initialTimeoutInSecs, int& retries) { #if defined(ANDROID) // Could not put code in here for Android due to header file errors/conflicts in C++ code android_res_getDnsSrvTimeouts(&initialTimeoutInSecs, &retries); #else # if defined(__pingtel_on_posix__) initialTimeoutInSecs = _res.retrans; # else initialTimeoutInSecs = _sip_res.retrans; # endif #endif } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* * Lock to protect the resolver routines, which cannot tolerate multithreaded * use. */ OsMutex SipSrvLookup::sMutex(OsMutex::Q_PRIORITY | OsMutex::DELETE_SAFE | OsMutex::INVERSION_SAFE); // Initialize the variables pointing to the list of servers found thus far. void server_list_initialize(server_t*& list, int& list_length_allocated, int& list_length_used) { list_length_allocated = 2; list = new server_t[list_length_allocated]; list_length_used = 0; } // Add server_t to the end of a list of server addresses. void server_insert_addr(server_t*& list, int& list_length_allocated, int& list_length_used, const char* host, OsSocket::IpProtocolSocketType type, struct sockaddr_in sin, unsigned int priority, unsigned int weight) { if (type != OsSocket::UNKNOWN) { // If the transport is specified, just insert the record. server_insert(list, list_length_allocated, list_length_used, host, type, sin, priority, weight); } else { // If the transport is not specified, insert a UDP record. server_insert(list, list_length_allocated, list_length_used, host, OsSocket::UDP, sin, priority, weight); // If specified, insert a TCP record. if (!SipSrvLookup::getOption(SipSrvLookup::OptionCodeNoDefaultTCP)) { server_insert(list, list_length_allocated, list_length_used, host, OsSocket::TCP, sin, priority, weight); } } } // Add server_t to the end of a list of server addresses. void server_insert(server_t*& list, int& list_length_allocated, int& list_length_used, const char* host, OsSocket::IpProtocolSocketType type, struct sockaddr_in sin, unsigned int priority, unsigned int weight) { // Make sure there is room in the list. if (list_length_used == list_length_allocated) { // Allocate the new list. int new_length = 2 * list_length_allocated; server_t* new_list = new server_t[new_length]; // Copy all the elements binarily, to avoid the overhead of // duplicating all the host strings. bcopy((char*) list, (char*) new_list, list_length_used * sizeof (server_t)); // Erase the host pointers in the old list. for (int i = 0; i < list_length_used; i++) { list[i].host = NULL; } // Free the old list. delete[] list; // Replace the old list with the new one. list = new_list; list_length_allocated = new_length; } // Copy the element into the list. list[list_length_used].host = host != NULL ? strdup(host) : NULL; list[list_length_used].type = type; list[list_length_used].sin = sin; list[list_length_used].priority = priority; list[list_length_used].weight = weight; // Construct the score. // Why we construct it this way is described in // sipXtackLib/doc/developer/scores/README. if (weight == 0) { // If weight is 0, set score to infinity. list[list_length_used].score = 1000; } else { int i = rand(); // If random number is 0, change it to 1, so log() doesn't have a problem. if (i == 0) { i = 1; } list[list_length_used].score = - log(((float) i) / RAND_MAX) / weight; } // Increment the count of elements in the list. list_length_used++; } /* * Look up SRV records for a domain name, and from them find server * addresses to insert into the list of servers. */ void lookup_SRV(server_t*& list, int& list_length_allocated, int& list_length_used, const char* domain, ///< domain name const char* service, ///< "sip" or "sips" const char* proto_string, ///< protocol string for DNS lookup OsSocket::IpProtocolSocketType proto_code, ///< protocol code for result list const char* srcIp ) { // To hold the return of res_query_and_parse. res_response* response; const char* canonical_name; // Construct buffer to hold the key string for the lookup: // _service._protocol.domain // 5 bytes suffices for the added components and the ending NUL. char* lookup_name = (char*) malloc(strlen(service) + strlen(proto_string) + strlen(domain) + 5); // Construct the domain name to search on. sprintf(lookup_name, "_%s._%s.%s", service, proto_string, domain); #if defined(_WIN32) // set the srcIp, and populate the DNS server list res_init_ip(srcIp); #else res_init(); #endif // Make the query and parse the response. SipSrvLookup::res_query_and_parse(lookup_name, T_SRV, NULL, canonical_name, response); if (response != NULL) { unsigned int i; // For each answer that is an SRV record for this domain name. // Search the answer list of RRs. for (i = 0; i < response->header.ancount; i++) { if (response->answer[i]->rclass == C_IN && response->answer[i]->type == T_SRV && // Note we look for the canonical name now. strcasecmp(canonical_name, response->answer[i]->name) == 0) { // Call lookup_A to get the A records for the target host // name. Give it the pointer to our current response, // because it might have the A records. If not, lookup_A // will do a DNS lookup to get them. lookup_A(list, list_length_allocated, list_length_used, response->answer[i]->rdata.srv.target, proto_code, response, response->answer[i]->rdata.srv.port, response->answer[i]->rdata.srv.priority, response->answer[i]->rdata.srv.weight); } } // Search the additional list of RRs. for (i = 0; i < response->header.arcount; i++) { if (response->additional[i]->rclass == C_IN && response->additional[i]->type == T_SRV && // Note we look for the canonical name now. strcasecmp(canonical_name, response->additional[i]->name) == 0) { // Call lookup_A to get the A records for the target host // name. Give it the pointer to our current response, // because it might have the A records. If not, lookup_A // will do a DNS lookup to get them. lookup_A(list, list_length_allocated, list_length_used, response->additional[i]->rdata.srv.target, proto_code, response, response->additional[i]->rdata.srv.port, response->additional[i]->rdata.srv.priority, response->additional[i]->rdata.srv.weight); } } } // Free the result of res_parse. if (response != NULL) { res_free(response); } if (canonical_name != NULL && canonical_name != lookup_name) { free((void*) canonical_name); } free((void*) lookup_name); } /* * Look up A records for a domain name, and insert them into the list * of servers. */ void lookup_A(server_t*& list, int& list_length_allocated, int& list_length_used, const char* domain, ///< domain name OsSocket::IpProtocolSocketType proto_code, ///< protocol code for result list res_response* in_response, ///< current DNS response, or NULL int port, ///< port unsigned int priority, ///< priority unsigned int weight ///< weight ) { // To hold the return of res_query_and_parse. res_response* response; const char* canonical_name; // Make the query and parse the response. SipSrvLookup::res_query_and_parse(domain, T_A, in_response, canonical_name, response); // Search the list of RRs. // For each answer that is an SRV record for this domain name. if (response != NULL) { unsigned int i; // Search the answer list. for (i = 0; i < response->header.ancount; i++) { if (response->answer[i]->rclass == C_IN && response->answer[i]->type == T_A && // Note we look for the canonical name now. strcasecmp(canonical_name, response->answer[i]->name) == 0) { // An A record has been found. // Assemble the needed information and add it to the server list. struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_addr = response->answer[i]->rdata.address; sin.sin_family = AF_INET; sin.sin_port = htons(port); server_insert_addr(list, list_length_allocated, list_length_used, (const char*) domain, proto_code, sin, priority, weight); } } // Search the additional list. for (i = 0; i < response->header.arcount; i++) { if (response->additional[i]->rclass == C_IN && response->additional[i]->type == T_A && // Note we look for the canonical name now. strcasecmp(canonical_name, response->additional[i]->name) == 0) { // An A record has been found. // Assemble the needed information and add it to the server list. struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_addr = response->additional[i]->rdata.address; sin.sin_family = AF_INET; sin.sin_port = htons(port); server_insert_addr(list, list_length_allocated, list_length_used, (const char*) domain, proto_code, sin, priority, weight); } } } // Free the result of res_parse if necessary. if (response != NULL && response != in_response) { res_free(response); } if (canonical_name != NULL && canonical_name != domain) { free((void*) canonical_name); } } // Perform a DNS query and parse the results. Follows CNAME records. void SipSrvLookup::res_query_and_parse(const char* in_name, int type, res_response* in_response, const char*& out_name, res_response*& out_response ) { // The number of CNAMEs we have followed. int cname_count = 0; // The response currently being examined. res_response* response = in_response; // The name currently being examined. const char* name = in_name; // TRUE if 'response' was a lookup for 'name' and 'type'. UtlBoolean response_for_this_name = FALSE; // Buffer into which to read DNS replies. char answer[DNS_RESPONSE_SIZE]; union u_rdata* p; // Loop until we find a reason to exit. Each turn around the loop does // another DNS lookup. while (1) { // While response != NULL and there is a CNAME record for name // in response. while (response != NULL && (p = look_for(response, name, T_CNAME)) != NULL) { cname_count++; if (cname_count > SipSrvLookup::getOption(SipSrvLookup::OptionCodeCNAMELimit)) { break; } // If necessary, free the current 'name'. if (name != in_name) { free((void*) name); } // Copy the canonical name from the CNAME record into 'name', so // we can still use it after freeing 'response'. name = strdup(p->string); // Remember that we are now looking for a name that was not the one // that we searched for to produce this response. Hence, if we don't // find any RRs for it, that is not authoritative and we have to do // another DNS query. response_for_this_name = FALSE; // Go back and check whether the result name of the CNAME is listed // in this response. } // This response does not contain a CNAME for 'name'. So it is either // a final response that gives us the RRs we are looking for, or // we need to do a lookup on 'name'. // Check whether the response was for this name, or contains records // of the type we are looking for. If either, then any records we // are looking for are in this response, so we can return. if (response_for_this_name || (response != NULL && look_for(response, name, type) != NULL)) { break; } // We must do another lookup. // Start by freeing 'response' if we need to. if (response != in_response) { res_free(response); } response = NULL; // Now, 'response' will be from a query for 'name'. response_for_this_name = TRUE; // Debugging print. if (SipSrvLookup::getOption(SipSrvLookup::OptionCodePrintAnswers)) { printf("res_query(\"%s\", class = %d, type = %d)\n", name, C_IN, type); } // Use res_query, not res_search, so defaulting rules are not // applied to the domain. if (res_query(name, C_IN, type, (unsigned char*) answer, sizeof (answer)) == -1) { // res_query failed, return. break; } response = res_parse((char*) &answer); if (response == NULL) { // res_parse failed, return. break; } // If requested for testing purposes, sort the query and print it. // Sort first, so we see how sorting came out. if (SipSrvLookup::getOption(SipSrvLookup::OptionCodeSortAnswers)) { sort_answers(response); } if (SipSrvLookup::getOption(SipSrvLookup::OptionCodePrintAnswers)) { res_print(response); } // Now that we have a fresh DNS query to analyze, go back and check it // for a CNAME for 'name' and then for records of the requested type. } // Final processing: Copy the working name and response to the output // variables. out_name = name; out_response = response; } union u_rdata* look_for(res_response* response, const char* name, int type) { unsigned i; for (i = 0; i < response->header.ancount; i++) { if (response->answer[i]->rclass == C_IN && response->answer[i]->type == type && strcasecmp(name, response->answer[i]->name) == 0) { return &response->answer[i]->rdata; } } for (i = 0; i < response->header.arcount; i++) { if (response->additional[i]->rclass == C_IN && response->additional[i]->type == type && strcasecmp(name, response->additional[i]->name) == 0) { return &response->additional[i]->rdata; } } return NULL; } // Function to compare two server entries. int server_compare(const void* a, const void* b) { int result = 0; const server_t* s1 = (const server_t*) a; const server_t* s2 = (const server_t*) b; /* First compare priorities. Lower priority values are preferred, and * should go at the beginning of the list, and so should be returned * as less-than. */ if (s1->priority > s2->priority) { result = 1; } else if (s1->priority < s2->priority) { result = -1; } // Next compare the scores derived from the weights. // With the new scheme for computing scores, lower score values should // sort to the beginning of the list, that is, should compare less thn // higher scores. // See sipXtackLib/doc/developer/scores/README for details. else if (s1->score < s2->score) { result = -1; } else if (s1->score > s2->score) { result = 1; } // Compare the transport type, so UDP is favored over TCP. // That means that TCP must be larger than UDP. else if (s1->type == OsSocket::TCP && s2->type != OsSocket::TCP) { result = 1; } else if (s1->type != OsSocket::TCP && s2->type == OsSocket::TCP) { result = -1; } return result; } /* //////////////////////////// server_t ///////////////////////////////// */ /// Initializer for server_t server_t::server_t() : host(NULL) { } // Copy constructor for server_t server_t::server_t(const server_t& rserver_t) : host(rserver_t.host != NULL ? strdup(rserver_t.host) : NULL), type(rserver_t.type), sin(rserver_t.sin), priority(rserver_t.priority), weight(rserver_t.weight), score(rserver_t.score) { } // Assignment operator for server_t server_t& server_t::operator=(const server_t& rhs) { // Handle the assignment-to-self case. if (this == &rhs) { return *this; } // Copy the host strign, if present. host = rhs.host != NULL ? strdup(rhs.host) : NULL; // Copy the other fields. type = rhs.type; sin = rhs.sin; priority = rhs.priority; weight = rhs.weight; score = rhs.score; return *this; } /// Destructor for server_t server_t::~server_t() { // All that needs to be done is free the host string, if any. if (host != NULL) { free(host); } } /// Inquire if this is a valid SRV record UtlBoolean server_t::isValidServerT() { // Entry is valid if host is not NULL. return host != NULL; } /// Accessor for host name void server_t::getHostNameFromServerT(UtlString& hostName) { hostName = (host != NULL) ? host : ""; } /// Accessor for host IP address void server_t::getIpAddressFromServerT(UtlString& hostName) { OsSocket::inet_ntoa_pt(sin.sin_addr, hostName); } /// Accessor for port int server_t::getPortFromServerT() { return ntohs(sin.sin_port); } /// Accessor for weight unsigned int server_t::getWeightFromServerT() { return weight; } /// Accessor for score float server_t::getScoreFromServerT() { return score; } /// Accessor for priority unsigned int server_t::getPriorityFromServerT() { return priority; } /// Accessor for protocol OsSocket::IpProtocolSocketType server_t::getProtocolFromServerT() { return type; } /** * Post-process the results of res_parse by sorting the lists of "answer" and * "additional" RRs, so that responses are reproducible. (named tends to * rotate multiple answer RRs to the same query.) */ static void sort_answers(res_response* response) { qsort((void*) response->answer, response->header.ancount, sizeof (s_rr*), rr_compare); qsort((void*) response->additional, response->header.arcount, sizeof (s_rr*), rr_compare); } /** * Function to compare two RRs for qsort. * * I was hoping to sort records by TTL values, but Bind cleverly gives all * answers the same TTL (the minimum of the lot). So we have to sort by * address (for A records) or port/target (for SRV records). */ static int rr_compare(const void* a, const void* b) { int t; // a and b are pointers to entries in the array of s_rr*'s. // Get the pointers to the s_rr's: s_rr* a_rr = *(s_rr**) a; s_rr* b_rr = *(s_rr**) b; // Compare on type. t = a_rr->type - b_rr->type; if (t != 0) { return t; } // Case on type. switch (a_rr->type) { case T_SRV: // Compare on target. t = strcmp(a_rr->rdata.srv.target, b_rr->rdata.srv.target); if (t != 0) { return t; } // Compare on port. if (a_rr->rdata.srv.port < b_rr->rdata.srv.port) { return -1; } else if (a_rr->rdata.srv.port > b_rr->rdata.srv.port) { return 1; } // Give up. return 0; case T_A: // Compare on address. return memcmp((const void*) &a_rr->rdata.address, (const void*) &b_rr->rdata.address, sizeof (struct sockaddr)); default: return 0; } } sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipSubscribeClient.cpp0000644000175000017500000010411012205613256025427 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie (dpetrie AT SIPez DOT com) // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // Private class to contain subscription client states class SubscribeClientState : public UtlString { public: // The parent UtlString contains the dialogHandle as a key SubscribeClientState(); virtual ~SubscribeClientState(); void toString(UtlString& dumpString); // UtlString::data contains the Dialog Handle; SipSubscribeClient::SubscriptionState mState; void* mpApplicationData; void fireStateCallback(SipSubscribeClient::SubscriptionState newState, const char* earlyDialogHandle, const char* dialogHandle, void* applicationData, int responseCode, const char* responseText, long expiration, const SipMessage* subscribeResponse) { mState = newState; if (mLastFiredState != newState) { (mpStateCallback)(newState, earlyDialogHandle, dialogHandle, applicationData, responseCode, responseText, expiration, subscribeResponse); mLastFiredState = newState; } } SipSubscribeClient::SubscriptionStateCallback mpStateCallback; SipSubscribeClient::NotifyEventCallback mpNotifyCallback; private: //! DISALLOWED accendental copying SubscribeClientState(const SubscribeClientState& rSubscribeClientState); SubscribeClientState& operator=(const SubscribeClientState& rhs); SipSubscribeClient::SubscriptionState mLastFiredState; }; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor for private class SubscribeClientState::SubscribeClientState() : mLastFiredState(SipSubscribeClient::SUBSCRIPTION_UNKNOWN) { mpApplicationData = NULL; mpStateCallback = NULL; mpNotifyCallback = NULL; } // Destructor for private class SubscribeClientState::~SubscribeClientState() { } // Debug dump of private class client state void SubscribeClientState::toString(UtlString& dumpString) { dumpString = "SubscribeClientState:\n"; dumpString.append("\nmpData: "); dumpString.append(*this); dumpString.append("\nmState: "); UtlString subStateString; SipSubscribeClient::getSubscriptionStateEnumString(mState, subStateString); dumpString.append(subStateString); dumpString.append("\nmpApplicationData: "); char pointerString[20]; sprintf(pointerString, "%p", mpApplicationData); dumpString.append(pointerString); dumpString.append("\nmpStateCallback: "); sprintf(pointerString, "%p", mpStateCallback); dumpString.append(pointerString); dumpString.append("\nmpNotifyCallback: "); sprintf(pointerString, "%p", mpNotifyCallback); dumpString.append(pointerString); dumpString.append('\n'); } SipSubscribeClient* SipSubscribeClient::buildBasicClient(SipUserAgent& userAgent) { SipDialogMgr* dialogMgr = new SipDialogMgr(); SipRefreshManager* refreshMgr = new SipRefreshManager(userAgent, *dialogMgr); refreshMgr->start(); return(new SipSubscribeClient(userAgent, *dialogMgr, *refreshMgr)); } // Constructor SipSubscribeClient::SipSubscribeClient(SipUserAgent& userAgent, SipDialogMgr& dialogMgr, SipRefreshManager& refreshMgr) : OsServerTask("SipSubscribeClient-%d") , mSubcribeClientMutex(OsMutex::Q_FIFO) { mpUserAgent = &userAgent; mpDialogMgr = &dialogMgr; mpRefreshMgr = &refreshMgr; mCallIdCount = 0; mTagCount = 0; } // Copy constructor SipSubscribeClient::SipSubscribeClient(const SipSubscribeClient& rSipSubscribeClient) : mSubcribeClientMutex(OsMutex::Q_FIFO) { } // Destructor SipSubscribeClient::~SipSubscribeClient() { // Do not delete mpUserAgent ,mpDialogMgr or mpRefreshMgr. They // may be used else where and need to be deleted outside the // SipSubscribeClient. // Stop receiving NOTIFY requests mpUserAgent->removeMessageObserver(*(getMessageQueue())); // Wait until this OsServerTask has stopped or handleMethod // might access something we are about to delete here. waitUntilShutDown(); // Delete the event type strings mEventTypes.destroyAll(); // Unsubscribe to anything that is in the list endAllSubscriptions(); // mSubscriptions should now be empty } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipSubscribeClient& SipSubscribeClient::operator=(const SipSubscribeClient& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } UtlBoolean SipSubscribeClient::addSubscription(const char* resourceId, const char* eventHeaderValue, const char* acceptHeaderValue, const char* fromFieldValue, const char* toFieldValue, const char* contactFieldValue, int subscriptionPeriodSeconds, void* applicationData, const SubscriptionStateCallback subscriptionStateCallback, const NotifyEventCallback notifyEventsCallback, UtlString& earlyDialogHandle) { UtlString callId; getNextCallId(resourceId, eventHeaderValue, fromFieldValue, contactFieldValue, callId); // Construct a SUBSCRIBE request SipMessage subscribeRequest; subscribeRequest.setSubscribeData(resourceId, fromFieldValue, toFieldValue, callId, 1, // cseq eventHeaderValue, acceptHeaderValue, NULL, // Event header id parameter contactFieldValue, NULL, // initial request no routeField subscriptionPeriodSeconds); // Create a subscription (i.e. send the request and keep the // subscription refreshed). return(addSubscription(subscribeRequest, applicationData, subscriptionStateCallback, notifyEventsCallback, earlyDialogHandle)); } UtlBoolean SipSubscribeClient::addSubscription(SipMessage& subscriptionRequest, void* applicationData, const SubscriptionStateCallback subscriptionStateCallback, const NotifyEventCallback notifyEventsCallback, UtlString& earlyDialogHandle) { // Verify the from tag is set Url fromUrl; subscriptionRequest.getFromUrl(fromUrl); UtlString fromTag; fromUrl.getFieldParameter("tag",fromTag); if(fromTag.isNull()) { UtlString resourceId; subscriptionRequest.getRequestUri(&resourceId); UtlString eventHeaderValue; subscriptionRequest.getEventField(eventHeaderValue); UtlString contactFieldValue; subscriptionRequest.getContactField(0, contactFieldValue); UtlString fromFieldValue; fromUrl.toString(fromFieldValue); getNextFromTag(resourceId, eventHeaderValue, fromFieldValue, contactFieldValue, fromTag); fromUrl.setFieldParameter("tag", fromTag); fromUrl.toString(fromFieldValue); subscriptionRequest.setRawFromField(fromFieldValue); } // Get the event type and make sure we are registerd to // receive NOTIFY requests for this event type UtlString eventType; subscriptionRequest.getEventField(&eventType, NULL, NULL); // If this event type is not in the list, we need to register // to receive SUBSCRIBE responses for this event type lock(); if(mEventTypes.find(&eventType) == NULL) { // receive NOTIFY requests for this event type mpUserAgent->addMessageObserver(*(getMessageQueue()), SIP_NOTIFY_METHOD, TRUE, // yes requests FALSE, // no responses TRUE, // incoming, FALSE, // outgoing eventType); // Note: we do not register to receive SUBSCRIBE responses // as the refreshManager will do that and invoke the // SubScribeClient'c callback. // Add this event type to the list so we know we // have registered for the responses with the user agent mEventTypes.insert(new UtlString(eventType)); } unlock(); // Create a SubscribeState and set the members SubscribeClientState* clientState = new SubscribeClientState; subscriptionRequest.getDialogHandle(*clientState); clientState->mState = SUBSCRIPTION_UNKNOWN; clientState->mpApplicationData = applicationData; clientState->mpStateCallback = subscriptionStateCallback; clientState->mpNotifyCallback = notifyEventsCallback; earlyDialogHandle = *clientState; // Put the state in the list lock(); addState(*clientState); unlock(); // Give the request to the refresh manager to send the // subscribe and keep the subscription alive UtlBoolean initialSendOk = mpRefreshMgr->initiateRefresh(subscriptionRequest, this, // this comes back as app. data in callback refreshCallback, earlyDialogHandle); return(initialSendOk); } UtlBoolean SipSubscribeClient::endSubscription(const char* dialogHandle) { UtlBoolean foundSubscription = FALSE; UtlString matchDialog(dialogHandle); lock(); SubscribeClientState* clientState = removeState(matchDialog); unlock(); if(clientState) { foundSubscription = TRUE; // If there is a state change of interest and // there is a callback function if(clientState->mState != SUBSCRIPTION_FAILED && clientState->mpStateCallback) { UtlBoolean isEarlyDialog = mpDialogMgr->earlyDialogExists(matchDialog); // Indicate that the subscription was terminated clientState->fireStateCallback(SUBSCRIPTION_TERMINATED, isEarlyDialog ? dialogHandle : NULL, isEarlyDialog ? NULL : dialogHandle, clientState->mpApplicationData, -1, // no response code NULL, // no response text 0, // expires now NULL); // no response } delete clientState; clientState = NULL; } // Did not find a dialog to match else { // dialogHandle may be a handle to an early dialog. // See if we can find the dialog matching an early dialog handle. // It is possible that there is more than one dialog that matches // this early dialog handle. UtlString earlyDialogHandle; while(mpDialogMgr->getEarlyDialogHandleFor(matchDialog, earlyDialogHandle)) { lock(); clientState = removeState(earlyDialogHandle); unlock(); if(clientState) { foundSubscription = TRUE; // If there is a state change of interest and // there is a callback function if(clientState->mState != SUBSCRIPTION_FAILED && clientState->mpStateCallback) { // Indicate that the subscription was terminated clientState->fireStateCallback(SUBSCRIPTION_TERMINATED, earlyDialogHandle, dialogHandle, clientState->mpApplicationData, -1, // no response code NULL, // no response text 0, // expires now NULL); // no response } } } } // Stop the refresh and unsubscribe UtlBoolean foundRefreshSubscription = mpRefreshMgr->stopRefresh(dialogHandle); return(foundSubscription || foundRefreshSubscription); } void SipSubscribeClient::endAllSubscriptions() { SubscribeClientState* clientState = NULL; SubscribeClientState* dialogKey = NULL; UtlString earlyDialogHandle; // Not sure if we can take the lock and hold it while we // unsubscribe. The refreshMgr is going to invoke call backs. // If this lock blocks the same thread from taking the lock, // we will have a deadlock. Would like to take the lock once // to prevent additions to the mSubscription container until // we are all done unsubscribing. lock(); UtlHashMapIterator iterator(mSubscriptions); while((dialogKey = (SubscribeClientState*) iterator())) { clientState = removeState(*dialogKey); if(clientState) { // If there is a state change of interest and // there is a callback function if(clientState->mState != SUBSCRIPTION_FAILED && clientState->mpStateCallback) { mpDialogMgr->getEarlyDialogHandleFor(*dialogKey, earlyDialogHandle); // Indicate that the subscription was terminated clientState->fireStateCallback(SUBSCRIPTION_TERMINATED, clientState->mState == SUBSCRIPTION_INITIATED ? earlyDialogHandle.data() : NULL, clientState->mState == SUBSCRIPTION_SETUP ? dialogKey->data() : NULL, clientState->mpApplicationData, -1, // no response code NULL, // no response text 0, // expires now NULL); // no response } // Unsubscribe and stop refreshing the subscription mpRefreshMgr->stopRefresh(*dialogKey); delete clientState; clientState = NULL; dialogKey = NULL; // dialogKey and state should be the same object } } unlock(); } UtlBoolean SipSubscribeClient::handleMessage(OsMsg &eventMessage) { int msgType = eventMessage.getMsgType(); int msgSubType = eventMessage.getMsgSubType(); // SIP message if(msgType == OsMsg::PHONE_APP && msgSubType == SipMessage::NET_SIP_MESSAGE) { const SipMessage* sipMessage = ((SipMessageEvent&)eventMessage).getMessage(); // If this is a NOTIFY request UtlString method; if(sipMessage) sipMessage->getRequestMethod(&method); if(sipMessage) { if(method.compareTo(SIP_NOTIFY_METHOD) == 0 && !sipMessage->isResponse()) { handleNotifyRequest(*sipMessage); } //else if(method.compareTo(SIP_SUBSCRIBE_METHOD) == 0 && // sipMessage->isResponse()) // Subscribe responses should go to the refreshManager // where a callback will be used to notify the subscribe // client of the outcome via refreshCallback. else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipSubscribeClient::handleMessage unexpected %s %s", method.data(), sipMessage->isResponse() ? "response" : "request"); } } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipSubscribeClient::handleMessage SipMessageEvent with NULL SipMessage"); } } return(TRUE); } /* ============================ ACCESSORS ================================= */ int SipSubscribeClient::countSubscriptions() { int count = 0; lock(); count = mSubscriptions.entries(); unlock(); return(count); } int SipSubscribeClient::dumpStates(UtlString& dumpString) { int count = 0; dumpString.remove(0); UtlString oneClientDump; SubscribeClientState* clientState = NULL; lock(); UtlHashMapIterator iterator(mSubscriptions); while((clientState = (SubscribeClientState*) iterator())) { clientState->toString(oneClientDump); dumpString.append(oneClientDump); count++; } unlock(); return(count); } void SipSubscribeClient::getSubscriptionStateEnumString(enum SubscriptionState stateValue, UtlString& stateString) { switch(stateValue) { case SUBSCRIPTION_UNKNOWN: stateString = "SUBSCRIPTION_UNKNOWN"; break; case SUBSCRIPTION_INITIATED: // Early dialog stateString = "SUBSCRIPTION_INITIATED"; break; case SUBSCRIPTION_SETUP: // Established dialog stateString = "SUBSCRIPTION_SETUP"; break; case SUBSCRIPTION_FAILED: // Failed dialog setup or refresh stateString = "SUBSCRIPTION_FAILED"; break; case SUBSCRIPTION_TERMINATED: stateString = "SUBSCRIPTION_TERMINATED"; break; default: { char stateNum[20]; sprintf(stateNum, "%d", stateValue); stateString = "INVALID: "; stateString.append(stateNum); } break; } } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ void SipSubscribeClient::refreshCallback(SipRefreshManager::RefreshRequestState newState, const char* earlyDialogHandle, const char* dialogHandle, void* subscribeClientPtr, int responseCode, const char* responseText, long expirationDate, // epoch seconds const SipMessage* subscribeResponse) { if(subscribeClientPtr) { long now = OsDateTime::getSecsSinceEpoch(); SipSubscribeClient* subClient = (SipSubscribeClient*) subscribeClientPtr; switch(newState) { // Do nothing for early dialog for subscribes case SipRefreshManager::REFRESH_REQUEST_PENDING: break; case SipRefreshManager::REFRESH_REQUEST_SUCCEEDED: { // Variable scope // Either the subscription dialog went from early to established, // or a second dailog was created from the early dialog. Hense // there may be more than one established dialog // Determine which case we have: // 1) transition of early dialog to established // 2) second or subsequent dialog established // 3) refresh failed, but subscription not expired yet subClient->lock(); SubscribeClientState* clientState = NULL; // See if we can find an state for the early dialog if(earlyDialogHandle && *earlyDialogHandle) { UtlString dialogString(earlyDialogHandle); clientState = subClient->removeState(dialogString); // If we could not find the state for the early dialog // it must have been a second dialog created from the // same early dialog. // TODO: copy subscription state and create a second // (or subsequent) subscription. if(clientState == NULL) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipSubscribeClient::refreshCallback failed to find early dialog: %s", earlyDialogHandle); } else { // Change the dialogHandle as we switched from an // early to an established dialog // Update the subscription state // Take the state out of the hashbag, change the key // and put it back in as it is not clear the hasbag // will work correctly if you modify the key in place. *((UtlString*)clientState) = dialogHandle; clientState->mState = SUBSCRIPTION_SETUP; subClient->addState(*clientState); } } else { UtlString dialogString(dialogHandle); clientState = subClient->getState(dialogString); } // If the response code is > 299, the reSUBSCRIBE failed, // but a prior SUBSCRIBE has not expired yet if(clientState) { if(expirationDate < now) { clientState->mState = SUBSCRIPTION_TERMINATED; } else { clientState->mState = SUBSCRIPTION_SETUP; } if(clientState->mpStateCallback) { clientState->fireStateCallback(clientState->mState, earlyDialogHandle, dialogHandle, clientState->mpApplicationData, responseCode, responseText, expirationDate, subscribeResponse); } // We do not remove the subscription state, that is the // applications job to explicitly call endSubscription } subClient->unlock(); } break; case SipRefreshManager::REFRESH_REQUEST_FAILED: { // Variable scope // Early or established dialog failed. If the dialog was // established and the subscription had not expired yet // we would have recieved a DIALOG_ESTABLISHED with an // error response code. So if the state is DIALOG_FAILED, // either the early dialog failed, or the subscription // has expired and the reSUBSCRIBE failed. We do not hear // about SUBSCRIBEs that fail due to authorization unless // there is no matching credentials or the credentials did // not work. // Find the subscription state. The dialog should not // have changed for this case so we use the established dialog // if it is provided, otherwise we use the early dialog UtlString dailogString(dialogHandle ? dialogHandle : earlyDialogHandle); subClient->lock(); SubscribeClientState* clientState = subClient->getState(dailogString); if(clientState) { if(expirationDate < now) { clientState->mState = SUBSCRIPTION_TERMINATED; } else { clientState->mState = SUBSCRIPTION_SETUP; } if(clientState->mpStateCallback) { clientState->fireStateCallback(clientState->mState, earlyDialogHandle, dialogHandle, clientState->mpApplicationData, responseCode, responseText, expirationDate, subscribeResponse); } // We do not remove the subscription state, that is the // applications job to explicitly call endSubscription } subClient->unlock(); } break; // This should not happen case SipRefreshManager::REFRESH_REQUEST_UNKNOWN: default: OsSysLog::add(FAC_SIP, PRI_ERR, "SipSubscribeClient::refreshCallback invalid dialog state change: %d", newState); break; } } } /* //////////////////////////// PRIVATE /////////////////////////////////// */ void SipSubscribeClient::handleNotifyRequest(const SipMessage& notifyRequest) { UtlString eventField; notifyRequest.getEventField(&eventField, NULL); // We could validate that the event field is // set and is the right event type, but mostly // we should not care as we know the event type // from the subscription. We can be tolerant of // missing or malformed event headers in the // NOTIFY request. However this does not support // multiple event types in the same dialog UtlString notifyDialogHandle; notifyRequest.getDialogHandle(notifyDialogHandle); // Is there an established dialog? UtlBoolean foundDialog = mpDialogMgr->dialogExists(notifyDialogHandle); // Is there an early dialog? // Even if there is an established dialog, we still need // the early dialog handle to pass to the callback // routines. UtlString earlyDialogHandle; UtlBoolean foundEarlyDialog = mpDialogMgr->getEarlyDialogHandleFor(notifyDialogHandle, earlyDialogHandle); UtlBoolean subscriptionFound = FALSE; UtlBoolean newTransaction = FALSE; #ifdef TEST_PRINT osPrintf("SipSubscribeClient::handleNotifyRequest looking for NOTIFY dialog: %s\n", notifyDialogHandle.data()); #endif if(foundDialog) { newTransaction = mpDialogMgr->isNewRemoteTransaction(notifyRequest); } // No established dialog else { // We can get a NOTIFY for an early dialog as there is a // race condition where the NOTIFY can pass the final // response to the initial SUBSCRIBE // Is there an early dialog for this NOTIFY which should // be an established dialog (i.e. From and To tags)? if(foundEarlyDialog) { newTransaction = mpDialogMgr->isNewRemoteTransaction(notifyRequest); } } // Request is a new transaction (i.e. cseq greater than // last remote transaction if(newTransaction) { // Update the dialog mpDialogMgr->updateDialog(notifyRequest, notifyDialogHandle); // Get the SubScriptionState SubscribeClientState* clientState = NULL; lock(); if(!foundDialog && foundEarlyDialog) { // Change the dialogHandle as we switched from an // early to an established dialog clientState = removeState(earlyDialogHandle); // Update the subscription state // Take the state out of the hashbag, change the key // and put it back in as it is not clear the hasbag // will work correctly if you modify the key in place. if(clientState) { *((UtlString*)clientState) = notifyDialogHandle; clientState->mState = SUBSCRIPTION_SETUP; addState(*clientState); // invoke the subsription state call back to let // the application know the subscription is established if(clientState->mpStateCallback) { // Indicate that the subscription was established clientState->fireStateCallback(SUBSCRIPTION_SETUP, earlyDialogHandle, notifyDialogHandle, clientState->mpApplicationData, -1, // no response code NULL, // no response text -1, // do not know expiration NULL); // no response } } } // Established dialog else { // Use the notify dialogHandle to get the subscription state clientState = getState(notifyDialogHandle); } // invoke the Notify callback if it exists if(clientState) { subscriptionFound = TRUE; if(clientState->mpNotifyCallback) { (clientState->mpNotifyCallback)(earlyDialogHandle, notifyDialogHandle, clientState->mpApplicationData, ¬ifyRequest); } } unlock(); } // NOTIFY does not match a dialog if(!subscriptionFound) { SipMessage noSubscriptionResponse; noSubscriptionResponse.setBadTransactionData(¬ifyRequest); mpUserAgent->send(noSubscriptionResponse); } // Send a OK response this NOTIFY matched a subscription state else { SipMessage notifyOk; notifyOk.setOkResponseData(¬ifyRequest); mpUserAgent->send(notifyOk); } } void SipSubscribeClient::addState(SubscribeClientState& clientState) { mSubscriptions.insert(&clientState); } SubscribeClientState* SipSubscribeClient::getState(const UtlString& dialogHandle) { SubscribeClientState* foundState = (SubscribeClientState*) mSubscriptions.find(&dialogHandle); if(foundState == NULL) { // Swap the tags around to see if it is keyed the other way UtlString reversedHandle; SipDialog::reverseTags(dialogHandle, reversedHandle); foundState = (SubscribeClientState*) mSubscriptions.find(&reversedHandle); } return(foundState); } SubscribeClientState* SipSubscribeClient::removeState(UtlString& dialogHandle) { SubscribeClientState* foundState = (SubscribeClientState*) mSubscriptions.remove(&dialogHandle); if(foundState == NULL) { // Swap the tags around to see if it is keyed the other way UtlString reversedHandle; SipDialog::reverseTags(dialogHandle, reversedHandle); foundState = (SubscribeClientState*) mSubscriptions.remove(&reversedHandle); } return(foundState); } void SipSubscribeClient::lock() { mSubcribeClientMutex.acquire(); } void SipSubscribeClient::unlock() { mSubcribeClientMutex.release(); } void SipSubscribeClient::getNextCallId(const char* resourceId, const char* eventHeaderValue, const char* fromFieldValue, const char* contactFieldValue, UtlString& callId) { char callidCountString[256]; lock(); mCallIdCount++; long epochTime = OsDateTime::getSecsSinceEpoch(); sprintf(callidCountString, "%ld%d", epochTime, mCallIdCount); unlock(); UtlString left(callidCountString); left.append(resourceId); left.append(eventHeaderValue); left.append(fromFieldValue); UtlString right(callidCountString); right.append(contactFieldValue); UtlString encoded; encoded.capacity(34); callId = "ssc-"; NetMd5Codec::encode(left, encoded); callId.append(encoded); callId.append('@'); encoded.remove(0); NetMd5Codec::encode(right, encoded); callId.append(encoded); } void SipSubscribeClient::getNextFromTag(const char* resourceId, const char* eventHeaderValue, const char* fromFieldValue, const char* contactFieldValue, UtlString& fromTag) { char numString[20]; lock(); mTagCount++; sprintf(numString, "%d", mTagCount); unlock(); UtlString tagToEncode(numString); int tagRandomness = rand(); sprintf(numString, "%d", tagRandomness); tagToEncode.append(numString); tagToEncode.append(resourceId); tagToEncode.append(eventHeaderValue); tagToEncode.append(fromFieldValue); tagToEncode.append(contactFieldValue); NetMd5Codec::encode(tagToEncode, fromTag); } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipSubscribeServer.cpp0000644000175000017500000006170512205613256025473 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie (dpetrie AT SIPez DOT com) // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include #include #include // Private class to contain event type and event specific utilities class SubscribeServerEventData : public UtlString { public: SubscribeServerEventData(); virtual ~SubscribeServerEventData(); // Parent UtlString contains the eventType SipSubscribeServerEventHandler* mpEventSpecificHandler; SipUserAgent* mpEventSpecificUserAgent; SipPublishContentMgr* mpEventSpecificContentMgr; SipSubscriptionMgr* mpEventSpecificSubscriptionMgr; private: //! DISALLOWED accidental copying SubscribeServerEventData(const SubscribeServerEventData& rSubscribeServerEventData); SubscribeServerEventData& operator=(const SubscribeServerEventData& rhs); }; SubscribeServerEventData::SubscribeServerEventData() { mpEventSpecificHandler = NULL; mpEventSpecificUserAgent = NULL; mpEventSpecificContentMgr = NULL; mpEventSpecificSubscriptionMgr = NULL; } SubscribeServerEventData::~SubscribeServerEventData() { } // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ SipSubscribeServer* SipSubscribeServer::buildBasicServer(SipUserAgent& userAgent, const char* eventType) { SipSubscribeServer* newServer = NULL; // Create a default publisher container SipPublishContentMgr* publishContent = new SipPublishContentMgr(); // Create a default event handler SipSubscribeServerEventHandler* eventHandler = new SipSubscribeServerEventHandler(); // Create a default subscription mgr SipSubscriptionMgr* subscriptionMgr = new SipSubscriptionMgr(); newServer = new SipSubscribeServer(userAgent, *publishContent, *subscriptionMgr, *eventHandler); if(eventType && *eventType) { // Enable the server to accept the given SIP event package newServer->enableEventType(eventType, &userAgent, publishContent, eventHandler, subscriptionMgr); } return(newServer); } // Constructor SipSubscribeServer::SipSubscribeServer(SipUserAgent& defaultUserAgent, SipPublishContentMgr& defaultContentMgr, SipSubscriptionMgr& defaultSubscriptionMgr, SipSubscribeServerEventHandler& defaultEventHandler) : OsServerTask("SipSubscribeServer-%d") , mSubscribeServerMutex(OsMutex::Q_FIFO) { mpDefaultUserAgent = &defaultUserAgent; mpDefaultContentMgr = &defaultContentMgr; mpDefaultSubscriptionMgr = &defaultSubscriptionMgr; mpDefaultEventHandler = &defaultEventHandler; } // Copy constructor NOT IMPLEMENTED SipSubscribeServer::SipSubscribeServer(const SipSubscribeServer& rSipSubscribeServer) : mSubscribeServerMutex(OsMutex::Q_FIFO) { } // Destructor SipSubscribeServer::~SipSubscribeServer() { /* * Don't delete mpDefaultContentMgr, mpDefaultSubscriptionMgr, or mpDefaultEventHandler * they are owned by whoever constructed this server. */ /* * jaro: actually these are never deleted, and good habit is to delete * objects in the same class where they are created if we keep pointer * to them in member variables. This doesn't cause any problems in Windows. * If it causes problems for someone, investigate it please, and don't solve * it by not deleting something. */ delete mpDefaultEventHandler; delete mpDefaultSubscriptionMgr; delete mpDefaultContentMgr; // Iterate through and delete all the event data // TODO: } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipSubscribeServer& SipSubscribeServer::operator=(const SipSubscribeServer& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } void SipSubscribeServer::contentChangeCallback(void* applicationData, const char* resourceId, const char* eventTypeKey, const char* eventType, UtlBoolean isDefaultContent) { SipSubscribeServer* subServer = (SipSubscribeServer*)applicationData; subServer->notifySubscribers(resourceId, eventTypeKey, eventType, isDefaultContent); } UtlBoolean SipSubscribeServer::notifySubscribers(const char* resourceId, const char* eventTypeKey, const char* eventType, UtlBoolean isDefaultContent) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSubscribeServer::notifySubscribers resourceId '%s', eventTypeKey '%s', eventType '%s', isDefaultContent %d", resourceId, eventTypeKey, eventType, isDefaultContent); UtlBoolean notifiedSubscribers = FALSE; UtlString eventName(eventType ? eventType : ""); lockForRead(); SubscribeServerEventData* eventData = (SubscribeServerEventData*) mEventDefinitions.find(&eventName); // Get the event specific info to find subscriptions interested in // this content if(eventData) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSubscribeServer::notifySubscribers received the request for sending out the notification for resourceId '%s', event type '%s'", resourceId, eventType); int numSubscriptions = 0; SipMessage** notifyArray = NULL; UtlString** acceptHeaderValuesArray = NULL; eventData->mpEventSpecificSubscriptionMgr-> createNotifiesDialogInfo(resourceId, eventTypeKey, numSubscriptions, acceptHeaderValuesArray, notifyArray); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSubscribeServer::notifySubscribers numSubscriptions for %s = %d", resourceId, numSubscriptions); // Setup and send a NOTIFY for each subscription interested in // this resourcesId and eventTypeKey SipMessage* notify = NULL; for(int notifyIndex = 0; notifyArray != NULL && notifyIndex < numSubscriptions && notifyArray[notifyIndex] != NULL; notifyIndex++) { notify = notifyArray[notifyIndex]; // Fill in the NOTIFY request body/content eventData->mpEventSpecificHandler-> getNotifyContent(resourceId, eventTypeKey, eventType, *(eventData->mpEventSpecificContentMgr), *(acceptHeaderValuesArray[notifyIndex]), *notify); // Send the NOTIFY request eventData->mpEventSpecificUserAgent->send(*notify); } // Free up the NOTIFY requests and accept header field values eventData->mpEventSpecificSubscriptionMgr-> freeNotifies(numSubscriptions, acceptHeaderValuesArray, notifyArray); } // event type not enabled else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipSubscribeServer::notifySubscribers event type: %s not enabled", eventName.data()); } unlockForRead(); return(notifiedSubscribers); } UtlBoolean SipSubscribeServer::enableEventType(const char* eventTypeToken, SipUserAgent* userAgent, SipPublishContentMgr* contentMgr, SipSubscribeServerEventHandler* eventHandler, SipSubscriptionMgr* subscriptionMgr) { UtlBoolean addedEvent = FALSE; UtlString eventName(eventTypeToken ? eventTypeToken : ""); lockForWrite(); // Only add the event support if it does not already exist; SubscribeServerEventData* eventData = (SubscribeServerEventData*) mEventDefinitions.find(&eventName); if(!eventData) { addedEvent = TRUE; eventData = new SubscribeServerEventData(); *((UtlString*)eventData) = eventName; eventData->mpEventSpecificUserAgent = userAgent ? userAgent : mpDefaultUserAgent; eventData->mpEventSpecificContentMgr = contentMgr ? contentMgr : mpDefaultContentMgr; eventData->mpEventSpecificHandler = eventHandler ? eventHandler : mpDefaultEventHandler; eventData->mpEventSpecificSubscriptionMgr = subscriptionMgr ? subscriptionMgr : mpDefaultSubscriptionMgr; mEventDefinitions.insert(eventData); // Register an interest in SUBSCRIBE requests and NOTIFY responses // for this event type eventData->mpEventSpecificUserAgent->addMessageObserver(*(getMessageQueue()), SIP_SUBSCRIBE_METHOD, TRUE, // requests FALSE, // not reponses TRUE, // incoming FALSE, // no outgoing eventName, NULL, NULL); eventData->mpEventSpecificUserAgent->addMessageObserver(*(getMessageQueue()), SIP_NOTIFY_METHOD, FALSE, // no requests TRUE, // reponses TRUE, // incoming FALSE, // no outgoing eventName, NULL, NULL); // Register the callback for changes that occur in the // publish content manager eventData->mpEventSpecificContentMgr->setContentChangeObserver(eventName, this, contentChangeCallback); } unlockForWrite(); return(addedEvent); } UtlBoolean SipSubscribeServer::disableEventType(const char* eventTypeToken, SipUserAgent*& userAgent, SipPublishContentMgr*& contentMgr, SipSubscribeServerEventHandler*& eventHandler, SipSubscriptionMgr*& subscriptionMgr) { UtlBoolean removedEvent = FALSE; UtlString eventName(eventTypeToken ? eventTypeToken : ""); lockForWrite(); // Only add the event support if it does not already exist; SubscribeServerEventData* eventData = (SubscribeServerEventData*) mEventDefinitions.remove(&eventName); if(eventData) { removedEvent = TRUE; userAgent = eventData->mpEventSpecificUserAgent == mpDefaultUserAgent ? NULL : eventData->mpEventSpecificUserAgent; contentMgr = eventData->mpEventSpecificContentMgr == mpDefaultContentMgr ? NULL : eventData->mpEventSpecificContentMgr; eventHandler = eventData->mpEventSpecificHandler == mpDefaultEventHandler ? NULL : eventData->mpEventSpecificHandler; subscriptionMgr = eventData->mpEventSpecificSubscriptionMgr == mpDefaultSubscriptionMgr ? NULL : eventData->mpEventSpecificSubscriptionMgr; // Unregister interest in SUBSCRIBE requests and NOTIFY // responses for this event type eventData->mpEventSpecificUserAgent->removeMessageObserver(*(getMessageQueue())); delete eventData; eventData = NULL; } else { userAgent = NULL; contentMgr = NULL; eventHandler = NULL; subscriptionMgr = NULL; } unlockForWrite(); return(removedEvent); } UtlBoolean SipSubscribeServer::handleMessage(OsMsg &eventMessage) { int msgType = eventMessage.getMsgType(); int msgSubType = eventMessage.getMsgSubType(); // Timer fired if(msgType == OsMsg::OS_EVENT && msgSubType == OsEventMsg::NOTIFY) { OsTimer* timer = 0; UtlString* subscribeDialogHandle = NULL; ((OsEventMsg&)eventMessage).getUserData((intptr_t&)subscribeDialogHandle); ((OsEventMsg&)eventMessage).getEventData((intptr_t&)timer); if(subscribeDialogHandle) { // Check if the subscription really expired and send // the final NOTIFY if it did. handleExpiration(subscribeDialogHandle, timer); // Delete the handle; delete subscribeDialogHandle; // do not delete the timer. // handlExpiration deals with that and may reuse the timer } } // SIP message else if(msgType == OsMsg::PHONE_APP && msgSubType == SipMessage::NET_SIP_MESSAGE) { const SipMessage* sipMessage = ((SipMessageEvent&)eventMessage).getMessage(); UtlString method; if(sipMessage) { sipMessage->getCSeqField(NULL, &method); } // SUBSCRIBE requests if(sipMessage && !sipMessage->isResponse() && method.compareTo(SIP_SUBSCRIBE_METHOD) == 0) { handleSubscribe(*sipMessage); } // NOTIFY responses else if(sipMessage && sipMessage->isResponse() && method.compareTo(SIP_NOTIFY_METHOD) == 0) { handleNotifyResponse(*sipMessage); } } return(TRUE); } /* ============================ ACCESSORS ================================= */ SipSubscribeServerEventHandler* SipSubscribeServer::getEventHandler(const UtlString& eventType) { SipSubscribeServerEventHandler* eventHandler = NULL; lockForRead(); SubscribeServerEventData* eventData = (SubscribeServerEventData*) mEventDefinitions.find(&eventType); if(eventData) { eventHandler = eventData->mpEventSpecificHandler; } else { eventHandler = mpDefaultEventHandler; } unlockForRead(); return(eventHandler); } SipPublishContentMgr* SipSubscribeServer::getPublishMgr(const UtlString& eventType) { SipPublishContentMgr* contentMgr = NULL; lockForRead(); SubscribeServerEventData* eventData = (SubscribeServerEventData*) mEventDefinitions.find(&eventType); if(eventData) { contentMgr = eventData->mpEventSpecificContentMgr; } else { contentMgr = mpDefaultContentMgr; } unlockForRead(); return(contentMgr); } SipSubscriptionMgr* SipSubscribeServer::getSubscriptionMgr(const UtlString& eventType) { SipSubscriptionMgr* subscribeMgr = NULL; lockForRead(); SubscribeServerEventData* eventData = (SubscribeServerEventData*) mEventDefinitions.find(&eventType); if(eventData) { subscribeMgr = eventData->mpEventSpecificSubscriptionMgr; } else { subscribeMgr = mpDefaultSubscriptionMgr; } unlockForRead(); return(subscribeMgr); } /* ============================ INQUIRY =================================== */ UtlBoolean SipSubscribeServer::isEventTypeEnabled(const UtlString& eventType) { lockForRead(); // Only add the event support if it does not already exist; SubscribeServerEventData* eventData = (SubscribeServerEventData*) mEventDefinitions.find(&eventType); unlockForRead(); return(eventData != NULL); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ UtlBoolean SipSubscribeServer::handleSubscribe(const SipMessage& subscribeRequest) { UtlBoolean handledSubscribe = FALSE; UtlString eventName; subscribeRequest.getEventField(&eventName, NULL); // Not modifying the SubscribeServerEventData, just reading it lockForRead(); // Get the event specific handler and information SubscribeServerEventData* eventPackageInfo = (SubscribeServerEventData*) mEventDefinitions.find(&eventName); // We handle this event type if(eventPackageInfo) { handledSubscribe = TRUE; UtlString resourceId; UtlString eventTypeKey, eventType; SipSubscribeServerEventHandler* handler = eventPackageInfo->mpEventSpecificHandler; // Get the keys used to identify the event state content handler->getKeys(subscribeRequest, resourceId, eventTypeKey, eventType); SipMessage subscribeResponse; // Check if authenticated (or if it needs to be authenticated) if(handler->isAuthenticated(subscribeRequest, resourceId, eventTypeKey, subscribeResponse)) { // Check if authorized (or if authorization is required) if(handler->isAuthorized(subscribeRequest, resourceId, eventTypeKey, subscribeResponse)) { // The subscription is allowed, so update the // subscription state. Set the To field tag if // this request initiated the dialog UtlString subscribeDialogHandle; UtlBoolean isNewDialog; UtlBoolean isExpiredSubscription; eventPackageInfo->mpEventSpecificSubscriptionMgr->updateDialogInfo( subscribeRequest, resourceId, eventTypeKey, getMessageQueue(), subscribeDialogHandle, isNewDialog, isExpiredSubscription, subscribeResponse); // Send the response ASAP to minimize resend handling of request eventPackageInfo->mpEventSpecificUserAgent->send(subscribeResponse); // Build a NOTIFY SipMessage notifyRequest; // Set the dialog information eventPackageInfo->mpEventSpecificSubscriptionMgr->getNotifyDialogInfo(subscribeDialogHandle, notifyRequest); // Set the NOTIFY content UtlString acceptHeaderValue; subscribeRequest.getAcceptField(acceptHeaderValue); handler->getNotifyContent(resourceId, eventTypeKey, eventType, *(eventPackageInfo->mpEventSpecificContentMgr), acceptHeaderValue, notifyRequest); // Send the notify request eventPackageInfo->mpEventSpecificUserAgent->send(notifyRequest); } // Not authorized else { // Send the response eventPackageInfo->mpEventSpecificUserAgent->send(subscribeResponse); } } // Not authenticated else { // Send the response eventPackageInfo->mpEventSpecificUserAgent->send(subscribeResponse); } } // We should not have received SUBSCRIBE requests for this event type // This event type has not been enabled in this SubscribeServer else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipSubscribeServer::handleSubscribe event type: %s not enabled", eventName.data()); SipMessage eventTypeNotHandled; eventTypeNotHandled.setResponseData(&subscribeRequest, SIP_BAD_EVENT_CODE, SIP_BAD_EVENT_TEXT); mpDefaultUserAgent->send(eventTypeNotHandled); } unlockForRead(); return(handledSubscribe); } UtlBoolean SipSubscribeServer::handleNotifyResponse(const SipMessage& notifyResponse) { UtlBoolean handledNotifyResponse = FALSE; int responseCode = notifyResponse.getResponseStatusCode(); // Ignore provisional responses or success cases if(responseCode >= SIP_3XX_CLASS_CODE) { UtlString dialogHandle; notifyResponse.getDialogHandle(dialogHandle); // Not modifying the SubscribeServerEventData, just reading it lockForRead(); // Get the event specific handler and information SubscribeServerEventData* eventPackageInfo = NULL; UtlHashMapIterator iterator(mEventDefinitions); while((eventPackageInfo = (SubscribeServerEventData*) iterator())) { // End this subscription as we got an error response from // the NOTIFY request. // Returns TRUE if the SipSubscriptionMgr has this dialog handledNotifyResponse = eventPackageInfo->mpEventSpecificSubscriptionMgr->endSubscription( dialogHandle); if(handledNotifyResponse) { break; } } unlockForRead(); // Should not happen, first of all we should never get a // response which does not correspond to a request sent from // the SipUserAgent. Secondly, we should not get a response to // and event type that we do not support if(!handledNotifyResponse) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipSubscribeServer::handleNotifyResponse NOTIFY response with no dialog. Handle: %s", dialogHandle.data()); } } // Provisional or 2XX class responses else { handledNotifyResponse = TRUE; } return(handledNotifyResponse); } UtlBoolean SipSubscribeServer::handleExpiration(UtlString* subscribeDialogHandle, OsTimer* timer) { // TODO: Currently timers are not set for the subscription // expiration time. It is not clear this is really a useful // thing to do other than the fact that RFC 3265 says you // should send a final NOTIFY indicating that the subscription // expired. I cannot come up with a use case where it is // needed that the subscribe client gets a final NOTIFY. // The client should already know when the expiration is // going to occur and that it has not reSUBSCRIBEd. OsSysLog::add(FAC_SIP, PRI_ERR, "SipSubscribeServer::handleExpiration not implemented"); return(FALSE); } void SipSubscribeServer::lockForRead() { mSubscribeServerMutex.acquireRead(); } void SipSubscribeServer::unlockForRead() { mSubscribeServerMutex.releaseRead(); } void SipSubscribeServer::lockForWrite() { mSubscribeServerMutex.acquireWrite(); } void SipSubscribeServer::unlockForWrite() { mSubscribeServerMutex.releaseWrite(); } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipSubscribeServerEventHandler.cpp0000644000175000017500000001455512205613256027774 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie (dpetrie AT SIPez DOT com) // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include #include // Private class to contain callback for eventTypeKey class SubscribeServerSubscriptionState : public UtlString { public: SubscribeServerSubscriptionState(); virtual ~SubscribeServerSubscriptionState(); // Parent UtlString contains the dialog handle private: //! DISALLOWED accidental copying SubscribeServerSubscriptionState(const SubscribeServerSubscriptionState& rSubscribeServerSubscriptionState); SubscribeServerSubscriptionState& operator=(const SubscribeServerSubscriptionState& rhs); }; // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ SubscribeServerSubscriptionState::SubscribeServerSubscriptionState() { } SubscribeServerSubscriptionState::~SubscribeServerSubscriptionState() { } // Constructor SipSubscribeServerEventHandler::SipSubscribeServerEventHandler() { } // Copy constructor NOT IMPLEMENTED SipSubscribeServerEventHandler::SipSubscribeServerEventHandler(const SipSubscribeServerEventHandler& rSipSubscribeServerEventHandler) { } // Destructor SipSubscribeServerEventHandler::~SipSubscribeServerEventHandler() { // Iterate through and delete all the dialogs // TODO: } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipSubscribeServerEventHandler& SipSubscribeServerEventHandler::operator=(const SipSubscribeServerEventHandler& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } UtlBoolean SipSubscribeServerEventHandler::getKeys(const SipMessage& subscribeRequest, UtlString& resourceId, UtlString& eventTypeKey, UtlString& eventType) { // default resourceId is the identity UtlString uriString; subscribeRequest.getRequestUri(&uriString); Url uri(uriString); uri.getIdentity(resourceId); // Default event key is the event type with no parameters subscribeRequest.getEventField(&eventTypeKey, NULL); // Event type is the same. eventType = eventTypeKey; return(TRUE); } UtlBoolean SipSubscribeServerEventHandler::isAuthenticated(const SipMessage& subscribeRequest, const UtlString& resourceId, const UtlString& eventTypeKey, SipMessage& subscribeResponse) { // By default no authentication required return(TRUE); } UtlBoolean SipSubscribeServerEventHandler::isAuthorized(const SipMessage& subscribeRequest, const UtlString& resourceId, const UtlString& eventTypeKey, SipMessage& subscribeResponse) { // By default no authorization required return(TRUE); } UtlBoolean SipSubscribeServerEventHandler::getNotifyContent(const UtlString& resourceId, const UtlString& eventTypeKey, const UtlString& eventType, SipPublishContentMgr& contentMgr, const char* acceptHeaderValue, SipMessage& notifyRequest) { UtlBoolean gotBody = FALSE; // Default behavior is to just go get the content from // the content manager and attach it to the notify HttpBody* messageBody = NULL; UtlBoolean isDefaultEventContent; gotBody = contentMgr.getContent(resourceId, eventTypeKey, eventType, acceptHeaderValue, messageBody, isDefaultEventContent); // The body will be freed with the notify message. if(messageBody) { const char* contentTypePtr = messageBody->getContentType(); UtlString contentType; if(contentTypePtr) { contentType = contentTypePtr; } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipSubscribeServerEventHandler::getNotifyContent body published for resourceId: %s eventTypeKey: %s with no content type", resourceId.data() ? resourceId.data() : "", eventTypeKey.data() ? eventTypeKey.data() : ""); contentType = "text/unknown"; } notifyRequest.setContentType(contentType); notifyRequest.setBody(messageBody); UtlString body; int bodyLength; notifyRequest.getBytes(&body, &bodyLength); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSubscribeServerEventHandler::getNotifyContent resourceId <%s>, eventTypeKey <%s> contentType <%s>\nNotify message length = %d, messageBody =\n%s\n", resourceId.data(), eventTypeKey.data(), contentType.data(), bodyLength, body.data()); } return(gotBody); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipSubscriptionMgr.cpp0000644000175000017500000007352212205613256025515 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2008 SIPez LLC All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie (dpetrie AT SIPez DOT com) // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include #include // Private class to contain callback for eventTypeKey class SubscriptionServerState : public UtlString { public: SubscriptionServerState(); virtual ~SubscriptionServerState(); // Parent UtlString contains the dialog handle UtlString mResourceId; UtlString mEventTypeKey; UtlString mAcceptHeaderValue; long mExpirationDate; // epoch time SipMessage* mpLastSubscribeRequest; OsTimer* mpExpirationTimer; private: //! DISALLOWED accidental copying SubscriptionServerState(const SubscriptionServerState& rSubscriptionServerState); SubscriptionServerState& operator=(const SubscriptionServerState& rhs); }; class SubscriptionServerStateIndex : public UtlString { public: SubscriptionServerStateIndex(); virtual ~SubscriptionServerStateIndex(); // Parent UtlString contains the dialog handle SubscriptionServerState* mpState; private: //! DISALLOWED accidental copying SubscriptionServerStateIndex(const SubscriptionServerStateIndex& rSubscriptionServerStateIndex); SubscriptionServerStateIndex& operator=(const SubscriptionServerStateIndex& rhs); }; // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ SubscriptionServerState::SubscriptionServerState() { mExpirationDate = -1; mpLastSubscribeRequest = NULL; mpExpirationTimer = NULL; } SubscriptionServerState::~SubscriptionServerState() { if(mpLastSubscribeRequest) { delete mpLastSubscribeRequest; mpLastSubscribeRequest = NULL; } if(mpExpirationTimer) { // Timer should have been stopped and the the task upon // which the fired timer queues its message need to have // synchronized to make sure it does not get touched after // it is deleted here. delete mpExpirationTimer; mpExpirationTimer = NULL; } } SubscriptionServerStateIndex::SubscriptionServerStateIndex() { mpState = NULL; } SubscriptionServerStateIndex::~SubscriptionServerStateIndex() { // Do not delete mpState, it is freed else where } // Constructor SipSubscriptionMgr::SipSubscriptionMgr() : mSubscriptionMgrMutex(OsMutex::Q_FIFO) { mEstablishedDialogCount = 0; mMinExpiration = 32; mDefaultExpiration = 3600; mMaxExpiration = 86400; } // Copy constructor NOT IMPLEMENTED SipSubscriptionMgr::SipSubscriptionMgr(const SipSubscriptionMgr& rSipSubscriptionMgr) : mSubscriptionMgrMutex(OsMutex::Q_FIFO) { } // Destructor SipSubscriptionMgr::~SipSubscriptionMgr() { // Iterate through and delete all the dialogs // TODO: } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipSubscriptionMgr& SipSubscriptionMgr::operator=(const SipSubscriptionMgr& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } UtlBoolean SipSubscriptionMgr::updateDialogInfo(const SipMessage& subscribeRequest, const UtlString& resourceId, const UtlString& eventTypeKey, OsMsgQ* subscriptionTimeoutQueue, UtlString& subscribeDialogHandle, UtlBoolean& isNew, UtlBoolean& isSubscriptionExpired, SipMessage& subscribeResponse) { isNew = FALSE; UtlBoolean subscriptionSucceeded = FALSE; UtlString dialogHandle; subscribeRequest.getDialogHandle(dialogHandle); SubscriptionServerState* state = NULL; int expiration = -1; isSubscriptionExpired = TRUE; // If this is an early dialog we need to make it an established dialog. if(SipDialog::isEarlyDialog(dialogHandle)) { UtlString establishedDialogHandle; if(mDialogMgr.getEstablishedDialogHandleFor(dialogHandle, establishedDialogHandle)) { OsSysLog::add(FAC_SIP, PRI_WARNING, "Incoming early SUBSCRIBE dialog: %s matches established dialog: %s", dialogHandle.data(), establishedDialogHandle.data()); } // make up a To tag and set it UtlString toTagClearText; // Should probably add something like the local IP address and SIP port toTagClearText.append(dialogHandle); char numBuffer[20]; lock(); mEstablishedDialogCount++; sprintf(numBuffer, "%d", mEstablishedDialogCount); unlock(); toTagClearText.append(numBuffer); UtlString toTag; NetMd5Codec::encode(toTagClearText, toTag); // Get and validate the expires period // This potentially should be delegated to the event handler specifics if(!subscribeRequest.getExpiresField(&expiration)) { expiration = mDefaultExpiration; } else if(expiration > mMaxExpiration) { expiration = mMaxExpiration; } // Acceptable expiration, create a subscription and dialog if(expiration >= mMinExpiration || expiration == 0 || // :WORKAROUND: Also allow expiration == 1, to support the // 1-second subscriptions the pick-up agent makes because // current Snom phones do not respond to 0-second subscriptions. // See XPB-399 and ENG-319. expiration == 1) { // Create a dialog and subscription state even if // the expiration is zero as we need the dialog info // to route the one time NOTIFY. The immediately // expired dialog will be garbage collected. SipMessage* subscribeCopy = new SipMessage(subscribeRequest); subscribeCopy->setToFieldTag(toTag); // Re-get the dialog handle now that the To tag is set subscribeCopy->getDialogHandle(dialogHandle); // Create the dialog mDialogMgr.createDialog(*subscribeCopy, FALSE, dialogHandle); isNew = TRUE; // Create a subscription state state = new SubscriptionServerState(); *((UtlString*)state) = dialogHandle; state->mEventTypeKey = eventTypeKey; state->mpLastSubscribeRequest = subscribeCopy; state->mResourceId = resourceId; subscribeCopy->getAcceptField(state->mAcceptHeaderValue); long now = OsDateTime::getSecsSinceEpoch(); state->mExpirationDate = now + expiration; // TODO: currently the SipSubsribeServer does not handle timeout // events to send notifications that the subscription has ended. // So we do not set a timer at the end of the subscription state->mpExpirationTimer = NULL; // Create the index by resourceId and eventTypeKey key SubscriptionServerStateIndex* stateKey = new SubscriptionServerStateIndex; *((UtlString*)stateKey) = resourceId; stateKey->append(eventTypeKey); stateKey->mpState = state; // Set the contact to the same request URI that came in UtlString contact; subscribeRequest.getRequestUri(&contact); // Add the angle brackets for contact Url url(contact); url.includeAngleBrackets(); contact = url.toString(); subscribeResponse.setResponseData(subscribeCopy, SIP_ACCEPTED_CODE, SIP_ACCEPTED_TEXT, contact); subscribeResponse.setExpiresField(expiration); subscribeCopy->getDialogHandle(subscribeDialogHandle); lock(); mSubscriptionStatesByDialogHandle.insert(state); mSubscriptionStateResourceIndex.insert(stateKey); if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { UtlString requestContact; subscribeRequest.getContactField(0, requestContact); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSubscriptionMgr::updateDialogInfo insert early-dialog subscription for key '%s', contact '%s', mExpirationDate %ld", stateKey->data(), requestContact.data(), state->mExpirationDate); } // Not safe to touch these after we unlock stateKey = NULL; state = NULL; subscribeCopy = NULL; unlock(); subscriptionSucceeded = TRUE; // One time subscribe? isSubscriptionExpired = expiration == 0; } // Expiration too small else { // Set expiration too small error subscribeResponse.setResponseData(&subscribeRequest, SIP_TOO_BRIEF_CODE, SIP_SUB_TOO_BRIEF_TEXT); subscribeResponse.setMinExpiresField(mMinExpiration); isSubscriptionExpired = TRUE; } } // The dialog for this message should already exist else { // Get and validate the expires period // This potentially should be delegated to the event handler specifics if(!subscribeRequest.getExpiresField(&expiration)) { expiration = mDefaultExpiration; } else if(expiration > mMaxExpiration) { expiration = mMaxExpiration; } // Acceptable expiration, create a subscription and dialog if(expiration > mMinExpiration || expiration == 0) { // Update the dialog state mDialogMgr.updateDialog(subscribeRequest, dialogHandle); // Get the subscription state and update that // TODO: This assumes that no one reuses the same dialog // to subscribe to more than one event type. mSubscriptionStatesByDialogHandle // will need to be changed to a HashBag and we will need to // search through to find a matching event type lock(); state = (SubscriptionServerState*) mSubscriptionStatesByDialogHandle.find(&dialogHandle); if(state) { long now = OsDateTime::getSecsSinceEpoch(); state->mExpirationDate = now + expiration; if(state->mpLastSubscribeRequest) { delete state->mpLastSubscribeRequest; } state->mpLastSubscribeRequest = new SipMessage(subscribeRequest); subscribeRequest.getAcceptField(state->mAcceptHeaderValue); // Set the contact to the same request URI that came in UtlString contact; subscribeRequest.getRequestUri(&contact); // Add the angle brackets for contact Url url(contact); url.includeAngleBrackets(); contact = url.toString(); subscribeResponse.setResponseData(&subscribeRequest, SIP_ACCEPTED_CODE, SIP_ACCEPTED_TEXT, contact); subscribeResponse.setExpiresField(expiration); subscriptionSucceeded = TRUE; isSubscriptionExpired = FALSE; subscribeDialogHandle = dialogHandle; } // No state, basically assume this is a new subscription else { SipMessage* subscribeCopy = new SipMessage(subscribeRequest); // Create the dialog mDialogMgr.createDialog(*subscribeCopy, FALSE, dialogHandle); isNew = TRUE; // Create a subscription state state = new SubscriptionServerState(); *((UtlString*)state) = dialogHandle; state->mEventTypeKey = eventTypeKey; state->mpLastSubscribeRequest = subscribeCopy; state->mResourceId = resourceId; subscribeCopy->getAcceptField(state->mAcceptHeaderValue); long now = OsDateTime::getSecsSinceEpoch(); state->mExpirationDate = now + expiration; // TODO: currently the SipSubsribeServer does not handle timeout // events to send notifications that the subscription has ended. // So we do not set a timer at the end of the subscription state->mpExpirationTimer = NULL; // Create the index by resourceId and eventTypeKey key SubscriptionServerStateIndex* stateKey = new SubscriptionServerStateIndex; *((UtlString*)stateKey) = resourceId; stateKey->append(eventTypeKey); stateKey->mpState = state; mSubscriptionStatesByDialogHandle.insert(state); mSubscriptionStateResourceIndex.insert(stateKey); if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { UtlString requestContact; subscribeRequest.getContactField(0, requestContact); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSubscriptionMgr::updateDialogInfo insert subscription for key '%s', contact '%s', mExpirationDate %ld", stateKey->data(), requestContact.data(), state->mExpirationDate); } // Not safe to touch these after we unlock stateKey = NULL; state = NULL; subscribeCopy = NULL; // Set the contact to the same request URI that came in UtlString contact; subscribeRequest.getRequestUri(&contact); // Add the angle brackets for contact Url url(contact); url.includeAngleBrackets(); contact = url.toString(); subscribeResponse.setResponseData(&subscribeRequest, SIP_ACCEPTED_CODE, SIP_ACCEPTED_TEXT, contact); subscribeResponse.setExpiresField(expiration); subscriptionSucceeded = TRUE; // Unsubscribe if(expiration == 0) { isSubscriptionExpired = TRUE; } else { isSubscriptionExpired = FALSE; } subscribeDialogHandle = dialogHandle; } unlock(); } // Expiration too small else { // Set expiration too small error subscribeResponse.setResponseData(&subscribeRequest, SIP_TOO_BRIEF_CODE, SIP_SUB_TOO_BRIEF_TEXT); subscribeResponse.setMinExpiresField(mMinExpiration); isSubscriptionExpired = isExpired(dialogHandle); } } return(subscriptionSucceeded); } UtlBoolean SipSubscriptionMgr::getNotifyDialogInfo(const UtlString& subscribeDialogHandle, SipMessage& notifyRequest) { UtlBoolean notifyInfoSet = FALSE; lock(); SubscriptionServerState* state = (SubscriptionServerState*) mSubscriptionStatesByDialogHandle.find(&subscribeDialogHandle); if(state) { notifyInfoSet = mDialogMgr.setNextLocalTransactionInfo(notifyRequest, SIP_NOTIFY_METHOD, subscribeDialogHandle); // Set the event header, if we know what it is. if(state->mpLastSubscribeRequest) { UtlString eventHeader; state->mpLastSubscribeRequest->getEventField(eventHeader); notifyRequest.setEventField(eventHeader); } // Set the subscription-state header. long expires = state->mExpirationDate - OsDateTime::getSecsSinceEpoch(); char buffer[30]; sprintf(buffer, (expires > 0 ? "active;expires=%ld" : "terminated;reason=timeout"), expires); notifyRequest.setHeaderValue(SIP_SUBSCRIPTION_STATE_FIELD, buffer, 0); } unlock(); return(notifyInfoSet); } UtlBoolean SipSubscriptionMgr::createNotifiesDialogInfo(const char* resourceId, const char* eventTypeKey, int& numNotifiesCreated, UtlString**& acceptHeaderValuesArray, SipMessage**& notifyArray) { UtlString contentKey(resourceId); contentKey.append(eventTypeKey); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSubscriptionMgr::createNotifiesDialogInfo try to find contentKey '%s' in mSubscriptionStateResourceIndex (%"PRIuPTR" entries)", contentKey.data(), mSubscriptionStateResourceIndex.entries()); lock(); UtlHashBagIterator iterator(mSubscriptionStateResourceIndex, &contentKey); int count = 0; int index = 0; acceptHeaderValuesArray = NULL; notifyArray = NULL; while(iterator()) { count++; } if(count > 0) { SubscriptionServerStateIndex* contentTypeIndex = NULL; acceptHeaderValuesArray = new UtlString*[count]; notifyArray = new SipMessage*[count]; iterator.reset(); long now = OsDateTime::getSecsSinceEpoch(); while((contentTypeIndex = (SubscriptionServerStateIndex*)iterator())) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSubscriptionMgr::createNotifiesDialogInfo now %ld, mExpirationDate %ld", now, contentTypeIndex->mpState->mExpirationDate); // Should not happen, the container is supposed to be locked if(index >= count) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipSubscriptionMgr::createNotifiesDialogInfo iterator elements count changed from: %d to %d while locked", count, index); } // Should not happen, the index should be created and // deleted with the state else if(contentTypeIndex->mpState == NULL) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipSubscriptionMgr::createNotifiesDialogInfo SubscriptionServerStateIndex with NULL mpState"); } // If not expired yet else if(contentTypeIndex->mpState->mExpirationDate >= now) { // Get the accept value. acceptHeaderValuesArray[index] = new UtlString(contentTypeIndex->mpState->mAcceptHeaderValue); // Create the NOTIFY message. notifyArray[index] = new SipMessage; mDialogMgr.setNextLocalTransactionInfo(*(notifyArray[index]), SIP_NOTIFY_METHOD, *(contentTypeIndex->mpState)); // Set the event header, if we know what it is. UtlString eventHeader; if(contentTypeIndex->mpState->mpLastSubscribeRequest) { contentTypeIndex->mpState->mpLastSubscribeRequest->getEventField(eventHeader); } notifyArray[index]->setEventField(eventHeader); // Set the subscription-state header. char buffer[30]; sprintf(buffer, "active;expires=%ld", contentTypeIndex->mpState->mExpirationDate - now); notifyArray[index]->setHeaderValue(SIP_SUBSCRIPTION_STATE_FIELD, buffer, 0); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSubscriptionMgr::createNotifiesDialogInfo index %d, mAcceptHeaderValue '%s', getEventField '%s'", index, acceptHeaderValuesArray[index]->data(), eventHeader.data()); index++; } } } unlock(); numNotifiesCreated = index; return(index > 0); } void SipSubscriptionMgr::freeNotifies(int numNotifies, UtlString** acceptHeaderValues, SipMessage** notifiesArray) { if (notifiesArray && acceptHeaderValues && numNotifies > 0) { for(int index = 0; index < numNotifies; index++) { if(acceptHeaderValues[index]) { delete acceptHeaderValues[index]; } if(notifiesArray[index]) { delete notifiesArray[index]; } } delete[] acceptHeaderValues; delete[] notifiesArray; } } UtlBoolean SipSubscriptionMgr::endSubscription(const UtlString& dialogHandle) { UtlBoolean subscriptionFound = FALSE; lock(); SubscriptionServerState* state = (SubscriptionServerState*) mSubscriptionStatesByDialogHandle.find(&dialogHandle); if(state) { SubscriptionServerStateIndex* stateIndex = NULL; UtlString contentKey(state->mResourceId); contentKey.append(state->mEventTypeKey); UtlHashBagIterator iterator(mSubscriptionStateResourceIndex, &contentKey); while((stateIndex = (SubscriptionServerStateIndex*) iterator())) { if(stateIndex->mpState == state) { mSubscriptionStatesByDialogHandle.removeReference(state); mSubscriptionStateResourceIndex.removeReference(stateIndex); if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { UtlString requestContact; state->mpLastSubscribeRequest->getContactField(0, requestContact); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSubscriptionMgr::endSubscription delete subscription for key '%s', contact '%s', mExpirationDate %ld", stateIndex->data(), requestContact.data(), state->mExpirationDate); } delete state; delete stateIndex; subscriptionFound = TRUE; break; } } // Could not find the state index that cooresponded to the state // SHould not happen, there should always be one of each if(!subscriptionFound) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipSubscriptionMgr::endSubscription could not find SubscriptionServerStateIndex for state with dialog: %s", dialogHandle.data()); } } unlock(); // Remove the dialog mDialogMgr.deleteDialog(dialogHandle); return(subscriptionFound); } int SipSubscriptionMgr::dumpOldSubscriptions(long oldEpochTimeSeconds) { int totalStates = 0; int oldStates = 0; int stateIndicesWithNoState = 0; lock(); UtlHashBagIterator iterator(mSubscriptionStateResourceIndex); SubscriptionServerStateIndex* stateIndex = NULL; while((stateIndex = (SubscriptionServerStateIndex*) iterator())) { totalStates++; if(stateIndex->mpState) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "substate: %s expires: %d old date: %d", stateIndex->mpState->data(), stateIndex->mpState->mExpirationDate, oldEpochTimeSeconds); if(stateIndex->mpState->mExpirationDate < oldEpochTimeSeconds) { if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { UtlString requestContact; stateIndex->mpState->mpLastSubscribeRequest-> getContactField(0, requestContact); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSubscriptionMgr::removeOldSubscriptions old subscription for key '%s', contact '%s', mExpirationDate %ld", stateIndex->data(), requestContact.data(), stateIndex->mpState->mExpirationDate); } oldStates++; } } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipSubscriptionMgr::removeOldSubscriptions SubscriptionServerStateIndex with NULL mpState, should be removed"); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSubscriptionMgr::removeOldSubscriptions should remove subscription for key '%s'", stateIndex->data()); stateIndicesWithNoState++; } } unlock(); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSubscriptionMgr::removeOldSubscriptions states removed: %d indices w/o state: %d total states: %d", oldStates, stateIndicesWithNoState, totalStates); return(oldStates); } int SipSubscriptionMgr::removeOldSubscriptions(long oldEpochTimeSeconds) { int totalStates = 0; int removedStates = 0; int stateIndicesWithNoState = 0; lock(); UtlHashBagIterator iterator(mSubscriptionStateResourceIndex); SubscriptionServerStateIndex* stateIndex = NULL; while((stateIndex = (SubscriptionServerStateIndex*) iterator())) { totalStates++; if(stateIndex->mpState) { if(stateIndex->mpState->mExpirationDate < oldEpochTimeSeconds) { if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { UtlString requestContact; stateIndex->mpState->mpLastSubscribeRequest-> getContactField(0, requestContact); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSubscriptionMgr::removeOldSubscriptions delete subscription for key '%s', contact '%s', mExpirationDate %ld", stateIndex->data(), requestContact.data(), stateIndex->mpState->mExpirationDate); } mDialogMgr.deleteDialog(*(stateIndex->mpState)); mSubscriptionStatesByDialogHandle.removeReference(stateIndex->mpState); removedStates++; delete stateIndex->mpState; stateIndex->mpState = NULL; mSubscriptionStateResourceIndex.removeReference(stateIndex); delete stateIndex; } } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipSubscriptionMgr::removeOldSubscriptions SubscriptionServerStateIndex with NULL mpState, deleting"); mSubscriptionStateResourceIndex.removeReference(stateIndex); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSubscriptionMgr::removeOldSubscriptions delete subscription for key '%s'", stateIndex->data()); stateIndicesWithNoState++; delete stateIndex; } } unlock(); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipSubscriptionMgr::removeOldSubscriptions states removed: %d indices w/o state: %d total states: %d", removedStates, stateIndicesWithNoState, totalStates); return(removedStates); } void SipSubscriptionMgr::setMaxExpiration(int maxExpiration) { if(maxExpiration > 0) { mMaxExpiration = maxExpiration; } } /* ============================ ACCESSORS ================================= */ SipDialogMgr* SipSubscriptionMgr::getDialogMgr() { return &mDialogMgr; } int SipSubscriptionMgr::getStateCount() { int count = 0; lock(); count = mSubscriptionStatesByDialogHandle.entries(); unlock(); return(count); } /* ============================ INQUIRY =================================== */ UtlBoolean SipSubscriptionMgr::dialogExists(UtlString& dialogHandle) { UtlBoolean subscriptionFound = FALSE; lock(); SubscriptionServerState* state = (SubscriptionServerState*) mSubscriptionStatesByDialogHandle.find(&dialogHandle); if(state) { subscriptionFound = TRUE; } unlock(); return(subscriptionFound); } UtlBoolean SipSubscriptionMgr::isExpired(UtlString& dialogHandle) { UtlBoolean subscriptionExpired = TRUE; lock(); SubscriptionServerState* state = (SubscriptionServerState*) mSubscriptionStatesByDialogHandle.find(&dialogHandle); if(state) { long now = OsDateTime::getSecsSinceEpoch(); if(now <= state->mExpirationDate) { subscriptionExpired = FALSE; } } unlock(); return(subscriptionExpired); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ void SipSubscriptionMgr::lock() { mSubscriptionMgrMutex.acquire(); } void SipSubscriptionMgr::unlock() { mSubscriptionMgrMutex.release(); } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipTcpServer.cpp0000644000175000017500000002417112205613256024274 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include // APPLICATION INCLUDES #include #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS //#define TEST_PRINT // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipTcpServer::SipTcpServer(int port, SipUserAgent* userAgent, const char* protocolString, const char* taskName, UtlBoolean bUseNextAvailablePort, const char* szBindAddr) : SipProtocolServerBase(userAgent, protocolString, taskName) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTcpServer::_ port = %d, taskName = '%s', bUseNextAvailablePort = %d, szBindAddr = '%s'", port, taskName, bUseNextAvailablePort, szBindAddr); mServerPort = port ; mpServerBrokerListener = new SipServerBrokerListener(this); #ifdef _DISABLE_MULTIPLE_INTERFACE_SUPPORT szBindAddr = "0.0.0.0" ; #endif if (szBindAddr && 0 != strcmp(szBindAddr, "0.0.0.0")) { mDefaultIp = szBindAddr; createServerSocket(szBindAddr, mServerPort, bUseNextAvailablePort); } else { int numAddresses = MAX_IP_ADDRESSES; const HostAdapterAddress* adapterAddresses[MAX_IP_ADDRESSES]; getAllLocalHostIps(adapterAddresses, numAddresses); for (int i = 0; i < numAddresses; i++) { createServerSocket(adapterAddresses[i]->mAddress.data(), mServerPort, bUseNextAvailablePort); if (0 == i) { // use the first IP address in the array // for the 'default ip' mDefaultIp = adapterAddresses[i]->mAddress.data(); } delete adapterAddresses[i]; } } mDefaultPort = SIP_PORT; } UtlBoolean SipTcpServer::startListener() { UtlBoolean bRet(FALSE); # ifdef TEST_PRINT osPrintf("SIP Server binding to port %d\n", serverPort); # endif // iterate over the SipServerBroker map and call start UtlHashMapIterator iterator(mServerBrokers); UtlVoidPtr* pBrokerContainer = NULL; SipServerBroker* pBroker = NULL; UtlString* pKey = NULL; while((pKey = (UtlString*)iterator())) { pBrokerContainer = (UtlVoidPtr*) iterator.value(); if (pBrokerContainer) { pBroker = (SipServerBroker*)pBrokerContainer->getValue(); if (pBroker) { pBroker->start(); bRet = TRUE; } } } return bRet; } OsStatus SipTcpServer::createServerSocket(const char* szBindAddr, int& port, const UtlBoolean& bUseNextAvailablePort) { OsStatus rc = OS_FAILED; if (port != PORT_NONE) { OsServerSocket* pSocket = new OsServerSocket(64, port, szBindAddr); // If the socket is busy or unbindable and the user requested using the // next available port, try the next SIP_MAX_PORT_RANGE ports. if (pSocket && !pSocket->isOk() && bUseNextAvailablePort) { for (int i=1; i<=SIP_MAX_PORT_RANGE; i++) { delete pSocket; pSocket = new OsServerSocket(64, port+i); if (pSocket && pSocket->isOk()) { break ; } } } if (pSocket && pSocket->isOk()) { port = pSocket->getLocalHostPort(); SIPX_CONTACT_ADDRESS contact; strcpy(contact.cIpAddress, szBindAddr); contact.iPort = port; contact.eContactType = CONTACT_LOCAL; UtlString adapterName; getContactAdapterName(adapterName, contact.cIpAddress, false); strcpy(contact.cInterface, adapterName.data()); contact.eTransportType = TRANSPORT_TCP; mSipUserAgent->addContactAddress(contact); // add address and port to the maps mServerSocketMap.insertKeyAndValue(new UtlString(szBindAddr), new UtlVoidPtr((void*)pSocket)); mServerPortMap.insertKeyAndValue(new UtlString(szBindAddr), new UtlInt(pSocket->getLocalHostPort())); mServerBrokers.insertKeyAndValue(new UtlString(szBindAddr), new UtlVoidPtr(new SipServerBroker((OsServerTask*)mpServerBrokerListener, pSocket))); } } return rc; } // Copy constructor SipTcpServer::SipTcpServer(const SipTcpServer& rSipTcpServer) : SipProtocolServerBase(NULL, SIP_TRANSPORT_TCP, "SipTcpServer-%d") { } // Destructor SipTcpServer::~SipTcpServer() { if (mpServerBrokerListener) { mpServerBrokerListener->requestShutdown(); delete mpServerBrokerListener; } waitUntilShutDown(); { SipServerBroker* pBroker = NULL; UtlHashMapIterator iterator(this->mServerBrokers); UtlVoidPtr* pBrokerContainer = NULL; UtlString* pKey = NULL; while ((pKey = (UtlString*)iterator())) { pBrokerContainer = (UtlVoidPtr*)iterator.value(); if (pBrokerContainer) { pBroker = (SipServerBroker*)pBrokerContainer->getValue(); if (pBroker) { delete pBroker; } } } mServerBrokers.destroyAll(); } /* { OsSocket* pSocket = NULL; UtlHashMapIterator iterator(mServerSocketMap); UtlVoidPtr* pSocketContainer = NULL; UtlString* pKey = NULL; while (pKey = (UtlString*)iterator()) { pSocketContainer = (UtlVoidPtr*)iterator.value(); if (pSocketContainer) { pSocket = (OsSocket*)pSocketContainer->getValue(); if (pSocket) { delete pSocket; } } } mServerSocketMap.destroyAll(); } */ mServerSocketMap.destroyAll(); mServerPortMap.destroyAll(); } /* ============================ MANIPULATORS ============================== */ int SipTcpServer::run(void* runArgument) { while (!isShuttingDown()) { OsTask::delay(500); // this method really shouldn't do anything } return(0); } void SipTcpServer::shutdownListener() { requestShutdown(); shutdownClients(); } OsSocket* SipTcpServer::buildClientSocket(int hostPort, const char* hostAddress, const char* localIp) { // Create a socket in non-blocking mode while connecting OsConnectionSocket* socket = new OsConnectionSocket(hostPort, hostAddress, FALSE, localIp); if (socket) { socket->makeBlocking(); } return(socket); } // Assignment operator SipTcpServer& SipTcpServer::operator=(const SipTcpServer& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } /* ============================ ACCESSORS ================================= */ // The the local server port for this server int SipTcpServer::getServerPort() const { return mServerPort ; } UtlBoolean SipServerBrokerListener::handleMessage(OsMsg& eventMessage) { UtlBoolean bRet(FALSE); int msgType = eventMessage.getMsgType(); int msgSubType = eventMessage.getMsgSubType(); OsPtrMsg *pPtrMsg = NULL; if (msgType == OsMsg::OS_EVENT) { // if we are receiving this message, a socket an accept has // occurred, and the socket is being sent to us in this message if (msgSubType == SIP_SERVER_BROKER_NOTIFY) { // unpackage the client socket pPtrMsg = static_cast(&eventMessage); assert(pPtrMsg); OsConnectionSocket* clientSocket = reinterpret_cast(pPtrMsg->getPtr()); assert (clientSocket); SipClient* client = NULL; client = new SipClient(clientSocket); if(mpOwner->mSipUserAgent) { client->setUserAgent(mpOwner->mSipUserAgent); } UtlString hostAddress; int hostPort; clientSocket->getRemoteHostIp(&hostAddress, &hostPort); OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServer::run client: %p %s:%d", mpOwner->mProtocolString.data(), client, hostAddress.data(), hostPort); UtlBoolean clientStarted = client->start(); if(!clientStarted) { OsSysLog::add(FAC_SIP, PRI_ERR, "SIP %s Client failed to start", mpOwner->mProtocolString.data()); } mpOwner->addClient(client); bRet = TRUE; } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SIP %s Client received spurious message", mpOwner->mProtocolString.data()); } } return bRet; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipTransaction.cpp0000644000175000017500000057305512205613256024656 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define SIP_UDP_RESEND_TIMES 7 #define MIN_Q_DELTA_SQUARE 0.0000000001 // Smallest Q difference is 0.00001 #define BRANCH_ID_PREFIX "z9hG4bK" // STATIC VARIABLE INITIALIZATIONS int SipTransaction::smTransactionNum = 0; UtlString SipTransaction::smBranchIdBase; //#define TEST_PRINT //#define LOG_FORKING //#define ROUTE_DEBUG /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipTransaction::SipTransaction(SipMessage* request, UtlBoolean isOutgoing, UtlBoolean userAgentTransaction) : mRequestMethod(""), mpTransport(NULL) { mIsUaTransaction = userAgentTransaction; mpRequest = NULL; mpLastProvisionalResponse = NULL; mpLastFinalResponse = NULL; mpAck = NULL; mpCancel = NULL; mpCancelResponse = NULL; mpParentTransaction = NULL; mIsCanceled = FALSE; mIsRecursing = FALSE; mQvalue = 1.0; mExpires = -1; mIsBusy = FALSE; mWaitingList = NULL; mDispatchedFinalResponse = FALSE; mProvisionalSdp = FALSE; mpDnsSrvRecords = NULL; mIsDnsSrvChild = FALSE; mSendToPort = PORT_NONE; mSendToProtocol = OsSocket::UNKNOWN; # ifdef ROUTE_DEBUG { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::_ new %p msg %p %s %s", this, &request, isOutgoing ? "OUTGOING" : "INCOMING", userAgentTransaction ? "UA" : "SERVER" ); } # endif if(request) { mIsServerTransaction = request->isServerTransaction(isOutgoing); request->getCallIdField(&mCallId); // Set the hash key buildHash(*request, isOutgoing, *this); request->getCSeqField(&mCseq, &mRequestMethod); if(!request->isResponse()) { request->getRequestUri(&mRequestUri); request->getRequestMethod(&mRequestMethod); // Do not attach the request here as it will get passed in // later for handleOutgoing or handleIncoming if( 0 != mRequestMethod.compareTo(SIP_INVITE_METHOD) // not INVITE || !request->getExpiresField(&mExpires)) // or no Expires header field { mExpires = -1; } } else // this is a response { // Do not attach the response here as it will get passed in // later for handleOutgoing or handleIncoming } request->getToUrl(mToField); request->getFromUrl(mFromField); if(!mIsServerTransaction) // is this a new client transaction? { // Yes - create a new branch id getNewBranchId(*request, mBranchId); } else { // This is a server transaction, so the branch id is // created by the client and passed in the via UtlString viaField; request->getViaFieldSubField(&viaField, 0); SipMessage::getViaTag(viaField.data(), "branch", mBranchId); } } else { mIsServerTransaction = FALSE; } mTransactionState = TRANSACTION_LOCALLY_INIITATED; mTransactionStartTime = -1; touch(); mTransactionCreateTime = mTimeStamp; } // Copy constructor SipTransaction::SipTransaction(const SipTransaction& rSipTransaction) { } // Destructor SipTransaction::~SipTransaction() { #ifdef TEST_PRINT osPrintf("*******************************\n"); osPrintf("Deleting messages at:\n"); osPrintf(" %X\n",mpRequest); osPrintf(" %X\n",mpLastProvisionalResponse); osPrintf(" %X\n",mpLastFinalResponse); osPrintf(" %X\n",mpAck); osPrintf(" %X\n",mpCancel); osPrintf(" %X\n",mpCancelResponse); osPrintf("*******************************\n"); #endif // Optimization: stop timers before doing anything else deleteTimers(); if(mpRequest) delete mpRequest; mpRequest = NULL; if(mpLastProvisionalResponse) delete mpLastProvisionalResponse; mpLastProvisionalResponse = NULL; if(mpLastFinalResponse) delete mpLastFinalResponse; mpLastFinalResponse = NULL; if(mpAck) delete mpAck; mpAck = NULL; if(mpCancel) delete mpCancel; mpCancel = NULL; if(mpCancelResponse) delete mpCancelResponse; mpCancelResponse = NULL; if(mpDnsSrvRecords) { delete[] mpDnsSrvRecords; } if(mWaitingList) { int numEvents = mWaitingList->entries(); if(mpParentTransaction) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::~SipTransaction non parent has %d waiting events", numEvents); } if(numEvents > 0) { // Cannot call signalAllAvailable as it traverses what // may be a broken (i.e. partially deleted) tree UtlVoidPtr* eventNode = NULL; while ((eventNode = (UtlVoidPtr*) mWaitingList->get())) { if(eventNode) { OsEvent* waitingEvent = (OsEvent*) eventNode->getValue(); if(waitingEvent) { // If it is already signaled, the other side // is no longer waiting for the event, so this // side must delete the event. if(waitingEvent->signal(0) == OS_ALREADY_SIGNALED) { delete waitingEvent; waitingEvent = NULL; } } delete eventNode; eventNode = NULL; } } OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::~ %d waiting events in list", numEvents); } delete mWaitingList; mWaitingList = NULL; } } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipTransaction& SipTransaction::operator=(const SipTransaction& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } void SipTransaction::getNewBranchId(SipMessage& request, UtlString& branchId) { branchId.remove(0); branchId.append(BRANCH_ID_PREFIX); // Magic cookie must be in front branchId.append("-"); // :TODO: it would be interesting to add some debugging data here // For example, if we could encode what sort of // transaction this is and where it is in the tree (what # child?) // into a short code here so that we could recognize it in traces... // build up the unique part of the branch id by hashing // - a value unique to this call // - a value unique to this host // - a monotonically increasing counter UtlString branchUniqCode; UtlString branchSeed; // input to the hash request.getCallIdField(&branchSeed); if(smBranchIdBase.isNull()) { // use the ip address as a value unique to this host (better be true) OsSocket::getHostIp(&smBranchIdBase); } branchSeed.append(smBranchIdBase); int transNum = (smTransactionNum++); char buf[32]; sprintf(buf, "%d", transNum); branchSeed.append(buf); NetMd5Codec::encode(branchSeed.data(), branchUniqCode); #ifdef USE_LONG_CALL_IDS // MD5 component of branchId to 16 bytes branchUniqCode.remove(16) ; #else // MD5 component of branchId to 12 bytes branchUniqCode.remove(12) ; #endif branchId.append(branchUniqCode); } enum SipTransaction::messageRelationship SipTransaction::addResponse(SipMessage*& response, UtlBoolean isOutGoing, // intravert/extravert enum messageRelationship relationship) // casual/serious { if(relationship == MESSAGE_UNKNOWN) { relationship = whatRelation(*response, isOutGoing); } switch(relationship) { case MESSAGE_REQUEST: // I do not know why this should ever occur // Typically the transaction will first be created with a request if(mpRequest) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::addResponse of request to existing transaction, IGNORED"); delete response ; response = NULL; } else { mpRequest = response; } if(mTransactionState < TRANSACTION_CALLING) { mTransactionState = TRANSACTION_CALLING; OsTime time; OsDateTime::getCurTimeSinceBoot(time); mTransactionStartTime = time.seconds(); } break; case MESSAGE_PROVISIONAL: if(mpLastProvisionalResponse) { delete mpLastProvisionalResponse; } mpLastProvisionalResponse = response; if(mTransactionState < TRANSACTION_PROCEEDING) mTransactionState = TRANSACTION_PROCEEDING; // If check if there is early media // We need this state member as there may be multiple // provisional responses and we cannot rely upon the fact // that the last one has SDP or not to indicate that there // was early media or not. if(!mProvisionalSdp) { if((response->getSdpBody(response->getSecurityAttributes()))) { mProvisionalSdp = TRUE; } } break; case MESSAGE_FINAL: if(mpLastFinalResponse) { delete mpLastFinalResponse; } mpLastFinalResponse = response; if(mTransactionState < TRANSACTION_COMPLETE) mTransactionState = TRANSACTION_COMPLETE; break; case MESSAGE_ACK: case MESSAGE_2XX_ACK: if(mpAck) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::addResponse ACK already exists, IGNORED"); delete response ; response = NULL; } else { mpAck = response; } break; case MESSAGE_CANCEL: if(mpCancel) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::addResponse CANCEL already exists, IGNORED"); delete response ; response = NULL; } else { mpCancel = response; } break; case MESSAGE_CANCEL_RESPONSE: if(mpCancelResponse) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::addResponse CANCEL response already exists, IGNORED"); delete response ; response = NULL; } else { mpCancelResponse = response; } break; case MESSAGE_UNKNOWN: case MESSAGE_UNRELATED: case MESSAGE_DUPLICATE: default: OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::addResponse message with bad relationship: %d", relationship); delete response ; response = NULL; break; } return(relationship); } UtlBoolean SipTransaction::handleOutgoing(SipMessage& outgoingMessage, SipUserAgent& userAgent, SipTransactionList& transactionList, enum messageRelationship relationship, SIPX_TRANSPORT_DATA* pTransport) { if (!mpTransport) mpTransport = pTransport; UtlBoolean isResponse = outgoingMessage.isResponse(); //UtlString toAddress; //UtlString protocol; SipMessage* message = &outgoingMessage; UtlBoolean isOrignalRequest = FALSE; UtlBoolean sendSucceeded = FALSE; UtlString method; int cSeq; UtlString seqMethod; outgoingMessage.getCSeqField(&cSeq, &seqMethod); outgoingMessage.getRequestMethod(&method); if(relationship == MESSAGE_UNKNOWN) relationship = whatRelation(outgoingMessage, TRUE); if(relationship == MESSAGE_DUPLICATE) { // If this transaction was contructed with this message // it will appear as a duplicate if(!isResponse && mpRequest && !mIsServerTransaction && mpRequest->getTimesSent() == 0 && mRequestMethod.compareTo(method) == 0) { isOrignalRequest = TRUE; message = mpRequest; } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::handleOutgoing send of duplicate message"); } } UtlBoolean addressRequiresDnsSrvLookup(FALSE); UtlString toAddress; int port = PORT_NONE; OsSocket::IpProtocolSocketType protocol = OsSocket::UNKNOWN; if(isResponse) { UtlString protocolString; message->getResponseSendAddress(toAddress, port, protocolString); # ifdef ROUTE_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleOutgoing called getResponseSendAddress, returned toAddress = '%s', port = %d, protocolString = '%s'", toAddress.data(), port, protocolString.data()); # endif SipMessage::convertProtocolStringToEnum(protocolString.data(), protocol); } else { // Fix the request so that it is ready to send prepareRequestForSend(*message, userAgent, addressRequiresDnsSrvLookup, toAddress, port, protocol); # ifdef ROUTE_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleOutgoing called prepareRequestForSend, returned toAddress = '%s', port = %d, protocol = OsSocket::SocketProtocolTypes(%d), addressRequiresDnsSrvLookup = %d", toAddress.data(), port, protocol, addressRequiresDnsSrvLookup); # endif if(mSendToAddress.isNull()) { # ifdef ROUTE_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleOutgoing setting mSendTo* variables"); # endif mSendToAddress = toAddress; mSendToPort = port; mSendToProtocol = protocol; } } // Do not send out CANCEL requests on DNS SRV parents. // They do not actually send request and so should not // send CANCELs either. if( !isResponse && !mIsDnsSrvChild && (method.compareTo(SIP_CANCEL_METHOD) == 0)) { if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { UtlString requestString; int len; outgoingMessage.getBytes(&requestString, &len); UtlString transString; toString(transString, TRUE); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleOutgoing " "should not send CANCEL on DNS parent\n%s\n%s", requestString.data(), transString.data()); } } // Request that requires DNS SRV lookup else if ( !isResponse && addressRequiresDnsSrvLookup && method.compareTo(SIP_ACK_METHOD) != 0 && method.compareTo(SIP_CANCEL_METHOD) != 0 && !mIsDnsSrvChild ) { if(mpRequest != NULL) { if (OsSysLog::willLog(FAC_SIP, PRI_WARNING)) { UtlString requestString; int len; outgoingMessage.getBytes(&requestString, &len); UtlString transString; toString(transString, TRUE); OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::handleOutgoing mpRequest should be NULL\n%s\n%s", requestString.data(), transString.data()); } } if(relationship != MESSAGE_REQUEST) { if (OsSysLog::willLog(FAC_SIP, PRI_WARNING)) { UtlString relString; SipTransaction::getRelationshipString(relationship, relString); UtlString requestString; int len; outgoingMessage.getBytes(&requestString, &len); UtlString transString; toString(transString, TRUE); OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::handleOutgoing invalid relationship: %s\n%s\n%s", relString.data(), requestString.data(), transString.data()); } } // Make a copy to attach to the transaction SipMessage* requestCopy = new SipMessage(outgoingMessage); addResponse(requestCopy, TRUE, // outgoing relationship); // Look up the DNS SRV records, create the children tranaction // and start pursuing the first child if (SIPX_TRANSPORT_DATA::isCustomTransport(mpTransport)) { protocol = OsSocket::CUSTOM; } if (protocol == OsSocket::CUSTOM) { sendSucceeded = recurseDnsSrvChildren(userAgent, transactionList, mpTransport); } else { sendSucceeded = recurseDnsSrvChildren(userAgent, transactionList, NULL); } } else { // check the message's URI - // if "sips" is the scheme, // use SSL_SOCKET as the protocol UtlString toUrl; message->getToField(&toUrl); Url parsedUri(toUrl); Url::Scheme scheme = parsedUri.getScheme(); if (scheme == Url::SipsUrlScheme) { protocol = OsSocket::SSL_SOCKET; } if (SIPX_TRANSPORT_DATA::isCustomTransport(mpTransport)) { protocol = OsSocket::CUSTOM; } // also, take the transport hint from the to-field and/or from-field. If there is a transport= in it, // and it is not tls, tcp, or udp, use custom and set mpTransport UtlString tempFromField; UtlString tempToField; message->getFromField(&tempFromField); message->getToField(&tempToField); UtlString transport; Url tempToUrl(tempToField); Url tempFromUrl(tempFromField); tempToUrl.getUrlParameter("transport", transport, 0); if (transport.length() < 1 || transport.compareTo("udp") == 0 || transport.compareTo("tls") == 0 || transport.compareTo("tcp") == 0) { tempFromUrl.getUrlParameter("transport", transport, 0); if (transport.compareTo("udp") == 0 || transport.compareTo("tls") == 0 || transport.compareTo("tcp") == 0) { transport = ""; } } UtlString localIp; int dummy; userAgent.getLocalAddress(&localIp, &dummy); if (!mpTransport && transport.length() > 0) { mpTransport = (SIPX_TRANSPORT_DATA*)userAgent.lookupExternalTransport(transport, localIp); if (mpTransport) { protocol = OsSocket::CUSTOM; } } sendSucceeded = doFirstSend(*message, relationship, userAgent, toAddress, port, protocol, mpTransport); touch(); } return(sendSucceeded); } // end handleOutgoing void SipTransaction::prepareRequestForSend(SipMessage& request, SipUserAgent& userAgent, UtlBoolean& addressRequiresDnsSrvLookup, UtlString& toAddress, int& port, OsSocket::IpProtocolSocketType& toProtocol) { UtlString protocol; // Make sure max-forwards is set and it is not // greater than the default value int maxForwards; int defaultMaxForwards = userAgent.getMaxForwards(); if(!request.getMaxForwards(maxForwards) || maxForwards > defaultMaxForwards) { request.setMaxForwards(defaultMaxForwards); } // ACKs for 200 response do NOT reuse the INVITEs routing and URI UtlBoolean ackFor2xx = FALSE; UtlString method; request.getRequestMethod(&method); if(method.compareTo(SIP_ACK_METHOD) == 0 && mpLastFinalResponse) { int responseCode; responseCode = mpLastFinalResponse->getResponseStatusCode(); if(responseCode >= SIP_2XX_CLASS_CODE && responseCode < SIP_3XX_CLASS_CODE) { ackFor2xx = TRUE; } } // If this is an ACK for a 2xx response so we have to look it up // We have already figured out how to route this request. if(mIsDnsSrvChild && !mSendToAddress.isNull() && !ackFor2xx) { toAddress = mSendToAddress; port = mSendToPort; toProtocol = mSendToProtocol; addressRequiresDnsSrvLookup = FALSE; # ifdef ROUTE_DEBUG { UtlString protoString; SipMessage::convertProtocolEnumToString(toProtocol,protoString); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::prepareRequestForSend %p - SRV child ready" " to %s:%d via '%s'", &request, toAddress.data(), port, protoString.data() ); } # endif } // Look at the request and figure out how to route it. else { // For INVITE, process header parameters in the request uri if (0 == method.compareTo(SIP_INVITE_METHOD)) { request.applyTargetUriHeaderParams(); } // Use the proxy only for requests userAgent.getProxyServer(0, &toAddress, &port, &protocol); # ifdef ROUTE_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::prepareRequestForSend %p got proxy toAddress '%s', port %d, protocol '%s'", &request, toAddress.data(), port, protocol.data()); # endif // See if there is a route UtlString routeUri; UtlString routeAddress; int routePort; UtlString routeProtocol; request.getRouteUri(0, &routeUri); Url routeUrlParser(routeUri); UtlString dummyValue; UtlBoolean nextHopLooseRoutes = routeUrlParser.getUrlParameter("lr", dummyValue, 0); UtlString maddr; routeUrlParser.getUrlParameter("maddr", maddr); UtlString routeHost; SipMessage::parseAddressFromUri(routeUri.data(), &routeHost, &routePort, &routeProtocol); // All of this URL maipulation should be done via // the Url (routeUrlParser) object. However to // be safe, we are only using it to // get the maddr If the maddr is present use it as the address if(!maddr.isNull()) { routeAddress = maddr; } else { routeAddress = routeHost; } # ifdef ROUTE_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::prepareRequestForSend %p getting first route uri: '%s'", &request, routeUri.data()); # endif // If there is no route use the configured outbound proxy if(routeAddress.isNull()) { // It is already set in toAddress } else //if(!routeAddress.isNull()) { toAddress = routeAddress; port = routePort; protocol = routeProtocol; // If this is not a loose route set the URI UtlString value; if(!nextHopLooseRoutes) { //Change the URI in the first line to the route Uri // so pop the first route uri request.removeRouteUri(0, &routeUri); # ifdef ROUTE_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::prepareRequestForSend %p" " removing route, no proxy, uri: '%s'", &request, routeUri.data()); # endif // We need to push the URI on the end of the routes UtlString uri; request.getRequestUri(&uri); request.addLastRouteUri(uri.data()); // Set the URI to the popped route UtlString ChangedUri; routeUrlParser.getUri(ChangedUri); request.changeRequestUri(ChangedUri); } # ifdef ROUTE_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::prepareRequestForSend %p - using route address" " to %s:%d via '%s'", &request, toAddress.data(), port, protocol.data() ); # endif } // No proxy, no route URI, try to use URI from message if(toAddress.isNull()) { UtlString uriString; request.getRequestUri(&uriString); Url requestUri(uriString, TRUE); requestUri.getHostAddress(toAddress); port = requestUri.getHostPort(); requestUri.getUrlParameter("transport", protocol); if(requestUri.getUrlParameter("maddr", maddr) && !maddr.isNull()) { toAddress = maddr; } # ifdef ROUTE_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::prepareRequestForSend %p - " " using request URI address: %s:%d via '%s'", &request, toAddress.data(), port, protocol.data() ); # endif } // No proxy, route URI, or message URI, use the To field if(toAddress.isNull()) { request.getToAddress(&toAddress, &port, &protocol); # ifdef ROUTE_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::prepareRequestForSend %p " "No URI address, using To address" " to %s:%d via '%s'", &request, toAddress.data(), port, protocol.data() ); # endif } UtlString toField; request.getToField(&toField); Url toUrl(toField); UtlString toMaddr; toUrl.getUrlParameter("maddr", toMaddr); // Trying to have a low impact on the code All of this should just use the Url object if(!toMaddr.isNull()) { toAddress = toMaddr; } #ifdef TEST_PRINT osPrintf("SipTransaction::prepareRequestForSend UA Sending SIP REQUEST to: \"%s\" port: %d\n", toAddress.data(), port); #endif //SDUA UtlString sPort; UtlString thisMethod; request.getRequestMethod(&thisMethod); //check if CANCEL method and has corresponding INVITE if(strcmp(thisMethod.data(), SIP_CANCEL_METHOD) == 0) { //Stick DNS parameters because this cancel is for the same transaction as invite //find correcponding INVITE request //SipMessage * InviteMsg = sentMessages.getInviteFor( &message); if ( !mIsServerTransaction && mpRequest && mRequestMethod.compareTo(SIP_INVITE_METHOD) == 0) { //copy DNS parameters if ( mpRequest->getDNSField(&protocol , &toAddress , &sPort)) { request.setDNSField( protocol , toAddress , sPort); } } } // USE CONTACT OR RECORD ROUTE FIELDS FOR 200 OK responses //check if ACK method and if it has contact field set //if contact field is set then it is a 200 OK response //therefore do not set sticky DNS prameters or DNS look up //if DNS field is present request if (request.getDNSField(&protocol , &toAddress, &sPort)) { port = atoi(sPort.data()); } else { addressRequiresDnsSrvLookup = TRUE; } // If no one specified which protocol if(protocol.isNull()) { toProtocol = OsSocket::UNKNOWN; } else { SipMessage::convertProtocolStringToEnum(protocol.data(), toProtocol); } } # ifdef ROUTE_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::prepareRequestForSend %p prepared SIP REQUEST" " DNS SRV lookup: %s" " to %s:%d via '%s'", &request, addressRequiresDnsSrvLookup ? "NEEDED" : "NOT NEEDED", toAddress.data(), port, protocol.data() ); # endif } UtlBoolean SipTransaction::doFirstSend(SipMessage& message, enum messageRelationship relationship, SipUserAgent& userAgent, UtlString& toAddress, int& port, OsSocket::IpProtocolSocketType& toProtocol, SIPX_TRANSPORT_DATA* pTransport) { if (!mpTransport) mpTransport = pTransport; UtlBoolean sendSucceeded = FALSE; UtlBoolean isResponse = message.isResponse(); UtlString method; UtlString seqMethod; int responseCode = -1; OsSocket::IpProtocolSocketType lastSentProtocol = message.getSendProtocol(); int resendDuration; int resendTime; # ifdef ROUTE_DEBUG { UtlString logRelationship; SipTransaction::getRelationshipString(relationship, logRelationship); UtlString logProtocol; SipMessage::convertProtocolEnumToString(toProtocol, logProtocol); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::doFirstSend %p %s to %s:%d via '%s'", &message, logRelationship.data(), toAddress.data(), port, logProtocol.data() ); } # endif if(toProtocol == OsSocket::UNKNOWN) { if ( lastSentProtocol == OsSocket::UNKNOWN ) { /* * :HACK: This is a problem, and a more comprehensive fix is still needed. [XSL-49] * * We get to here when sending an ACK to 2xx responses, and we shouldn't; * those really should be going through the normal routing to determine the * protocol using DNS SRV lookups, but there is code elsewhere that prevents * that from happening. * * Forcing UDP may not always be correct, but it's the best we can do now. */ toProtocol = OsSocket::UDP; OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::doFirstSend protocol not explicitly set - using UDP" ); } else { toProtocol = lastSentProtocol; } } // Responses: if(isResponse) { responseCode = message.getResponseStatusCode(); int cSeq; message.getCSeqField(&cSeq, &seqMethod); # ifdef ROUTE_DEBUG { UtlString protocolStr; SipMessage::convertProtocolEnumToString(toProtocol, protocolStr); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::doFirstSend %p " "Sending RESPONSE to: %s:%d via: %s", this, toAddress.data(), port, protocolStr.data()); } # endif // This is the first send, save the address and port to which it get sent message.setSendAddress(toAddress.data(), port); message.setFirstSent(); } // Requests: else { // This is the first send, save the address and port to which it get sent message.setSendAddress(toAddress.data(), port); message.setFirstSent(); message.getRequestMethod(&method); // Add a via to requests, now that we know the protocol userAgent.prepareVia(message, mBranchId, toProtocol, toAddress.data(), &port, mpTransport); } if(toProtocol == OsSocket::TCP) { lastSentProtocol = OsSocket::TCP; resendDuration = 0; resendTime = userAgent.getReliableTransportTimeout() * 1000; } # ifdef SIP_TLS else if(toProtocol == OsSocket::SSL_SOCKET) { lastSentProtocol = OsSocket::SSL_SOCKET; resendDuration = 0; resendTime = userAgent.getReliableTransportTimeout() * 1000; } # endif else if (OsSocket::CUSTOM == toProtocol) { lastSentProtocol = OsSocket::CUSTOM; if (pTransport->bIsReliable) { resendDuration = 0; resendTime = userAgent.getReliableTransportTimeout() * 1000; } else { resendTime = userAgent.getFirstResendTimeout() * 1000; resendDuration = userAgent.getFirstResendTimeout(); } } else { if(toProtocol != OsSocket::UDP) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::doFirstSend %p unknown protocol: %d using UDP", &message, toProtocol); } resendTime = userAgent.getFirstResendTimeout() * 1000; resendDuration = userAgent.getFirstResendTimeout(); lastSentProtocol = OsSocket::UDP; } // Set the transport information message.setResendDuration(resendDuration); message.setSendProtocol(lastSentProtocol); message.touchTransportTime(); SipMessage* transactionMessageCopy = NULL; if(relationship == MESSAGE_REQUEST || relationship == MESSAGE_PROVISIONAL || relationship == MESSAGE_FINAL || relationship == MESSAGE_CANCEL || relationship == MESSAGE_CANCEL_RESPONSE || relationship == MESSAGE_ACK || relationship == MESSAGE_2XX_ACK) { // Make a copy to attach to the transaction transactionMessageCopy = new SipMessage(message); // Need to add the message to the transaction before it // is sent to avoid the race of receiving the response before // the request is added to the transaction. addResponse(transactionMessageCopy, TRUE, // outgoing relationship); } if(toProtocol == OsSocket::TCP) { # ifdef TEST_PRINT message.logTimeEvent("SENDING TCP"); # endif sendSucceeded = userAgent.sendTcp(&message, toAddress.data(), port); } else if(toProtocol == OsSocket::SSL_SOCKET) { # ifdef TEST_PRINT message.logTimeEvent("SENDING TLS"); # endif sendSucceeded = userAgent.sendTls(&message, toAddress.data(), port); } else if (toProtocol >= OsSocket::CUSTOM) { sendSucceeded = userAgent.sendCustom(pTransport, &message, toAddress.data(), port); } else { # ifdef TEST_PRINT message.logTimeEvent("SENDING UDP"); # endif sendSucceeded = userAgent.sendUdp(&message, toAddress.data(), port); } if( MESSAGE_REQUEST == relationship && !sendSucceeded ) { mTransactionState = TRANSACTION_TERMINATED; } # ifdef TEST_PRINT message.dumpTimeLog(); # endif # ifdef TEST_PRINT osPrintf("SipTransaction::doFirstSend set Scheduling & resend data\n"); # endif // Increment after the send so the logging messages are // acurate message.incrementTimesSent(); if(transactionMessageCopy) transactionMessageCopy->incrementTimesSent(); if(sendSucceeded) { // Schedule a timeout for requests and final INVITE error // responses (2xx class INVITE responses will be resent // by user agents only) if( ( ! isResponse && strcmp(method.data(), SIP_ACK_METHOD) != 0 ) || ( isResponse && ( responseCode >= SIP_3XX_CLASS_CODE || (mIsUaTransaction && responseCode >= SIP_OK_CODE) ) && strcmp(seqMethod.data(), SIP_INVITE_METHOD) == 0 ) ) { # ifdef TEST_PRINT osPrintf("SipTransaction::doFirstSend Scheduling UDP %s timeout in %d msec\n", method.data(), userAgent.getFirstResendTimeout()); # endif // Set the transaction for the timeout message to make // it easier to find the transaction when the timer fires. message.setTransaction(this); if(transactionMessageCopy) transactionMessageCopy->setTransaction(this); // Keep separate copy for the timer SipMessageEvent* resendEvent = new SipMessageEvent(new SipMessage(message), SipMessageEvent::TRANSACTION_RESEND); # ifdef TEST_PRINT osPrintf("SipTransaction::doFirstSend timer scheduled for: %x\n", resendEvent->getMessage()); # endif // Set an event timer to resend the message // queue a message on this OsServerTask OsMsgQ* incomingQ = userAgent.getMessageQueue(); OsTimer* timer = new OsTimer(incomingQ, (intptr_t)resendEvent); mTimers.append(timer); #ifdef TEST_PRINT osPrintf("SipTransaction::doFirstSend added timer %p to timer list.\n", timer); #endif // Convert from mSeconds to uSeconds OsTime timerTime(0, resendTime); timer->oneshotAfter(timerTime); // If this is a client transaction and we are sending // a request, set an expires timer for the transaction if(!mIsServerTransaction && !isResponse) { int expireSeconds = mExpires; int maxExpires = userAgent.getDefaultExpiresSeconds(); // We cancel DNS SRV children after the configured DNS SRV timeout. // The timeout is ignored if we receive any response. // If this is the only child, do not set a short (DNS SRV) timeout if(mIsDnsSrvChild && mpParentTransaction && mpParentTransaction->isChildSerial()) { UtlString method; int dummyNum; message.getCSeqField(&dummyNum, &method); if (strcmp(method.data(), SIP_REGISTER_METHOD) == 0) { expireSeconds = userAgent.getRegisterResponseTimeout(); } else { expireSeconds = userAgent.getDnsSrvTimeout(); } } // Normal client transaction else if(expireSeconds <= 0) { if(mpParentTransaction && mpParentTransaction->isChildSerial()) { expireSeconds = userAgent.getDefaultSerialExpiresSeconds(); } else { expireSeconds = maxExpires; } } // Make sure the expiration is not longer than // the maximum length of time we keep a transaction around if(expireSeconds > maxExpires) { expireSeconds = maxExpires; } // Keep separate copy for the timer SipMessageEvent* expiresEvent = new SipMessageEvent(new SipMessage(message), SipMessageEvent::TRANSACTION_EXPIRATION); OsTimer* expiresTimer = new OsTimer(incomingQ, (intptr_t)expiresEvent); mTimers.append(expiresTimer); #ifdef TEST_PRINT osPrintf("SipTransaction::doFirstSend added timer %p to timer list.\n", expiresTimer); #endif OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::doFirstSend %p setting timeout %d", this, expireSeconds ); OsTime expiresTime(expireSeconds, 0); expiresTimer->oneshotAfter(expiresTime); } } } return(sendSucceeded); } // end doFirstSend void SipTransaction::handleResendEvent(const SipMessage& outgoingMessage, SipUserAgent& userAgent, enum messageRelationship relationship, SipTransactionList& transactionList, int& nextTimeout, SipMessage*& delayedDispatchedMessage, SIPX_TRANSPORT_DATA* pTransport) { if (!mpTransport) mpTransport = pTransport; if(delayedDispatchedMessage) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::handleResendEvent %p delayedDispatchedMessage is not NULL", this); delayedDispatchedMessage = NULL; } //osPrintf("SipTransaction::handleResendEvent\n"); nextTimeout = 0; // If this is not a duplicate, then there is something worng if(relationship != MESSAGE_DUPLICATE && relationship != MESSAGE_CANCEL) { UtlString relationString; getRelationshipString(relationship, relationString); OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::handleResendEvent %p timeout message is not duplicate: %s", this, relationString.data()); } // Responses if(outgoingMessage.isResponse()) { // The only responses which should have a timeout set // are INVITE responses for UA server transactions only if(mpLastFinalResponse == NULL) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::handleResendEvent response timeout with no response"); } // If this is a user agent server transaction and // the ACK has not been received yet // We should only be getting here for error final responses // when the transaction is on a proxy (i.e. !mIsUaTransaction) if(//mIsUaTransaction && // vs. proxy mIsServerTransaction && // vs. client mpAck == NULL && mpLastFinalResponse) { // We have not yet received the ACK //int nextTimeout = 0; // Use mpLastFinalResponse, not outgoingMessage as // mpLastFinalResponse may be a newer final response. // outgoingMessage is a snapshot that was taken when the // timer was set. UtlBoolean sentOk = doResend(*mpLastFinalResponse, userAgent, nextTimeout, mpTransport); if(sentOk) { // Schedule the next timeout // As this is a resend, we should be able to use // the same copy of the SIP message for the next timeout #ifdef TEST_PRINT if(outgoingMessage.getSipTransaction() == NULL) { UtlString msgString; int msgLen; outgoingMessage.getBytes(&msgString, &msgLen); OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::handleResendEvent reschedule of response resend with NULL transaction", msgString.data()); osPrintf("SipTransaction::handleResendEvent reschedule of response resend with NULL transaction\n", msgString.data()); } #endif // Schedule a timeout for requests which do not // receive a response SipMessageEvent* resendEvent = new SipMessageEvent(new SipMessage(outgoingMessage), SipMessageEvent::TRANSACTION_RESEND); OsMsgQ* incomingQ = userAgent.getMessageQueue(); OsTimer* timer = new OsTimer(incomingQ, (intptr_t)resendEvent); mTimers.append(timer); #ifdef TEST_PRINT osPrintf("SipTransaction::handleResendEvent added timer %p to timer list.\n", timer); #endif // Convert from mSeconds to uSeconds OsTime lapseTime(0, nextTimeout * 1000); timer->oneshotAfter(lapseTime); } else { if( MESSAGE_REQUEST == relationship ) { mTransactionState = TRANSACTION_TERMINATED; } // Do this outside so that we do not get blocked // on locking or delete the transaction out // from under ouselves // Cleanup the message //delete outgoingMessage; //outgoingMessage = NULL; //userAgent.dispatch(outgoingMessage, // SipMessageEvent::TRANSPORT_ERROR); } } // A legal response timeout // The ACK was received so we can quit // We should only be getting here for error final responses // when the transaction is on a proxy (i.e. !mIsUaTransaction) else if(// do we care if proxy or UA?? mIsUaTransaction && // vs. proxy mIsServerTransaction && // vs. client mpAck && mpLastFinalResponse) { nextTimeout = -1; } } // Requests else { // This should never be the case if(outgoingMessage.isFirstSend()) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::handleResendEvent %p called for first time send of message", this); } else if(!mIsCanceled && mpLastFinalResponse == NULL && mpLastProvisionalResponse == NULL && mTransactionState == TRANSACTION_CALLING) { UtlString method; outgoingMessage.getRequestMethod(&method); // This is a resend retrieve the address and port to send the message to. #ifdef TEST_PRINT UtlString toAddress; int port; outgoingMessage.getSendAddress(&toAddress, &port); osPrintf("SipTransaction::handleResendEvent Resend request %s:%d\n", toAddress.data(), port); #endif SipMessage* resendMessage = NULL; if(method.compareTo(SIP_ACK_METHOD) == 0) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::handleResendEvent resend of ACK"); resendMessage = mpAck; } else if(method.compareTo(SIP_CANCEL_METHOD) == 0) { resendMessage = mpCancel; } else { resendMessage = mpRequest; } //int nextTimeout = 0; UtlBoolean sentOk = doResend(*resendMessage, userAgent, nextTimeout, mpTransport); if(sentOk && nextTimeout > 0) { // Schedule the next timeout #ifdef TEST_PRINT if(outgoingMessage.getSipTransaction() == NULL) { UtlString msgString; int msgLen; outgoingMessage.getBytes(&msgString, &msgLen); OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::handleResendEvent reschedule of request resend with NULL transaction", msgString.data()); osPrintf("SipTransaction::handleResendEvent reschedule of request resend with NULL transaction\n", msgString.data()); } #endif // As this is a resend, we should be able to use // the same copy of the SIP message for the next timeout // Schedule a timeout for requests which do not // receive a response SipMessageEvent* resendEvent = new SipMessageEvent(new SipMessage(outgoingMessage), SipMessageEvent::TRANSACTION_RESEND); OsMsgQ* incomingQ = userAgent.getMessageQueue(); OsTimer* timer = new OsTimer(incomingQ, (intptr_t)resendEvent); mTimers.append(timer); #ifdef TEST_PRINT osPrintf("SipTransaction::handleResendEvent added timer %p to timer list.\n", timer); #endif // Convert from mSeconds to uSeconds OsTime lapseTime(0, nextTimeout * 1000); timer->oneshotAfter(lapseTime); } else { // Do this outside so that we do not get blocked // on locking or delete the transaction out // from under ouselves // Cleanup the message //delete outgoingMessage; //outgoingMessage = NULL; //userAgent.dispatch(outgoingMessage, // SipMessageEvent::TRANSPORT_ERROR); #ifdef TEST_PRINT osPrintf("SipTransaction::handleResendEvent sentOk: %d nextTimeout: %d\n", sentOk, nextTimeout); #endif if(!sentOk) { if ( MESSAGE_REQUEST == relationship ) { mTransactionState = TRANSACTION_TERMINATED; } else { mTransactionState = TRANSACTION_COMPLETE; } } else if ( nextTimeout < 0 ) { mTransactionState = TRANSACTION_COMPLETE; #ifdef TEST_PRINT osPrintf("SipTransaction::handleResendEvent failed to send request, TRANSACTION_COMPLETE\n"); #endif } // else nextTimeout == 0, which should mean the // final response was received } } else { // We are all done, do not reschedule and do not // send transport error nextTimeout = -1; if(mTransactionState == TRANSACTION_CALLING) mTransactionState = TRANSACTION_COMPLETE; OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleResendEvent no response, TRANSACTION_COMPLETE"); } } if(mpParentTransaction) { mpParentTransaction->handleChildTimeoutEvent(*this, outgoingMessage, userAgent, relationship, transactionList, nextTimeout, delayedDispatchedMessage, mpTransport); } touch(); } // end handleResendEvent void SipTransaction::handleExpiresEvent(const SipMessage& outgoingMessage, SipUserAgent& userAgent, enum messageRelationship relationship, SipTransactionList& transactionList, int& nextTimeout, SipMessage*& delayedDispatchedMessage, SIPX_TRANSPORT_DATA* pTransport) { if (!mpTransport) mpTransport = pTransport; #ifdef TEST_PRINT osPrintf( "SipTransaction::handleExpiresEvent %p\n", this ); #endif if(delayedDispatchedMessage) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::handleExpiresEvent delayedDispatchedMessage not NULL"); delayedDispatchedMessage = NULL; } // Responses if(outgoingMessage.isResponse()) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::handleExpiresEvent %p expires event timed out on SIP response", this); } // Requests else { #ifdef TEST_PRINT UtlString transactionTreeString; dumpTransactionTree(transactionTreeString, FALSE); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleExpiresEvent %p\n%s", this, transactionTreeString.data()); #else OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleExpiresEvent %p", this); #endif // Do not cancel a DNS SRV child that received any response. // The parent client transaction may be canceled which will // recursively cancel the children. However if this timeout // event is for a DNS SRV child we do not cancel if there was // any sort of response. if(mIsDnsSrvChild && (mpLastProvisionalResponse || mpLastFinalResponse)) { // no-op OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleExpiresEvent %p ignoring cancel of DNS SRV child", this); } // Do not cancel an early dialog with early media if this // transaction is a child to a serial search/fork. // This may be a gateway sending IVR prompts ala // American Airlines, so we do not want to cancel in // the middle of the user entering DTMF else if(!mIsDnsSrvChild && !mIsServerTransaction && mpParentTransaction && mpParentTransaction->isChildSerial() && mRequestMethod.compareTo(SIP_INVITE_METHOD) == 0 && isChildEarlyDialogWithMedia()) { // no op OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleExpiresEvent %p ignoring cancel of early media branch of serial search", this); } // Do not cancel a completed transaction else if((mIsRecursing || mTransactionState == TRANSACTION_CALLING || mTransactionState == TRANSACTION_PROCEEDING || mTransactionState == TRANSACTION_LOCALLY_INIITATED)) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleExpiresEvent %p canceling expired transaction", this); // This transaction has expired cancel it cancel(userAgent, transactionList); } #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleExpiresEvent this: %p", this); UtlString transactionDump; if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { dumpTransactionTree(transactionDump, FALSE); } else { transactionDump = "NOT DUMPED"; } // dpetrie: The following is very expensive (and not necessary in this context) // transactionList.toString(transactionDump); OsSysLog::add(FAC_SIP, PRI_DEBUG, "%s", transactionDump.data()); #endif // Check the parents in the heirarchy to see if there are // other branches to pursue if(mpParentTransaction) { mpParentTransaction->handleChildTimeoutEvent(*this, outgoingMessage, userAgent, relationship, transactionList, nextTimeout, delayedDispatchedMessage, mpTransport); } // This is the top most parent and it is a client transaction // we need to find the best result else if(!mIsServerTransaction) { handleChildTimeoutEvent(*this, outgoingMessage, userAgent, relationship, transactionList, nextTimeout, delayedDispatchedMessage, mpTransport); } touch(); } } UtlBoolean SipTransaction::handleChildIncoming(//SipTransaction& child, SipMessage& incomingMessage, SipUserAgent& userAgent, enum messageRelationship relationship, SipTransactionList& transactionList, UtlBoolean childSaysShouldDispatch, SipMessage*& delayedDispatchedMessage, SIPX_TRANSPORT_DATA* pTransport) { if (!mpTransport) mpTransport = pTransport; UtlBoolean shouldDispatch = childSaysShouldDispatch; #ifdef TEST_PRINT { UtlString relateStr; getRelationshipString( relationship, relateStr ); osPrintf("SipTransaction::handleChildIncoming %p relate %s childSays %d\n", this, relateStr.data(), childSaysShouldDispatch); } #endif //UtlBoolean isResponse = incomingMessage.isResponse(); if( relationship == MESSAGE_FINAL || relationship == MESSAGE_PROVISIONAL ) { int responseCode = incomingMessage.getResponseStatusCode(); // If there is a parent pass it up if(mpParentTransaction) { // May want to short cut this and first get // the top most parent. However if the state // change is interesting to intermediate (i.e. // not top most parent) transactions we need to // do it this way (recursively) shouldDispatch = mpParentTransaction->handleChildIncoming(//child, incomingMessage, userAgent, relationship, transactionList, childSaysShouldDispatch, delayedDispatchedMessage, mpTransport); # ifdef TEST_PRINT osPrintf("SipTransaction::handleChildIncoming %p parent says %d\n", this, shouldDispatch); # endif } else // this is the topmost parent transaction { // We do not dispatch if this is a server transaction // as the server transaction is the consumer of the // message. If there is no server transaction as the // top most parent, then we assume the consumer is a // local application (i.e. message queue). if(mIsServerTransaction) { if ( (responseCode > SIP_TRYING_CODE) // (responseCode >= SIP_2XX_CLASS_CODE) && (responseCode < SIP_3XX_CLASS_CODE) ) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleChildIncoming %p " "topmost parent dispatching %d", this, responseCode ); shouldDispatch = TRUE; } else { # ifdef DISPATCH_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleChildIncoming %p " "topmost parent NOT dispatching %d.", this, responseCode ); # endif shouldDispatch = FALSE; } } // CANCEL is hop by hop and should not be dispatched unless // the parent transaction was the originator of the CANCEL // request else if(!mIsCanceled) { int tempCseq; UtlString method; incomingMessage.getCSeqField(&tempCseq, &method); if(method.compareTo(SIP_CANCEL_METHOD) == 0) { shouldDispatch = FALSE; } } } # ifdef TEST_PRINT osPrintf("SipTransaction::handleChildIncoming %p check response %d\n", this, responseCode ); # endif if(responseCode < SIP_TRYING_CODE) { // What is this???? OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::handleChildIncoming dropped invalid response code: %d", responseCode); } // 100 Trying is hop by hop do not forward it else if(responseCode == SIP_TRYING_CODE) { // no op } // If this is a successful 2XX or provisional response // forward it immediately // Once a final response is sent we no longer // send provisional responses, but we still send 2XX // class responses else if( responseCode < SIP_3XX_CLASS_CODE && ( mpLastFinalResponse == NULL || responseCode >= SIP_2XX_CLASS_CODE ) ) { // If this is a server transaction for which the // response must be forwarded up stream if(mIsServerTransaction) { // If this is the // Forward immediately SipMessage response(incomingMessage); response.removeLastVia(); response.resetTransport(); response.clearDNSField(); #ifdef TEST_PRINT osPrintf("SipTransaction::handleChildIncoming immediately forwarding %d response\n", responseCode); #endif handleOutgoing(response, userAgent, transactionList, relationship, mpTransport); } // If we got a good response for which forking // or recursion should be canceled if(mpParentTransaction == NULL) { // Got a success if(responseCode >= SIP_2XX_CLASS_CODE) { // We are done - cancel all the outstanding requests cancelChildren(userAgent, transactionList); } } // Keep track of the fact that we dispatched a final // response (but not for 1xx responses where xx > 00) if( shouldDispatch && responseCode >= SIP_2XX_CLASS_CODE ) { # ifdef TEST_PRINT osPrintf("SipTransaction::handleChildIncoming %p" " should dispatch final response %d\n", this, __LINE__); # endif mDispatchedFinalResponse = TRUE; } // This should not occur. All 2xx class message for which // there is no parent server transaction should get dispatched else if(mpParentTransaction == NULL) { // xmlscott: despite the comment above, this happens a lot, // and seems to not always be bad, // so I'm changing the priority to get it out of // the logs. OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleChildIncoming " "%d response with parent client transaction NOT dispatched", responseCode); } } else { if (responseCode < SIP_2XX_CLASS_CODE) { // no op } // 3XX class responses else if(responseCode <= SIP_4XX_CLASS_CODE) { // Recursion is handled by the child # ifdef TEST_PRINT osPrintf( "SipTransaction::handleChildIncoming %p" " 3XX response - should not dispatch\n", this); # endif // Wait until all the children have been searched // before dispatching shouldDispatch = FALSE; } // 4XX & 5XX class responses else if(responseCode <= SIP_6XX_CLASS_CODE) { // See if there are other outstanding child transactions // If there are none and no more to recurse find the // best result // If there are more to recurse do so. // Wait until all the children have been searched // before dispatching shouldDispatch = FALSE; } // 6XX class responses else { if(mIsServerTransaction) { if(mpParentTransaction) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::handleChildIncoming" " 6XX server transaction is not top most parent" ); } // Cancel any outstanding child transactions cancelChildren(userAgent, transactionList); // If they are all canceled or timed out, send back the 6xx // response } // Wait until all the children have been searched // before dispatching shouldDispatch = FALSE; } # ifdef TEST_PRINT osPrintf( "SipTransaction::handleChildIncoming %p" " response=%d parent=%p final=%p dispatched=%d \n" ,this, responseCode, mpParentTransaction, mpLastFinalResponse, mDispatchedFinalResponse ); # endif // If this is the server transaction and we have not // yet sent back a final response check what is next if( ( mIsServerTransaction && mpLastFinalResponse == NULL ) // or if this is the parent client transaction on a UA // and we have not yet dispatched the final response || ( mpParentTransaction == NULL && ! mIsServerTransaction && mpLastFinalResponse == NULL && ! mDispatchedFinalResponse ) ) { # ifdef TEST_PRINT UtlString dumpString; osPrintf( "SipTransaction::handleChildIncoming %p UAS/nofinal | UAC/parent\n", this ); dumpTransactionTree(dumpString,FALSE); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleChildIncoming\n%s", dumpString.data()); # else OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleChildIncoming %p", this ); # endif if(mpParentTransaction) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::handleChildIncoming %p " "server transaction is not top most parent", this); } // See if there is anything to sequentially search // startSequentialSearch returns TRUE if something // is still searching or it starts the next sequential // search if(startSequentialSearch(userAgent, transactionList, mpTransport)) { } // Special case for when there is no server transaction // The parent client transaction, when it first gets a // 3xx response has no children, so we need to create them else if( mChildTransactions.isEmpty() && recurseChildren(userAgent, transactionList) // true if something started ) { # ifdef TEST_PRINT osPrintf("SipTransaction::handleChildIncoming %p creating children for 3XX\n", this); # endif } // Not waiting for outstanding transactions to complete else { SipMessage bestResponse; if(findBestResponse(bestResponse)) { # ifdef TEST_PRINT osPrintf("SipTransaction::handleChildIncoming %p sending best response\n", this); # endif if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { int bestResponseCode = bestResponse.getResponseStatusCode(); UtlString callId; bestResponse.getCallIdField(&callId); OsSysLog::add(FAC_SIP, PRI_DEBUG, // Format the Call-Id so it looks like // a header line in a SIP message, // so log processors see it. "SipTransaction::handleChildIncoming: " "response %d for \r\nCall-Id: %s\r", bestResponseCode, callId.data()); } if(mIsServerTransaction) { handleOutgoing(bestResponse, userAgent, transactionList, MESSAGE_FINAL, mpTransport); } if(!mDispatchedFinalResponse) { // Get the best message out to be dispatched. if(delayedDispatchedMessage) { delete delayedDispatchedMessage; delayedDispatchedMessage = NULL; } delayedDispatchedMessage = new SipMessage(bestResponse); # ifdef DISPATCH_DEBUG int delayedResponseCode = delayedDispatchedMessage->getResponseStatusCode(); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleChildIncoming %p " "delayed dispatch of %d\n", this, delayedResponseCode ); # endif # ifdef TEST_PRINT osPrintf("SipTransaction::handleChildIncoming %p " "should dispatch delayed message %d\n", this, __LINE__); # endif mDispatchedFinalResponse = TRUE; } } } } } // The response itself is getting dispatched if( shouldDispatch && responseCode >= SIP_2XX_CLASS_CODE ) { // Keep track of the fact that we dispatched a final // response mDispatchedFinalResponse = TRUE; # ifdef TEST_PRINT osPrintf("SipTransaction::handleChildIncoming %p should dispatch final response %d\n", this, __LINE__); # endif if(delayedDispatchedMessage) { // This is probably a bug. This should not // occur. For now log some noise and // drop the delayed response, if this ever // occurs // xmlscott: lowered priority OsSysLog::add(FAC_SIP, PRI_DEBUG, "sipTransaction::handleChildIncoming %p dropping delayed response", this); delete delayedDispatchedMessage; delayedDispatchedMessage = NULL; } } } // end new responses else if(relationship == MESSAGE_DUPLICATE) { // Proxy client transaction received a duplicate INVITE // response if(incomingMessage.isResponse() && //mIsUaTransaction && mRequestMethod.compareTo(SIP_INVITE_METHOD) == 0) { int responseCode = incomingMessage.getResponseStatusCode(); // The proxy must resend duplicate 2xx class responses // for reliability if(responseCode >= SIP_2XX_CLASS_CODE && responseCode < SIP_3XX_CLASS_CODE) { // If there is more than one Via, send it upstream. // The calling UAC should resend the ACK, not the // proxy. UtlString dummyVia; if(incomingMessage.getViaField(&dummyVia, 1)) { SipTransaction* parent = getTopMostParent(); if(parent && parent->mIsServerTransaction) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleChildIncoming " "proxy resending server transaction response %d", responseCode); userAgent.sendStatelessResponse(incomingMessage); } } // The ACK originated here, resend it else { if(mpAck) { // Resend the ACK SipMessage ackCopy(*mpAck); ackCopy.removeLastVia(); userAgent.sendStatelessRequest(ackCopy, mSendToAddress, mSendToPort, mSendToProtocol, mBranchId); } // If this is a duplicate 2xx response and there is only // one Via on the reponse, this UA should be the caller UAC. // We should have an ACK that was sent for the original 2xx // response. else { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::handleChildIncoming " "duplicate 2xx response received on UAC for INVITE " "with no ACK" ); } } } // INVITE with final response that failed else if(responseCode >= SIP_3XX_CLASS_CODE) { // For failed INVITE transactions, the ACK is // sent hop-by-hop if(mpAck) { // Resend the ACK SipMessage ackCopy(*mpAck); ackCopy.removeLastVia(); userAgent.sendStatelessRequest(ackCopy, mSendToAddress, mSendToPort, mSendToProtocol, mBranchId); } // No ACK for a duplicate failed response. Something // is wrong. The ACK should have been created locally // for the previous 3xx, 4xx, 5xx or 6xx final response else { OsSysLog::add(FAC_SIP, PRI_CRIT, "SipTransaction::handleChildIncoming " "duplicate final error response rcvd for INVITE with no ACK"); } } } } return(shouldDispatch); } // end handleChildIncoming void SipTransaction::handleChildTimeoutEvent(SipTransaction& child, const SipMessage& outgoingMessage, SipUserAgent& userAgent, enum messageRelationship relationship, SipTransactionList& transactionList, int& nextTimeout, SipMessage*& delayedDispatchedMessage, SIPX_TRANSPORT_DATA *pTransport) { if (!mpTransport) mpTransport = pTransport; if(mpParentTransaction) { // For now recurse. We might be able to short cut this // and go straight to the top most parent mpParentTransaction->handleChildTimeoutEvent(child, outgoingMessage, userAgent, relationship, transactionList, nextTimeout, delayedDispatchedMessage, mpTransport); } // Top most parent else { #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleChildTimeoutEvent found top most parent: %p", this); #endif //if(mIsServerTransaction) { UtlBoolean isResponse = outgoingMessage.isResponse(); UtlString method; outgoingMessage.getRequestMethod(&method); if( ! isResponse && method.compareTo(SIP_ACK_METHOD) == 0 ) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::handleChildTimeoutEvent timeout of ACK"); } else if( ! isResponse && method.compareTo(SIP_CANCEL_METHOD) == 0 ) { } else if( relationship == MESSAGE_DUPLICATE && ! isResponse ) { // Check if we should still be trying if(nextTimeout > 0) { // Still trying } //else if(nextTimeout == 0) //{ // We do not dispatch proxy transactions // nextTimeout = -1; //} // This transaction is done or has given up // See if we should start the next sequential search else { // We do not dispatch proxy transactions nextTimeout = -1; #ifdef TEST_PRINT osPrintf("SipTransaction::handleChildTimeoutEvent %d %p\n",__LINE__, this ); UtlString dumpString; dumpTransactionTree(dumpString,FALSE); OsSysLog::add(FAC_SIP, PRI_DEBUG, "sipTransaction::handleChildTimeoutEvent\n%s", dumpString.data()); #else OsSysLog::add(FAC_SIP, PRI_DEBUG, "sipTransaction::handleChildTimeoutEvent %p", this ); #endif if(startSequentialSearch(userAgent, transactionList, mpTransport)) { #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleChildTimeoutEvent %p starting/still searching", this); #endif } // Not waiting for outstanding transactions to complete // and we have not yet sent a final response else if(mpLastFinalResponse == NULL) { SipMessage bestResponse; UtlBoolean foundBestResponse = findBestResponse(bestResponse); // 2XX class responses are sent immediately so we // should not send it again int bestResponseCode = bestResponse.getResponseStatusCode(); if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { UtlString callId; bestResponse.getCallIdField(&callId); OsSysLog::add(FAC_SIP, PRI_DEBUG, // Format the Call-Id so it looks like // a header line in a SIP message, // so log processors see it. "SipTransaction::handleChildTimeoutEvent: response %d for \r\nCall-Id: %s\r", bestResponseCode, callId.data()); } // There is nothing to send if this is not a server transaction // (this is the top most parent, if it is a client transaction // the response gets dispatched). if( bestResponseCode >= SIP_3XX_CLASS_CODE && mIsServerTransaction && foundBestResponse ) { #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleChildTimeoutEvent %p sending best response", this); #endif if ( (SIP_REQUEST_TIMEOUT_CODE == bestResponseCode) && (!bestResponse.hasSelfHeader()) ) { userAgent.setSelfHeader(bestResponse); } handleOutgoing(bestResponse, userAgent, transactionList, MESSAGE_FINAL, mpTransport); } else { #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleChildTimeoutEvent %p not sending %d best response", this, bestResponseCode); #endif } if(foundBestResponse && !mDispatchedFinalResponse) { if(delayedDispatchedMessage) { delete delayedDispatchedMessage; delayedDispatchedMessage = NULL; } delayedDispatchedMessage = new SipMessage(bestResponse); # ifdef TEST_PRINT osPrintf("SipTransaction::handleChildIncoming %p should dispatch final response %d\n", this, __LINE__); # endif mDispatchedFinalResponse = TRUE; } } } } // Request timeout } // server transaction //else //{ // OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::handleChildTimeoutEvent top most parent is not server transaction\n"); //} } } UtlBoolean SipTransaction::startSequentialSearch(SipUserAgent& userAgent, SipTransactionList& transactionList, SIPX_TRANSPORT_DATA* pTransport) { if (!mpTransport) mpTransport = pTransport; UtlSListIterator iterator(mChildTransactions); SipTransaction* childTransaction = NULL; UtlBoolean childStillProceeding = FALSE; UtlBoolean startingNewSearch = FALSE; #ifdef TEST_PRINT osPrintf("SipTransaction::startSequentialSearch %p\n", this ); #endif while ((childTransaction = (SipTransaction*) iterator())) { if( ! childTransaction->mIsCanceled && ( childTransaction->mTransactionState == TRANSACTION_CALLING || childTransaction->mTransactionState == TRANSACTION_PROCEEDING ) ) { // The child is not done childStillProceeding = TRUE; #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::startSequentialSearch %p child: %p still proceeding", this, childTransaction); #endif } else if( childTransaction->mIsRecursing ) { // See if the grand children or decendants are still searching if(childTransaction->startSequentialSearch(userAgent, transactionList, mpTransport)) { childStillProceeding = TRUE; #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::startSequentialSearch %p child: %p decendent still proceeding", this, childTransaction); #endif } else { #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::startSequentialSearch %p child: %p no longer proceeding", this, childTransaction); #endif } } // A child has completed and may be recursed else if( ! childStillProceeding && ( childTransaction->mTransactionState == TRANSACTION_COMPLETE || childTransaction->mTransactionState == TRANSACTION_CONFIRMED ) && ! mIsCanceled && ! childTransaction->mIsCanceled ) { #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::startSequentialSearch %p child: %p completed, now recursing", this, childTransaction); #endif UtlBoolean recurseStartedNewSearch = childTransaction->recurseChildren(userAgent, transactionList); if(!startingNewSearch) { startingNewSearch = recurseStartedNewSearch; } // Do not break out of the loop because we want // to check all the currently proceeding transaction // to see if we should recurse. #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::startSequentialSearch %p child: %p startingNewSearch: %s", this, childTransaction, startingNewSearch ? "True" : "False"); #endif } // If there is another sequential search to kick off on this // parent else if( ! childStillProceeding && ! startingNewSearch && childTransaction->mTransactionState == TRANSACTION_LOCALLY_INIITATED && ! mIsCanceled && ! childTransaction->mIsCanceled ) { UtlBoolean recurseStartedNewSearch = FALSE; if(mpDnsSrvRecords) { recurseStartedNewSearch = recurseDnsSrvChildren(userAgent, transactionList, mpTransport); } else { recurseStartedNewSearch = recurseChildren(userAgent, transactionList); } if(!startingNewSearch) { startingNewSearch = recurseStartedNewSearch; } #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::startSequentialSearch %p child: %p starting sequential startingNewSearch: %s", this, childTransaction, startingNewSearch ? "True" : "False"); #endif if( recurseStartedNewSearch ) { break; } else { #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::startSequentialSearch %p failed to find child to transaction to pursue", this); #endif } } } mIsRecursing = childStillProceeding || startingNewSearch; #ifdef LOG_FORKING #ifdef TEST_PRINT osPrintf("SipTransaction::startSequentialSearch %p returning: %s childStillProceeding: %s startingNewSearch:%s\n", this, mIsRecursing ? "True" : "False", childStillProceeding ? "True" : "False", startingNewSearch ? "True" : "False"); #endif OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::startSequentialSearch %p returning: %s childStillProceeding: %s startingNewSearch:%s", this, mIsRecursing ? "True" : "False", childStillProceeding ? "True" : "False", startingNewSearch ? "True" : "False"); #endif return(mIsRecursing); } UtlBoolean SipTransaction::recurseDnsSrvChildren(SipUserAgent& userAgent, SipTransactionList& transactionList, SIPX_TRANSPORT_DATA* pTransport) { if (!mpTransport) mpTransport = pTransport; // If this is a client transaction requiring DNS SRV lookup // and we need to create the children to recurse if(!mIsServerTransaction && !mIsDnsSrvChild && mpDnsSrvRecords == NULL && mpRequest && // only applicable to requests not sent mpLastFinalResponse == NULL && // should be no response yet mChildTransactions.isEmpty()) { if(mSendToAddress.isNull()) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::recurseDnsSrvChildren no send address"); } else if(mTransactionState < TRANSACTION_CONFIRMED) { mTransactionState = TRANSACTION_CONFIRMED; // Do the DNS SRV lookup for the request destination mpDnsSrvRecords = SipSrvLookup::servers(mSendToAddress.data(), "sip", mSendToProtocol, mSendToPort, this->getRequest()->getLocalIp().data()); // HACK: // Add a via to this request so when we set a timer it is // identified (by branchId) which transaction it is related to if(mpRequest) { // This via should never see the light of day (or rather // the bits of the network). mpRequest->addVia("127.0.0.1", 9999, "UNKNOWN", mBranchId.data()); } // Set the transaction expires timeout for the DNS SRV parent int expireSeconds = mExpires; int maxExpires = userAgent.getDefaultExpiresSeconds(); // Non-INVITE transactions timeout sooner if(this->mRequestMethod.compareTo(SIP_INVITE_METHOD) != 0) { maxExpires = (userAgent.getSipStateTransactionTimeout())/1000; } if(expireSeconds <= 0) { if( mpParentTransaction && mpParentTransaction->isChildSerial()) { expireSeconds = userAgent.getDefaultSerialExpiresSeconds(); } else { expireSeconds = maxExpires; } } // Make sure the expiration is not longer than // the maximum length of time we keep a transaction around if(expireSeconds > maxExpires) { expireSeconds = maxExpires; } // Set the transaction for the timeout message to make // it easier to find the transaction when the timer fires. mpRequest->setTransaction(this); // Keep separate copy for the timer SipMessage* pRequestMessage = NULL; pRequestMessage = new SipMessage(*mpRequest); SipMessageEvent* expiresEvent = new SipMessageEvent(pRequestMessage, SipMessageEvent::TRANSACTION_EXPIRATION); OsMsgQ* incomingQ = userAgent.getMessageQueue(); OsTimer* expiresTimer = new OsTimer(incomingQ, (intptr_t)expiresEvent); mTimers.append(expiresTimer); #ifdef TEST_PRINT osPrintf("SipTransaction::recurseDnsSrvChildren added timer %p to timer list.\n", expiresTimer); #endif OsTime expiresTime(expireSeconds, 0); expiresTimer->oneshotAfter(expiresTime); if (pTransport) { SipTransaction* childTransaction = new SipTransaction(mpRequest, TRUE, // outgoing mIsUaTransaction); // same as parent if(childTransaction) { // Set the q values of the child based upon the parent // As DNS SRV is recursed serially the Q values are decremented // by a factor of the record index // Inherit the expiration from the parent childTransaction->mExpires = mExpires; // Mark this as a DNS SRV child childTransaction->mIsDnsSrvChild = TRUE; childTransaction->mIsBusy = mIsBusy; // Add it to the list transactionList.addTransaction(childTransaction); // Link it in to this parent this->linkChild(*childTransaction); } } else if(mpDnsSrvRecords) { int numSrvRecords = 0; int maxSrvRecords = userAgent.getMaxSrvRecords(); // Create child transactions for each SRV record // up to the maximum while(numSrvRecords < maxSrvRecords && mpDnsSrvRecords[numSrvRecords].isValidServerT()) { SipTransaction* childTransaction = new SipTransaction(mpRequest, TRUE, // outgoing mIsUaTransaction); // same as parent mpDnsSrvRecords[numSrvRecords]. getIpAddressFromServerT(childTransaction->mSendToAddress); childTransaction->mSendToPort = mpDnsSrvRecords[numSrvRecords].getPortFromServerT(); childTransaction->mSendToProtocol = mpDnsSrvRecords[numSrvRecords].getProtocolFromServerT(); # ifdef ROUTE_DEBUG { UtlString protoString; SipMessage::convertProtocolEnumToString(childTransaction->mSendToProtocol, protoString); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::recurseDnsSrvChildren " "new DNS SRV child %s:%d via '%s'", childTransaction->mSendToAddress.data(), childTransaction->mSendToPort, protoString.data()); } # endif // Do not create child for unsupported protocol types if(childTransaction->mSendToProtocol == OsSocket::UNKNOWN) { maxSrvRecords++; delete childTransaction; childTransaction = NULL; } if(childTransaction) { // Set the q values of the child based upon the parent // As DNS SRV is recursed serially the Q values are decremented // by a factor of the record index childTransaction->mQvalue = mQvalue - numSrvRecords * 0.0001; // Inherit the expiration from the parent childTransaction->mExpires = mExpires; // Mark this as a DNS SRV child childTransaction->mIsDnsSrvChild = TRUE; childTransaction->mIsBusy = mIsBusy; // Add it to the list transactionList.addTransaction(childTransaction); // Link it in to this parent this->linkChild(*childTransaction); } numSrvRecords++; } } // We got no DNS SRV records back else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::recurseDnsSrvChildren no DNS SRV records"); } } } UtlBoolean childRecursed = FALSE; UtlBoolean childRecursing = FALSE; if(!mIsServerTransaction && !mIsDnsSrvChild && mpDnsSrvRecords && mpRequest) { UtlSListIterator iterator(mChildTransactions); SipTransaction* childTransaction = NULL; while((childTransaction = (SipTransaction*) iterator()) && !childRecursed && !childRecursing) { if(childTransaction->mTransactionState == TRANSACTION_LOCALLY_INIITATED) { // Make a local copy to modify and send SipMessage recursedRequest(*mpRequest); // Clear the address and port of the previous send // of the parent request. recursedRequest.removeLastVia(); // the fake via for identifying this TX recursedRequest.resetTransport(); recursedRequest.clearDNSField(); #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::recurseDnsSrvChildren %p sending child transaction request %s:%d protocol: %d", this, childTransaction->mSendToAddress.data(), childTransaction->mSendToPort, childTransaction->mSendToProtocol); #endif // Start the transaction by sending its request if(childTransaction->handleOutgoing(recursedRequest, userAgent, transactionList, MESSAGE_REQUEST, mpTransport)) { childRecursed = TRUE; } } // If there is a child transaction that is currently // being pursued, do not start any new searches else if((childTransaction->mTransactionState == TRANSACTION_CALLING || childTransaction->mTransactionState == TRANSACTION_PROCEEDING) && !childTransaction->mIsCanceled) { childRecursing = TRUE; #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::recurseDnsSrvChildren %p still pursing", this); #endif } // This parent is not canceled (implicit) and we found a non-canceled // DNS SRV child with any sort of response, so there is not need to // recurse. We have a DNS SRV child that has succeeded (at least in // as much as getting a response). else if(!childTransaction->mIsCanceled && (childTransaction->mpLastProvisionalResponse || childTransaction->mpLastFinalResponse)) { break; } else { #ifdef LOG_FORKING UtlString state; SipTransaction::getStateString(childTransaction->mTransactionState, state); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::recurseDnsSrvChildren %p transaction not recursed state: %s", this, state.data()); #endif } } } if(childRecursed) mIsRecursing = TRUE; return(childRecursed); } UtlBoolean SipTransaction::recurseChildren(SipUserAgent& userAgent, SipTransactionList& transactionList) { UtlBoolean childRecursed = FALSE; #ifdef LOG_FORKING #ifdef TEST_PRINT osPrintf("SipTransaction::recurseChildren %p\n", this); #endif OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::recurseChildren %p", this); #endif if(mpRequest == NULL) { UtlString transactionString; toString(transactionString, TRUE); OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::recurseChildren NULL mpResponse\n======>\n%s\n======>", transactionString.data()); } if(mpLastFinalResponse && mpRequest) { SipTransaction* childTransaction = NULL; int responseCode = mpLastFinalResponse->getResponseStatusCode(); # ifdef TEST_PRINT osPrintf("SipTransaction: lastfinalsresponse & request forking enabled: %d ce: %d\n" ,userAgent.isForkingEnabled(), mChildTransactions.isEmpty() ); # endif // If this is a client transaction for which we received // a 3XX response on which recursion makes sense, create // the child transactions if( userAgent.isForkingEnabled() && responseCode >= SIP_3XX_CLASS_CODE && responseCode < SIP_4XX_CLASS_CODE && mChildTransactions.isEmpty() ) { int contactIndex = 0; UtlString contactString; while( mpLastFinalResponse->getContactField(contactIndex, contactString) ) { Url contactUrl(contactString); // Make sure we do not add the contact twice and // we have not already pursued this contact if(!isUriChild(contactUrl) && !isUriRecursed(contactUrl)) { childTransaction = new SipTransaction(mpRequest, TRUE, // outgoing mIsUaTransaction); // proxy transactions #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::recurseChildren %p adding child %p for contact: %s", this, childTransaction, contactString.data()); #ifdef TEST_PRINT osPrintf( "SipTransaction::recurseChildren adding transaction %p for contact: %s\n", childTransaction, contactString.data()); #endif #endif // Add it to the list of all transactions transactionList.addTransaction(childTransaction); // Set the URI of the copy to that from the contact contactUrl.getUri(childTransaction->mRequestUri); // Set the Q value and Expires value UtlString qString; UtlString expiresString; double qValue = 1.0; if(contactUrl.getFieldParameter("q", qString)) qValue = atof(qString.data()); int expiresSeconds = -1; if((mRequestMethod.compareTo(SIP_INVITE_METHOD) == 0) && contactUrl.getHeaderParameter("expires", expiresString)) { // All digits, the format is relative seconds if(Url::isDigitString(expiresString.data())) { expiresSeconds = atoi(expiresString.data()); } // Alphanumeric, it is an HTTP absolute date else { expiresSeconds = OsDateTime::convertHttpDateToEpoch(expiresString.data()); OsTime time; OsDateTime::getCurTimeSinceBoot(time); expiresSeconds -= time.seconds(); //expiresSeconds -= OsDateTime::getSecsSinceEpoch(); } } // Set the values of the child childTransaction->mQvalue = qValue; childTransaction->mExpires = expiresSeconds; // Link it in to this parent this->linkChild(*childTransaction); } // We have all ready recursed this contact else { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::recurseChildren %p already recursed: %s", this, contactString.data()); } contactIndex++; } // end for each contact } double nextQvalue = -1.0; int numRecursed = 0; UtlSListIterator iterator(mChildTransactions); while ((childTransaction = (SipTransaction*) iterator())) { // Until a request is successfully sent, reset the // current Q value at which transactions of equal // value are searched in parallel if(numRecursed == 0) nextQvalue = -1.0; if(childTransaction->mTransactionState == TRANSACTION_LOCALLY_INIITATED) { double qDelta = nextQvalue - childTransaction->mQvalue; double qDeltaSquare = qDelta * qDelta; #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::recurseChildren %p qDelta: %f qDeltaSquare: %f mQvalue: %f", this, qDelta, qDeltaSquare, childTransaction->mQvalue); #ifdef TEST_PRINT osPrintf( "SipTransaction::recurseChildren qDelta: %f qDeltaSquare: %f mQvalue: %f\n", qDelta, qDeltaSquare, childTransaction->mQvalue); #endif #endif if(nextQvalue <= 0.0 || qDeltaSquare < MIN_Q_DELTA_SQUARE) { nextQvalue = childTransaction->mQvalue; #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::recurseChildren %p should recurse child: %p q: %f", this, childTransaction, childTransaction->mQvalue); #ifdef TEST_PRINT osPrintf( "SipTransaction::recurseChildren parent: %p should recurse child: %p q: %f\n", this, childTransaction, childTransaction->mQvalue); #endif #endif // Make a local copy to modify and send SipMessage recursedRequest(*mpRequest); // Clear the address and port of the previous send // of the parent request. recursedRequest.removeLastVia(); recursedRequest.resetTransport(); recursedRequest.clearDNSField(); // If there was a loose route pop it off // The assumption is that this was previously routed // to the redirect server. Perhaps we can get the // parent's parent's request to use here instead. I just // cannot work it out in my head right now UtlString routeUri; recursedRequest.getRouteUri(0, &routeUri); Url routeUrlParser(routeUri); UtlString dummyValue; UtlBoolean nextHopLooseRoutes = routeUrlParser.getUrlParameter("lr", dummyValue, 0); if(nextHopLooseRoutes) { recursedRequest.removeRouteUri(0, &routeUri); } // Correct the URI of the request to be the recursed URI recursedRequest.setSipRequestFirstHeaderLine(mRequestMethod, childTransaction->mRequestUri, SIP_PROTOCOL_VERSION); // Decrement max-forwards int maxForwards; if(!recursedRequest.getMaxForwards(maxForwards)) { recursedRequest.setMaxForwards(userAgent.getMaxForwards() - 1); } else { recursedRequest.setMaxForwards(maxForwards - 1); } #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::recurseChildren %p sending child transaction request", this); #ifdef TEST_PRINT osPrintf( "SipTransaction::recurseChildren sending child transaction request\n"); #endif #endif // Start the transaction by sending its request if(childTransaction->handleOutgoing(recursedRequest, userAgent, transactionList, MESSAGE_REQUEST, mpTransport)) { numRecursed++; // Recursing is TRUE childRecursed = TRUE; // Recursion disabled } } else { #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::recurseChildren %p nextQvalue: %f qDeltaSquare: %f", this, nextQvalue, qDeltaSquare); #ifdef TEST_PRINT osPrintf( "SipTransaction::recurseChildren nextQvalue: %f qDeltaSquare: %f\n", nextQvalue, qDeltaSquare); #endif #endif } } // If there is a child transaction that is currently // being pursued, do not start any new searches else if((childTransaction->mTransactionState == TRANSACTION_CALLING || childTransaction->mTransactionState == TRANSACTION_PROCEEDING) && !childTransaction->mIsCanceled) { nextQvalue = childTransaction->mQvalue; #ifdef LOG_FORKING OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::recurseChildren %p still pursing", this); #ifdef TEST_PRINT osPrintf( "SipTransaction::recurseChildren still pursing\n"); #endif #endif } else { #ifdef LOG_FORKING UtlString state; SipTransaction::getStateString(childTransaction->mTransactionState, state); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::recurseChildren %p transaction not recursed state: %s", this, state.data()); #ifdef TEST_PRINT osPrintf( "SipTransaction::recurseChildren transaction not recursed state: %s\n", state.data()); #endif #endif } // Optionally we only look at the first contact // for 300 response (not 300 class e.g. 302) if(userAgent.recurseOnlyOne300Contact() && responseCode == SIP_MULTI_CHOICE_CODE) break; } } if(childRecursed) mIsRecursing = TRUE; return(childRecursed); } UtlBoolean SipTransaction::findBestResponse(SipMessage& bestResponse) { //osPrintf("SipTransaction::findBestResponse\n"); UtlSListIterator iterator(mChildTransactions); SipTransaction* childTransaction = NULL; UtlBoolean responseFound = FALSE; SipMessage* childResponse = NULL; int bestResponseCode = -1; int childResponseCode; UtlString authField; UtlBoolean foundChild = FALSE; #ifdef TEST_PRINT osPrintf("SipTransaction::findBestResponse %p\n", this); #endif while ((childTransaction = (SipTransaction*) iterator())) { // Check the child's decendents first // Note: we need to check the child's children even if this child // has no response. foundChild = childTransaction->findBestResponse(bestResponse); if(foundChild) responseFound = TRUE; childResponse = childTransaction->mpLastFinalResponse; if(childResponse) { bestResponseCode = bestResponse.getResponseStatusCode(); childResponseCode = childResponse->getResponseStatusCode(); if((bestResponseCode == HTTP_UNAUTHORIZED_CODE || bestResponseCode == HTTP_PROXY_UNAUTHORIZED_CODE) && (childResponseCode == HTTP_UNAUTHORIZED_CODE || childResponseCode == HTTP_PROXY_UNAUTHORIZED_CODE)) { // Aggregate Authenticate fields // Get the proxy authenticate challenges int authIndex = 0; while(childResponse->getAuthenticationField(authIndex, HttpMessage::PROXY, authField)) { bestResponse.addAuthenticationField(authField.data(), HttpMessage::PROXY); authIndex++; } // Get the UA server authenticate challenges authIndex = 0; while(childResponse->getAuthenticationField(authIndex, HttpMessage::SERVER, authField)) { bestResponse.addAuthenticationField(authField.data(), HttpMessage::SERVER); authIndex++; } } // 401 & 407 are better than any other 4xx, 5xx or 6xx else if(bestResponseCode >= SIP_4XX_CLASS_CODE && (bestResponseCode != HTTP_UNAUTHORIZED_CODE && bestResponseCode != HTTP_PROXY_UNAUTHORIZED_CODE) && (childResponseCode == HTTP_UNAUTHORIZED_CODE || childResponseCode == HTTP_PROXY_UNAUTHORIZED_CODE)) { bestResponse = *(childResponse); bestResponse.removeLastVia(); bestResponse.resetTransport(); bestResponse.clearDNSField(); responseFound = TRUE; } // 3xx is better than 4xx else if(bestResponseCode >= SIP_4XX_CLASS_CODE && childResponseCode <= SIP_4XX_CLASS_CODE && childTransaction->mChildTransactions.isEmpty()) { // An untryed 3xx response bestResponse = *(childResponse); bestResponse.removeLastVia(); bestResponse.resetTransport(); bestResponse.clearDNSField(); responseFound = TRUE; } // have not found a response that is not recursed yet // Ignore any 487s as these are responses to forking. // CANCELs from the client are responded to on the // server transaction upon receipt. else if(!responseFound && childResponse && childTransaction->mChildTransactions.isEmpty() && childResponseCode != SIP_REQUEST_TERMINATED_CODE) { bestResponse = *(childResponse); // Not suppose to return 503 unless we know that // there is absolutely no way to reach the end point if(childResponseCode == SIP_SERVICE_UNAVAILABLE_CODE) { bestResponse.setResponseFirstHeaderLine(SIP_PROTOCOL_VERSION, SIP_SERVER_INTERNAL_ERROR_CODE, SIP_SERVER_INTERNAL_ERROR_TEXT); } bestResponse.removeLastVia(); bestResponse.resetTransport(); bestResponse.clearDNSField(); // For now we do not support forking, just return // the first and should be the only final response responseFound = TRUE; //break; } } } // We have made it to the top and there are no responses if(!responseFound && mpParentTransaction == NULL) { if(mpRequest) { bestResponse.setResponseData(mpRequest, SIP_REQUEST_TIMEOUT_CODE, SIP_REQUEST_TIMEOUT_TEXT); responseFound = TRUE; } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::findBestResponse no request"); } } if(responseFound) { const char* firstHeaderLine = bestResponse.getFirstHeaderLine(); if(firstHeaderLine == NULL || *firstHeaderLine == '\0') { if (OsSysLog::willLog(FAC_SIP, PRI_WARNING)) { UtlString msgString; int msgLen; bestResponse.getBytes(&msgString, &msgLen); // We got a bad response OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::findBestResponse invalid response:\n%s", msgString.data()); # ifdef TEST_PRINT osPrintf("SipTransaction::findBestResponse invalid response:\n%s", msgString.data()); # endif } } } return(responseFound); } UtlBoolean SipTransaction::doResend(SipMessage& resendMessage, SipUserAgent& userAgent, int& nextTimeout, SIPX_TRANSPORT_DATA* pTransport) { if (!mpTransport) mpTransport = pTransport; // Find out how many times we have tried nextTimeout = 0; int numTries = resendMessage.getTimesSent(); OsSocket::IpProtocolSocketType protocol = resendMessage.getSendProtocol(); int lastTimeout = resendMessage.getResendDuration(); UtlString sendAddress; int sendPort; resendMessage.getSendAddress(&sendAddress, &sendPort); UtlBoolean sentOk = FALSE; // TCP only gets one try // UDP gets SIP_UDP_RESEND_TIMES tries if(protocol == OsSocket::UDP) { if(numTries < SIP_UDP_RESEND_TIMES) { // Try UDP again numTries++; if(userAgent.sendUdp(&resendMessage, sendAddress.data(), sendPort)) { // Do this after the send so that // the log message is correct resendMessage.setTimesSent(numTries); // Schedule a time out if(lastTimeout < userAgent.getFirstResendTimeout()) { nextTimeout = userAgent.getFirstResendTimeout(); } else if(lastTimeout < userAgent.getLastResendTimeout()) { nextTimeout = lastTimeout * 2; } else { nextTimeout = userAgent.getLastResendTimeout(); } resendMessage.setTimesSent(numTries); resendMessage.setResendDuration(nextTimeout); sentOk = TRUE; } } } #ifdef SIP_TLS else if(protocol == OsSocket::TCP || protocol == OsSocket::SSL_SOCKET) #else else if(protocol == OsSocket::TCP) #endif { if(numTries >= 1) { // we are done send back a transport error // Dispatch is called from above this method // Dispatch needs it own copy of the message //SipMessage* dispatchMessage = new SipMessage(resendMessage); // The TCP send failed, pass back an error //userAgent.dispatch(dispatchMessage, // SipMessageEvent::TRANSPORT_ERROR); } else { // Try TCP once numTries = 1; UtlBoolean sendOk; if(protocol == OsSocket::TCP) { sendOk = userAgent.sendTcp(&resendMessage, sendAddress.data(), sendPort); } #ifdef SIP_TLS else if(protocol == OsSocket::SSL_SOCKET) { sendOk = userAgent.sendTls(&resendMessage, sendAddress.data(), sendPort); } #endif else { sendOk = FALSE; } if(sendOk) { // Schedule a timeout nextTimeout = userAgent.getReliableTransportTimeout(); resendMessage.setTimesSent(numTries); resendMessage.setResendDuration(nextTimeout); resendMessage.setSendProtocol(protocol); #ifdef TEST_PRINT if(resendMessage.getSipTransaction() == NULL) { UtlString msgString; int msgLen; resendMessage.getBytes(&msgString, &msgLen); OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::doResend reschedule of request resend with NULL transaction", msgString.data()); osPrintf("SipTransaction::doResend reschedule of request resend with NULL transaction\n", msgString.data()); } #endif // Schedule a timeout for requests which do not // receive a response SipMessageEvent* resendEvent = new SipMessageEvent(new SipMessage(resendMessage), SipMessageEvent::TRANSACTION_RESEND); OsMsgQ* incomingQ = userAgent.getMessageQueue(); OsTimer* timer = new OsTimer(incomingQ, (intptr_t)resendEvent); mTimers.append(timer); #ifdef TEST_PRINT osPrintf("SipTransaction::doResend added timer %p to timer list.\n", timer); #endif // Convert from mSeconds to uSeconds OsTime lapseTime(0, nextTimeout * 1000); timer->oneshotAfter(lapseTime); sentOk = TRUE; } else { // Send failed send back the transport error // Dispatch is done from above this method // Dispatch needs it own copy of the message // SipMessage* dispatchMessage = new SipMessage(resendMessage); // The TCP send failed, pass back an error //userAgent.dispatch(dispatchMessage, // SipMessageEvent::TRANSPORT_ERROR); } } } // TCP else if (protocol == OsSocket::CUSTOM) { if(!pTransport->bIsReliable && numTries < SIP_UDP_RESEND_TIMES) { // Try again numTries++; if(userAgent.sendCustom(pTransport, &resendMessage, sendAddress.data(), sendPort)) { // Do this after the send so that // the log message is correct resendMessage.setTimesSent(numTries); // Schedule a time out if(lastTimeout < userAgent.getFirstResendTimeout()) { nextTimeout = userAgent.getFirstResendTimeout(); } else if(lastTimeout < userAgent.getLastResendTimeout()) { nextTimeout = lastTimeout * 2; } else { nextTimeout = userAgent.getLastResendTimeout(); } resendMessage.setTimesSent(numTries); resendMessage.setResendDuration(nextTimeout); sentOk = TRUE; } } } return(sentOk); } // end doResend UtlBoolean SipTransaction::handleIncoming(SipMessage& incomingMessage, SipUserAgent& userAgent, enum messageRelationship relationship, SipTransactionList& transactionList, SipMessage*& delayedDispatchedMessage, SIPX_TRANSPORT_DATA* pTransport) { if (!mpTransport) mpTransport = pTransport; if(delayedDispatchedMessage) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleIncoming delayedDispatchedMessage not NULL"); delayedDispatchedMessage = NULL; } UtlBoolean shouldDispatch = FALSE; if(relationship == MESSAGE_UNKNOWN) { relationship = whatRelation(incomingMessage, TRUE); } // This is a message was already recieved once if(relationship == MESSAGE_DUPLICATE) { // Update the time stamp so that this message // does not get garbage collected right away. // This is so that rogue UAs that keep sending // the same message for a long (i.e. longer than // transaction timeout) period of time are ignored. // Otherwise this message looks like a new message // after a transaction timeout and the original // copy gets garbage collected. We explicitly // do NOT touch the outgoing (i.e. sentMessages) // as we do not want to keep responding after // the transaction timeout. //previousMessage->touchTransportTime(); // If it is a request resend the response if it exists if(!(incomingMessage.isResponse())) { SipMessage* response = NULL; //sentMessages.getResponseFor(message); UtlString method; incomingMessage.getRequestMethod(&method); if(method.compareTo(SIP_ACK_METHOD) == 0) { // Do nothing, we already have the ACK } else if(method.compareTo(SIP_CANCEL_METHOD) == 0) { // Resend the CANCEL response response = mpCancelResponse; } else { // Resend the final response if there is one // Otherwise resend the provisional response response = mpLastFinalResponse ? mpLastFinalResponse : mpLastProvisionalResponse; } #ifdef TEST_PRINT osPrintf("SipTransaction::handleIncoming duplicate REQUEST response\n"); if(response) { osPrintf("response protocol: %d\n", response->getSendProtocol()); } #endif if(response) // No longer filter on reliable protocol as even if this // was TCP there could be a switch from TCP to UDP somewhere // in the proxy chain. Hense we should resend anyway //&& response->getSendProtocol() == OsSocket::UDP) { int sendProtocol = response->getSendProtocol(); UtlString sendAddress; int sendPort; response->getSendAddress(&sendAddress, &sendPort); if(sendProtocol == OsSocket::UDP) { userAgent.sendUdp(response, sendAddress.data(), sendPort); } else if(sendProtocol == OsSocket::TCP) { userAgent.sendTcp(response, sendAddress.data(), sendPort); } #ifdef SIP_TLS else if(sendProtocol == OsSocket::SSL_SOCKET) { userAgent.sendTls(response, sendAddress.data(), sendPort); } #endif else if (sendProtocol >= OsSocket::CUSTOM) { userAgent.sendCustom(NULL, response, sendAddress.data(), sendPort); } #ifdef TEST_PRINT osPrintf("SipTransaction::handleIncoming resending response\n"); #endif } } // If it is an INVITE response, resend the ACK if it exists // else { int cSeq; UtlString seqMethod; incomingMessage.getCSeqField(&cSeq, &seqMethod); // We assume ACK will only exist if this was an INVITE // transaction. We resend only if this is a // UA transaction. if ( !seqMethod.compareTo(SIP_CANCEL_METHOD) && mpAck && mIsUaTransaction ) { #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleIncoming resending ACK"); #endif int sendProtocol = mpAck->getSendProtocol(); UtlString sendAddress; int sendPort; mpAck->getSendAddress(&sendAddress, &sendPort); if(sendProtocol == OsSocket::UDP) { userAgent.sendUdp(mpAck, sendAddress.data(), sendPort); } else if(sendProtocol == OsSocket::TCP) { userAgent.sendTcp(mpAck, sendAddress.data(), sendPort); } #ifdef SIP_TLS else if(sendProtocol == OsSocket::SSL_SOCKET) { userAgent.sendTls(mpAck, sendAddress.data(), sendPort); } #endif else if (sendProtocol >= OsSocket::CUSTOM) { userAgent.sendCustom(NULL, mpAck, sendAddress.data(), sendPort); } #ifdef TEST_PRINT osPrintf("SipTransaction::handleIncoming resent ACK\n"); #endif } } } // The first time we received this message else if(relationship == MESSAGE_FINAL) { if(mpAck) { int cSeq; UtlString seqMethod; incomingMessage.getCSeqField(&cSeq, &seqMethod); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleIncoming resending ACK for final response %s", seqMethod.data() ); int sendProtocol = mpAck->getSendProtocol(); UtlString sendAddress; int sendPort; mpAck->getSendAddress(&sendAddress, &sendPort); if(sendProtocol == OsSocket::UDP) { userAgent.sendUdp(mpAck, sendAddress.data(), sendPort); } else if(sendProtocol == OsSocket::TCP) { userAgent.sendTcp(mpAck, sendAddress.data(), sendPort); } #ifdef SIP_TLS else if(sendProtocol == OsSocket::SSL_SOCKET) { userAgent.sendTls(mpAck, sendAddress.data(), sendPort); } #endif else if (sendProtocol >= OsSocket::CUSTOM) { userAgent.sendCustom(NULL, mpAck, sendAddress.data(), sendPort); } mpAck->incrementTimesSent(); mpAck->touchTransportTime(); shouldDispatch = TRUE; OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::handleIncoming received final response," "sending existing ACK" ); } else { // If this is an error final response to an INVITE // We can automatically construct the ACK here: if( mpRequest && (mRequestMethod.compareTo(SIP_INVITE_METHOD) == 0) && (incomingMessage.getResponseStatusCode() >= SIP_3XX_CLASS_CODE) ) { SipMessage ack; ack.setAckData(&incomingMessage, mpRequest); // SDUA // is err code > 300 , set the DNS data files in the response // We may not need this any more as the ACK for error // responses is now done here UtlString protocol; UtlString address; UtlString port; if (mpRequest->getDNSField( &protocol , &address , &port)) { ack.setDNSField(protocol, address, port); } #ifdef TEST_PRINT osPrintf("SipTransaction::handleIncoming %p sending ACK for error response\n", this); #endif handleOutgoing(ack, userAgent, transactionList, MESSAGE_ACK, mpTransport); shouldDispatch = TRUE; } // Non INVITE response or 2XX INVITE responses for which // there is no ACK yet get dispatched. The app layer must // generate the ACK for 2XX responses as it may contain // SDP else { shouldDispatch = TRUE; } } SipMessage* responseCopy = new SipMessage(incomingMessage); addResponse(responseCopy, FALSE, // Incoming relationship); } // End if new final response // Requests, provisional responses, Cancel response else { SipMessage* responseCopy = new SipMessage(incomingMessage); addResponse(responseCopy, FALSE, // Incoming relationship); if(relationship == MESSAGE_REQUEST && mIsServerTransaction) { if(mpLastProvisionalResponse) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::handleIncoming new request with and existing provisional response"); } else if(mpLastFinalResponse) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::handleIncoming new request with and existing final response"); } // INVITE transactions we can send trying to stop the resends else if(mRequestMethod.compareTo(SIP_INVITE_METHOD) == 0) { // Create and send a 100 Trying SipMessage trying; trying.setTryingResponseData(&incomingMessage); #ifdef TEST_PRINT osPrintf("SipTransaction::handleIncoming sending trying response\n"); #endif handleOutgoing(trying, userAgent, transactionList, MESSAGE_PROVISIONAL, mpTransport); } } // If this transaction was marked as canceled // but we could not send the cancel until we // get a provisional response, we can now send // the CANCEL (we only send CANCEL for INVITEs). if(relationship == MESSAGE_PROVISIONAL && !mIsServerTransaction && mIsCanceled && mpCancel == NULL && // have not already sent CANCEL mpRequest && mRequestMethod.compareTo(SIP_INVITE_METHOD) == 0) { SipMessage cancel; cancel.setCancelData(mpRequest); #ifdef TEST_PRINT osPrintf("SipTransaction::handleIncoming sending cancel after receiving first provisional response\n"); #endif handleOutgoing(cancel, userAgent, transactionList, MESSAGE_CANCEL, mpTransport); } // Incoming CANCEL, respond and cancel children else if(mIsServerTransaction && relationship == MESSAGE_CANCEL) { if(mpRequest) { UtlString reqMethod; mpRequest->getRequestMethod(&reqMethod); if(reqMethod.compareTo(SIP_INVITE_METHOD) == 0 && (mTransactionState == TRANSACTION_PROCEEDING || mTransactionState == TRANSACTION_CALLING)) { // Proxy transaction if(!mIsUaTransaction) { cancelChildren(userAgent, transactionList); shouldDispatch = FALSE; } // UA transaction else { shouldDispatch = TRUE; } if(mpLastFinalResponse == NULL) { // I think this is wrong only the app. layer of a // UAS should response with 487 // Respond to the server transaction INVITE //SipMessage inviteResponse; //inviteResponse.setResponseData(mpRequest, // SIP_REQUEST_TERMINATED_CODE, // SIP_REQUEST_TERMINATED_TEXT); //handleOutgoing(inviteResponse, userAgent, // MESSAGE_FINAL); } } else { // Erik Fournier 16/09/2005 // The 200 response should only be sent here if the CANCEL request // is not going to be dispatched to the application layer. // Too late to cancel, non-INVITE request and // successfully canceled INVITEs all get a // 200 response to the CANCEL SipMessage cancelResponse; cancelResponse.setResponseData(&incomingMessage, SIP_OK_CODE, SIP_OK_TEXT); #ifdef TEST_PRINT osPrintf("SipTransaction::handleIncoming sending CANCEL response\n"); #endif handleOutgoing(cancelResponse, userAgent, transactionList, MESSAGE_CANCEL_RESPONSE, mpTransport); } } // No request for to cancel else { // Send a transaction not found error SipMessage cancelError; cancelError.setBadTransactionData(&incomingMessage); #ifdef TEST_PRINT osPrintf("SipTransaction::handleIncoming transaction not found, sending CANCEL response\n"); #endif handleOutgoing(cancelError, userAgent, transactionList, MESSAGE_CANCEL_RESPONSE, mpTransport); } } // End cancel request else { // ACK received for server transaction if(mIsServerTransaction && relationship == MESSAGE_ACK) { int responseCode = -1; if(mpLastFinalResponse) { responseCode = mpLastFinalResponse->getResponseStatusCode(); } // If this INVITE transaction ended in an error final response // we do not forward the message via the clients transactions // the client generates its own ACK if(responseCode >= SIP_3XX_CLASS_CODE) { shouldDispatch = FALSE; } // Else if this was a successful INVITE the ACK should: // only come to this proxy if the INVITE was record-routed // or the previous hop that send this ACK incorrectly sent the // ACK to the same URI as the INVITE else { shouldDispatch = TRUE; } } else { shouldDispatch = TRUE; } } } // End: Requests, provisional responses, Cancel response # ifdef TEST_PRINT osPrintf("SipTransaction::handleIncoming %p asking parent shouldDispatch=%d delayed=%p\n", this, shouldDispatch, delayedDispatchedMessage ); # endif # ifdef DISPATCH_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleIncoming %p " "before handleChildIncoming shouldDispatch=%d delayed=%p\n", this, shouldDispatch, delayedDispatchedMessage ); # endif shouldDispatch = handleChildIncoming(incomingMessage, userAgent, relationship, transactionList, shouldDispatch, delayedDispatchedMessage, mpTransport); # ifdef DISPATCH_DEBUG OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::handleIncoming %p " "after handleChildIncoming shouldDispatch=%d delayed=%p\n", this, shouldDispatch, delayedDispatchedMessage ); # endif # ifdef TEST_PRINT osPrintf("SipTransaction::handleIncoming %p " "parent says shouldDispatch=%d delayed=%p\n", this, shouldDispatch, delayedDispatchedMessage ); # endif touch(); return(shouldDispatch); } // end handleIncoming void SipTransaction::removeTimer(OsTimer* timer) { OsTimer* pt = static_cast(mTimers.find(timer)); if(pt == NULL) { #ifdef TEST_PRINT osPrintf("SipTransaction::removeTimer could not find timer %p in timer list.\n", timer); #endif } else { OsTimer* removedTimer = static_cast(mTimers.remove(pt)); #ifdef TEST_PRINT if(removedTimer == NULL) { osPrintf("SipTransaction::removeTimer failed to remove timer %p from timer list.\n", timer); } else { osPrintf("SipTransaction::removeTimer removed timer %p from timer list.\n", timer); } #else removedTimer = removedTimer; // supress unused variable warning #endif } } void SipTransaction::deleteTimers() { UtlSListIterator iterator(mTimers); OsTimer* timer = NULL; while ((timer = (OsTimer*)iterator())) { #ifdef TEST_PRINT osPrintf("SipTransaction::deleteTimers deleting timer %p\n", timer); #endif // stop timer so it doesn't fire anymore timer->stop(); // remove timer from transaction removeTimer(timer); // delete timer if it's stopped and isn't stopped because it fired // but because we stopped it manually. Such timers are safe to delete. // Fired timers should be cleaned up in the message queue they posted // message to (SipUserAgent). if (timer->getState() == OsTimer::STOPPED && timer->getWasFired() == FALSE) { OsQueuedEvent *pEvent = (OsQueuedEvent*)timer->getNotifier(); intptr_t userData; pEvent->getUserData(userData); SipMessageEvent* pMsgEvent = (SipMessageEvent*) userData; delete pMsgEvent; delete timer; } } } void SipTransaction::stopTimers() { UtlSListIterator iterator(mTimers); OsTimer* timer = NULL; while ((timer = (OsTimer*)iterator())) { timer->stop(); } } void SipTransaction::startTimers() { /* // As if 2006-10-06 -- The timer subsystem has been rewritten and no // longer supports the ability to restart timers -- work is needed // to add this (not sure how much), but until then, disabling this // functionality. UtlSListIterator iterator(mTimers); OsTimer* timer = NULL; while ((timer = (OsTimer*)iterator())) { timer->start(); } */ } void SipTransaction::cancel(SipUserAgent& userAgent, SipTransactionList& transactionList) { if(mIsServerTransaction) { // SHould not get here this is only for kids (i.e. child client transactions) OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::cancel called on server transaction"); } else if(!mIsCanceled) { mIsCanceled = TRUE; if(mpRequest) { if(mpCancel) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::cancel cancel request already exists"); } // Do not send CANCELs for non-INVITE transactions // (all the other state stuff should be done) else if(mTransactionState == TRANSACTION_PROCEEDING && mIsDnsSrvChild && mRequestMethod.compareTo(SIP_INVITE_METHOD) == 0) { // We can only send a CANCEL if we have heard // back a provisional response. If we have a // final response it is too late SipMessage cancel; cancel.setCancelData(mpRequest); #ifdef TEST_PRINT osPrintf("SipTransaction::cancel sending CANCEL\n"); #endif handleOutgoing(cancel, userAgent, transactionList, MESSAGE_CANCEL, mpTransport); } //if(mIsRecursing) { cancelChildren(userAgent, transactionList); } } // If this transaction has been initiated (i.e. request // has been created and sent) else if(mTransactionState != TRANSACTION_LOCALLY_INIITATED) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::cancel no request"); } } #ifdef TEST_PRINT else { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::cancel already canceled"); } #endif } void SipTransaction::cancelChildren(SipUserAgent& userAgent, SipTransactionList& transactionList) { // Cancel all the child transactions UtlSListIterator iterator(mChildTransactions); SipTransaction* childTransaction = NULL; while ((childTransaction = (SipTransaction*) iterator())) { childTransaction->cancel(userAgent, transactionList); } } void SipTransaction::linkChild(SipTransaction& newChild) { if(newChild.mpParentTransaction) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::linkChild child.parent is not NULL"); } newChild.mpParentTransaction = this; newChild.mIsBusy = mIsBusy; if(mChildTransactions.containsReference(&newChild)) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::linkChild child already a child"); } else { // The children are supposed to be sorted by Q value, // largest first UtlSListIterator iterator(mChildTransactions); SipTransaction* childTransaction = NULL; UtlBoolean childInserted = FALSE; int sortIndex = 0; while ((childTransaction = (SipTransaction*) iterator())) { if(childTransaction->mQvalue < newChild.mQvalue) { mChildTransactions.insertAt(sortIndex, &newChild); childInserted = TRUE; break; } sortIndex++; } // It goes last if(!childInserted) mChildTransactions.append(&newChild); } if(mIsServerTransaction && mIsUaTransaction) { mIsUaTransaction = FALSE; OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::linkChild converting server UA transaction to server proxy transaction"); } } void SipTransaction::dumpTransactionTree(UtlString& dumpstring, UtlBoolean dumpMessagesAlso) { SipTransaction* parent = getTopMostParent(); if(parent == NULL) parent = this; if(parent) { parent->toString(dumpstring, dumpMessagesAlso); parent->dumpChildren(dumpstring, dumpMessagesAlso); } } void SipTransaction::dumpChildren(UtlString& dumpstring, UtlBoolean dumpMessagesAlso) { UtlSListIterator iterator(mChildTransactions); SipTransaction* childTransaction = NULL; UtlString childString; while ((childTransaction = (SipTransaction*) iterator())) { // Dump Child childString.remove(0); childTransaction->toString(childString, dumpMessagesAlso); dumpstring.append(childString); // Dump childred recursively childString.remove(0); childTransaction->dumpChildren(childString, dumpMessagesAlso); dumpstring.append(childString); } } void SipTransaction::toString(UtlString& dumpString, UtlBoolean dumpMessagesAlso) { char numBuffer[64]; dumpString.append(" SipTransaction dump:\n\tthis: "); sprintf(numBuffer, "%p", this); dumpString.append(numBuffer); dumpString.append("\n\thash: "); dumpString.append(this->data()); dumpString.append("\n\tmCallId: "); dumpString.append(mCallId); dumpString.append("\n\tmBranchId: "); dumpString.append(mBranchId); dumpString.append("\n\tmRequestUri: "); dumpString.append(mRequestUri); dumpString.append("\n\tmSendToAddress: "); dumpString.append(mSendToAddress); dumpString.append("\n\tmSendToPort: "); sprintf(numBuffer, "%d", mSendToPort); dumpString.append(numBuffer); dumpString.append("\n\tmSendToProtocol: "); UtlString protocolString; SipMessage::convertProtocolEnumToString(mSendToProtocol, protocolString); dumpString.append(protocolString); //sprintf(numBuffer, "%d", mSendToProtocol); //dumpString.append(numBuffer); if(mpDnsSrvRecords) { dumpString.append("\n\tmpDnsSrvRecords:\n\t\tPref\tWt\tType\tName(ip):Port"); UtlString srvName; UtlString srvIp; char srvRecordNums[128]; for (int i=0; mpDnsSrvRecords[i].isValidServerT(); i++) { mpDnsSrvRecords[i].getHostNameFromServerT(srvName); mpDnsSrvRecords[i].getIpAddressFromServerT(srvIp); sprintf(srvRecordNums, "\n\t\t%d\t%d\t%d\t", mpDnsSrvRecords[i].getPriorityFromServerT(), mpDnsSrvRecords[i].getWeightFromServerT(), mpDnsSrvRecords[i].getProtocolFromServerT()); dumpString.append(srvRecordNums); dumpString.append(srvName); dumpString.append("("); dumpString.append(srvIp); sprintf(srvRecordNums, "):%d", mpDnsSrvRecords[i].getPortFromServerT()); dumpString.append(srvRecordNums); } } else { dumpString.append("\n\tmpDnsSrvRecords: NULL"); } dumpString.append("\n\tmFromField: "); dumpString.append(mFromField.toString()); dumpString.append("\n\tmToField: "); dumpString.append(mToField.toString()); dumpString.append("\n\tmRequestMethod: "); dumpString.append(mRequestMethod); dumpString.append("\n\tmCseq: "); sprintf(numBuffer, "%d", mCseq); dumpString.append(numBuffer); dumpString.append("\n\tmIsServerTransaction: "); dumpString.append(mIsServerTransaction ? "TRUE" : " FALSE"); dumpString.append("\n\tmIsUaTransaction: "); dumpString.append(mIsUaTransaction ? "TRUE" : " FALSE"); UtlString msgString; int len; dumpString.append("\n\tmpRequest: "); if(mpRequest && dumpMessagesAlso) { mpRequest->getBytes(&msgString, &len); dumpString.append("\n==========>\n"); dumpString.append(msgString); dumpString.append("\n==========>\n"); } else { sprintf(numBuffer, "%p", mpRequest); dumpString.append(numBuffer); } dumpString.append("\n\tmpLastProvisionalResponse: "); if(mpLastProvisionalResponse && dumpMessagesAlso) { mpLastProvisionalResponse->getBytes(&msgString, &len); dumpString.append("\n==========>\n"); dumpString.append(msgString); dumpString.append("\n==========>\n"); } else { if (mpLastProvisionalResponse) { sprintf(numBuffer, "%d ", mpLastProvisionalResponse->getResponseStatusCode()); dumpString.append(numBuffer); } sprintf(numBuffer, "%p", mpLastProvisionalResponse); dumpString.append(numBuffer); } dumpString.append("\n\tmpLastFinalResponse: "); if(mpLastFinalResponse && dumpMessagesAlso) { mpLastFinalResponse->getBytes(&msgString, &len); dumpString.append("\n==========>\n"); dumpString.append(msgString); dumpString.append("\n==========>\n"); } else { if (mpLastFinalResponse) { sprintf(numBuffer, "%d ", mpLastFinalResponse->getResponseStatusCode()); dumpString.append(numBuffer); } sprintf(numBuffer, "%p", mpLastFinalResponse); dumpString.append(numBuffer); } dumpString.append("\n\tmpAck: "); if(mpAck && dumpMessagesAlso) { mpAck->getBytes(&msgString, &len); dumpString.append("\n==========>\n"); dumpString.append(msgString); dumpString.append("\n==========>\n"); } else { sprintf(numBuffer, "%p", mpAck); dumpString.append(numBuffer); } dumpString.append("\n\tmpCancel: "); if(mpCancel && dumpMessagesAlso) { mpCancel->getBytes(&msgString, &len); dumpString.append("\n==========>\n"); dumpString.append(msgString); dumpString.append("\n==========>\n"); } else { sprintf(numBuffer, "%p", mpCancel); dumpString.append(numBuffer); } dumpString.append("\n\tmpCancelResponse: "); if(mpCancelResponse && dumpMessagesAlso) { mpCancelResponse->getBytes(&msgString, &len); dumpString.append("\n==========>\n"); dumpString.append(msgString); dumpString.append("\n==========>\n"); } else { if (mpCancelResponse) { sprintf(numBuffer, "%d", mpCancelResponse->getResponseStatusCode()); dumpString.append(numBuffer); } sprintf(numBuffer, "%p", mpCancelResponse); dumpString.append(numBuffer); } dumpString.append("\n\tmpParentTransaction: "); sprintf(numBuffer, "%p", mpParentTransaction); dumpString.append(numBuffer); UtlSListIterator iterator(mChildTransactions); SipTransaction* childTransaction = NULL; int childCount = 0; while ((childTransaction = (SipTransaction*) iterator())) { dumpString.append("\n\tmChildTransactions["); sprintf(numBuffer, "%d]: %p", childCount, childTransaction); dumpString.append(numBuffer); childCount++; } if(childCount == 0) { dumpString.append("\n\tmChildTransactions: none"); } dumpString.append("\n\tmTransactionCreateTime: "); sprintf(numBuffer, "%ld", mTransactionCreateTime); dumpString.append(numBuffer); dumpString.append("\n\tmTransactionStartTime: "); sprintf(numBuffer, "%ld", mTransactionStartTime); dumpString.append(numBuffer); dumpString.append("\n\tmTimeStamp: "); sprintf(numBuffer, "%ld", mTimeStamp); dumpString.append(numBuffer); UtlString state; getStateString(mTransactionState, state); dumpString.append("\n\tmTransactionState: "); dumpString.append(state); dumpString.append("\n\tmIsCanceled: "); dumpString.append(mIsCanceled ? "TRUE" : " FALSE"); dumpString.append("\n\tmIsRecursing: "); dumpString.append(mIsRecursing ? "TRUE" : " FALSE"); dumpString.append("\n\tmIsDnsSrvChild: "); dumpString.append(mIsDnsSrvChild ? "TRUE" : " FALSE"); dumpString.append("\n\tmProvisionalSdp: "); dumpString.append(mProvisionalSdp ? "TRUE" : " FALSE"); dumpString.append("\n\tmQvalue: "); sprintf(numBuffer, "%lf", mQvalue); dumpString.append(numBuffer); dumpString.append("\n\tmExpires: "); sprintf(numBuffer, "%d", mExpires); dumpString.append(numBuffer); dumpString.append("\n\tmIsBusy: "); sprintf(numBuffer, "%d", mIsBusy); dumpString.append(numBuffer); dumpString.append("\n\tmBusyTaskName: "); dumpString.append(mBusyTaskName); dumpString.append("\n\tmWaitingList: "); sprintf(numBuffer, "%p ", mWaitingList); dumpString.append(numBuffer); if(mWaitingList) { sprintf(numBuffer, "(%"PRIuPTR")", mWaitingList->entries()); dumpString.append(numBuffer); } dumpString.append("\n"); } void SipTransaction::notifyWhenAvailable(OsEvent* availableEvent) { SipTransaction* parent = getTopMostParent(); if(parent == NULL) parent = this; if(parent && availableEvent) { if(parent->mWaitingList == NULL) { parent->mWaitingList = new UtlSList(); } UtlSList* list = parent->mWaitingList; UtlVoidPtr* eventNode = new UtlVoidPtr((void*)availableEvent); list->append(eventNode); } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::notifyWhenAvailable parent: %p avialableEvent: %p", parent, availableEvent); } } void SipTransaction::signalNextAvailable() { SipTransaction* parent = getTopMostParent(); if(parent == NULL) parent = this; if(parent && parent->mWaitingList) { // Remove the first event that is waiting for this transaction UtlVoidPtr* eventNode = (UtlVoidPtr*) parent->mWaitingList->get(); if(eventNode) { OsEvent* waitingEvent = (OsEvent*) eventNode->getValue(); //#ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::signalNextAvailable %p signaling: %p", parent, waitingEvent); //#endif if(waitingEvent) { // If the event is already signaled, the other side // gave up waiting, so this side needs to free up // the event. if(waitingEvent->signal(1) == OS_ALREADY_SIGNALED) { delete waitingEvent; waitingEvent = NULL; } } delete eventNode; eventNode = NULL; } } } void SipTransaction::signalAllAvailable() { SipTransaction* parent = getTopMostParent(); if(parent == NULL) parent = this; if(parent && parent->mWaitingList) { UtlSList* list = parent->mWaitingList; // Remove the first event that is waiting for this transaction UtlVoidPtr* eventNode = NULL; while ((eventNode = (UtlVoidPtr*) list->get())) { if(eventNode) { OsEvent* waitingEvent = (OsEvent*) eventNode->getValue(); #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::signalAllAvailable %p signaling: %p", parent, waitingEvent); #endif if(waitingEvent) { // If the event is already signaled, the other side // gave up waiting, so this side needs to free up // the event. if(waitingEvent->signal(1) == OS_ALREADY_SIGNALED) { delete waitingEvent; waitingEvent = NULL; } } delete eventNode; eventNode = NULL; } } } } /* ============================ ACCESSORS ================================= */ void SipTransaction::getStateString(enum transactionStates state, UtlString& stateString) { switch(state) { case TRANSACTION_UNKNOWN: stateString = "TRANSACTION_UNKNOWN"; break; case TRANSACTION_LOCALLY_INIITATED: stateString = "TRANSACTION_LOCALLY_INITIATED"; break; case TRANSACTION_CALLING: stateString = "TRANSACTION_CALLING"; break; case TRANSACTION_PROCEEDING: stateString = "TRANSACTION_PROCEEDING"; break; case TRANSACTION_COMPLETE: stateString = "TRANSACTION_COMPLETE"; break; case TRANSACTION_CONFIRMED: stateString = "TRANSACTION_CONFIRMED"; break; case TRANSACTION_TERMINATED: stateString = "TRANSACTION_TERMINATED"; break; default: char numBuffer[128]; sprintf(numBuffer, "UKNOWN Transaction state: %d", state); stateString = numBuffer; break; } } void SipTransaction::getRelationshipString(enum messageRelationship relationship, UtlString& relationshipString) { switch(relationship) { case MESSAGE_UNKNOWN: relationshipString = "MESSAGE_UNKNOWN"; break; case MESSAGE_UNRELATED: relationshipString = "MESSAGE_UNRELATED"; break; case MESSAGE_SAME_SESSION: relationshipString = "MESSAGE_SAME_SESSION"; break; case MESSAGE_DIFFERENT_BRANCH: relationshipString = "MESSAGE_DIFFERENT_BRANCH"; break; case MESSAGE_REQUEST: relationshipString = "MESSAGE_REQUEST"; break; case MESSAGE_PROVISIONAL: relationshipString = "MESSAGE_PROVISIONAL"; break; case MESSAGE_FINAL: relationshipString = "MESSAGE_FINAL"; break; case MESSAGE_NEW_FINAL: relationshipString = "MESSAGE_NEW_FINAL"; break; case MESSAGE_CANCEL: relationshipString = "MESSAGE_CANCEL"; break; case MESSAGE_ACK: relationshipString = "MESSAGE_ACK"; break; case MESSAGE_2XX_ACK: relationshipString = "MESSAGE_2XX_ACK"; break; case MESSAGE_DUPLICATE: relationshipString = "MESSAGE_DUPLICATE"; break; default: char buffer[128]; sprintf(buffer, "UKNOWN transaction relationship: %d", relationship); relationshipString = buffer; break; } } void SipTransaction::buildHash(const SipMessage& message, UtlBoolean isOutgoing, UtlString& hash) { UtlBoolean isServerTransaction = message.isServerTransaction(isOutgoing); message.getCallIdField(&hash); hash.append(isServerTransaction ? 's' : 'c'); int cSeq; //UtlString method; message.getCSeqField(&cSeq, NULL /*&method*/); char cSeqString[20]; sprintf(cSeqString, "%d", cSeq); hash.append(cSeqString); } SipTransaction* SipTransaction::getTopMostParent() const { SipTransaction* topParent = NULL; if(mpParentTransaction) { topParent = mpParentTransaction->getTopMostParent(); if(topParent == NULL) { topParent = mpParentTransaction; } } return(topParent); } void SipTransaction::getCallId(UtlString& callId) const { callId = mCallId; } enum SipTransaction::transactionStates SipTransaction::getState() const { return(mTransactionState); } /*long SipTransaction::getStartTime() const { return(mTransactionStartTime); }*/ long SipTransaction::getTimeStamp() const { return(mTimeStamp); } void SipTransaction::touch() { // We touch the whole parent, child tree so that // none of transactions get garbage collected // until they are all stale. This saves checking // up and down the tree during garbage collection // to see if there are any still active transactions. SipTransaction* topParent = getTopMostParent(); // We end up setting the date twice on this // transaction if it is not the top most parent // but so what. The alternative is using a local // variable to hold the date. There is no net // savings. OsTime time; OsDateTime::getCurTimeSinceBoot(time); mTimeStamp = time.seconds(); //osPrintf("SipTransaction::touch seconds: %ld usecs: %ld\n", // time.seconds(), time.usecs()); //mTimeStamp = OsDateTime::getSecsSinceEpoch(); if(topParent) { topParent->touchBelow(mTimeStamp); } else { touchBelow(mTimeStamp); } } void SipTransaction::touchBelow(int newDate) { mTimeStamp = newDate; #ifdef TEST_PRINT UtlString serialized; toString(serialized, FALSE); osPrintf("%s\n", serialized.data()); #endif // TEST_PRINT SipTransaction* child = NULL; UtlSListIterator iterator(mChildTransactions); while((child = (SipTransaction*) iterator())) { child->touchBelow(newDate); } } SipMessage* SipTransaction::getRequest() { return(mpRequest); } SipMessage* SipTransaction::getLastProvisionalResponse() { return(mpLastProvisionalResponse); } SipMessage* SipTransaction::getLastFinalResponse() { return(mpLastFinalResponse); } void SipTransaction::markBusy() { #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::markBusy %p", this); #endif if(mpParentTransaction) mpParentTransaction->markBusy(); else { OsTime time; OsDateTime::getCurTimeSinceBoot(time); int busyTime = time.seconds(); // Make sure it is not equal to zero if(!busyTime) busyTime++; doMarkBusy(busyTime); OsTask* busyTask = OsTask::getCurrentTask(); if(busyTask) mBusyTaskName = busyTask->getName(); else mBusyTaskName = ""; } } void SipTransaction::doMarkBusy(int markData) { #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::doMarkBusy(%d) %p", markData, this); #endif mIsBusy = markData; // Recurse through the children and mark them busy UtlSListIterator iterator(mChildTransactions); SipTransaction* childTransaction = NULL; while ((childTransaction = (SipTransaction*) iterator())) { childTransaction->doMarkBusy(markData); } } void SipTransaction::markAvailable() { #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransaction::markAvailable %p", this); #endif // Recurse to the parent if(mpParentTransaction) mpParentTransaction->markAvailable(); // This is the top most parent else { touch(); //set the last used time for parent and all children doMarkBusy(0); signalNextAvailable(); } } /*void SipTransaction::doMarkAvailable() { mIsBusy = FALSE; // Recurse through the children and mark them available UtlSListIterator iterator(mChildTransactions); SipTransaction* childTransaction = NULL; while(childTransaction = (SipTransaction*) iterator()) { childTransaction->doMarkAvailable(); } } */ /* ============================ INQUIRY =================================== */ UtlBoolean SipTransaction::isServerTransaction() const { return(mIsServerTransaction); } UtlBoolean SipTransaction::isDnsSrvChild() const { return(mIsDnsSrvChild); } UtlBoolean SipTransaction::isUaTransaction() const { return(mIsUaTransaction); } UtlBoolean SipTransaction::isChildSerial() { // The child transactions are supposed to be sorted by // Q value. So if we look at the first and last and they // are different then there are serially searched children UtlBoolean isSerial = FALSE; SipTransaction* child = (SipTransaction*)mChildTransactions.first(); if(child) { double q1 = child->mQvalue; child = (SipTransaction*)mChildTransactions.last(); if(child) { double q2 = child->mQvalue; if((q1-q2)*(q1-q2) > MIN_Q_DELTA_SQUARE) { isSerial = TRUE; } } } return(isSerial); } UtlBoolean SipTransaction::isEarlyDialogWithMedia() { UtlBoolean earlyDialogWithMedia = FALSE; if(mProvisionalSdp && mTransactionState > TRANSACTION_LOCALLY_INIITATED && mTransactionState < TRANSACTION_COMPLETE) { earlyDialogWithMedia = TRUE; // This should not occur, the state should be ?TERMINATED? if(mIsCanceled) { UtlString stateString; SipTransaction::getStateString(mTransactionState, stateString); OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::isEarlyDialogWithMedia transaction state: %s incorrect for canceled transaction", stateString.data()); } // This should not occur, the state should be COMPETED or CONFIRMED if(mIsRecursing) { UtlString stateString; SipTransaction::getStateString(mTransactionState, stateString); OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::isEarlyDialogWithMedia transaction state: %s incorrect for recursing transaction", stateString.data()); } } return(earlyDialogWithMedia); } UtlBoolean SipTransaction::isChildEarlyDialogWithMedia() { UtlBoolean earlyDialogWithMedia = FALSE; UtlSListIterator iterator(mChildTransactions); SipTransaction* childTransaction = NULL; while ((childTransaction = (SipTransaction*) iterator())) { // If the state is initiated, no request has been sent // for this transaction and this an all other children after // this one in the list should be in the same state if(childTransaction->mTransactionState == TRANSACTION_LOCALLY_INIITATED) { break; } earlyDialogWithMedia = childTransaction->isEarlyDialogWithMedia(); } return(earlyDialogWithMedia); } UtlBoolean SipTransaction::isMethod(const char* methodToMatch) const { return(strcmp(mRequestMethod.data(), methodToMatch) == 0); } enum SipTransaction::messageRelationship SipTransaction::whatRelation(const SipMessage& message, UtlBoolean isOutgoing) const { enum messageRelationship relationship = MESSAGE_UNKNOWN; UtlString msgCallId; message.getCallIdField(&msgCallId); // Note: this is nested to bail out as soon as possible // for efficiency reasons // CallId matches if(mCallId.compareTo(msgCallId) == 0) { int msgCseq; UtlString msgMethod; message.getCSeqField(&msgCseq, &msgMethod); UtlBoolean isResponse = message.isResponse(); int lastFinalResponseCode = mpLastFinalResponse ? mpLastFinalResponse->getResponseStatusCode() : -1; UtlString viaField; UtlString msgBranch; UtlBoolean msgHasVia = message.getViaFieldSubField(&viaField, 0); SipMessage::getViaTag(viaField.data(), "branch", msgBranch); //osPrintf("SipTransaction::whatRelation\n\tvia: %s \tbranch: %s\n", // viaField.data(), msgBranch.data()); UtlBoolean branchPrefixSet = (mBranchId.index(BRANCH_ID_PREFIX) != UTL_NOT_FOUND); UtlBoolean toTagMatches = FALSE; UtlBoolean fromTagMatches; UtlBoolean branchIdMatches = mBranchId.compareTo(msgBranch) == 0; UtlBoolean mustCheckTags; bool bCustomTransport; message.getTransportName(bCustomTransport); // If the branch prefix is set, we can assume that // all we need to look at is the branch parameter to // determine if this is the same transaction or not. // ACK to INVITEs with 200 response are really a different // transaction. For convenience we consider them to be // the same. CANCLE is also a different transaction // that we store in the same SipTransaction object. if(bCustomTransport || !branchPrefixSet || (!isResponse && (msgMethod.compareTo(SIP_CANCEL_METHOD) == 0 || (msgMethod.compareTo(SIP_ACK_METHOD) == 0 && lastFinalResponseCode < SIP_3XX_CLASS_CODE && lastFinalResponseCode >= SIP_2XX_CLASS_CODE) || (!mIsServerTransaction && mTransactionState == TRANSACTION_LOCALLY_INIITATED)))) { // Avoid looking at the tags as it is expensive to // parse the To and From fields into a Url object. mustCheckTags = TRUE; Url msgFrom; UtlString msgFromTag; UtlString fromTag; message.getFromUrl(msgFrom); msgFrom.getFieldParameter("tag", msgFromTag); Url *pFromUrl = (Url *)&mFromField; pFromUrl->getFieldParameter("tag", fromTag); fromTagMatches = msgFromTag.compareTo(fromTag) == 0; } else { mustCheckTags = FALSE; toTagMatches = branchIdMatches; fromTagMatches = branchIdMatches; } // From field tag matches if(fromTagMatches) { UtlString msgToTag; // Do not check if the to tag matches untill we know // the from tag matches. Also do not look at the to // tag if we can determine a match from the branch. // The parsing the To field into a Url is expensive // so we avoid it if we can. if(mustCheckTags) { Url msgTo; UtlString toTag; message.getToUrl(msgTo); msgTo.getFieldParameter("tag", msgToTag); Url *pToUrl = (Url *)&mToField; pToUrl->getFieldParameter("tag", toTag); toTagMatches = (toTag.isNull() || toTag.compareTo(msgToTag) == 0); } // To field tag matches if(toTagMatches) { if(mCseq == msgCseq) { UtlBoolean isMsgServerTransaction = message.isServerTransaction(isOutgoing); // The message and this transaction are either both // part of a server or client transaction if(isMsgServerTransaction == mIsServerTransaction) { UtlString finalResponseToTag; // Note getting and parsing a URL is expensive so // we avoid it if(mpLastFinalResponse && mustCheckTags) { Url responseTo; mpLastFinalResponse->getToUrl(responseTo); responseTo.getFieldParameter("tag", finalResponseToTag); } UtlString msgUri; UtlBoolean parentBranchIdMatches = FALSE; if(!isResponse && // request !mIsServerTransaction && // client transaction mTransactionState == TRANSACTION_LOCALLY_INIITATED) { SipTransaction* parent = getTopMostParent(); // Should this matter whether it is a server or client TX? if(parent && parent->mIsServerTransaction && msgBranch.compareTo(parent->mBranchId) == 0) { // We know that the request originated from // this client transaction's parent server // transaction. parentBranchIdMatches = TRUE; message.getRequestUri(&msgUri); } else if ((parent == NULL) && !msgHasVia) { // This is a client transaction with no parent and // it originated from this UA because there are no // vias parentBranchIdMatches = TRUE; message.getRequestUri(&msgUri); } } // The branch of this message matches the // transaction or // This is the request for this client transaction // and the Via had not been added yet for this // transaction. So the branch is not there yet. if(branchIdMatches || (parentBranchIdMatches && msgUri.compareTo(mRequestUri) == 0) || (mIsUaTransaction && // UA client ACK transaction for 2xx !mIsServerTransaction && !isResponse && !msgHasVia && msgMethod.compareTo(SIP_ACK_METHOD) == 0 && lastFinalResponseCode < SIP_3XX_CLASS_CODE && lastFinalResponseCode >= SIP_2XX_CLASS_CODE) || (mIsUaTransaction && // UA server ACK transaction for 2xx mIsServerTransaction && !isResponse && msgMethod.compareTo(SIP_ACK_METHOD) == 0 && lastFinalResponseCode < SIP_3XX_CLASS_CODE && lastFinalResponseCode >= SIP_2XX_CLASS_CODE && finalResponseToTag.compareTo(msgToTag) == 0) || (mIsUaTransaction && // UA client CANCEL transaction !mIsServerTransaction && !isResponse && !msgHasVia && msgMethod.compareTo(SIP_CANCEL_METHOD) == 0)) { if(isResponse) { int msgResponseCode = message.getResponseStatusCode(); // Provisional responses if(msgResponseCode < SIP_2XX_CLASS_CODE) { relationship = MESSAGE_PROVISIONAL; } // Final responses else { if(msgMethod.compareTo(SIP_ACK_METHOD) == 0) { OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransaction::messageRelationship ACK response"); } else if(msgMethod.compareTo(SIP_CANCEL_METHOD) == 0) { relationship = MESSAGE_CANCEL_RESPONSE; } else if(mpLastFinalResponse) { int finalResponseCode = mpLastFinalResponse->getResponseStatusCode(); if(finalResponseCode == msgResponseCode) { if (msgMethod.compareTo(SIP_INVITE_METHOD) == 0) { if(!mustCheckTags) { Url msgTo; message.getToUrl(msgTo); msgTo.getFieldParameter("tag", msgToTag); UtlString toTag; Url toUrl; mpLastFinalResponse->getToUrl(toUrl); toUrl.getFieldParameter("tag", toTag); toTagMatches = (toTag.isNull() || toTag.compareTo(msgToTag) == 0); } if (toTagMatches) { #ifdef TEST_PRINT osPrintf("DUPLICATED msg finalResponseCode - %d toTagMatches %d \n", finalResponseCode, toTagMatches); #endif relationship = MESSAGE_DUPLICATE; } else { #ifdef TEST_PRINT osPrintf("MESSAGE_NEW_FINAL - finalResponseCode - %d toTagMatches %d \n", finalResponseCode, toTagMatches); #endif relationship = MESSAGE_NEW_FINAL; } } else { #ifdef TEST_PRINT osPrintf("DUPLICATED msg finalResponseCode - %d \n", finalResponseCode); #endif relationship = MESSAGE_DUPLICATE; } } else { relationship = MESSAGE_NEW_FINAL; } } else { relationship = MESSAGE_FINAL; } } } // Requests else { if(mpRequest) { UtlString previousRequestMethod; mpRequest->getRequestMethod(&previousRequestMethod); if(previousRequestMethod.compareTo(msgMethod) == 0) { #ifdef TEST_PRINT osPrintf("DUPLICATED msg previousRequestMethod - %s \n", previousRequestMethod.data()); #endif relationship = MESSAGE_DUPLICATE; } else if(msgMethod.compareTo(SIP_ACK_METHOD) == 0) { if(mpLastFinalResponse) { int finalResponseCode = mpLastFinalResponse->getResponseStatusCode(); if(finalResponseCode >= SIP_3XX_CLASS_CODE) { relationship = MESSAGE_ACK; } else { if(!mIsUaTransaction) { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::messageRelationship ACK matches transaction with 2XX class response"); } relationship = MESSAGE_2XX_ACK; } } else { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransaction::messageRelationship ACK matches transaction with NO final response"); relationship = MESSAGE_ACK; } } else if(msgMethod.compareTo(SIP_CANCEL_METHOD) == 0) { relationship = MESSAGE_CANCEL; } else { relationship = MESSAGE_DUPLICATE; OsSysLog::add(FAC_SIP, PRI_WARNING, "WARNING SipTransaction::messageRelationship found %s request for transaction with %s", msgMethod.data(), previousRequestMethod.data()); } } else { if(msgMethod.compareTo(SIP_CANCEL_METHOD) == 0) { relationship = MESSAGE_CANCEL; } else if(msgMethod.compareTo(SIP_ACK_METHOD) == 0) { relationship = MESSAGE_ACK; } else { relationship = MESSAGE_REQUEST; } } } } else { relationship = MESSAGE_DIFFERENT_BRANCH; } } else { relationship = MESSAGE_DIFFERENT_BRANCH; } } else { relationship = MESSAGE_SAME_SESSION; } } else { relationship = MESSAGE_UNRELATED; } } else { relationship = MESSAGE_UNRELATED; } } else { relationship = MESSAGE_UNRELATED; } return(relationship); } UtlBoolean SipTransaction::isBusy() { return(mIsBusy); } UtlBoolean SipTransaction::isUriChild(Url& uri) { UtlSListIterator iterator(mChildTransactions); SipTransaction* childTransaction = NULL; UtlBoolean childHasSameUri = FALSE; UtlString uriString; uri.getUri(uriString); while ((childTransaction = (SipTransaction*) iterator())) { if(uriString.compareTo(childTransaction->mRequestUri) == 0) { childHasSameUri = TRUE; break; } } return(childHasSameUri); } UtlBoolean SipTransaction::isUriRecursed(Url& uri) { SipTransaction* parent = getTopMostParent(); if(parent == NULL) parent = this; UtlString uriString; uri.getUri(uriString); return(isUriRecursedChildren(uriString)); } UtlBoolean SipTransaction::isUriRecursedChildren(UtlString& uriString) { UtlSListIterator iterator(mChildTransactions); SipTransaction* childTransaction = NULL; UtlBoolean childHasSameUri = FALSE; while ((childTransaction = (SipTransaction*) iterator())) { if(childTransaction->mTransactionState > TRANSACTION_LOCALLY_INIITATED && uriString.compareTo(childTransaction->mRequestUri) == 0) { childHasSameUri = TRUE; break; } // Check recursively if(childTransaction->mTransactionState > TRANSACTION_LOCALLY_INIITATED && isUriRecursedChildren(uriString)) { childHasSameUri = TRUE; break; } } return(childHasSameUri); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipTransactionList.cpp0000644000175000017500000004245112205613256025501 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS //#define TIME_LOG /* turns on timestamping of finding and garbage collecting transactions */ #ifdef TIME_LOG # include #endif // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipTransactionList::SipTransactionList() : mTransactions(), mListMutex(OsMutex::Q_FIFO) { } // Copy constructor SipTransactionList::SipTransactionList(const SipTransactionList& rSipTransactionList) : mListMutex(OsMutex::Q_FIFO) { } // Destructor SipTransactionList::~SipTransactionList() { mTransactions.destroyAll(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipTransactionList& SipTransactionList::operator=(const SipTransactionList& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } void SipTransactionList::addTransaction(SipTransaction* transaction, UtlBoolean lockList) { if(lockList) lock(); mTransactions.insert(transaction); #ifdef TEST_PRINT osPrintf("***************************************\n"); osPrintf("inserting transaction %X\n",transaction); osPrintf("***************************************\n"); #endif if(lockList) unlock(); } //: Find a transaction for the given message SipTransaction* SipTransactionList::findTransactionFor(const SipMessage& message, UtlBoolean isOutgoing, enum SipTransaction::messageRelationship& relationship) { SipTransaction* transactionFound = NULL; UtlString callId; SipTransaction::buildHash(message, isOutgoing, callId); lock(); // See if the message knows its transaction // DO NOT TOUCH THE CONTENTS of this transaction as it may no // longer exist. It can only be used as an ID for the transaction. SipTransaction* messageTransaction = message.getSipTransaction(); UtlString matchTransaction(callId); UtlHashBagIterator iterator(mTransactions, &matchTransaction); relationship = SipTransaction::MESSAGE_UNKNOWN; while ((transactionFound = (SipTransaction*) iterator())) { // If the message knows its SIP transaction // and the found transaction pointer does not match, skip the // expensive relationship calculation // The messageTransaction MUST BE TREATED AS OPAQUE // as it may have been deleted. if( messageTransaction && transactionFound != messageTransaction ) { continue; } // If the transaction has never sent the original rquest // it should never get a match for any messages. if( messageTransaction == NULL // this message does not point to this TX && ((transactionFound->getState()) == SipTransaction::TRANSACTION_LOCALLY_INIITATED) ) { continue; } relationship = transactionFound->whatRelation(message, isOutgoing); if(relationship == SipTransaction::MESSAGE_REQUEST || relationship == SipTransaction::MESSAGE_PROVISIONAL || relationship == SipTransaction::MESSAGE_FINAL || relationship == SipTransaction::MESSAGE_NEW_FINAL || relationship == SipTransaction::MESSAGE_CANCEL || relationship == SipTransaction::MESSAGE_CANCEL_RESPONSE || relationship == SipTransaction::MESSAGE_ACK || relationship == SipTransaction::MESSAGE_2XX_ACK || relationship == SipTransaction::MESSAGE_DUPLICATE) { break; } } UtlBoolean isBusy = FALSE; if(transactionFound == NULL) { relationship = SipTransaction::MESSAGE_UNKNOWN; } else { isBusy = transactionFound->isBusy(); if(!isBusy) { transactionFound->markBusy(); } } unlock(); if(transactionFound && isBusy) { // If we cannot lock it, it does not exist if(!waitUntilAvailable(transactionFound, callId)) { if (OsSysLog::willLog(FAC_SIP, PRI_WARNING)) { UtlString relationString; SipTransaction::getRelationshipString(relationship, relationString); OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransactionList::findTransactionFor %p not available relation: %s", transactionFound, relationString.data()); } transactionFound = NULL; } } #if 0 // enable only for transaction match debugging - log is confusing otherwise UtlString relationString; SipTransaction::getRelationshipString(relationship, relationString); UtlString bytes; int len; message.getBytes(&bytes, &len); OsSysLog::add(FAC_SIP, PRI_DEBUG ,"SipTransactionList::findTransactionFor %p %s %s %s" # ifdef TIME_LOG "\n\tTime Log %s" # endif ,&message ,isOutgoing ? "OUTGOING" : "INCOMING" ,transactionFound ? "FOUND" : "NOT FOUND" ,relationString.data() # ifdef TIME_LOG ,findTimeLog.data() # endif ); #endif return(transactionFound); } void SipTransactionList::removeOldTransactions(long oldTransaction, long oldInviteTransaction) { SipTransaction** transactionsToBeDeleted = NULL; int deleteCount = 0; int busyCount = 0; # ifdef TIME_LOG OsTimeLog gcTimes; gcTimes.addEvent("start"); # endif lock(); int numTransactions = mTransactions.entries(); if(numTransactions > 0) { UtlHashBagIterator iterator(mTransactions); SipTransaction* transactionFound = NULL; long transTime; // Pull all of the transactions to be deleted out of the list while((transactionFound = (SipTransaction*) iterator())) { if(transactionFound->isBusy()) busyCount++; transTime = transactionFound->getTimeStamp(); // Invites need to be kept longer than other transactions if(((!transactionFound->isMethod(SIP_INVITE_METHOD) && transTime < oldTransaction) || transTime < oldInviteTransaction) && ! transactionFound->isBusy()) { // Remove it from the list mTransactions.removeReference(transactionFound); OsSysLog::add(FAC_SIP, PRI_DEBUG, "removing transaction %p\n",transactionFound); // Make sure we have a pointer array to hold it if(transactionsToBeDeleted == NULL) { transactionsToBeDeleted = new SipTransaction*[numTransactions]; } // Put it in the pointer array transactionsToBeDeleted[deleteCount] = transactionFound; deleteCount++; // Make sure the events waiting for the transaction // to be available are signaled before we delete // any of the transactions or we end up with // incomplete transaction trees (i.e. deleted branches) transactionFound->signalAllAvailable(); transactionFound = NULL; } } } unlock(); // We do not need the lock if the transactions have been // removed from the list if ( deleteCount || busyCount ) // do not log 'doing nothing when nothing to do', even at debug level { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::removeOldTransactions deleting %d of %d transactions (%d busy)\n", deleteCount , numTransactions, busyCount); } // Delete the transactions in the array if (transactionsToBeDeleted) { # ifdef TIME_LOG gcTimes.addEvent("start delete"); # endif for(int txIndex = 0; txIndex < deleteCount; txIndex++) { delete transactionsToBeDeleted[txIndex]; # ifdef TIME_LOG gcTimes.addEvent("transaction deleted"); # endif } # ifdef TIME_LOG gcTimes.addEvent("finish delete"); # endif /* while((transactionFound = (SipTransaction*) iterator())) { transactionFound->stopTimers(); } */ delete[] transactionsToBeDeleted; transactionsToBeDeleted = NULL; } # ifdef TIME_LOG UtlString timeString; gcTimes.getLogString(timeString); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::removeOldTransactions " "%s", timeString.data() ); # endif } void SipTransactionList::stopTransactionTimers() { lock(); int numTransactions = mTransactions.entries(); if(numTransactions > 0) { UtlHashBagIterator iterator(mTransactions); SipTransaction* transactionFound = NULL; while((transactionFound = (SipTransaction*) iterator())) { transactionFound->stopTimers(); } } unlock(); } void SipTransactionList::startTransactionTimers() { lock(); int numTransactions = mTransactions.entries(); if(numTransactions > 0) { UtlHashBagIterator iterator(mTransactions); SipTransaction* transactionFound = NULL; while((transactionFound = (SipTransaction*) iterator())) { transactionFound->startTimers(); } } unlock(); } void SipTransactionList::deleteTransactionTimers() { lock(); int numTransactions = mTransactions.entries(); if(numTransactions > 0) { UtlHashBagIterator iterator(mTransactions); SipTransaction* transactionFound = NULL; while((transactionFound = (SipTransaction*) iterator())) { transactionFound->deleteTimers(); } } unlock(); } void SipTransactionList::toString(UtlString& string) { lock(); string.remove(0); UtlHashBagIterator iterator(mTransactions); SipTransaction* transactionFound = NULL; UtlString oneTransactionString; while((transactionFound = (SipTransaction*) iterator())) { transactionFound->toString(oneTransactionString, FALSE); string.append(oneTransactionString); oneTransactionString.remove(0); } unlock(); } void SipTransactionList::toStringWithRelations(UtlString& string, SipMessage& message, UtlBoolean isOutGoing) { lock(); string.remove(0); UtlHashBagIterator iterator(mTransactions); SipTransaction* transactionFound = NULL; UtlString oneTransactionString; SipTransaction::messageRelationship relation; UtlString relationString; while((transactionFound = (SipTransaction*) iterator())) { relation = transactionFound->whatRelation(message, isOutGoing); SipTransaction::getRelationshipString(relation, relationString); string.append(relationString); string.append(" "); transactionFound->toString(oneTransactionString, FALSE); string.append(oneTransactionString); oneTransactionString.remove(0); string.append("\n"); } unlock(); } void SipTransactionList::lock() { mListMutex.acquire(); } void SipTransactionList::unlock() { mListMutex.release(); } UtlBoolean SipTransactionList::waitUntilAvailable(SipTransaction* transaction, const UtlString& hash) { UtlBoolean exists; UtlBoolean busy = FALSE; int numTries = 0; do { numTries++; lock(); exists = transactionExists(transaction, hash); if(exists) { busy = transaction->isBusy(); if(!busy) { transaction->markBusy(); unlock(); //#ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::waitUntilAvailable %p locked after %d tries\n", transaction, numTries); //#endif } else { // We set an event to be signaled when a // transaction is released. OsEvent* waitEvent = new OsEvent; transaction->notifyWhenAvailable(waitEvent); // Must unlock while we wait or there is a dead lock unlock(); //#ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::waitUntilAvailable %p waiting on: %p after %d tries\n", transaction, waitEvent, numTries); //#endif OsStatus waitStatus; OsTime transBusyTimeout(1, 0); int waitTime = 0; do { if(waitTime > 0) OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransactionList::waitUntilAvailable %p still waiting: %d", transaction, waitTime); waitStatus = waitEvent->wait(transBusyTimeout); waitTime+=1; } while(waitStatus != OS_SUCCESS && waitTime < 30); // If we were never signaled, then we signal the // event so the other side knows that it has to // free up the event if(waitEvent->signal(-1) == OS_ALREADY_SIGNALED) { delete waitEvent; waitEvent = NULL; } // If we bailed out before the event was signaled // pretend the transaction does not exist. if(waitStatus != OS_SUCCESS) { exists = FALSE; } if(waitTime > 1) { if (OsSysLog::willLog(FAC_SIP, PRI_WARNING)) { UtlString transTree; UtlString waitingTaskName; OsTask* waitingTask = OsTask::getCurrentTask(); if(waitingTask) waitingTaskName = waitingTask->getName(); transaction->dumpTransactionTree(transTree, FALSE); OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransactionList::waitUntilAvailable status: %d wait time: %d transaction: %p task: %s transaction tree: %s", waitStatus, waitTime, transaction, waitingTaskName.data(), transTree.data()); } } //#ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::waitUntilAvailable %p done waiting after %d tries\n", transaction, numTries); //#endif } } else { unlock(); //#ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::waitUntilAvailable %p gone after %d tries\n", transaction, numTries); //#endif } } while(exists && busy); return(exists && !busy); } void SipTransactionList::markAvailable(SipTransaction& transaction) { lock(); if(!transaction.isBusy()) { UtlString transactionString; transaction.toString(transactionString, FALSE); OsSysLog::add(FAC_SIP, PRI_ERR, "SipTransactionList::markAvailable transaction not locked: %s\n", transactionString.data()); } else { transaction.markAvailable(); } unlock(); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ UtlBoolean SipTransactionList::transactionExists(const SipTransaction* transaction, const UtlString& hash) { UtlBoolean foundTransaction = FALSE; SipTransaction* aTransaction = NULL; UtlString matchTransaction(hash); UtlHashBagIterator iterator(mTransactions, &matchTransaction); while ((aTransaction = (SipTransaction*) iterator())) { if(aTransaction == transaction) { foundTransaction = TRUE; break; } } if(!foundTransaction) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::transactionExists transaction: %p hash: %s not found\n", transaction, hash.data()); } return(foundTransaction); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipUdpServer.cpp0000644000175000017500000010206412205613256024274 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(_VXWORKS) # include # include //# include #elif defined(__pingtel_on_posix__) //# include # include # include #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS //#define TEST_PRINT //#define LOG_SIZE // STATIC VARIABLE INITIALIZATIONS class SipKeepAliveBinding { public: OsSocket* m_pSocket ; UtlString m_targetIp ; int m_targetPort ; UtlString m_method ; int m_iKeepAlive ; OsTimer* m_pTimer ; OsCallback* m_pCallback ; SipMessage* m_pSipMessage ; OsNatKeepaliveListener* m_pListener ; UtlString m_sendIp ; int m_sendPort ; SipKeepAliveBinding(OsSocket* pSocket, const UtlString& targetIp, int targetPort, const UtlString& method, int iKeepAlive, OsNatKeepaliveListener* pListener) { m_pSocket = pSocket ; m_targetIp = targetIp ; m_targetPort = targetPort ; m_method = method ; m_iKeepAlive = iKeepAlive ; m_pTimer = NULL ; m_pCallback = NULL ; m_pSipMessage = NULL ; m_pListener = pListener ; m_sendIp = targetIp ; m_sendPort = targetPort ; } OsNatKeepaliveEvent populateEvent(const char* szContactIp, const int contactPort) { OsNatKeepaliveEvent event ; if (!m_method.compareTo("OPTIONS")) event.type = OS_NAT_KEEPALIVE_SIP_OPTIONS ; else if (!m_method.compareTo("PING")) event.type = OS_NAT_KEEPALIVE_SIP_PING ; else event.type = OS_NAT_KEEPALIVE_INVALID ; event.remoteAddress = m_targetIp ; event.remotePort = m_targetPort; event.keepAliveSecs = m_iKeepAlive ; event.mappedAddress = szContactIp ; event.mappedPort = contactPort ; return event ; } void start(SipUdpServer* pServer) { if (m_pTimer == NULL) { m_pCallback = new OsCallback((intptr_t)pServer, SipUdpServer::SipKeepAliveCallback) ; m_pTimer = new OsTimer(*m_pCallback) ; } // Fire off event if (m_pListener) m_pListener->OnKeepaliveStart(populateEvent(NULL, PORT_NONE)) ; m_pTimer->periodicEvery(OsTime(0, 0), OsTime(m_iKeepAlive, 0)) ; } void fireFeedback(const char* szContactIp, int contactPort) { // Fire off event if (m_pListener) m_pListener->OnKeepaliveFeedback(populateEvent(szContactIp, contactPort)) ; } void fireFailure() { // Fire off event if (m_pListener) m_pListener->OnKeepaliveFailure(populateEvent(NULL, PORT_NONE)) ; } void stop() { if (m_pTimer) { m_pTimer->stop() ; // Fire off event if (m_pListener) m_pListener->OnKeepaliveStop(populateEvent(NULL, PORT_NONE)) ; } } UtlBoolean matches(OsSocket* pSocket, const char* szRemoteIp, const int remotePort, const char* szMethod) { return ((pSocket == m_pSocket) && (m_targetIp.compareTo(szRemoteIp) == 0) && (remotePort == m_targetPort) && (m_method.compareTo(szMethod) == 0)) ; } ~SipKeepAliveBinding() { stop() ; delete m_pTimer ; delete m_pCallback ; delete m_pSipMessage ; } } ; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipUdpServer::SipUdpServer(int port, SipUserAgent* userAgent, int udpReadBufferSize, UtlBoolean bUseNextAvailablePort, const char* szBoundIp) : SipProtocolServerBase(userAgent, "UDP", "SipUdpServer-%d"), mStunRefreshSecs(28), mStunPort(PORT_NONE), mKeepAliveMutex(OsRWMutex::Q_FIFO), mMapLock(OsMutex::Q_FIFO) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUdpServer::_ port = %d, bUseNextAvailablePort = %d, szBoundIp = '%s'", port, bUseNextAvailablePort, szBoundIp); #ifdef _DISABLE_MULTIPLE_INTERFACE_SUPPORT szBoundIp = "0.0.0.0" ; #endif if (szBoundIp && 0 != strcmp(szBoundIp, "0.0.0.0")) { mDefaultIp = szBoundIp; int serverSocketPort = port; createServerSocket(szBoundIp, serverSocketPort, bUseNextAvailablePort, udpReadBufferSize); } else { int numAddresses = MAX_IP_ADDRESSES; const HostAdapterAddress* adapterAddresses[MAX_IP_ADDRESSES]; getAllLocalHostIps(adapterAddresses, numAddresses); for (int i = 0; i < numAddresses; i++) { int serverSocketPort = port; createServerSocket(adapterAddresses[i]->mAddress.data(), serverSocketPort, bUseNextAvailablePort, udpReadBufferSize); if (0 == i) { // use the first IP address in the array // for the 'default ip' mDefaultIp = adapterAddresses[i]->mAddress.data(); } delete adapterAddresses[i]; } } } // Destructor SipUdpServer::~SipUdpServer() { waitUntilShutDown(); SipClient* pServer = NULL; UtlHashMapIterator iterator(mServers); UtlVoidPtr* pServerContainer = NULL; UtlString* pKey = NULL; while ((pKey = (UtlString*)iterator())) { pServerContainer = (UtlVoidPtr*)iterator.value(); if (pServerContainer) { pServer = (SipClient*)pServerContainer->getValue(); pServer->requestShutdown(); delete pServer; } } mServers.destroyAll(); mServerPortMap.destroyAll(); mServerSocketMap.destroyAll(); } /* ============================ MANIPULATORS ============================== */ OsStatus SipUdpServer::createServerSocket(const char* szBoundIp, int& port, const UtlBoolean& bUseNextAvailablePort, int udpReadBufferSize) { OsStatus rc = OS_FAILED; OsNatDatagramSocket* pSocket = new OsNatDatagramSocket(0, NULL, port, szBoundIp, NULL); if (pSocket) { // If the socket is busy or unbindable and the user requested using the // next available port, try the next SIP_MAX_PORT_RANGE ports. if (bUseNextAvailablePort & portIsValid(port) && pSocket && !pSocket->isOk()) { for (int i=1; i<=SIP_MAX_PORT_RANGE; i++) { delete pSocket ; pSocket = new OsNatDatagramSocket(0, NULL, port+i, szBoundIp, NULL); if (pSocket->isOk()) { break ; } } } } if (pSocket) { pSocket->enableTransparentReads(false); port = pSocket->getLocalHostPort(); SIPX_CONTACT_ADDRESS contact; strcpy(contact.cIpAddress, szBoundIp); contact.iPort = port; contact.eContactType = CONTACT_LOCAL; UtlString adapterName; getContactAdapterName(adapterName, contact.cIpAddress, false); strcpy(contact.cInterface, adapterName.data()); contact.eTransportType = TRANSPORT_UDP; mSipUserAgent->addContactAddress(contact); // add address and port to the maps mServerSocketMap.insertKeyAndValue(new UtlString(szBoundIp), new UtlVoidPtr((void*)pSocket)); port = pSocket->getLocalHostPort() ; mServerPortMap.insertKeyAndValue(new UtlString(szBoundIp), new UtlInt(port)); int sockbufsize = 0; int size = sizeof(int); getsockopt(pSocket->getSocketDescriptor(), SOL_SOCKET, SO_RCVBUF, (char*)&sockbufsize, #if defined(__pingtel_on_posix__) (socklen_t*) // caste #endif &size); #ifdef LOG_SIZE OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUdpServer::SipUdpServer UDP buffer size: %d size: %d\n", sockbufsize, size); #endif /* LOG_SIZE */ if(udpReadBufferSize > 0) { setsockopt(pSocket->getSocketDescriptor(), SOL_SOCKET, SO_RCVBUF, (char*)&udpReadBufferSize, sizeof(int)); getsockopt(pSocket->getSocketDescriptor(), SOL_SOCKET, SO_RCVBUF, (char*)&sockbufsize, #if defined(__pingtel_on_posix__) (socklen_t*) // caste #endif &size); #ifdef LOG_SIZE OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUdpServer::SipUdpServer reset UDP buffer size: %d size: %d\n", sockbufsize, size); #endif /* LOG_SIZE */ } } return rc; } int SipUdpServer::run(void* runArg) { return 0 ; } void SipUdpServer::enableStun(const char* szStunServer, int iStunPort, const char* szLocalIp, int refreshPeriodInSecs, OsNotification* pNotification) { OsLock lock(mMapLock); // Store settings mStunPort = iStunPort ; mStunRefreshSecs = refreshPeriodInSecs ; if (szStunServer) { mStunServer = szStunServer ; } else { mStunServer.remove(0) ; } UtlHashMapIterator iterator(mServerSocketMap); UtlString* pKey = NULL; char szIpToStun[256]; memset((void*)szIpToStun, 0, sizeof(szIpToStun)); if (szLocalIp) { strcpy(szIpToStun, szLocalIp); } bool bStunAll = false; if (0 == strcmp(szIpToStun, "") || 0 == strcmp(szIpToStun, "0.0.0.0")) { bStunAll = true; // if no ip specified, start on the first one pKey = (UtlString*) iterator(); if (pKey) { strcpy(szIpToStun, pKey->data()); } } while (0 != strcmp(szIpToStun, "")) { UtlVoidPtr* pSocketContainer; UtlString key(szIpToStun); pSocketContainer = (UtlVoidPtr*)this->mServerSocketMap.findValue(&key); OsNatDatagramSocket* pSocket = NULL; if (pSocketContainer) { pSocket = (OsNatDatagramSocket*)pSocketContainer->getValue(); } if (pSocket) { pSocket->disableStun() ; // Update server client if (pSocket && mStunServer.length()) { pSocket->setNotifier(pNotification) ; pSocket->enableStun(mStunServer, mStunPort, refreshPeriodInSecs, 0, false) ; } } if (bStunAll) { // get the next address to stun pKey = (UtlString*) iterator(); if (pKey) { strcpy(szIpToStun, pKey->data()); } else { strcpy(szIpToStun, ""); } } else { break; } } // end while } void SipUdpServer::shutdownListener() { OsLock lock(mMapLock); SipClient* pServer = NULL; UtlHashMapIterator iterator(mServers); UtlVoidPtr* pServerContainer = NULL; UtlString* pKey = NULL; while ((pKey = (UtlString*)iterator())) { pServerContainer = (UtlVoidPtr*) iterator.value(); pServer = (SipClient*)pServerContainer->getValue(); if (pServer) { pServer->requestShutdown(); } } } UtlBoolean SipUdpServer::sendTo(const SipMessage& message, const char* address, int port, const char* szLocalSipIp) { UtlBoolean sendOk; UtlVoidPtr* pServerContainer = NULL; SipClient* pServer = NULL; if (szLocalSipIp) { UtlString localKey(szLocalSipIp); pServerContainer = (UtlVoidPtr*)this->mServers.findValue(&localKey); if (pServerContainer) { pServer = (SipClient*) pServerContainer->getValue(); } } else { // no local sip IP specified, so, use the default one UtlString defaultKey(mDefaultIp); pServerContainer = (UtlVoidPtr*) mServers.findValue(&defaultKey); if (pServerContainer) { pServer = (SipClient*) pServerContainer->getValue(); } } if (pServer) { sendOk = pServer->sendTo(message, address, port); } else { sendOk = false; } return(sendOk); } OsSocket* SipUdpServer::buildClientSocket(int hostPort, const char* hostAddress, const char* localIp) { OsNatDatagramSocket* pSocket = NULL; if (mSipUserAgent && mSipUserAgent->getUseRport()) { UtlVoidPtr* pSocketContainer = NULL; assert(localIp != NULL); UtlString localKey(localIp); pSocketContainer = (UtlVoidPtr*)mServerSocketMap.findValue(&localKey); assert(pSocketContainer); pSocket = (OsNatDatagramSocket*)pSocketContainer->getValue(); assert(pSocket); } else { pSocket = new OsNatDatagramSocket(0, NULL, 0, localIp) ; pSocket->enableTransparentReads(false); if (mStunServer.length() != 0) { pSocket->enableStun(mStunServer, mStunPort, mStunRefreshSecs, 0, true) ; } } return pSocket ; } UtlBoolean SipUdpServer::addCrLfKeepAlive(const char* szLocalIp, const char* szRemoteIp, const int remotePort, const int keepAliveSecs, OsNatKeepaliveListener* pListener) { OsLock lock(mMapLock); UtlHashMapIterator iterator(mServerSocketMap); UtlString* pKey = NULL; OsNatDatagramSocket* pSocket = NULL; UtlBoolean bSuccess = false ; while (pKey = (UtlString*) iterator()) { if ( (pKey->compareTo(szLocalIp) == 0) || (strcmp(szLocalIp, "0.0.0.0") == 0) || (strlen(szLocalIp) == 0) ) { UtlVoidPtr* pValue = (UtlVoidPtr*) mServerSocketMap.findValue(pKey) ; if (pValue) { pSocket = (OsNatDatagramSocket*) pValue->getValue() ; if (pSocket) { if (pSocket->addCrLfKeepAlive(szRemoteIp, remotePort, keepAliveSecs, pListener)) { bSuccess = true ; } } } } } return bSuccess ; } UtlBoolean SipUdpServer::removeCrLfKeepAlive(const char* szLocalIp, const char* szRemoteIp, const int remotePort) { OsLock lock(mMapLock); UtlHashMapIterator iterator(mServerSocketMap); UtlString* pKey = NULL; OsNatDatagramSocket* pSocket = NULL; UtlBoolean bSuccess = false ; while (pKey = (UtlString*) iterator()) { if ( (pKey->compareTo(szLocalIp) == 0) || (strcmp(szLocalIp, "0.0.0.0") == 0) || (strlen(szLocalIp) == 0) ) { UtlVoidPtr* pValue = (UtlVoidPtr*) mServerSocketMap.findValue(pKey) ; if (pValue) { pSocket = (OsNatDatagramSocket*) pValue->getValue() ; if (pSocket) { if (pSocket->removeCrLfKeepAlive(szRemoteIp, remotePort)) { bSuccess = true ; } } } } } return bSuccess ; } UtlBoolean SipUdpServer::addStunKeepAlive(const char* szLocalIp, const char* szRemoteIp, const int remotePort, const int keepAliveSecs, OsNatKeepaliveListener* pListener) { OsLock lock(mMapLock); UtlHashMapIterator iterator(mServerSocketMap); UtlString* pKey = NULL; OsNatDatagramSocket* pSocket = NULL; UtlBoolean bSuccess = false ; while (pKey = (UtlString*) iterator()) { if ( (pKey->compareTo(szLocalIp) == 0) || (strcmp(szLocalIp, "0.0.0.0") == 0) || (strlen(szLocalIp) == 0) ) { UtlVoidPtr* pValue = (UtlVoidPtr*) mServerSocketMap.findValue(pKey) ; if (pValue) { pSocket = (OsNatDatagramSocket*) pValue->getValue() ; if (pSocket) { if (pSocket->addStunKeepAlive(szRemoteIp, remotePort, keepAliveSecs, pListener)) { bSuccess = true ; } } } } } return bSuccess ; } UtlBoolean SipUdpServer::removeStunKeepAlive(const char* szLocalIp, const char* szRemoteIp, const int remotePort) { OsLock lock(mMapLock); UtlHashMapIterator iterator(mServerSocketMap); UtlString* pKey = NULL; OsNatDatagramSocket* pSocket = NULL; UtlBoolean bSuccess = false ; while (pKey = (UtlString*) iterator()) { if ( (pKey->compareTo(szLocalIp) == 0) || (strcmp(szLocalIp, "0.0.0.0") == 0) || (strlen(szLocalIp) == 0) ) { UtlVoidPtr* pValue = (UtlVoidPtr*) mServerSocketMap.findValue(pKey) ; if (pValue) { pSocket = (OsNatDatagramSocket*) pValue->getValue() ; if (pSocket) { if (pSocket->removeStunKeepAlive(szRemoteIp, remotePort)) { bSuccess = true ; } } } } } return bSuccess ; } UtlBoolean SipUdpServer::addSipKeepAlive(const char* szLocalIp, const char* szRemoteIp, const int remotePort, const char* szMethod, const int keepAliveSecs, OsNatKeepaliveListener* pListener) { UtlHashMapIterator iterator(mServerSocketMap); UtlString* pKey = NULL; OsNatDatagramSocket* pSocket = NULL; UtlBoolean bSuccess = false ; while (pKey = (UtlString*) iterator()) { if ( (pKey->compareTo(szLocalIp) == 0) || (strcmp(szLocalIp, "0.0.0.0") == 0) || (strlen(szLocalIp) == 0) ) { UtlVoidPtr* pValue = (UtlVoidPtr*) mServerSocketMap.findValue(pKey) ; if (pValue) { pSocket = (OsNatDatagramSocket*) pValue->getValue() ; if (pSocket) { SipKeepAliveBinding* pBinding = NULL ; mKeepAliveMutex.acquireWrite() ; pBinding = (SipKeepAliveBinding*) findKeepAliveBinding( pSocket, szRemoteIp, remotePort, szMethod) ; if (pBinding == NULL) { pBinding = new SipKeepAliveBinding(pSocket, szRemoteIp, remotePort, szMethod, keepAliveSecs, pListener) ; bSuccess = addKeepAliveBinding(pBinding) ; } else { // If we found a binding, stop it to avoid multiple // timers. pBinding->stop() ; } mKeepAliveMutex.releaseWrite() ; if (bSuccess && pBinding) { OsNatAgentTask::getInstance()->addExternalBinding( NULL, szRemoteIp, remotePort, "", 0) ; pBinding->start(this) ; } } } } } return bSuccess ; } UtlBoolean SipUdpServer::removeSipKeepAlive(const char* szLocalIp, const char* szRemoteIp, const int remotePort, const char* szMethod) { UtlHashMapIterator iterator(mServerSocketMap); UtlString* pKey = NULL; OsNatDatagramSocket* pSocket = NULL; UtlBoolean bSuccess = false ; while (pKey = (UtlString*) iterator()) { if ( (pKey->compareTo(szLocalIp) == 0) || (strcmp(szLocalIp, "0.0.0.0") == 0) || (strlen(szLocalIp) == 0) ) { UtlVoidPtr* pValue = (UtlVoidPtr*) mServerSocketMap.findValue(pKey) ; if (pValue) { pSocket = (OsNatDatagramSocket*) pValue->getValue() ; if (pSocket) { SipKeepAliveBinding* pBinding = NULL ; mKeepAliveMutex.acquireWrite() ; pBinding = (SipKeepAliveBinding*) findKeepAliveBinding( pSocket, szRemoteIp, remotePort, szMethod) ; if (pBinding) { bSuccess = removeKeepAliveBinding(pBinding) ; } mKeepAliveMutex.releaseWrite() ; // Stop/Delete binding will stop timer delete pBinding ; } } } } return bSuccess ; } void SipUdpServer::updateSipKeepAlive(const char* szLocalIp, const char* szMethod, const char* szRemoteIp, const int remotePort, const char* szContactIp, const int contactPort) { UtlHashMapIterator iterator(mServerSocketMap); UtlString* pKey = NULL; OsNatDatagramSocket* pSocket = NULL; while (pKey = (UtlString*) iterator()) { if ( (pKey->compareTo(szLocalIp) == 0) || (strcmp(szLocalIp, "0.0.0.0") == 0) || (strlen(szLocalIp) == 0) ) { UtlVoidPtr* pValue = (UtlVoidPtr*) mServerSocketMap.findValue(pKey) ; if (pValue) { pSocket = (OsNatDatagramSocket*) pValue->getValue() ; if (pSocket) { SipKeepAliveBinding* pBinding = NULL ; mKeepAliveMutex.acquireRead() ; pBinding = (SipKeepAliveBinding*) findKeepAliveBinding( pSocket, szRemoteIp, remotePort, szMethod) ; if (pBinding) { pBinding->fireFeedback(szContactIp, contactPort) ; } mKeepAliveMutex.releaseRead() ; } } } } } /* ============================ ACCESSORS ================================= */ void SipUdpServer::printStatus() { OsLock lock(mMapLock); SipClient* pServer = NULL; UtlHashMapIterator iterator(mServers); UtlVoidPtr* pServerContainer = NULL; UtlString* pKey = NULL; while ((pKey = (UtlString*)iterator())) { pServerContainer = (UtlVoidPtr*) iterator.value(); if (pServerContainer) { pServer = (SipClient*)pServerContainer->getValue(); } if (pServer) { UtlString clientNames; long clientTouchedTime = pServer->getLastTouchedTime(); UtlBoolean clientOk = pServer->isOk(); pServer->getClientNames(clientNames); osPrintf("UDP server %p last used: %ld ok: %d names: \n%s \n", this, clientTouchedTime, clientOk, clientNames.data()); SipProtocolServerBase::printStatus(); } } } int SipUdpServer::getServerPort(const char* szLocalIp) { int port = PORT_NONE; char szLocalIpForPortLookup[256]; memset((void*)szLocalIpForPortLookup, 0, sizeof(szLocalIpForPortLookup)); if (NULL == szLocalIp) { strcpy(szLocalIpForPortLookup, mDefaultIp); } else { strcpy(szLocalIpForPortLookup, szLocalIp); } UtlString localIpKey(szLocalIpForPortLookup); UtlInt* pUtlPort; pUtlPort = (UtlInt*)this->mServerPortMap.findValue(&localIpKey); if (pUtlPort) { port = pUtlPort->getValue(); } return port ; } UtlBoolean SipUdpServer::getStunAddress(UtlString* pIpAddress, int* pPort, const char* szLocalIp) { UtlBoolean bRet = false; OsNatDatagramSocket* pSocket = NULL; UtlVoidPtr* pSocketContainer = NULL; if (szLocalIp) { UtlString localIpKey(szLocalIp); pSocketContainer = (UtlVoidPtr*)this->mServerSocketMap.findValue(&localIpKey); if (pSocketContainer) { pSocket = (OsNatDatagramSocket*)pSocketContainer->getValue(); } } else { // just use the default Socket in our collection UtlString defaultIpKey(mDefaultIp); pSocketContainer = (UtlVoidPtr*)mServerSocketMap.findValue(&defaultIpKey); if (pSocketContainer != NULL ) { pSocket = (OsNatDatagramSocket*)pSocketContainer->getValue(); } } if (pSocket) { bRet = pSocket->getMappedIp(pIpAddress, pPort) ; } return bRet; } UtlBoolean SipUdpServer::addKeepAliveBinding(void* pBinding) { UtlVoidPtr key(pBinding) ; UtlBoolean bSuccess = false ; if (mSipKeepAliveBindings.find(&key) == NULL) { if (mSipKeepAliveBindings.insert(new UtlVoidPtr(pBinding)) != NULL) { bSuccess = true ; } } return bSuccess ; } UtlBoolean SipUdpServer::removeKeepAliveBinding(void* pBinding) { UtlVoidPtr key(pBinding) ; UtlBoolean bSuccess ; bSuccess = mSipKeepAliveBindings.destroy(&key) ; return bSuccess ; } void* SipUdpServer::findKeepAliveBinding(OsTimer* pTimer) { void* pRC = NULL ; UtlSListIterator itor(mSipKeepAliveBindings) ; while (UtlContainable* pCont = itor()) { SipKeepAliveBinding* pBinding = (SipKeepAliveBinding*) ((UtlVoidPtr*) pCont)->getValue() ; if (pBinding->m_pTimer == pTimer) { pRC = pBinding ; break ; } } return pRC ; } void* SipUdpServer::findKeepAliveBinding(OsSocket* pSocket, const char* szRemoteIp, const int remotePort, const char* szMethod) { void* pRC = NULL ; UtlSListIterator itor(mSipKeepAliveBindings) ; while (UtlContainable* pCont = itor()) { SipKeepAliveBinding* pBinding = (SipKeepAliveBinding*) ((UtlVoidPtr*) pCont)->getValue() ; if (pBinding->matches(pSocket, szRemoteIp, remotePort, szMethod)) { pRC = pBinding ; break ; } } return pRC ; } void SipUdpServer::sendSipKeepAlive(OsTimer* pTimer) { assert(pTimer) ; if (pTimer) { SipKeepAliveBinding* pBinding ; OsReadLock lock(mKeepAliveMutex) ; if (pBinding = (SipKeepAliveBinding*) findKeepAliveBinding(pTimer)) { if (pBinding->m_pSipMessage == NULL) { pBinding->m_pSipMessage = new SipMessage() ; // Setup From Field UtlString from; mSipUserAgent->getContactUri(&from); char fromTag[80]; sprintf(fromTag, ";tag=%d%d", rand(), rand()); from.append(fromTag); // Setup To Field Url toUrl ; toUrl.setScheme(Url::SipUrlScheme) ; toUrl.setHostAddress(pBinding->m_targetIp) ; if (pBinding->m_targetPort != SIP_PORT) { toUrl.setHostPort(pBinding->m_targetPort) ; } UtlString to = toUrl.toString(); // Resolve the raw address from a DNS SRV, A record // to an IP address server_t* dnsSrvRecords = SipSrvLookup::servers( pBinding->m_targetIp, "sip", OsSocket::UDP, pBinding->m_targetPort, mDefaultIp); if(dnsSrvRecords[0].isValidServerT()) { // Note: we are not doing any failover here as that is // a little tricky with the NAT stuff. We cannot change // addresses with every transaction as we may get different // ports and addresses every time we send a ping. For now // we do one DNS SRV lookup at the begining of time and // stick to that result. dnsSrvRecords[0].getIpAddressFromServerT(pBinding->m_sendIp); pBinding->m_sendPort = dnsSrvRecords[0].getPortFromServerT(); // If the ping URL or DNS SRV did not specify a port // bind it to the default port. if (!portIsValid(pBinding->m_sendPort)) { pBinding->m_sendPort = SIP_PORT; } } else { // Log failure and kill timer } delete[] dnsSrvRecords; // Generate CallId UtlString callId(mDefaultIp) ; long epochTime = OsDateTime::getSecsSinceEpoch(); char callIdPrefix[80]; sprintf(callIdPrefix, "%ld%d-ping-", epochTime, rand()); callId.insert(0,callIdPrefix); pBinding->m_pSipMessage->setRequestData(pBinding->m_method, to, from, to, callId, rand() % 32768) ; // Set User Agent header mSipUserAgent->setUserAgentHeader(*pBinding->m_pSipMessage) ; } // Update Via if (!mSipUserAgent->sendSymmetricUdp( *pBinding->m_pSipMessage, pBinding->m_sendIp, pBinding->m_sendPort)) { pBinding->fireFailure() ; } pBinding->m_pSipMessage->incrementCSeqNumber() ; } } } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ void SipUdpServer::SipKeepAliveCallback(const intptr_t userData, const intptr_t eventData) { SipUdpServer* pUdpServer = (SipUdpServer*) userData ; OsTimer* pTimer = (OsTimer*) eventData ; assert(pUdpServer) ; assert(pTimer) ; if (pUdpServer && pTimer) { OsPtrMsg msg(OsMsg::PHONE_APP, SipUserAgent::KEEPALIVE_MESSAGE, pUdpServer, pTimer) ; pUdpServer->mSipUserAgent->postMessage(msg) ; } } sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipUserAgentBase.cpp0000644000175000017500000000511712205613256025046 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipUserAgentBase::SipUserAgentBase(int sipTcpPort, int sipUdpPort, int sipTlsPort, int queueSize) : OsServerTask("SipUserAgent-%d", NULL, queueSize), mObserverMutex(OsRWMutex::Q_FIFO) { mTcpPort = sipTcpPort; mUdpPort = sipUdpPort; mTlsPort = sipTlsPort; mMessageLogEnabled = TRUE; } // Destructor SipUserAgentBase::~SipUserAgentBase() { } /* ============================ MANIPULATORS ============================== */ void SipUserAgentBase::addConfigChangeConsumer(OsMsgQ& messageQueue) { UtlVoidPtr* observer = new UtlVoidPtr((void*) &messageQueue); OsWriteLock lock(mObserverMutex); mConfigChangeObservers.insert(observer); } /* ============================ ACCESSORS ================================= */ void SipUserAgentBase::getContactUri(UtlString* contactUri) { contactUri->remove(0); contactUri->append(mContactAddress); } /* ============================ INQUIRY =================================== */ UtlBoolean SipUserAgentBase::isReady() { return(isStarted()); } UtlBoolean SipUserAgentBase::waitUntilReady() { // Lazy hack, should be a semaphore or event while(!isReady()) { delay(500); } return(TRUE); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ // Assignment operator SipUserAgentBase& SipUserAgentBase::operator=(const SipUserAgentBase& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } // Copy constructor SipUserAgentBase::SipUserAgentBase(const SipUserAgentBase& rSipUserAgentBase) : mObserverMutex(OsRWMutex::Q_FIFO) { } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipUserAgent.cpp0000644000175000017500000044036212205613256024260 0ustar00danieldaniel00000000000000// // Copyright (C) 2007-2010 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2008 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Daniel Petrie // SYSTEM INCLUDES //#define TEST_PRINT #include // APPLICATION INCLUDES #if defined(_WIN32) # include "resparse/wnt/nterrno.h" #elif defined(__pingtel_on_posix__) # include # include # include #endif #include #include #include #include #include #include #include #include #include #ifdef SIP_TLS #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef _WIN32 // version.h is generated as part of the build by other platforms. For // windows, the sip stack version is defined under the project settings. #include #endif #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define MAXIMUM_SIP_LOG_SIZE 100000 #define SIP_UA_LOG "sipuseragent.log" #define CONFIG_LOG_DIR SIPX_LOGDIR #ifndef VENDOR # define VENDOR "sipX" #endif #ifndef PLATFORM_UA_PARAM #if defined(_WIN32) # define PLATFORM_UA_PARAM " (WinNT)" #elif defined(_VXWORKS) # define PLATFORM_UA_PARAM " (VxWorks)" #elif defined(__APPLE__) # define PLATFORM_UA_PARAM " (Darwin)" #elif defined(ANDROID) # define PLATFORM_UA_PARAM " (Android)" #elif defined(__linux__) # define PLATFORM_UA_PARAM " (Linux)" #elif defined(sun) # define PLATFORM_UA_PARAM " (Solaris)" #endif #endif /* PLATFORM_UA_PARAM */ //#define TEST_PRINT 1 //#define LOG_TIME // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipUserAgent::SipUserAgent(int sipTcpPort, int sipUdpPort, int sipTlsPort, const char* publicAddress, const char* defaultUser, const char* defaultAddress, const char* sipProxyServers, const char* sipDirectoryServers, const char* sipRegistryServers, const char* authenticationScheme, const char* authenticateRealm, OsConfigDb* authenticateDb, OsConfigDb* authorizeUserIds, OsConfigDb* authorizePasswords, SipLineMgr* lineMgr, int sipFirstResendTimeout, UtlBoolean defaultToUaTransactions, int readBufferSize, int queueSize, UtlBoolean bUseNextAvailablePort, UtlString certNickname, UtlString certPassword, UtlString dbLocation, UtlBoolean doUaMessageChecks ) : SipUserAgentBase(sipTcpPort, sipUdpPort, sipTlsPort, queueSize) , mSipTcpServer(NULL) , mSipUdpServer(NULL) #ifdef SIP_TLS , mSipTlsServer(NULL) #endif , mMessageLogRMutex(OsRWMutex::Q_FIFO) , mMessageLogWMutex(OsRWMutex::Q_FIFO) , mpLineMgr(NULL) , mIsUaTransactionByDefault(defaultToUaTransactions) , mbUseRport(FALSE) , mUseRportMapping(TRUE) , mbUseLocationHeader(FALSE) , mbIncludePlatformInUserAgentName(TRUE) , mDoUaMessageChecks(doUaMessageChecks) , mbShuttingDown(FALSE) , mbShutdownDone(FALSE) , mRegisterTimeoutSeconds(4) , mbAllowHeader(true) , mbDateHeader(true) , mbShortNames(false) , mAcceptLanguage() , mpLastSipMessage(NULL) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUserAgent::_ sipTcpPort = %d, sipUdpPort = %d, sipTlsPort = %d", sipTcpPort, sipUdpPort, sipTlsPort); // Make SIP logging off by default mMessageLogEnabled = FALSE; // Get pointer to line manager mpLineMgr = lineMgr; // Create and start the SIP TLS, TCP and UDP Servers if (mUdpPort != PORT_NONE) { mSipUdpServer = new SipUdpServer(mUdpPort, this, readBufferSize, bUseNextAvailablePort, defaultAddress ); mSipUdpServer->startListener(); mUdpPort = mSipUdpServer->getServerPort() ; } if (mTcpPort != PORT_NONE) { mSipTcpServer = new SipTcpServer(mTcpPort, this, SIP_TRANSPORT_TCP, "SipTcpServer-%d", bUseNextAvailablePort, defaultAddress); mSipTcpServer->startListener(); mTcpPort = mSipTcpServer->getServerPort() ; } #ifdef SIP_TLS if (mTlsPort != PORT_NONE) { mSipTlsServer = new SipTlsServer(mTlsPort, this, bUseNextAvailablePort, certNickname, certPassword, dbLocation, defaultAddress); mSipTlsServer->startListener(); mTlsPort = mSipTlsServer->getServerPort() ; } #endif mMaxMessageLogSize = MAXIMUM_SIP_LOG_SIZE; mMaxForwards = SIP_DEFAULT_MAX_FORWARDS; // TCP sockets not used for an hour are garbage collected mMaxTcpSocketIdleTime = 3600; // INVITE transactions need to stick around for a minimum of // 3 minutes mMinInviteTransactionTimeout = 180; mForkingEnabled = TRUE; mRecurseOnlyOne300Contact = FALSE; // By default copy all of the Vias from incoming requests that have // a max-forwards == 0 mReturnViasForMaxForwards = TRUE; mMaxSrvRecords = 4; mDnsSrvTimeout = 4; // seconds #ifdef TEST_PRINT // Default the log on startMessageLog(); #else // Disable the message log stopMessageLog(); #endif // Authentication if(authenticationScheme) { mAuthenticationScheme.append(authenticationScheme); HttpMessage::cannonizeToken(mAuthenticationScheme); // Do not require authentication if not BASIC or DIGEST if( 0 != mAuthenticationScheme.compareTo(HTTP_BASIC_AUTHENTICATION, UtlString::ignoreCase ) && 0 !=mAuthenticationScheme.compareTo(HTTP_DIGEST_AUTHENTICATION, UtlString::ignoreCase ) ) { mAuthenticationScheme.remove(0); } } if(authenticateRealm) { mAuthenticationRealm.append(authenticateRealm); } if(authenticateDb) { mpAuthenticationDb = authenticateDb; } else { mpAuthenticationDb = new OsConfigDb(); } if(authorizeUserIds) { mpAuthorizationUserIds = authorizeUserIds; } else { mpAuthorizationUserIds = new OsConfigDb(); } if(authorizePasswords) { mpAuthorizationPasswords = authorizePasswords; } else { mpAuthorizationPasswords = new OsConfigDb(); } // SIP Server info if(sipProxyServers) { proxyServers.append(sipProxyServers); } if(sipDirectoryServers) { directoryServers.append(sipDirectoryServers); } if(defaultUser) { defaultSipUser.append(defaultUser); defaultSipUser.strip(UtlString::both); } if (!defaultAddress || strcmp(defaultAddress, "0.0.0.0") == 0) { // get the first CONTACT entry in the Db SIPX_CONTACT_ADDRESS* pContact = mContactDb.find(1); assert(pContact) ; // Bind to the contact's Ip if (pContact) { defaultSipAddress = pContact->cIpAddress; } } else { defaultSipAddress.append(defaultAddress); sipIpAddress.append(defaultAddress); } if(sipRegistryServers) { registryServers.append(sipRegistryServers); } if(publicAddress && *publicAddress) { mConfigPublicAddress = publicAddress ; // make a config CONTACT entry UtlString adapterName; SIPX_CONTACT_ADDRESS contact; contact.eContactType = CONTACT_CONFIG; strcpy(contact.cIpAddress, publicAddress); if (getContactAdapterName(adapterName, defaultSipAddress, false)) { strcpy(contact.cInterface, adapterName.data()); } else { // If getContactAdapterName can't find an adapter. OsSysLog::add(FAC_SIP, PRI_WARNING, "SipUserAgent::_ no adapter found for address '%s'", defaultSipAddress.data()); strcpy(contact.cInterface, "(unknown)"); } contact.iPort = mUdpPort; // what about the TCP port? contact.eTransportType = TRANSPORT_UDP; // what about TCP transport? addContactAddress(contact); } else { sipIpAddress = defaultSipAddress; } mSipPort = PORT_NONE; UtlString hostIpAddress(sipIpAddress.data()); //Timers if ( sipFirstResendTimeout <= 0) { mFirstResendTimeoutMs = SIP_DEFAULT_RTT; } else if ( sipFirstResendTimeout > 0 && sipFirstResendTimeout < 100) { mFirstResendTimeoutMs = SIP_MINIMUM_RTT; } else { mFirstResendTimeoutMs = sipFirstResendTimeout; } mLastResendTimeoutMs = 8 * mFirstResendTimeoutMs; mReliableTransportTimeoutMs = 2 * mLastResendTimeoutMs; mTransactionStateTimeoutMs = 10 * mLastResendTimeoutMs; // How long before we expire transactions by default mDefaultExpiresSeconds = 180; // mTransactionStateTimeoutMs / 1000; mDefaultSerialExpiresSeconds = 20; if(portIsValid(mUdpPort)) { SipMessage::buildSipUrl(&mContactAddress, hostIpAddress.data(), (mUdpPort == SIP_PORT) ? PORT_NONE : mUdpPort, (mUdpPort == mTcpPort) ? "" : SIP_TRANSPORT_UDP, defaultSipUser.data()); #ifdef TEST_PRINT osPrintf("UDP default contact: \"%s\"\n", mContactAddress.data()); #endif } if(portIsValid(mTcpPort) && mTcpPort != mUdpPort) { SipMessage::buildSipUrl(&mContactAddress, hostIpAddress.data(), (mTcpPort == SIP_PORT) ? PORT_NONE : mUdpPort, SIP_TRANSPORT_TCP, defaultSipUser.data()); #ifdef TEST_PRINT osPrintf("TCP default contact: \"%s\"\n", mContactAddress.data()); #endif } // Initialize the transaction id seed SipTransaction::smBranchIdBase = mContactAddress; // Allow the default SIP methods allowMethod(SIP_INVITE_METHOD); allowMethod(SIP_ACK_METHOD); allowMethod(SIP_CANCEL_METHOD); allowMethod(SIP_BYE_METHOD); allowMethod(SIP_REFER_METHOD); allowMethod(SIP_OPTIONS_METHOD); allowMethod(SIP_PING_METHOD); defaultUserAgentName.append( VENDOR ); defaultUserAgentName.append( "/" ); defaultUserAgentName.append( SIP_STACK_VERSION ); OsMsgQ* incomingQ = getMessageQueue(); mpTimer = new OsTimer(incomingQ, 0); // Convert from mSeconds to uSeconds OsTime lapseTime(0, mTransactionStateTimeoutMs * 1000); mpTimer->periodicEvery(lapseTime, lapseTime); OsTime time; OsDateTime::getCurTimeSinceBoot(time); mLastCleanUpTime = time.seconds(); // bandreasen: This was removed on main -- not sure why // given that this boolean is passed in mIsUaTransactionByDefault = defaultToUaTransactions; } // Copy constructor SipUserAgent::SipUserAgent(const SipUserAgent& rSipUserAgent) : mMessageLogRMutex(OsRWMutex::Q_FIFO), mMessageLogWMutex(OsRWMutex::Q_FIFO) , mbAllowHeader(false) , mbDateHeader(false) , mbShortNames(false) , mAcceptLanguage() , mRegisterTimeoutSeconds(4) { } // Destructor SipUserAgent::~SipUserAgent() { mpTimer->stop(); delete mpTimer; mpTimer = NULL; OsSysLog::add(FAC_SIP, PRI_INFO, "SipUserAgent::~SipUserAgent waitUntilShutDown"); OsSysLog::flush(); // Wait until this OsServerTask has stopped or handleMethod // might access something we are about to delete here. waitUntilShutDown(); if(mSipTcpServer) { OsSysLog::add(FAC_SIP, PRI_INFO, "SipUserAgent::~SipUserAgent shutting down mSipTcpServer"); OsSysLog::flush(); mSipTcpServer->shutdownListener(); mSipTcpServer->requestShutdown(); delete mSipTcpServer; mSipTcpServer = NULL; } if(mSipUdpServer) { OsSysLog::add(FAC_SIP, PRI_INFO, "SipUserAgent::~SipUserAgent shutting down mSipUdpServer"); OsSysLog::flush(); mSipUdpServer->shutdownListener(); mSipUdpServer->requestShutdown(); delete mSipUdpServer; mSipUdpServer = NULL; } #ifdef SIP_TLS if(mSipTlsServer) { OsSysLog::add(FAC_SIP, PRI_INFO, "SipUserAgent::~SipUserAgent shutting down mSipTlsServer"); OsSysLog::flush(); mSipTlsServer->shutdownListener(); mSipTlsServer->requestShutdown(); delete mSipTlsServer; mSipTlsServer = NULL; } #endif OsSysLog::add(FAC_SIP, PRI_INFO, "SipUserAgent::~SipUserAgent deleting databases"); OsSysLog::flush(); if(mpAuthenticationDb) { delete mpAuthenticationDb; mpAuthenticationDb = NULL; } if(mpAuthorizationUserIds) { delete mpAuthorizationUserIds; mpAuthorizationUserIds = NULL; } if(mpAuthorizationPasswords) { delete mpAuthorizationPasswords; mpAuthorizationPasswords = NULL; } allowedSipMethods.destroyAll(); mMessageObservers.destroyAll(); allowedSipExtensions.destroyAll(); OsSysLog::add(FAC_SIP, PRI_INFO, "SipUserAgent::~SipUserAgent exiting"); OsSysLog::flush(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipUserAgent& SipUserAgent::operator=(const SipUserAgent& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } void SipUserAgent::shutdown(UtlBoolean blockingShutdown) { OsSysLog::add(FAC_SIP, PRI_INFO, "SipUserAgent::shutdown(blocking=%s) starting shutdown", blockingShutdown ? "TRUE" : "FALSE"); OsSysLog::flush(); mbShuttingDown = TRUE; mSipTransactions.stopTransactionTimers(); if(blockingShutdown == TRUE) { OsEvent shutdownEvent; OsStatus res; intptr_t rpcRetVal; mbBlockingShutdown = TRUE; OsRpcMsg shutdownMsg(OsMsg::PHONE_APP, SipUserAgent::SHUTDOWN_MESSAGE, shutdownEvent); postMessage(shutdownMsg); OsSysLog::add(FAC_SIP, PRI_INFO, "SipUserAgent::shutdown waiting for shutdown to complete"); OsSysLog::flush(); res = shutdownEvent.wait(); OsSysLog::add(FAC_SIP, PRI_INFO, "SipUserAgent::shutdown shutdown complete wait status=%d", res); OsSysLog::flush(); assert(res == OS_SUCCESS); res = shutdownEvent.getEventData(rpcRetVal); OsSysLog::add(FAC_SIP, PRI_INFO, "SipUserAgent::shutdown shutdown event status=%d", rpcRetVal); OsSysLog::flush(); assert(res == OS_SUCCESS && rpcRetVal == OS_SUCCESS); mbShutdownDone = TRUE; } else { mbBlockingShutdown = FALSE; OsMsg shutdownMsg(OsMsg::PHONE_APP, SipUserAgent::SHUTDOWN_MESSAGE); postMessage(shutdownMsg); } OsSysLog::add(FAC_SIP, PRI_INFO, "SipUserAgent::shutdown exiting shutdown"); OsSysLog::flush(); } void SipUserAgent::enableStun(const char* szStunServer, int iStunPort, int refreshPeriodInSecs, OsNotification* pNotification, const char* szIp) { if (mSipUdpServer) { mSipUdpServer->enableStun(szStunServer, iStunPort, szIp, refreshPeriodInSecs, pNotification) ; } } void SipUserAgent::addMessageConsumer(OsServerTask* messageEventListener) { // Need to do the real thing by keeping a list of consumers // and putting a mutex around the add to list //if(messageListener) //{ // osPrintf("WARNING: message consumer is NOT a LIST\n"); //} //messageListener = messageEventListener; if(messageEventListener) { addMessageObserver(*(messageEventListener->getMessageQueue())); } } void SipUserAgent::addMessageObserver(OsMsgQ& messageQueue, const char* sipMethod, UtlBoolean wantRequests, UtlBoolean wantResponses, UtlBoolean wantIncoming, UtlBoolean wantOutGoing, const char* eventName, SipSession* pSession, void* observerData) { SipObserverCriteria* observer = new SipObserverCriteria(observerData, &messageQueue, sipMethod, wantRequests, wantResponses, wantIncoming, wantOutGoing, eventName, pSession); { // Add the observer and its filter criteria to the list lock scope OsWriteLock lock(mObserverMutex); mMessageObservers.insert(observer); // Allow the specified method if(sipMethod && *sipMethod && wantRequests) allowMethod(sipMethod); } } UtlBoolean SipUserAgent::removeMessageObserver(OsMsgQ& messageQueue, void* pObserverData /*=NULL*/) { OsWriteLock lock(mObserverMutex); SipObserverCriteria* pObserver = NULL ; UtlBoolean bRemovedObservers = FALSE ; // Traverse all of the observers and remove any that match the // message queue/observer data. If the pObserverData is null, all // matching message queue/observers will be removed. Otherwise, only // those observers that match both the message queue and observer data // are removed. UtlHashBagIterator iterator(mMessageObservers); while ((pObserver = (SipObserverCriteria*) iterator())) { if (pObserver->getObserverQueue() == &messageQueue) { if ((pObserverData == NULL) || (pObserverData == pObserver->getObserverData())) { bRemovedObservers = true ; UtlContainable* wasRemoved = mMessageObservers.removeReference(pObserver); if(wasRemoved) { delete wasRemoved; } } } } return bRemovedObservers ; } void SipUserAgent::allowMethod(const char* methodName, const bool bAllow) { if(methodName) { UtlString matchName(methodName); // Do not add the name if it is already in there if(NULL == allowedSipMethods.find(&matchName)) { if (bAllow) { allowedSipMethods.append(new UtlString(methodName)); } } else { if (!bAllow) { allowedSipMethods.destroy(allowedSipMethods.find(&matchName)); } } } } UtlBoolean SipUserAgent::send(SipMessage& message, OsMsgQ* responseListener, void* responseListenerData, SIPX_TRANSPORT_DATA* pTransport) { if(mbShuttingDown) { return FALSE; } UtlBoolean sendSucceeded = FALSE; UtlBoolean isResponse = message.isResponse(); mpLastSipMessage = &message; // =========================================== // Do all the stuff that does not require transaction locking first // Make sure the date field is set long epochDate; if(!message.getDateField(&epochDate) && mbDateHeader) { message.setDateField(); } if (mbUseLocationHeader) { message.setLocationField(mLocationHeader.data()); } // Make sure the message includes a contact if required and // update it to the best possible known contact. prepareContact(message, NULL, NULL) ; // Get Method UtlString method; if(isResponse) { int num = 0; message.getCSeqField(&num , &method); } else { message.getRequestMethod(&method); // Make sure that max-forwards is set int maxForwards; if(!message.getMaxForwards(maxForwards)) { message.setMaxForwards(mMaxForwards); } } // =========================================== // Do the stuff that requires the transaction type knowledge // i.e. UA verse proxy transaction if(!isResponse) { // This should always be true now: if(message.isFirstSend()) { // Save the transaction listener info if (responseListener) { message.setResponseListenerQueue(responseListener); } if (responseListenerData) { message.setResponseListenerData(responseListenerData); } } // This is not the first time this message has been sent else { // Should not be getting here. OsSysLog::add(FAC_SIP, PRI_WARNING, "SipUserAgent::send message being resent"); } } // =========================================== // Find or create a transaction: UtlBoolean isUaTransaction = TRUE; enum SipTransaction::messageRelationship relationship; //mSipTransactions.lock(); #if 0 // TODO enable only for transaction match debugging - log is confusing otherwise OsSysLog::add(FAC_SIP, PRI_DEBUG ,"SipUserAgent::send searching for existing transaction" ); #endif // verify that the transaction does not already exist SipTransaction* transaction = mSipTransactions.findTransactionFor( message, TRUE, // outgoing relationship); // Found a transaction for this message if(transaction) { isUaTransaction = transaction->isUaTransaction(); // Response for which a transaction already exists if(isResponse) { if(isUaTransaction) { // It seems that the polite thing to do is to add the // allowed methods to all final responses UtlString allowedMethodsSet; if(message.getResponseStatusCode() >= SIP_OK_CODE && !message.getAllowField(allowedMethodsSet) && mbAllowHeader && mbAllowHeader) { UtlString allowedMethods; getAllowedMethods(&allowedMethods); message.setAllowField(allowedMethods); } } } // Request for which a transaction already exists else { // should not get here unless this is a CANCEL or ACK // request if((method.compareTo(SIP_CANCEL_METHOD) == 0) || (method.compareTo(SIP_ACK_METHOD) == 0)) { } // A request for which a transaction already exists // other than ACK and CANCEL else { // Should not be getting here OsSysLog::add(FAC_SIP, PRI_WARNING, "SipUserAgent::send %s request matches existing transaction", method.data()); // We pretend there is no match so this becomes a // new transaction branch. Make sure we unlock the // transaction before we reset to NULL. mSipTransactions.markAvailable(*transaction); transaction = NULL; } } } // No existing transaction for this message if(transaction == NULL) { if(isResponse) { // Should not get here except possibly on a server OsSysLog::add(FAC_SIP, PRI_WARNING, "SipUserAgent::send response without an existing transaction" ); } else { // If there is already a via in the request this must // be a proxy transaction UtlString viaField; SipTransaction* parentTransaction = NULL; enum SipTransaction::messageRelationship parentRelationship; if(message.getViaField(&viaField, 0)) { isUaTransaction = FALSE; // See if there is a parent server proxy transaction #if 0 // TODO enable only for transaction match debugging - log is confusing otherwise OsSysLog::add(FAC_SIP, PRI_DEBUG ,"SipUserAgent::send searching for parent transaction" ); #endif parentTransaction = mSipTransactions.findTransactionFor(message, FALSE, // incoming parentRelationship); } // Create a new transactions // This should only be for requests transaction = new SipTransaction(&message, TRUE, isUaTransaction); transaction->markBusy(); mSipTransactions.addTransaction(transaction); if(!isUaTransaction && parentTransaction) { if(parentRelationship == SipTransaction::MESSAGE_DUPLICATE) { // Link the parent server transaction to the // child client transaction parentTransaction->linkChild(*transaction); // The parent will be unlocked with the transaction } else { UtlString parentRelationshipString; SipTransaction::getRelationshipString(parentRelationship, parentRelationshipString); OsSysLog::add(FAC_SIP, PRI_WARNING, "SipUserAgent::send proxied client transaction not " "part of server transaction, parent relationship: %s", parentRelationshipString.data()); if(parentTransaction) { mSipTransactions.markAvailable(*parentTransaction); } } } else if(!isUaTransaction) { // this happens all the time in the authproxy, so log only at debug OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUserAgent::send proxied client transaction does not have parent"); } else if(parentTransaction) { mSipTransactions.markAvailable(*parentTransaction); } relationship = SipTransaction::MESSAGE_UNKNOWN; } } if(transaction) { // Make sure the User Agent field is set if(isUaTransaction) { setSelfHeader(message); // Make sure the accept language is set UtlString language; message.getAcceptLanguageField(&language); if(language.isNull() && !mAcceptLanguage.isNull()) { // Beware that this value does not describe the desired media // sessions, but rather the preferred languages for reason // phrases, etc. (RFC 3261 sec. 20.3) Thus, it is useful to // have a value for this header even in requests like // SUBSCRIBE/NOTIFY which are expected to not be seen by a human. // This value should be configurable, though. message.setAcceptLanguageField(mAcceptLanguage); } // add allow field to Refer and Invite request . It is // mandatory for refer method UtlString allowedMethodsSet; if ( ! message.getAllowField(allowedMethodsSet) && ( method.compareTo(SIP_REFER_METHOD) == 0 || method.compareTo(SIP_INVITE_METHOD) == 0 ) ) { if (mbAllowHeader) { UtlString allowedMethods; getAllowedMethods(&allowedMethods); message.setAllowField(allowedMethods); } } // Set the supported extensions if this is not // an ACK or NOTIFY request and the Supported field // is not already set. if( method.compareTo(SIP_ACK_METHOD) != 0 && method.compareTo(SIP_NOTIFY_METHOD) != 0 && !message.getHeaderValue(0, SIP_SUPPORTED_FIELD) ) { UtlString supportedExtensions; getSupportedExtensions(supportedExtensions); if (supportedExtensions.length() > 0) { message.setSupportedField(supportedExtensions.data()); } } } // If this is the top most parent and it is a client transaction // There is no server transaction, so cancel all of the children if( !isResponse && (method.compareTo(SIP_CANCEL_METHOD) == 0) && transaction->getTopMostParent() == NULL && !transaction->isServerTransaction() ) { transaction->cancel(*this, mSipTransactions); } else { // All other messages just get sent. // check for external transport bool bDummy; UtlString transport = message.getTransportName(bDummy); if (!pTransport) { UtlString localIp = message.getLocalIp(); int dummy; if (localIp.length() < 1) { getLocalAddress(&localIp, &dummy, TRANSPORT_UDP); } pTransport = (SIPX_TRANSPORT_DATA*)lookupExternalTransport(transport, localIp); } sendSucceeded = transaction->handleOutgoing(message, *this, mSipTransactions, relationship, pTransport); } mSipTransactions.markAvailable(*transaction); } else { OsSysLog::add(FAC_SIP, PRI_ERR,"SipUserAgent::send failed to construct new transaction"); } return(sendSucceeded); } UtlBoolean SipUserAgent::sendUdp(SipMessage* message, const char* serverAddress, int port) { UtlBoolean isResponse = message->isResponse(); UtlString method; int seqNum; UtlString seqMethod; int responseCode = 0; UtlBoolean sentOk = FALSE; UtlString msgBytes; UtlString messageStatusString = "SipUserAgent::sendUdp "; int timesSent = message->getTimesSent(); prepareContact(*message, serverAddress, &port) ; if(!isResponse) { message->getRequestMethod(&method); } else { message->getCSeqField(&seqNum, &seqMethod); responseCode = message->getResponseStatusCode(); } if(timesSent == 0) { #ifdef TEST_PRINT osPrintf("First UDP send of message\n"); #endif message->touchTransportTime(); #ifdef TEST_PRINT osPrintf("SipUserAgent::sendUdp Sending UDP message\n"); #endif } // get the message if it was previously sent. else { char buffer[20]; sprintf(buffer, "%d", timesSent); messageStatusString.append("resend "); messageStatusString.append(buffer); messageStatusString.append(" of UDP message\n"); } // Send the message if (mbShortNames || message->getUseShortFieldNames()) { message->replaceLongFieldNames(); } // Disallow an address begining with * as it gets broadcasted on NT if(! strchr(serverAddress, '*') && *serverAddress) { sentOk = mSipUdpServer->send(message, serverAddress, port); } else if(*serverAddress == '\0') { // Only bother processing if the logs are enabled if ( isMessageLoggingEnabled() || OsSysLog::willLog(FAC_SIP_OUTGOING, PRI_INFO)) { UtlString msgBytes; int msgLen; message->getBytes(&msgBytes, &msgLen); msgBytes.insert(0, "No send address\n"); msgBytes.append("--------------------END--------------------\n"); logMessage(msgBytes.data(), msgBytes.length()); OsSysLog::add(FAC_SIP_OUTGOING, PRI_INFO, "%s", msgBytes.data()); } sentOk = FALSE; } else { sentOk = FALSE; } #ifdef TEST_PRINT osPrintf("SipUserAgent::sendUdp sipUdpServer send returned: %d\n", sentOk); osPrintf("SipUserAgent::sendUdp isResponse: %d method: %s seqmethod: %s responseCode: %d\n", isResponse, method.data(), seqMethod.data(), responseCode); #endif // If we have not failed schedule a resend if(sentOk) { messageStatusString.append("UDP SIP User Agent sent message:\n"); messageStatusString.append("----Remote Host:"); messageStatusString.append(serverAddress); messageStatusString.append("---- Port: "); char buff[10]; sprintf(buff, "%d", !portIsValid(port) ? 5060 : port); messageStatusString.append(buff); messageStatusString.append("----\n"); #ifdef TEST_PRINT osPrintf("%s", messageStatusString.data()); #endif } else { messageStatusString.append("UDP SIP User Agent failed to send message:\n"); messageStatusString.append("----Remote Host:"); messageStatusString.append(serverAddress); messageStatusString.append("---- Port: "); char buff[10]; sprintf(buff, "%d", !portIsValid(port) ? 5060 : port); messageStatusString.append(buff); messageStatusString.append("----\n"); message->logTimeEvent("FAILED"); } // Only bother processing if the logs are enabled if ( isMessageLoggingEnabled() || OsSysLog::willLog(FAC_SIP_OUTGOING, PRI_INFO)) { int len; message->getBytes(&msgBytes, &len); msgBytes.insert(0, messageStatusString.data()); msgBytes.append("--------------------END--------------------\n"); #ifdef TEST_PRINT osPrintf("%s", msgBytes.data()); #endif logMessage(msgBytes.data(), msgBytes.length()); if (msgBytes.length()) { OsSysLog::add(FAC_SIP_OUTGOING, PRI_INFO, "%s", msgBytes.data()); } } // if we failed to send it is the calling functions problem to deal with the error return(sentOk); } UtlBoolean SipUserAgent::sendSymmetricUdp(SipMessage& message, const char* serverAddress, int port) { prepareContact(message, serverAddress, &port) ; // Update Via int bestKnownPort; UtlString bestKnownAddress; getViaInfo(OsSocket::UDP, bestKnownAddress, bestKnownPort, serverAddress, &port) ; message.removeLastVia() ; message.addVia(bestKnownAddress, bestKnownPort, SIP_TRANSPORT_UDP); message.setLastViaTag("", "rport"); // Send away UtlBoolean sentOk = mSipUdpServer->sendTo(message, serverAddress, port); // Don't bother processing unless the logs are enabled if ( isMessageLoggingEnabled() || OsSysLog::willLog(FAC_SIP_OUTGOING, PRI_INFO)) { UtlString msgBytes; int msgLen; message.getBytes(&msgBytes, &msgLen); UtlString outcomeMsg; char portString[20]; sprintf(portString, "%d", !portIsValid(port) ? 5060 : port); if(sentOk) { outcomeMsg.append("UDP SIP User Agent sentTo message:\n----Remote Host:"); outcomeMsg.append(serverAddress); outcomeMsg.append("---- Port: "); outcomeMsg.append(portString); outcomeMsg.append("----\n"); msgBytes.insert(0, outcomeMsg); msgBytes.append("--------------------END--------------------\n"); } else { outcomeMsg.append("SIP User agent FAILED sendTo message:\n----Remote Host:"); outcomeMsg.append(serverAddress); outcomeMsg.append("---- Port: "); outcomeMsg.append(portString); outcomeMsg.append("----\n"); msgBytes.insert(0, outcomeMsg); msgBytes.append("--------------------END--------------------\n"); } logMessage(msgBytes.data(), msgBytes.length()); OsSysLog::add(FAC_SIP_OUTGOING, PRI_INFO, "%s", msgBytes.data()); } return(sentOk); } UtlBoolean SipUserAgent::sendCustom(SIPX_TRANSPORT_DATA* pTransport, SipMessage* message, const char* sendAddress, const int sendPort) { UtlBoolean bSent(false); UtlString bytes; int length; message->getBytes(&bytes, &length); if (!pTransport) { bool bCustom = false; const UtlString transportName = message->getTransportName(bCustom); if (bCustom) { pTransport = (SIPX_TRANSPORT_DATA*)lookupExternalTransport(transportName, message->getLocalIp()); } } if (pTransport) { if (pTransport->bRouteByUser) { UtlString from, to ; Url fromUrl, toUrl ; UtlString temp ; /* * Routing by "user" mode is a bit odd. Ideally, we return the * identity of the user (user@domain) without a port value. * However, if we only have hostname, we will return just that * (as opposed to "@hostname" which getIndentity returns). */ message->getFromUrl(message->isResponse() ? toUrl : fromUrl) ; message->getToUrl(message->isResponse() ? fromUrl : toUrl) ; // Parse From routing id fromUrl.setHostPort(-1) ; fromUrl.getUserId(temp) ; if (temp.isNull()) fromUrl.getHostAddress(from) ; else { fromUrl.getUserId(from) ; } // Parse To routing it toUrl.setHostPort(-1) ; toUrl.getUserId(temp) ; if (temp.isNull()) toUrl.getHostAddress(to) ; else { toUrl.getHostAddress(temp) ; if (temp.compareTo("aol.com", UtlString::ignoreCase) == 0) toUrl.getUserId(to) ; else toUrl.getIdentity(to) ; } if (OsSysLog::willLog(FAC_SIP_CUSTOM, PRI_DEBUG)) { UtlString data((const char*) bytes.data(), length) ; OsSysLog::add(FAC_SIP_CUSTOM, PRI_DEBUG, "[Sent] From: %s To: %s\r\n%s\r\n", from.data(), to.data(), data.data()) ; } bSent = pTransport->pFnWriteProc(pTransport->hTransport, to.data(), -1, from.data(), -1, (void*)bytes.data(), length, pTransport->pUserData); } else { if (OsSysLog::willLog(FAC_SIP_CUSTOM, PRI_DEBUG)) { UtlString data((const char*) bytes.data(), length) ; OsSysLog::add(FAC_SIP_CUSTOM, PRI_DEBUG, "[Sent] From: %s To: %s\r\n%s\r\n", pTransport->szLocalIp, sendAddress, data.data()) ; } bSent = pTransport->pFnWriteProc(pTransport->hTransport, sendAddress, sendPort, pTransport->szLocalIp, pTransport->iLocalPort, (void*)bytes.data(), length, pTransport->pUserData); } } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipUserAgent::sendCustom - no external transport record found"); } return bSent; } UtlBoolean SipUserAgent::sendStatelessResponse(SipMessage& rresponse) { UtlBoolean sendSucceeded = FALSE; // Forward via the server transaction SipMessage responseCopy(rresponse); responseCopy.removeLastVia(); responseCopy.resetTransport(); responseCopy.clearDNSField(); UtlString sendProtocol; UtlString sendAddress; int sendPort; int receivedPort; UtlBoolean receivedSet; UtlBoolean maddrSet; UtlBoolean receivedPortSet; // use the via as the place to send the response responseCopy.getLastVia(&sendAddress, &sendPort, &sendProtocol, &receivedPort, &receivedSet, &maddrSet, &receivedPortSet); // If the sender of the request indicated support of // rport (i.e. received port) send this response back to // the same port it came from if(portIsValid(receivedPort) && receivedPortSet) { sendPort = receivedPort; } if(sendProtocol.compareTo(SIP_TRANSPORT_UDP, UtlString::ignoreCase) == 0) { sendSucceeded = sendUdp(&responseCopy, sendAddress.data(), sendPort); } else if(sendProtocol.compareTo(SIP_TRANSPORT_TCP, UtlString::ignoreCase) == 0) { sendSucceeded = sendTcp(&responseCopy, sendAddress.data(), sendPort); } #ifdef SIP_TLS else if(sendProtocol.compareTo(SIP_TRANSPORT_TLS, UtlString::ignoreCase) == 0) { sendSucceeded = sendTls(&responseCopy, sendAddress.data(), sendPort); } #endif else // must be custom { sendSucceeded = sendCustom(NULL, &responseCopy, sendAddress.data(), sendPort); } return(sendSucceeded); } UtlBoolean SipUserAgent::sendStatelessRequest(SipMessage& request, UtlString& address, int port, OsSocket::IpProtocolSocketType protocol, UtlString& branchId) { // Convert the enum to a protocol string UtlString viaProtocolString; SipMessage::convertProtocolEnumToString(protocol, viaProtocolString); // Get via info UtlString viaAddress; int viaPort; getViaInfo(protocol, viaAddress, viaPort, address.data(), &port); // Add the via field data request.addVia(viaAddress.data(), viaPort, viaProtocolString, branchId.data()); // Send using the correct protocol UtlBoolean sendSucceeded = FALSE; if(protocol == OsSocket::UDP) { sendSucceeded = sendUdp(&request, address.data(), port); } else if(protocol == OsSocket::TCP) { sendSucceeded = sendTcp(&request, address.data(), port); } #ifdef SIP_TLS else if(protocol == OsSocket::SSL_SOCKET) { sendSucceeded = sendTls(&request, address.data(), port); } #endif else if (protocol >= OsSocket::CUSTOM) { sendSucceeded = sendCustom(NULL, &request, address.data(), port); } return(sendSucceeded); } UtlBoolean SipUserAgent::sendTcp(SipMessage* message, const char* serverAddress, int port) { UtlBoolean sendSucceeded = FALSE; int len; UtlString msgBytes; UtlString messageStatusString = "SipUserAgent::sendTcp "; if (mbShortNames || message->getUseShortFieldNames()) { message->replaceLongFieldNames(); } // Disallow an address begining with * as it gets broadcasted on NT if(!strchr(serverAddress,'*') && *serverAddress) { if (mSipTcpServer) { sendSucceeded = mSipTcpServer->send(message, serverAddress, port); } } else if(*serverAddress == '\0') { if ( isMessageLoggingEnabled() || OsSysLog::willLog(FAC_SIP_OUTGOING, PRI_INFO)) { message->getBytes(&msgBytes, &len); msgBytes.insert(0, "No send address\n"); msgBytes.append("--------------------END--------------------\n"); logMessage(msgBytes.data(), msgBytes.length()); OsSysLog::add(FAC_SIP_OUTGOING, PRI_INFO, "%s", msgBytes.data()); } sendSucceeded = FALSE; } else { sendSucceeded = FALSE; } if(sendSucceeded) { messageStatusString.append("TCP SIP User Agent sent message:\n"); //osPrintf("%s", messageStatusString.data()); } else { messageStatusString.append("TCP SIP User Agent failed to send message:\n"); //osPrintf("%s", messageStatusString.data()); message->logTimeEvent("FAILED"); } if ( isMessageLoggingEnabled() || OsSysLog::willLog(FAC_SIP_OUTGOING, PRI_INFO) ) { message->getBytes(&msgBytes, &len); messageStatusString.append("----Remote Host:"); messageStatusString.append(serverAddress); messageStatusString.append("---- Port: "); char buff[10]; sprintf(buff, "%d", !portIsValid(port) ? 5060 : port); messageStatusString.append(buff); messageStatusString.append("----\n"); msgBytes.insert(0, messageStatusString.data()); msgBytes.append("--------------------END--------------------\n"); #ifdef TEST_PRINT osPrintf("%s", msgBytes.data()); #endif logMessage(msgBytes.data(), msgBytes.length()); OsSysLog::add(FAC_SIP_OUTGOING , PRI_INFO, "%s", msgBytes.data()); } return(sendSucceeded); } UtlBoolean SipUserAgent::sendTls(SipMessage* message, const char* serverAddress, int port) { #ifdef SIP_TLS int sendSucceeded = FALSE; int len; UtlString msgBytes; UtlString messageStatusString; if (mbShortNames || message->getUseShortFieldNames()) { message->replaceLongFieldNames(); } // Disallow an address begining with * as it gets broadcasted on NT if(!strchr(serverAddress,'*') && *serverAddress) { sendSucceeded = mSipTlsServer->send(message, serverAddress, port); } else if(*serverAddress == '\0') { if ( isMessageLoggingEnabled() || OsSysLog::willLog(FAC_SIP_OUTGOING, PRI_INFO)) { message->getBytes(&msgBytes, &len); msgBytes.insert(0, "No send address\n"); msgBytes.append("--------------------END--------------------\n"); logMessage(msgBytes.data(), msgBytes.length()); OsSysLog::add(FAC_SIP_OUTGOING, PRI_INFO, "%s", msgBytes.data()); } sendSucceeded = FALSE; } else { sendSucceeded = FALSE; } if(sendSucceeded) { messageStatusString.append("TLS SIP User Agent sent message:\n"); //osPrintf("%s", messageStatusString.data()); } else { messageStatusString.append("TLS SIP User Agent failed to send message:\n"); //osPrintf("%s", messageStatusString.data()); message->logTimeEvent("FAILED"); } if ( isMessageLoggingEnabled() || OsSysLog::willLog(FAC_SIP_OUTGOING, PRI_INFO)) { message->getBytes(&msgBytes, &len); messageStatusString.append("----Remote Host:"); messageStatusString.append(serverAddress); messageStatusString.append("---- Port: "); char buff[10]; sprintf(buff, "%d", !portIsValid(port) ? 5060 : port); messageStatusString.append(buff); messageStatusString.append("----\n"); msgBytes.insert(0, messageStatusString.data()); msgBytes.append("--------------------END--------------------\n"); #ifdef TEST_PRINT osPrintf("%s", msgBytes.data()); #endif logMessage(msgBytes.data(), msgBytes.length()); OsSysLog::add(FAC_SIP_OUTGOING , PRI_INFO, "%s", msgBytes.data()); } return(sendSucceeded); #else return FALSE ; #endif } void SipUserAgent::dispatch(SipMessage* message, int messageType, SIPX_TRANSPORT_DATA* pTransport) { if(mbShuttingDown) { delete message; return; } int len; UtlString msgBytes; UtlString messageStatusString; UtlBoolean resentWithAuth = FALSE; UtlBoolean isResponse = message->isResponse(); UtlBoolean shouldDispatch = FALSE; SipMessage* delayedDispatchMessage = NULL; #ifdef LOG_TIME OsTimeLog eventTimes; eventTimes.addEvent("start"); #endif // Get the message bytes for logging before the message is // potentially deleted or nulled out. if ( isMessageLoggingEnabled() || OsSysLog::willLog(FAC_SIP_INCOMING_PARSED, PRI_DEBUG) || OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { message->getBytes(&msgBytes, &len); } if (isResponse) { UtlString viaAddr ; int viaPort = -1 ; int receivedPort = -1 ; UtlString viaProtocol ; UtlBoolean receivedSet = false ; UtlBoolean maddrSet = false ; UtlBoolean receivedPortSet = false ; message->getLastVia(&viaAddr, &viaPort, &viaProtocol, &receivedPort, &receivedSet, &maddrSet, &receivedPortSet) ; if (mUseRportMapping && (receivedSet || receivedPortSet)) { UtlString sendAddress ; int sendPort ; if (receivedPortSet && portIsValid(receivedPort)) { viaPort = receivedPort ; } // Inform NAT agent (used for lookups) message->getSendAddress(&sendAddress, &sendPort) ; OsNatAgentTask::getInstance()->addExternalBinding(NULL, sendAddress, sendPort, viaAddr, viaPort) ; // Inform UDP server (used for events) if (mSipUdpServer) { UtlString method ; int cseq; message->getCSeqField(&cseq, &method); mSipUdpServer->updateSipKeepAlive(message->getLocalIp(), method, sendAddress, sendPort, viaAddr, viaPort) ; } } else { UtlString sendAddress ; int sendPort ; message->getSendAddress(&sendAddress, &sendPort) ; OsNatAgentTask::getInstance()->clearExternalBinding(NULL, sendAddress, sendPort, true) ; } } if(messageType == SipMessageEvent::APPLICATION) { #ifdef TEST_PRINT osPrintf("SIP User Agent received message via protocol: %d\n", message->getSendProtocol()); message->logTimeEvent("DISPATCHING"); #endif UtlBoolean isUaTransaction = mIsUaTransactionByDefault; enum SipTransaction::messageRelationship relationship; SipTransaction* transaction = mSipTransactions.findTransactionFor(*message, FALSE, // incoming relationship); #ifdef LOG_TIME eventTimes.addEvent("found TX"); #endif if(transaction == NULL) { if(isResponse) { OsSysLog::add(FAC_SIP, PRI_WARNING,"SipUserAgent::dispatch " "received response without transaction"); #ifdef TEST_PRINT if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "=Response w/o request=>\n%s\n======================>\n", msgBytes.data()); UtlString transString; mSipTransactions.toStringWithRelations(transString, *message, FALSE); OsSysLog::add(FAC_SIP, PRI_DEBUG, "Transaction list:\n%s\n===End transaction list===", transString.data()); } #endif } // New transaction for incoming request else { transaction = new SipTransaction(message, FALSE /* incoming */, isUaTransaction); // Add the new transaction to the list transaction->markBusy(); mSipTransactions.addTransaction(transaction); UtlString method; message->getRequestMethod(&method); if(method.compareTo(SIP_ACK_METHOD) == 0) { // This may be normal - it will occur whenever the ACK is not traversing // the same proxy where the transaction is completing was origniated. // This happens on each call setup in the authproxy, for example, because // the original transaction was in the forking proxy. relationship = SipTransaction::MESSAGE_ACK; OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUserAgent::dispatch received ACK without transaction"); } else if(method.compareTo(SIP_CANCEL_METHOD) == 0) { relationship = SipTransaction::MESSAGE_CANCEL; OsSysLog::add(FAC_SIP, PRI_WARNING, "SipUserAgent::dispatch received CANCEL without transaction"); } else { relationship = SipTransaction::MESSAGE_REQUEST; } } } #ifdef LOG_TIME eventTimes.addEvent("handling TX"); #endif // This is a message that was already recieved once if ( transaction && relationship == SipTransaction::MESSAGE_DUPLICATE ) { // Resends of final INVITE responses need to be // passed through if they are 2xx class or the ACk // needs to be resent if it was a failure (i.e. 3xx,4xx,5xx,6xx) if(message->isResponse()) { int responseCode = message->getResponseStatusCode(); UtlString transactionMethod; int respCseq; message->getCSeqField(&respCseq, &transactionMethod); if ( responseCode >= SIP_2XX_CLASS_CODE && transactionMethod.compareTo(SIP_INVITE_METHOD) == 0 ) { transaction->handleIncoming(*message, *this, relationship, mSipTransactions, delayedDispatchMessage, pTransport); // Should never dispatch a resendof a 2xx if(delayedDispatchMessage) { delete delayedDispatchMessage; delayedDispatchMessage = NULL; } } } messageStatusString.append("Received duplicate message\n"); #ifdef TEST_PRINT osPrintf("%s", messageStatusString.data()); #endif } // The first time we received this message else if(transaction) { switch (relationship) { case SipTransaction::MESSAGE_FINAL: case SipTransaction::MESSAGE_PROVISIONAL: case SipTransaction::MESSAGE_CANCEL_RESPONSE: { int delayedResponseCode = -1; SipMessage* request = transaction->getRequest(); isUaTransaction = transaction->isUaTransaction(); shouldDispatch = transaction->handleIncoming(*message, *this, relationship, mSipTransactions, delayedDispatchMessage, pTransport); if(delayedDispatchMessage) { delayedResponseCode = delayedDispatchMessage->getResponseStatusCode(); } // Check for Authentication Error if( request && delayedDispatchMessage && delayedResponseCode == HTTP_UNAUTHORIZED_CODE && isUaTransaction ) { resentWithAuth = resendWithAuthorization(delayedDispatchMessage, request, &messageType, HttpMessage::SERVER); } // Check for Proxy Authentication Error if( request && delayedDispatchMessage && delayedResponseCode == HTTP_PROXY_UNAUTHORIZED_CODE && isUaTransaction ) { resentWithAuth = resendWithAuthorization(delayedDispatchMessage, request, &messageType, HttpMessage::PROXY); } // If we requested authentication for this response, // validate the authorization UtlString requestAuthScheme; if( request && request->getAuthenticationScheme(&requestAuthScheme, HttpMessage::SERVER)) { UtlString reqUri; request->getRequestUri(&reqUri); if(authorized(message, reqUri.data())) { #ifdef TEST_PRINT osPrintf("response is authorized\n"); #endif } // What do we do with an unauthorized response? // For now we just let it through. else { OsSysLog::add(FAC_SIP, PRI_WARNING, "UNAUTHORIZED RESPONSE"); # ifdef TEST_PRINT osPrintf("WARNING: UNAUTHORIZED RESPONSE\n"); # endif } } // If we have a request for this incoming response // Forward it on to interested applications if ( request && (shouldDispatch || delayedDispatchMessage) ) { UtlString method; request->getRequestMethod(&method); OsMsgQ* responseQ = NULL; responseQ = request->getResponseListenerQueue(); if (responseQ && shouldDispatch) { SipMessage * msg = new SipMessage(*message); msg->setResponseListenerData(request->getResponseListenerData() ); SipMessageEvent eventMsg(msg); eventMsg.setMessageStatus(messageType); responseQ->send(eventMsg); // The SipMessage gets freed with the SipMessageEvent msg = NULL; } if(responseQ && delayedDispatchMessage) { SipMessage* tempDelayedDispatchMessage = new SipMessage(*delayedDispatchMessage); tempDelayedDispatchMessage->setResponseListenerData( request->getResponseListenerData()); SipMessageEvent eventMsg(tempDelayedDispatchMessage); eventMsg.setMessageStatus(messageType); if (!mbShuttingDown) { responseQ->send(eventMsg); } // The SipMessage gets freed with the SipMessageEvent tempDelayedDispatchMessage = NULL; } } } break; case SipTransaction::MESSAGE_REQUEST: { // if this is a request check if it is supported SipMessage* response = NULL; UtlString disallowedExtensions; UtlString method; UtlString allowedMethods; UtlString contentEncoding; UtlString toAddress; UtlString fromAddress; UtlString uriAddress; UtlString protocol; UtlString sipVersion; int port; int seqNumber; UtlString seqMethod; UtlString callIdField; int maxForwards; message->getRequestMethod(&method); if(isUaTransaction) { getAllowedMethods(&allowedMethods); whichExtensionsNotAllowed(message, &disallowedExtensions); message->getContentEncodingField(&contentEncoding); //delete leading and trailing white spaces disallowedExtensions = disallowedExtensions.strip(UtlString::both); allowedMethods = allowedMethods.strip(UtlString::both); contentEncoding = contentEncoding.strip(UtlString::both); } message->getToAddress(&toAddress, &port, &protocol); message->getFromAddress(&fromAddress, &port, &protocol); message->getUri(&uriAddress, &port, &protocol); message->getRequestProtocol(&sipVersion); sipVersion.toUpper(); message->getCSeqField(&seqNumber, &seqMethod); seqMethod.toUpper(); message->getCallIdField(&callIdField); // Check if the method is supported if( isUaTransaction && !isMethodAllowed(method.data()) ) { response = new SipMessage(); response->setRequestUnimplemented(message); } // Check if the extensions are supported else if( mDoUaMessageChecks && isUaTransaction && !disallowedExtensions.isNull() ) { response = new SipMessage(); response->setRequestBadExtension(message, disallowedExtensions); } // Check if the encoding is supported // i.e. no encoding else if( mDoUaMessageChecks && isUaTransaction && !contentEncoding.isNull() ) { response = new SipMessage(); response->setRequestBadContentEncoding(message,""); } // Check the addresses are present else if(toAddress.isNull() || fromAddress.isNull() || uriAddress.isNull()) { response = new SipMessage(); response->setRequestBadAddress(message); } // Check SIP version else if(strcmp(sipVersion.data(), SIP_PROTOCOL_VERSION) != 0) { response = new SipMessage(); response->setRequestBadVersion(message); } // Check for missing CSeq or Call-Id else if(callIdField.isNull() || seqNumber < 0 || strcmp(seqMethod.data(), method.data()) != 0) { response = new SipMessage(); response->setRequestBadRequest(message); } // Authentication Required else if(isUaTransaction && shouldAuthenticate(message)) { if(!authorized(message)) { #ifdef TEST_PRINT osPrintf("SipUserAgent::dispatch message Unauthorized\n"); #endif response = new SipMessage(); response->setRequestUnauthorized(message, mAuthenticationScheme.data(), mAuthenticationRealm.data(), "1234567890", // :TODO: nonce should be generated by SipNonceDb "abcdefghij" // opaque ); } #ifdef TEST_PRINT else { osPrintf("SipUserAgent::dispatch message Authorized\n"); } #endif //TEST_PRINT } // Process Options requests :TODO: - this does not route in the redirect server else if(isUaTransaction && !message->isResponse() && method.compareTo(SIP_OPTIONS_METHOD) == 0) { // Send an OK, the allowed field will get added to all final responces. response = new SipMessage(); response->setResponseData(message, SIP_OK_CODE, SIP_OK_TEXT); delete(message); message = NULL; } else if(message->getMaxForwards(maxForwards)) { if(maxForwards <= 0) { response = new SipMessage(); response->setResponseData(message, SIP_TOO_MANY_HOPS_CODE, SIP_TOO_MANY_HOPS_TEXT); response->setWarningField(SIP_WARN_MISC_CODE, sipIpAddress.data(), SIP_TOO_MANY_HOPS_TEXT ); setSelfHeader(*response); // If we are suppose to return the vias in the // error response for Max-Forwards exeeded if(mReturnViasForMaxForwards) { // The setBody method frees up the body before // setting the new one, if there is a body // We remove the body so that we can serialize // the message without getting the body message->setBody(NULL); UtlString sipFragString; int sipFragLen; message->getBytes(&sipFragString, &sipFragLen); // Create a body to contain the Vias from the request HttpBody* sipFragBody = new HttpBody(sipFragString.data(), sipFragLen, CONTENT_TYPE_MESSAGE_SIPFRAG); // Attach the body to the response response->setBody(sipFragBody); // Set the content type of the body to be sipfrag response->setContentType(CONTENT_TYPE_MESSAGE_SIPFRAG); } delete(message); message = NULL; } } else { message->setMaxForwards(mMaxForwards); } // If the request is invalid if(response) { // Send the error response transaction->handleOutgoing(*response, *this, mSipTransactions, SipTransaction::MESSAGE_FINAL, pTransport); delete response; response = NULL; if(message) delete message; message = NULL; } else if(message) { mpLastSipMessage = message; shouldDispatch = transaction->handleIncoming(*message, *this, relationship, mSipTransactions, delayedDispatchMessage, pTransport); } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipUserAgent::dispatch NULL message to handle"); //osPrintf("ERROR: SipUserAgent::dispatch NULL message to handle\n"); } } break; case SipTransaction::MESSAGE_ACK: case SipTransaction::MESSAGE_2XX_ACK: case SipTransaction::MESSAGE_CANCEL: { int maxForwards; // Check the ACK max-forwards has not gone too many hopes if(!isResponse && (relationship == SipTransaction::MESSAGE_ACK || relationship == SipTransaction::MESSAGE_2XX_ACK) && message->getMaxForwards(maxForwards) && maxForwards <= 0 ) { // Drop ACK on the floor. if(message) delete(message); message = NULL; } else if(message) { shouldDispatch = transaction->handleIncoming(*message, *this, relationship, mSipTransactions, delayedDispatchMessage, pTransport); } } break; case SipTransaction::MESSAGE_NEW_FINAL: { // Forward it on to interested applications SipMessage* request = transaction->getRequest(); shouldDispatch = TRUE; if( request) { UtlString method; request->getRequestMethod(&method); OsMsgQ* responseQ = NULL; responseQ = request->getResponseListenerQueue(); if (responseQ) { SipMessage * msg = new SipMessage(*message); msg->setResponseListenerData(request->getResponseListenerData() ); SipMessageEvent eventMsg(msg); eventMsg.setMessageStatus(messageType); responseQ->send(eventMsg); // The SipMessage gets freed with the SipMessageEvent msg = NULL; } } } break; default: { if (OsSysLog::willLog(FAC_SIP, PRI_WARNING)) { UtlString relationString; SipTransaction::getRelationshipString(relationship, relationString); OsSysLog::add(FAC_SIP, PRI_WARNING, "SipUserAgent::dispatch unhandled incoming message: %s", relationString.data()); } } break; } } if(transaction) { mSipTransactions.markAvailable(*transaction); } } else { shouldDispatch = TRUE; messageStatusString.append("SIP User agent FAILED to send message:\n"); } #ifdef LOG_TIME eventTimes.addEvent("queuing"); #endif if ( isMessageLoggingEnabled() || OsSysLog::willLog(FAC_SIP_INCOMING_PARSED, PRI_DEBUG) ) { msgBytes.insert(0, messageStatusString.data()); msgBytes.append("++++++++++++++++++++END++++++++++++++++++++\n"); #ifdef TEST_PRINT osPrintf("%s", msgBytes.data()); #endif logMessage(msgBytes.data(), msgBytes.length()); OsSysLog::add(FAC_SIP_INCOMING_PARSED, PRI_DEBUG, "%s", msgBytes.data()); } if(message && shouldDispatch) { #ifdef TEST_PRINT osPrintf("DISPATCHING message\n"); #endif queueMessageToObservers(message, messageType); } else { delete message; message = NULL; } if(delayedDispatchMessage) { if ( isMessageLoggingEnabled() || OsSysLog::willLog(FAC_SIP_INCOMING_PARSED, PRI_DEBUG) ) { UtlString delayMsgString; int delayMsgLen; delayedDispatchMessage->getBytes(&delayMsgString, &delayMsgLen); delayMsgString.insert(0, "SIP User agent delayed dispatch message:\n"); delayMsgString.append("++++++++++++++++++++END++++++++++++++++++++\n"); #ifdef TEST_PRINT osPrintf("%s", delayMsgString.data()); #endif logMessage(delayMsgString.data(), delayMsgString.length()); OsSysLog::add(FAC_SIP_INCOMING_PARSED, PRI_DEBUG, "%s", delayMsgString.data()); } queueMessageToObservers(delayedDispatchMessage, messageType); } #ifdef LOG_TIME eventTimes.addEvent("GC"); #endif // All garbage collection should now be done in the // context of the SipUserAgent to prevent hickups in // the reading of SipMessages off the sockets. //garbageCollection(); #ifdef LOG_TIME eventTimes.addEvent("finish"); UtlString timeString; eventTimes.getLogString(timeString); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUserAgent::dispatch time log: %s", timeString.data()); #endif } #undef LOG_TIME void SipUserAgent::queueMessageToObservers(SipMessage* message, int messageType) { UtlString callId; message->getCallIdField(&callId); UtlString method; message->getRequestMethod(&method); // Create a new message event SipMessageEvent event(message); event.setMessageStatus(messageType); // Find all of the observers which are interested in // this method and post the message UtlBoolean isRsp = message->isResponse(); if(isRsp) { int cseq; message->getCSeqField(&cseq, &method); } queueMessageToInterestedObservers(event, method); // send it to those with no method descrimination as well queueMessageToInterestedObservers(event, ""); // Do not delete the message it gets deleted with the event message = NULL; } void SipUserAgent::queueMessageToInterestedObservers(SipMessageEvent& event, const UtlString& method) { const SipMessage* message; if((message = event.getMessage())) { // Find all of the observers which are interested in // this method and post the message UtlString messageEventName; message->getEventField(&messageEventName, NULL, NULL); // do these constructors before taking the lock UtlString observerMatchingMethod(method); // lock the message observer list OsReadLock lock(mObserverMutex); UtlHashBagIterator observerIterator(mMessageObservers, &observerMatchingMethod); SipObserverCriteria* observerCriteria; while ((observerCriteria = (SipObserverCriteria*) observerIterator())) { // Check message direction and type if ( ( message->isResponse() && observerCriteria->wantsResponses()) || (! message->isResponse() && observerCriteria->wantsRequests()) ) { // Decide if the event filter applies bool useEventFilter = false; bool matchedEvent = false; if (! message->isResponse()) // events apply only to requests { UtlString criteriaEventName; observerCriteria->getEventName(criteriaEventName); useEventFilter = ! criteriaEventName.isNull(); if (useEventFilter) { // see if the event type matches matchedEvent = ( ( method.compareTo(SIP_SUBSCRIBE_METHOD, UtlString::ignoreCase) == 0 || method.compareTo(SIP_NOTIFY_METHOD, UtlString::ignoreCase) == 0 ) && 0==messageEventName.compareTo(criteriaEventName, UtlString::ignoreCase ) ); } } // else - this is a response - event filter is not applicable // Check to see if the session criteria matters SipSession* pCriteriaSession = observerCriteria->getSession() ; bool useSessionFilter = (NULL != pCriteriaSession); UtlBoolean matchedSession = FALSE; if (useSessionFilter) { // it matters; see if it matches matchedSession = pCriteriaSession->isSameSession((SipMessage&) *message); } // We have a message type (req|rsp) the observer wants - apply filters if ( (! useSessionFilter || matchedSession) && (! useEventFilter || matchedEvent) ) { // This event is interesting, so send it up... OsMsgQ* observerQueue = observerCriteria->getObserverQueue(); void* observerData = observerCriteria->getObserverData(); // Cheat a little and set the observer data to be passed back ((SipMessage*) message)->setResponseListenerData(observerData); // Put the message in the observers queue if (!mbShuttingDown) { int numMsgs = observerQueue->numMsgs(); int maxMsgs = observerQueue->maxMsgs(); if (numMsgs < maxMsgs) { observerQueue->send(event); } else { OsSysLog::add(FAC_SIP, PRI_ERR, "queueMessageToInterestedObservers - queue full (name=%s, numMsgs=%d)", observerQueue->getName().data(), numMsgs); } } } } else { // either direction or req/rsp not a match } } // while observers } else { OsSysLog::add(FAC_SIP, PRI_CRIT, "queueMessageToInterestedObservers - no message"); } } UtlBoolean checkMethods(SipMessage* message) { return(TRUE); } UtlBoolean checkExtensions(SipMessage* message) { return(TRUE); } UtlBoolean SipUserAgent::handleMessage(OsMsg& eventMessage) { UtlBoolean messageProcessed = FALSE; //osPrintf("SipUserAgent: handling message\n"); int msgType = eventMessage.getMsgType(); int msgSubType = eventMessage.getMsgSubType(); // Print message if input queue to SipUserAgent exceeds 100. if (getMessageQueue()->numMsgs() > 100) { SipMessageEvent* sipEvent; OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUserAgent::handleMessage msgType = %d, msgSubType = %d, msgEventType = %d, " "queue length = %d", msgType, msgSubType, // Only extract msgEventType if msgType and msgSubType are right. msgType == OsMsg::OS_EVENT && msgSubType == OsEventMsg::NOTIFY ? (((OsEventMsg&)eventMessage).getUserData((intptr_t&)sipEvent), sipEvent ? sipEvent->getMessageStatus() : -98) : -99 /* dummy value */, getMessageQueue()->numMsgs()); } if(msgType == OsMsg::PHONE_APP) { // Final message from SipUserAgent::shutdown - all timers are stopped and are safe to delete if(msgSubType == SipUserAgent::SHUTDOWN_MESSAGE) { #ifdef TEST_PRINT osPrintf("SipUserAgent::handleMessage shutdown complete message.\n"); #endif mSipTransactions.deleteTransactionTimers(); if(mbBlockingShutdown == TRUE) { OsEvent* pEvent = ((OsRpcMsg&)eventMessage).getEvent(); OsStatus res = pEvent->signal(OS_SUCCESS); assert(res == OS_SUCCESS); } else { mbShutdownDone = TRUE; } } else if (msgSubType == SipUserAgent::KEEPALIVE_MESSAGE) { OsPtrMsg& msg = (OsPtrMsg&) eventMessage ; SipUdpServer* pUdpServer = (SipUdpServer*) msg.getPtr() ; OsTimer* pTimer = (OsTimer*) msg.getPtr2() ; if (pUdpServer && pTimer) { pUdpServer->sendSipKeepAlive(pTimer) ; } } else { SipMessage* sipMsg = (SipMessage*)((SipMessageEvent&)eventMessage).getMessage(); if(sipMsg) { //messages for which the UA is consumer will end up here. OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUserAgent::handleMessage posting message"); // I cannot remember what kind of message ends up here??? if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { int len; UtlString msgBytes; sipMsg->getBytes(&msgBytes, &len); OsSysLog::add(FAC_SIP, PRI_DEBUG, "??????????????????????????????????????\n" "%s???????????????????????????????????\n", msgBytes.data()); } } } messageProcessed = TRUE; } // A timer expired else if(msgType == OsMsg::OS_EVENT && msgSubType == OsEventMsg::NOTIFY) { OsTimer* timer; SipMessageEvent* sipEvent = NULL; ((OsEventMsg&)eventMessage).getUserData((intptr_t&)sipEvent); ((OsEventMsg&)eventMessage).getEventData((intptr_t&)timer); if(sipEvent) { const SipMessage* sipMessage = sipEvent->getMessage(); int msgEventType = sipEvent->getMessageStatus(); // Resend timeout if(msgEventType == SipMessageEvent::TRANSACTION_RESEND) { if(sipMessage) { // Note: only delete the timer and notifier if there // is a message AND we can get a lock on the transaction. // WARNING: you cannot touch the contents of the transaction // attached to the message until the transaction has been // locked (via findTransactionFor, if no transaction is // returned, it either no longer exists or we could not get // a lock for it. # ifdef TEST_PRINT { UtlString callId; int protocolType = sipMessage->getSendProtocol(); sipMessage->getCallIdField(&callId); if(sipMessage->getSipTransaction() == NULL) { osPrintf("SipUserAgent::handleMessage " "resend Timeout message with NULL transaction\n"); } osPrintf("SipUserAgent::handleMessage " "resend Timeout of message for %d protocol, callId: \"%s\" \n", protocolType, callId.data()); } # endif int nextTimeout = -1; enum SipTransaction::messageRelationship relationship; //mSipTransactions.lock(); SipTransaction* transaction = mSipTransactions.findTransactionFor(*sipMessage, TRUE, // timers are only set for outgoing messages I think relationship); if(transaction) { if(timer) { transaction->removeTimer(timer); delete timer; timer = NULL; } // If we are in shutdown mode, unlock the transaction // and set it to null. We pretend that the transaction // does not exist (i.e. noop). if(mbShuttingDown) { mSipTransactions.markAvailable(*transaction); transaction = NULL; } } // If we cannot lock it, it does not exist (or atleast // pretend it does not exist. The transaction will be // null if it has been deleted or we cannot get a lock // on the transaction. if(transaction) { SipMessage* delayedDispatchMessage = NULL; bool bCustom = false; const UtlString transportName = sipMessage->getTransportName(bCustom); SIPX_TRANSPORT_DATA* pTransport = NULL; if (bCustom) { pTransport = (SIPX_TRANSPORT_DATA*)lookupExternalTransport(transportName, sipMessage->getLocalIp()); } transaction->handleResendEvent(*sipMessage, *this, relationship, mSipTransactions, nextTimeout, delayedDispatchMessage, pTransport); if(nextTimeout == 0) { if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { UtlString transactionString; transaction->toString(transactionString, TRUE); transactionString.insert(0, "SipUserAgent::handleMessage " "timeout send failed\n" ); OsSysLog::add(FAC_SIP, PRI_DEBUG, "%s\n", transactionString.data()); //osPrintf("%s\n", transactionString.data()); } } if(delayedDispatchMessage) { // Only bother processing if the logs are enabled if ( isMessageLoggingEnabled() || OsSysLog::willLog(FAC_SIP_INCOMING, PRI_DEBUG)) { UtlString delayMsgString; int delayMsgLen; delayedDispatchMessage->getBytes(&delayMsgString, &delayMsgLen); delayMsgString.insert(0, "SIP User agent delayed dispatch message:\n"); delayMsgString.append("++++++++++++++++++++END++++++++++++++++++++\n"); #ifdef TEST_PRINT osPrintf("%s", delayMsgString.data()); #endif logMessage(delayMsgString.data(), delayMsgString.length()); OsSysLog::add(FAC_SIP_INCOMING_PARSED, PRI_DEBUG,"%s", delayMsgString.data()); } // if the request has a responseQueue, post the response. OsMsgQ* responseQ = NULL; responseQ = sipMessage->getResponseListenerQueue(); if ( responseQ && !sipMessage->isResponse() && delayedDispatchMessage->isResponse()) { SipMessage *messageToQ = new SipMessage(*delayedDispatchMessage); messageToQ->setResponseListenerData(sipMessage->getResponseListenerData()); SipMessageEvent eventMsg(messageToQ); eventMsg.setMessageStatus(SipMessageEvent::APPLICATION); responseQ->send(eventMsg); // The SipMessage gets freed with the SipMessageEvent messageToQ = NULL; } queueMessageToObservers(delayedDispatchMessage, SipMessageEvent::APPLICATION ); // delayedDispatchMessage gets freed in queueMessageToObservers delayedDispatchMessage = NULL; } } // No transaction for this timeout else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipUserAgent::handleMessage " "SIP message timeout expired with no matching transaction"); // Somehow the transaction got deleted perhaps it timed // out and there was a log jam that prevented the handling // of the timeout ????? This should not happen. } if(transaction) { mSipTransactions.markAvailable(*transaction); } // Do this outside so that we do not get blocked // on locking or delete the transaction out // from under ouselves if(nextTimeout == 0) { // Make a copy and dispatch it dispatch(new SipMessage(*sipMessage), SipMessageEvent::TRANSPORT_ERROR); } // The timer made its own copy of this message. // It is deleted by dispatch ?? if it is not // rescheduled. } // End if sipMessage } // End SipMessageEvent::TRANSACTION_RESEND // Timeout for garbage collection else if(msgEventType == SipMessageEvent::TRANSACTION_GARBAGE_COLLECTION) { #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUserAgent::handleMessage garbage collecting"); osPrintf("SipUserAgent::handleMessage garbage collecting\n"); #endif } // Timeout for an transaction to expire else if(msgEventType == SipMessageEvent::TRANSACTION_EXPIRATION) { #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUserAgent::handleMessage transaction expired"); #endif if(sipMessage) { // Note: only delete the timer and notifier if there // is a message AND we can get a lock on the transaction. // WARNING: you cannot touch the contents of the transaction // attached to the message until the transaction has been // locked (via findTransactionFor, if no transaction is // returned, it either no longer exists or we could not get // a lock for it. #ifdef TEST_PRINT if(sipMessage->getSipTransaction() == NULL) { osPrintf("SipUserAgent::handleMessage expires Timeout message with NULL transaction\n"); } #endif int nextTimeout = -1; enum SipTransaction::messageRelationship relationship; //mSipTransactions.lock(); SipTransaction* transaction = mSipTransactions.findTransactionFor(*sipMessage, TRUE, // timers are only set for outgoing? relationship); if(transaction) { if(timer) { transaction->removeTimer(timer); delete timer; timer = NULL; } // If we are in shutdown mode, unlock the transaction // and set it to null. We pretend that the transaction // does not exist (i.e. noop). if(mbShuttingDown) { mSipTransactions.markAvailable(*transaction); transaction = NULL; } } if(transaction) { SipMessage* delayedDispatchMessage = NULL; transaction->handleExpiresEvent(*sipMessage, *this, relationship, mSipTransactions, nextTimeout, delayedDispatchMessage, NULL); mSipTransactions.markAvailable(*transaction); if(delayedDispatchMessage) { // Only bother processing if the logs are enabled if ( isMessageLoggingEnabled() || OsSysLog::willLog(FAC_SIP_INCOMING_PARSED, PRI_DEBUG)) { UtlString delayMsgString; int delayMsgLen; delayedDispatchMessage->getBytes(&delayMsgString, &delayMsgLen); delayMsgString.insert(0, "SIP User agent delayed dispatch message:\n"); delayMsgString.append("++++++++++++++++++++END++++++++++++++++++++\n"); #ifdef TEST_PRINT osPrintf("%s", delayMsgString.data()); #endif logMessage(delayMsgString.data(), delayMsgString.length()); OsSysLog::add(FAC_SIP_INCOMING_PARSED, PRI_DEBUG,"%s", delayMsgString.data()); } // wdn - if the request has a responseQueue, post the response. OsMsgQ* responseQ = NULL; responseQ = sipMessage->getResponseListenerQueue(); if ( responseQ && !sipMessage->isResponse() && delayedDispatchMessage->isResponse()) { SipMessage *messageToQ = new SipMessage(*delayedDispatchMessage); messageToQ->setResponseListenerData(sipMessage->getResponseListenerData()); SipMessageEvent eventMsg(messageToQ); eventMsg.setMessageStatus(SipMessageEvent::APPLICATION); responseQ->send(eventMsg); // The SipMessage gets freed with the SipMessageEvent messageToQ = NULL; } // delayedDispatchMessage gets freed in queueMessageToObservers queueMessageToObservers(delayedDispatchMessage, SipMessageEvent::APPLICATION ); //delayedDispatchMessage gets freed in queueMessageToObservers delayedDispatchMessage = NULL; } } else // Could not find a transaction for this exired message { if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG)) { UtlString noTxMsgString; int noTxMsgLen; sipMessage->getBytes(&noTxMsgString, &noTxMsgLen); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUserAgent::handleMessage " "event timeout with no matching transaction: %s", noTxMsgString.data()); } } } } // Unknown timeout else { OsSysLog::add(FAC_SIP, PRI_WARNING, "SipUserAgent::handleMessage unknown timeout event: %d.", msgEventType); # ifdef TEST_PRINT osPrintf("ERROR: SipUserAgent::handleMessage unknown timeout event: %d.\n", msgEventType); # endif } // As this is OsMsg is attached as a void* to the timeout event // it must be explicitly deleted. The attached SipMessage // will get freed with it. delete sipEvent; sipEvent = NULL; } // end if sipEvent messageProcessed = TRUE; } else { #ifdef TEST_PRINT osPrintf("SipUserAgent: Unknown message type: %d\n", msgType); #endif messageProcessed = TRUE; } // Only GC if no messages are waiting -- othewise we may delete a timer // that is queued up for us. if (getMessageQueue()->isEmpty()) { garbageCollection(); OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUserAgent::handleMessage after GC, queue size = %d handled message type: %d subtype: %d", getMessageQueue()->numMsgs(), msgType, msgSubType); } return(messageProcessed); } void SipUserAgent::garbageCollection() { OsTime time; OsDateTime::getCurTimeSinceBoot(time); long bootime = time.seconds(); long then = bootime - (mTransactionStateTimeoutMs / 1000); long tcpThen = bootime - mMaxTcpSocketIdleTime; long oldTransaction = then - (mTransactionStateTimeoutMs / 1000); long oldInviteTransaction = then - mMinInviteTransactionTimeout; // If the timeout is negative we never timeout or garbage collect // tcp connections if(mMaxTcpSocketIdleTime < 0) { tcpThen = -1; } if(mLastCleanUpTime < then) { # ifdef LOG_TIME OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUserAgent::garbageCollection" " bootime: %ld then: %ld tcpThen: %ld" " oldTransaction: %ld oldInviteTransaction: %ld", bootime, then, tcpThen, oldTransaction, oldInviteTransaction); #endif mSipTransactions.removeOldTransactions(oldTransaction, oldInviteTransaction); # ifdef LOG_TIME OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUserAgent::garbageCollection starting removeOldClients(udp)"); # endif // Changed by Udit for null pointer check if (mSipUdpServer) { mSipUdpServer->removeOldClients(then); } if (mSipTcpServer) { # ifdef LOG_TIME OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUserAgent::garbageCollection starting removeOldClients(tcp)"); # endif mSipTcpServer->removeOldClients(tcpThen); } #ifdef SIP_TLS if (mSipTlsServer) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUserAgent::garbageCollection starting removeOldClients(tls)"); mSipTlsServer->removeOldClients(tcpThen); } #endif # ifdef LOG_TIME OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipUserAgent::garbageCollection done"); # endif mLastCleanUpTime = bootime; } } UtlBoolean SipUserAgent::addCrLfKeepAlive(const char* szLocalIp, const char* szRemoteIp, const int remotePort, const int keepAliveSecs, OsNatKeepaliveListener* pListener) { UtlBoolean bSuccess = false ; if (mSipUdpServer) { bSuccess = mSipUdpServer->addCrLfKeepAlive(szLocalIp, szRemoteIp, remotePort, keepAliveSecs, pListener) ; } return bSuccess ; } UtlBoolean SipUserAgent::removeCrLfKeepAlive(const char* szLocalIp, const char* szRemoteIp, const int remotePort) { UtlBoolean bSuccess = false ; if (mSipUdpServer) { bSuccess = mSipUdpServer->removeCrLfKeepAlive(szLocalIp, szRemoteIp, remotePort) ; } return bSuccess ; } UtlBoolean SipUserAgent::addStunKeepAlive(const char* szLocalIp, const char* szRemoteIp, const int remotePort, const int keepAliveSecs, OsNatKeepaliveListener* pListener) { UtlBoolean bSuccess = false ; if (mSipUdpServer) { bSuccess = mSipUdpServer->addStunKeepAlive(szLocalIp, szRemoteIp, remotePort, keepAliveSecs, pListener) ; } return bSuccess ; } UtlBoolean SipUserAgent::removeStunKeepAlive(const char* szLocalIp, const char* szRemoteIp, const int remotePort) { UtlBoolean bSuccess = false ; if (mSipUdpServer) { bSuccess = mSipUdpServer->removeStunKeepAlive(szLocalIp, szRemoteIp, remotePort) ; } return bSuccess ; } UtlBoolean SipUserAgent::addSipKeepAlive(const char* szLocalIp, const char* szRemoteIp, const int remotePort, const char* szMethod, const int keepAliveSecs, OsNatKeepaliveListener* pListener) { UtlBoolean bSuccess = false ; if (mSipUdpServer) { bSuccess = mSipUdpServer->addSipKeepAlive(szLocalIp, szRemoteIp, remotePort, szMethod, keepAliveSecs, pListener) ; } return bSuccess ; } UtlBoolean SipUserAgent::removeSipKeepAlive(const char* szLocalIp, const char* szRemoteIp, const int remotePort, const char* szMethod) { UtlBoolean bSuccess = false ; if (mSipUdpServer) { bSuccess = mSipUdpServer->removeSipKeepAlive(szLocalIp, szRemoteIp, remotePort, szMethod) ; } return bSuccess ; } /* ============================ ACCESSORS ================================= */ // Enable or disable the outbound use of rport (send packet to actual // port -- not advertised port). UtlBoolean SipUserAgent::setUseRport(UtlBoolean bEnable) { UtlBoolean bOld = mbUseRport ; mbUseRport = bEnable ; return bOld ; } void SipUserAgent::setUseRportMapping(UtlBoolean bEnable) { mUseRportMapping = bEnable; } UtlBoolean SipUserAgent::getUseRportMapping() const { return(mUseRportMapping); } // Is use report set? UtlBoolean SipUserAgent::getUseRport() const { return mbUseRport ; } void SipUserAgent::setUserAgentName(const UtlString& name) { defaultUserAgentName = name; return; } const UtlString& SipUserAgent::getUserAgentName() const { return defaultUserAgentName; } // Get the manually configured public address UtlBoolean SipUserAgent::getConfiguredPublicAddress(UtlString* pIpAddress, int* pPort) { UtlBoolean bSuccess = FALSE ; if (mConfigPublicAddress.length()) { if (pIpAddress) { *pIpAddress = mConfigPublicAddress ; } if (pPort) { *pPort = mSipUdpServer->getServerPort() ; } bSuccess = TRUE ; } return bSuccess ; } // Get the local address and port UtlBoolean SipUserAgent::getLocalAddress(UtlString* pIpAddress, int* pPort, SIPX_TRANSPORT_TYPE protocol) { if (pIpAddress) { if (defaultSipAddress.length() > 0) { *pIpAddress = defaultSipAddress; } else { OsSocket::getHostIp(pIpAddress) ; } } if (pPort) { switch (protocol) { case TRANSPORT_UDP: if (mSipUdpServer) *pPort = mSipUdpServer->getServerPort() ; break; case TRANSPORT_TCP: if (mSipTcpServer) *pPort = mSipTcpServer->getServerPort() ; break; #ifdef SIP_TLS case TRANSPORT_TLS: if (mSipTlsServer) *pPort = mSipTlsServer->getServerPort(); break; #endif default: if (mSipUdpServer) *pPort = mSipUdpServer->getServerPort() ; break; } } return TRUE ; } // Get the NAT mapped address and port UtlBoolean SipUserAgent::getNatMappedAddress(UtlString* pIpAddress, int* pPort) { UtlBoolean bRet(FALSE); if (mSipUdpServer) { bRet = mSipUdpServer->getStunAddress(pIpAddress, pPort); } else if (mSipTcpServer) { // TODO - a TCP server should also be able to return a stun address //bRet = mSipTcpServer->getStunAddress(pIpAddress, pPort); } return bRet; } void SipUserAgent::setIsUserAgent(UtlBoolean isUserAgent) { mIsUaTransactionByDefault = isUserAgent; } /// Add either Server or User-Agent header, as appropriate void SipUserAgent::setSelfHeader(SipMessage& message) { if (mIsUaTransactionByDefault) { setUserAgentHeader(message); } else { setServerHeader(message); } } // setUserAgentHeaderProperty // provides a string to be appended to the standard User-Agent // header value between "/" and the platform (eg "(VxWorks)") // Value should be formated either as "token/token" or "(string)" // with no leading or trailing space. void SipUserAgent::setUserAgentHeaderProperty( const char* property ) { if ( property ) { mUserAgentHeaderProperties.append(" "); mUserAgentHeaderProperties.append( property ); } } void SipUserAgent::setMaxForwards(int maxForwards) { if(maxForwards > 0) { mMaxForwards = maxForwards; } else { OsSysLog::add(FAC_SIP, PRI_DEBUG,"SipUserAgent::setMaxForwards maxForwards <= 0: %d", maxForwards); } } int SipUserAgent::getMaxForwards() { int maxForwards; if(mMaxForwards <= 0) { OsSysLog::add(FAC_SIP, PRI_DEBUG,"SipUserAgent::getMaxForwards maxForwards <= 0: %d", mMaxForwards); maxForwards = SIP_DEFAULT_MAX_FORWARDS; } else { maxForwards = mMaxForwards; } return(maxForwards); } int SipUserAgent::getMaxSrvRecords() const { return(mMaxSrvRecords); } void SipUserAgent::setMaxSrvRecords(int maxSrvRecords) { mMaxSrvRecords = maxSrvRecords; } int SipUserAgent::getDnsSrvTimeout() { return(mDnsSrvTimeout); } void SipUserAgent::setDnsSrvTimeout(int timeout) { mDnsSrvTimeout = timeout; } void SipUserAgent::setForking(UtlBoolean enabled) { mForkingEnabled = enabled; } void SipUserAgent::prepareContact(SipMessage& message, const char* szTargetUdpAddress, const int* piTargetUdpPort) { // Add a default contact if none is present // AND To all requests -- except REGISTERs (server mode?) // OR all non-failure responses int num = 0; UtlString method ; message.getCSeqField(&num , &method); UtlString contact ; if ( !message.getContactUri(0, &contact) && ((!message.isResponse() && (method.compareTo(SIP_REGISTER_METHOD, UtlString::ignoreCase) != 0)) || (message.getResponseStatusCode() < SIP_MULTI_CHOICE_CODE))) { UtlString contactIp ; if (message.isResponse()) contactIp = message.getLocalIp() ; if (contactIp.isNull()) contactIp = sipIpAddress ; // TODO:: We need to figure out what the protocol SHOULD be if not // already specified. For example, if we are sending via TCP // we should use a TCP contact -- the application layer and override // if desired by passing a contact. SipMessage::buildSipUrl(&contact, contactIp, mUdpPort == SIP_PORT ? PORT_NONE : mUdpPort, NULL, defaultSipUser.data()); message.setContactField(contact) ; } // Update contact if we know anything about the target and our NAT binding if (message.getContactField(0, contact)) { Url urlContact(contact) ; UtlString contactIp ; int contactPort ; // Init Contact Info urlContact.getHostAddress(contactIp) ; contactPort = urlContact.getHostPort() ; // Try specified send to host:port if (szTargetUdpAddress && piTargetUdpPort && (OsNatAgentTask::getInstance()->findContactAddress( szTargetUdpAddress, *piTargetUdpPort, &contactIp, &contactPort))) { urlContact.setHostAddress(contactIp) ; urlContact.setHostPort(contactPort) ; message.removeHeader(SIP_CONTACT_FIELD, 0) ; message.setContactField(urlContact.toString()) ; } else { // Otherwise dig out info from message -- also make sure this is // contact we should adjust UtlString sendProtocol ; if ((urlContact.getScheme() == Url::SipUrlScheme) && ((urlContact.getUrlParameter("transport", sendProtocol) == false) || (sendProtocol.compareTo("udp", UtlString::ignoreCase) == 0))) { if (message.isResponse()) { // Response: See if we have a better contact address to the // remote party UtlString receivedFromAddress ; int receivedFromPort ; message.getSendAddress(&receivedFromAddress, &receivedFromPort) ; if (OsNatAgentTask::getInstance()->findContactAddress( receivedFromAddress, receivedFromPort, &contactIp, &contactPort)) { urlContact.setHostAddress(contactIp) ; urlContact.setHostPort(contactPort) ; message.removeHeader(SIP_CONTACT_FIELD, 0) ; message.setContactField(urlContact.toString()) ; } } else { // Request: See if we have a better contact address to the // remote party UtlString requestUriAddress ; int requestUriPort ; UtlString requestUriProtocol ; // ignored message.getUri(&requestUriAddress, &requestUriPort, &requestUriProtocol) ; if (OsNatAgentTask::getInstance()->findContactAddress( requestUriAddress, requestUriPort, &contactIp, &contactPort)) { urlContact.setHostAddress(contactIp) ; urlContact.setHostPort(contactPort) ; message.removeHeader(SIP_CONTACT_FIELD, 0) ; message.setContactField(urlContact.toString()) ; } } } } } } void SipUserAgent::getAllowedMethods(UtlString* allowedMethods) { UtlDListIterator iterator(allowedSipMethods); allowedMethods->remove(0); UtlString* method; while ((method = (UtlString*) iterator())) { if(!method->isNull()) { if(!allowedMethods->isNull()) { allowedMethods->append(", "); } allowedMethods->append(method->data()); } } } void SipUserAgent::getViaInfo(int protocol, UtlString& address, int& port, const char* pszTargetAddress, const int* piTargetPort) { address = sipIpAddress; if(protocol == OsSocket::TCP) { port = mTcpPort == SIP_PORT ? PORT_NONE : mTcpPort; } #ifdef SIP_TLS else if(protocol == OsSocket::SSL_SOCKET) { port = mTlsPort == SIP_TLS_PORT ? PORT_NONE : mTlsPort; } #endif else { if(portIsValid(mSipPort)) { port = mSipPort; } else if(mUdpPort == SIP_PORT) { port = PORT_NONE; } else { port = mUdpPort; } if (pszTargetAddress && piTargetPort) { OsNatAgentTask::getInstance()->findContactAddress(pszTargetAddress, *piTargetPort, &address, &port) ; } } } void SipUserAgent::getFromAddress(UtlString* address, int* port, UtlString* protocol) { UtlTokenizer tokenizer(registryServers); UtlString regServer; tokenizer.next(regServer, ","); SipMessage::parseAddressFromUri(regServer.data(), address, port, protocol); if(address->isNull()) { protocol->remove(0); // TCP only if(portIsValid(mTcpPort) && !portIsValid(mUdpPort)) { protocol->append(SIP_TRANSPORT_TCP); *port = mTcpPort; } // UDP only else if(portIsValid(mUdpPort) && !portIsValid(mTcpPort)) { protocol->append(SIP_TRANSPORT_UDP); *port = mUdpPort; } // TCP & UDP on non-standard port else if(mTcpPort != SIP_PORT) { *port = mTcpPort; } // TCP & UDP on standard port else { *port = PORT_NONE; } // If there is an address configured use it UtlNameValueTokenizer::getSubField(defaultSipAddress.data(), 0, ", \t", address); // else use the local host ip address if(address->isNull()) { address->append(sipIpAddress); //OsSocket::getHostIp(address); } } } void SipUserAgent::getDirectoryServer(int index, UtlString* address, int* port, UtlString* protocol) { UtlString serverAddress; UtlNameValueTokenizer::getSubField(directoryServers.data(), 0, SIP_MULTIFIELD_SEPARATOR, &serverAddress); address->remove(0); *port = PORT_NONE; protocol->remove(0); SipMessage::parseAddressFromUri(serverAddress.data(), address, port, protocol); serverAddress.remove(0); } void SipUserAgent::getProxyServer(int index, UtlString* address, int* port, UtlString* protocol) { UtlString serverAddress; UtlNameValueTokenizer::getSubField(proxyServers.data(), 0, SIP_MULTIFIELD_SEPARATOR, &serverAddress); address->remove(0); *port = PORT_NONE; protocol->remove(0); SipMessage::parseAddressFromUri(serverAddress.data(), address, port, protocol); serverAddress.remove(0); } void SipUserAgent::setProxyServers(const char* sipProxyServers) { if (sipProxyServers) { proxyServers = sipProxyServers ; } else { proxyServers.remove(0) ; } } int SipUserAgent::getSipStateTransactionTimeout() { return mTransactionStateTimeoutMs; } int SipUserAgent::getReliableTransportTimeout() { return(mReliableTransportTimeoutMs); } int SipUserAgent::getFirstResendTimeout() { return(mFirstResendTimeoutMs); } int SipUserAgent::getLastResendTimeout() { return(mLastResendTimeoutMs); } int SipUserAgent::getDefaultExpiresSeconds() const { return(mDefaultExpiresSeconds); } void SipUserAgent::setDefaultExpiresSeconds(int expiresSeconds) { if(expiresSeconds > 0 && expiresSeconds <= mMinInviteTransactionTimeout) { mDefaultExpiresSeconds = expiresSeconds; } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipUserAgent::setDefaultExpiresSeconds " "illegal expiresSeconds value: %d IGNORED", expiresSeconds); } } int SipUserAgent::getDefaultSerialExpiresSeconds() const { return(mDefaultSerialExpiresSeconds); } void SipUserAgent::setDefaultSerialExpiresSeconds(int expiresSeconds) { if(expiresSeconds > 0 && expiresSeconds <= mMinInviteTransactionTimeout) { mDefaultSerialExpiresSeconds = expiresSeconds; } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipUserAgent::setDefaultSerialExpiresSeconds " "illegal expiresSeconds value: %d IGNORED", expiresSeconds); } } void SipUserAgent::setMaxTcpSocketIdleTime(int idleTimeSeconds) { if(mMinInviteTransactionTimeout < idleTimeSeconds) { mMaxTcpSocketIdleTime = idleTimeSeconds; } else { OsSysLog::add(FAC_SIP, PRI_ERR, "SipUserAgent::setMaxTcpSocketIdleTime " "idleTimeSeconds: %d less than mMinInviteTransactionTimeout: %d IGNORED", idleTimeSeconds, mMinInviteTransactionTimeout); } } void SipUserAgent::setHostAliases(UtlString& aliases) { UtlString aliasString; int aliasIndex = 0; while(UtlNameValueTokenizer::getSubField(aliases.data(), aliasIndex, ", \t", &aliasString)) { Url aliasUrl(aliasString); UtlString hostAlias; aliasUrl.getHostAddress(hostAlias); int port = aliasUrl.getHostPort(); if(!portIsValid(port)) { hostAlias.append(":5060"); } else { char portString[20]; sprintf(portString, ":%d", port); hostAlias.append(portString); } UtlString* newAlias = new UtlString(hostAlias); mMyHostAliases.insert(newAlias); aliasIndex++; } } void SipUserAgent::printStatus() { if(mSipUdpServer) { mSipUdpServer->printStatus(); } if(mSipTcpServer) { mSipTcpServer->printStatus(); } #ifdef SIP_TLS if(mSipTlsServer) { mSipTlsServer->printStatus(); } #endif UtlString txString; mSipTransactions.toString(txString); osPrintf("Transactions:\n%s\n", txString.data()); } void SipUserAgent::startMessageLog(int newMaximumLogSize) { if(newMaximumLogSize > 0) mMaxMessageLogSize = newMaximumLogSize; if(newMaximumLogSize == -1) mMaxMessageLogSize = -1; mMessageLogEnabled = TRUE; { OsWriteLock Writelock(mMessageLogWMutex); OsReadLock ReadLock(mMessageLogRMutex); if(mMaxMessageLogSize > 0) mMessageLog.capacity(mMaxMessageLogSize); } } void SipUserAgent::stopMessageLog() { mMessageLogEnabled = FALSE; } void SipUserAgent::clearMessageLog() { OsWriteLock Writelock(mMessageLogWMutex); OsReadLock Readlock(mMessageLogRMutex); mMessageLog.remove(0); } void SipUserAgent::logMessage(const char* message, int messageLength) { if(mMessageLogEnabled) { #ifdef TEST_PRINT osPrintf("SIP LOGGING ENABLED\n"); #endif {// lock scope OsWriteLock Writelock(mMessageLogWMutex); // Do not allow the log go grow beyond the maximum if(mMaxMessageLogSize > 0 && ((((int)mMessageLog.length()) + messageLength) > mMaxMessageLogSize)) { mMessageLog.remove(0, mMessageLog.length() + messageLength - mMaxMessageLogSize); } mMessageLog.append(message, messageLength); }//lock scope } #ifdef TEST_PRINT else osPrintf("SIP LOGGING DISABLED\n"); #endif } void SipUserAgent::getMessageLog(UtlString& logData) { OsReadLock Readlock(mMessageLogRMutex); logData = mMessageLog; } void SipUserAgent::allowExtension(const char* extension) { #ifdef TEST_PRINT osPrintf("Allowing extension: \"%s\"\n", extension); #endif UtlString* extensionName = new UtlString(extension); allowedSipExtensions.append(extensionName); } void SipUserAgent::getSupportedExtensions(UtlString& extensionsString) { extensionsString.remove(0); UtlString* extensionName = NULL; UtlDListIterator iterator(allowedSipExtensions); while ((extensionName = (UtlString*) iterator())) { if(!extensionsString.isNull()) extensionsString.append(", "); extensionsString.append(extensionName->data()); } } void SipUserAgent::setLocationHeader(const char* szHeader) { mLocationHeader = szHeader; } void SipUserAgent::setRecurseOnlyOne300Contact(UtlBoolean recurseOnlyOne) { mRecurseOnlyOne300Contact = recurseOnlyOne; } SipMessage* SipUserAgent::getRequest(const SipMessage& response) { // If the transaction exists and can be locked it // is returned. enum SipTransaction::messageRelationship relationship; SipTransaction* transaction = mSipTransactions.findTransactionFor(response, FALSE, // incoming relationship); SipMessage* request = NULL; if(transaction && transaction->getRequest()) { // Make a copy to return request = new SipMessage(*(transaction->getRequest())); } // Need to unlock the transaction if(transaction) mSipTransactions.markAvailable(*transaction); return(request); } int SipUserAgent::getTcpPort() const { int iPort = PORT_NONE ; if (mSipTcpServer) { iPort = mSipTcpServer->getServerPort() ; } return iPort ; } int SipUserAgent::getUdpPort() const { int iPort = PORT_NONE ; if (mSipUdpServer) { iPort = mSipUdpServer->getServerPort() ; } return iPort ; } int SipUserAgent::getTlsPort() const { int iPort = PORT_NONE ; #ifdef SIP_TLS if (mSipTlsServer) { iPort = mSipTlsServer->getServerPort() ; } #endif return iPort ; } /* ============================ INQUIRY =================================== */ UtlBoolean SipUserAgent::isMethodAllowed(const char* method) { UtlString methodName(method); UtlBoolean isAllowed = (allowedSipMethods.occurrencesOf(&methodName) > 0); if (!isAllowed) { /* The method was not explicitly requested, but check for whether the * application has registered for the wildcard. If so, the method is * allowed, but we do not advertise that fact in the Allow header.*/ UtlString wildcardMethod; OsReadLock lock(mObserverMutex); isAllowed = mMessageObservers.contains(&wildcardMethod); } return(isAllowed); } UtlBoolean SipUserAgent::isExtensionAllowed(const char* extension) const { #ifdef TEST_PRINT osPrintf("isExtensionAllowed extension: \"%s\"\n", extension); #endif UtlString extensionString; if(extension) extensionString.append(extension); extensionString.toLower(); UtlString extensionName(extensionString); extensionString.remove(0); return(allowedSipExtensions.occurrencesOf(&extensionName) > 0); } void SipUserAgent::whichExtensionsNotAllowed(const SipMessage* message, UtlString* disallowedExtensions) const { int extensionIndex = 0; UtlString extension; disallowedExtensions->remove(0); while(message->getRequireExtension(extensionIndex, &extension)) { if(!isExtensionAllowed(extension.data())) { if(!disallowedExtensions->isNull()) { disallowedExtensions->append(SIP_MULTIFIELD_SEPARATOR); disallowedExtensions->append(SIP_SINGLE_SPACE); } disallowedExtensions->append(extension.data()); } extensionIndex++; } extension.remove(0); } UtlBoolean SipUserAgent::isMessageLoggingEnabled() { return(mMessageLogEnabled); } UtlBoolean SipUserAgent::isReady() { return isStarted(); } UtlBoolean SipUserAgent::waitUntilReady() { // Lazy hack, should be a semaphore or event int count = 0; while(!isReady() && count < 5) { delay(500); count++; } return isReady() ; } UtlBoolean SipUserAgent::isForkingEnabled() { return(mForkingEnabled); } UtlBoolean SipUserAgent::isMyHostAlias(Url& route) const { UtlString hostAlias; route.getHostAddress(hostAlias); int port = route.getHostPort(); if(port == PORT_NONE) { hostAlias.append(":5060"); } else { char portString[20]; sprintf(portString, ":%d", port); hostAlias.append(portString); } UtlString aliasMatch(hostAlias); UtlContainable* found = mMyHostAliases.find(&aliasMatch); return(found != NULL); } UtlBoolean SipUserAgent::recurseOnlyOne300Contact() { return(mRecurseOnlyOne300Contact); } UtlBoolean SipUserAgent::isOk(OsSocket::IpProtocolSocketType socketType) { UtlBoolean retval = FALSE; switch(socketType) { case OsSocket::TCP : if (mSipTcpServer) { retval = mSipTcpServer->isOk(); } break; case OsSocket::UDP : if (mSipUdpServer) { retval = mSipUdpServer->isOk(); } break; #ifdef SIP_TLS case OsSocket::SSL_SOCKET : if (mSipTlsServer) { retval = mSipTlsServer->isOk(); } break; #endif default : OsSysLog::add(FAC_SIP, PRI_ERR, "SipUserAgent::isOK - invalid socket type %d", socketType); break; } return retval; } UtlBoolean SipUserAgent::isShutdownDone() { return mbShutdownDone; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ UtlBoolean SipUserAgent::shouldAuthenticate(SipMessage* message) const { UtlString method; message->getRequestMethod(&method); //SDUA - Do not authenticate if a CANCEL or an ACK req/res from other side UtlBoolean methodCompare = TRUE ; if ( strcmp(method.data(), SIP_ACK_METHOD) == 0 || strcmp(method.data(), SIP_CANCEL_METHOD) == 0 ) { methodCompare = FALSE; } method.remove(0); return( methodCompare && ( 0 == mAuthenticationScheme.compareTo(HTTP_BASIC_AUTHENTICATION, UtlString::ignoreCase ) || 0 == mAuthenticationScheme.compareTo(HTTP_DIGEST_AUTHENTICATION, UtlString::ignoreCase ) ) ); } UtlBoolean SipUserAgent::authorized(SipMessage* request, const char* uri) const { UtlBoolean allowed = FALSE; // Need to create a nonce database for nonce's created // for each message (or find the message for the previous // sequence number containing the authentication response // and nonce for this request) const char* nonce = "1234567890"; // :TBD: should be using nonce from the message if(mAuthenticationScheme.compareTo("") == 0) { allowed = TRUE; } else { UtlString user; UtlString password; // Get the user id request->getAuthorizationUser(&user); // Look up the password mpAuthenticationDb->get(user.data(), password); #ifdef TEST_PRINT osPrintf("SipUserAgent::authorized user:%s password found:\"%s\"\n", user.data(), password.data()); #endif // If basic is set allow basic or digest if(mAuthenticationScheme.compareTo(HTTP_BASIC_AUTHENTICATION, UtlString::ignoreCase ) == 0 ) { allowed = request->verifyBasicAuthorization(user.data(), password.data()); // Try Digest if basic failed if(! allowed) { #ifdef TEST_PRINT osPrintf("SipUserAgent::authorized basic auth. failed\n"); #endif allowed = request->verifyMd5Authorization(user.data(), password.data(), nonce, mAuthenticationRealm.data(), uri); } #ifdef TEST_PRINT else { osPrintf("SipUserAgent::authorized basic auth. passed\n"); } #endif } // If digest is set allow only digest else if(mAuthenticationScheme.compareTo(HTTP_DIGEST_AUTHENTICATION, UtlString::ignoreCase ) == 0 ) { allowed = request->verifyMd5Authorization(user.data(), password.data(), nonce, mAuthenticationRealm.data(), uri); } user.remove(0); password.remove(0); } return(allowed); } void SipUserAgent::addAuthentication(SipMessage* message) const { message->setAuthenticationData(mAuthenticationScheme.data(), mAuthenticationRealm.data(), "1234567890", // nonce "abcdefghij"); // opaque } UtlBoolean SipUserAgent::resendWithAuthorization(SipMessage* response, SipMessage* request, int* messageType, int authorizationEntity) { UtlBoolean requestResent =FALSE; int sequenceNum; UtlString method; response->getCSeqField(&sequenceNum, &method); // The transaction sends the ACK for error cases now //if(method.compareTo(SIP_INVITE_METHOD , UtlString::ignoreCase) == 0) //{ // Need to send an ACK to finish transaction // SipMessage ackMessage; // ackMessage.setAckData(response, request); // send(ackMessage); //} SipMessage* authorizedRequest = new SipMessage(); #ifdef TEST_PRINT osPrintf("**************************************\n"); osPrintf("CREATING message in resendWithAuthorization @ address: %X\n",authorizedRequest); osPrintf("**************************************\n"); #endif if ( mpLineMgr && mpLineMgr->buildAuthenticatedRequest(response, request,authorizedRequest)) { #ifdef TEST_PRINT osPrintf("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n"); UtlString authBytes; int authBytesLen; authorizedRequest->getBytes(&authBytes, &authBytesLen); osPrintf("Auth. message:\n%s", authBytes.data()); osPrintf("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n"); #endif requestResent = send(*authorizedRequest); // Send the response back to the application // to notify it of the CSeq change for the response *messageType = SipMessageEvent::AUTHENTICATION_RETRY; } #ifdef TEST else { osPrintf("Giving up on entity %d authorization, userId: \"%s\"\n", authorizationEntity, dbUserId.data()); osPrintf("authorization failed previously sent: %d\n", request->getAuthorizationField(&authField, authorizationEntity)); } #endif delete authorizedRequest; return(requestResent); } void SipUserAgent::lookupSRVSipAddress(UtlString protocol, UtlString& sipAddress, int& port, UtlString& srcIp) { OsSocket::IpProtocolSocketType transport = OsSocket::UNKNOWN; if (sipIpAddress != "127.0.0.1") { server_t *server_list; server_list = SipSrvLookup::servers(sipAddress.data(), "sip", transport, port, srcIp.data()); // The returned value is a sorted array of server_t with last element having host=NULL. // The servers are arranged in order of decreasing preference. if ( !server_list ) { #ifdef TEST_PRINT osPrintf("The DNS server is not SRV capable; \nbind servers v8.0 and above are SRV capable\n"); #endif } else { // The result array contains the hostname, // socket type, IP address and port (in network byte order) // DNS preference and weight server_t toServerUdp; server_t toServerTcp; int i; #ifdef TEST_PRINT osPrintf("\n Pref Wt Type Name(IP):Port\n"); for (i=0; SipSrvLookup::isValidServerT(server_list[i]); i++) { UtlString name; UtlString ip; SipSrvLookup::getHostNameFromServerT(server_list[i], name); SipSrvLookup::getIpAddressFromServerT(server_list[i], ip); osPrintf( "%6d %5d %5d %s(%s):%d\n", SipSrvLookup::getPreferenceFromServerT(server_list[i]), SipSrvLookup::getWeightFromServerT(server_list[i]), SipSrvLookup::getProtocolFromServerT(server_list[i]), name.data(), ip.data(), SipSrvLookup::getPortFromServerT(server_list[i]) ); } #endif for (i=0; server_list[i].isValidServerT(); i++) { if (server_list[i].getProtocolFromServerT() == OsSocket::UDP) { if (! toServerUdp.isValidServerT()) { toServerUdp = server_list[i]; #ifdef TEST_PRINT UtlString name; SipSrvLookup::getHostNameFromServerT(toServerUdp, name); osPrintf("UDP server %s\n", name.data()); #endif } } else if (server_list[i].getProtocolFromServerT() == OsSocket::TCP) { if (toServerTcp.isValidServerT()) { toServerTcp = server_list[i]; #ifdef TEST_PRINT UtlString name; SipSrvLookup::getHostNameFromServerT(toServerTcp, name); osPrintf("TCP server %s\n", name.data()); #endif } } } if (!protocol.compareTo("TCP") && toServerTcp.isValidServerT()) { int newPort = toServerTcp.getPortFromServerT(); if (portIsValid(newPort)) { toServerTcp.getIpAddressFromServerT(sipAddress); port = newPort; } OsSysLog::add(FAC_SIP, PRI_DEBUG,"SipUserAgent:: found TCP server %s port %d", sipAddress.data(), newPort ); } else if (toServerUdp.isValidServerT()) { int newPort = toServerUdp.getPortFromServerT(); if (portIsValid(newPort)) { toServerUdp.getIpAddressFromServerT(sipAddress); port = newPort; } #ifdef TEST_PRINT osPrintf("found UDP server %s port %d/%d\n", sipAddress.data(), newPort, SipSrvLookup::getPortFromServerT(toServerUdp)); #endif } delete[] server_list; } } } void SipUserAgent::setServerHeader(SipMessage& message) { UtlString existing; message.getServerField(&existing); if(existing.isNull()) { UtlString headerValue; selfHeaderValue(headerValue); message.setServerField(headerValue.data()); } } void SipUserAgent::setUserAgentHeader(SipMessage& message) { UtlString uaName; message.getUserAgentField(&uaName); if(uaName.isNull()) { selfHeaderValue(uaName); message.setUserAgentField(uaName.data()); } } void SipUserAgent::selfHeaderValue(UtlString& self) { self = defaultUserAgentName; if ( !mUserAgentHeaderProperties.isNull() ) { self.append(mUserAgentHeaderProperties); } if (mbIncludePlatformInUserAgentName) { self.append(PLATFORM_UA_PARAM); } } void SipUserAgent::setIncludePlatformInUserAgentName(const bool bInclude) { mbIncludePlatformInUserAgentName = bInclude; } const bool SipUserAgent::addContactAddress(SIPX_CONTACT_ADDRESS& contactAddress) { bool bRC = mContactDb.updateContact(contactAddress) ; if (!bRC) bRC = mContactDb.addContact(contactAddress); return bRC ; } void SipUserAgent::getContactAddresses(SIPX_CONTACT_ADDRESS* pContacts[], int &numContacts) { mContactDb.getAll(pContacts, numContacts); } void SipUserAgent::setHeaderOptions(const bool bAllowHeader, const bool bDateHeader, const bool bShortNames, const UtlString& acceptLanguage) { mbAllowHeader = bAllowHeader; mbDateHeader = bDateHeader; mbShortNames = bShortNames; mAcceptLanguage = acceptLanguage; } void SipUserAgent::prepareVia(SipMessage& message, UtlString& branchId, OsSocket::IpProtocolSocketType& toProtocol, const char* szTargetAddress, const int* piTargetPort, SIPX_TRANSPORT_DATA* pTransport) { UtlString viaAddress; UtlString viaProtocolString; SipMessage::convertProtocolEnumToString(toProtocol, viaProtocolString); if ((pTransport) && toProtocol == OsSocket::CUSTOM) { viaProtocolString = pTransport->szTransport ; } int viaPort; getViaInfo(toProtocol, viaAddress, viaPort, szTargetAddress, piTargetPort); // if the viaAddress is a local address that // has a STUN or RELAY address associated with it, // and the CONTACT is not a local address, // then change the viaAddress and port to match // the address and port from the Contact UtlString stunnedAddress; UtlString relayAddress; UtlString contactAddress; int contactPort; UtlString contactProtocol; SIPX_CONTACT_ADDRESS* pLocalContact = getContactDb().find(viaAddress, viaPort, CONTACT_LOCAL); SIPX_CONTACT_ADDRESS* pStunnedAddress = NULL; SIPX_CONTACT_ADDRESS* pRelayAddress = NULL; int numStunnedContacts = 0; const SIPX_CONTACT_ADDRESS* stunnedContacts[MAX_IP_ADDRESSES]; int numRelayContacts = 0; const SIPX_CONTACT_ADDRESS* relayContacts[MAX_IP_ADDRESSES]; if (pLocalContact) { getContactDb().getAllForAdapter(stunnedContacts, pLocalContact->cInterface, numStunnedContacts, CONTACT_NAT_MAPPED); getContactDb().getAllForAdapter(relayContacts, pLocalContact->cInterface, numRelayContacts, CONTACT_RELAY); int i = 0; bool bFound = false; while (!bFound && TRUE == message.getContactAddress(i++, &contactAddress, &contactPort, &contactProtocol)) { int j = 0; for (j = 0; j < numStunnedContacts; j++) { if (strcmp(contactAddress, stunnedContacts[j]->cIpAddress) == 0) { // contact is a stunned address, corresponding to // the local address in the via, so, use it viaAddress = stunnedContacts[j]->cIpAddress; viaPort = stunnedContacts[j]->iPort; bFound = true; break; } } for (j = 0; j < numRelayContacts; j++) { if (strcmp(contactAddress, relayContacts[j]->cIpAddress) == 0) { // contact is a stunned address, corresponding to // the local address in the via, so, use it viaAddress = relayContacts[j]->cIpAddress; viaPort = relayContacts[j]->iPort; bFound = true; break; } } } } UtlString routeId ; if ((pTransport) && toProtocol == OsSocket::CUSTOM) { routeId = pTransport->cRoutingId ; } // Add the via field data message.addVia(viaAddress.data(), viaPort, viaProtocolString, branchId.data(), (toProtocol == OsSocket::UDP) && getUseRport(), routeId.data()); return; } void SipUserAgent::addExternalTransport(const UtlString transportName, const SIPX_TRANSPORT_DATA* const pTransport) { const UtlString key = transportName + "|" + UtlString(pTransport->szLocalIp); mExternalTransports.insertKeyAndValue((UtlContainable*)new UtlString(key), new UtlVoidPtr((void*)pTransport)); return; } void SipUserAgent::removeExternalTransport(const UtlString transportName, const SIPX_TRANSPORT_DATA* const pTransport) { const UtlString key = transportName + "|" + UtlString(pTransport->szLocalIp); mExternalTransports.destroy((UtlContainable*)&key); return; } const SIPX_TRANSPORT_DATA* const SipUserAgent::lookupExternalTransport(const UtlString transportName, const UtlString ipAddress) const { const UtlString key = transportName + "|" + ipAddress; UtlVoidPtr* pTransportContainer; pTransportContainer = (UtlVoidPtr*) mExternalTransports.findValue(&key); if (pTransportContainer) { const SIPX_TRANSPORT_DATA* const pTransport = (const SIPX_TRANSPORT_DATA* const) pTransportContainer->getValue(); return pTransport; } return NULL; } #ifdef SIP_TLS // ITlsSink implementations bool SipUserAgent::onServerCertificate(void* pCert, char* serverHostName) { bool bRet = true; if (!mpLastSipMessage) { bRet = false; } else { char szSubjAltName[256]; memset(szSubjAltName, 0, sizeof(szSubjAltName)); SmimeBody::getSubjAltName(szSubjAltName, (CERTCertificate*)pCert, sizeof(szSubjAltName)); bRet = mpLastSipMessage->fireSecurityEvent(this, SECURITY_TLS, SECURITY_CAUSE_TLS_SERVER_CERTIFICATE, mpLastSipMessage->getSecurityAttributes(), pCert, szSubjAltName); if (!bRet) { mpLastSipMessage->fireSecurityEvent(this, SECURITY_TLS, SECURITY_CAUSE_TLS_CERTIFICATE_REJECTED, mpLastSipMessage->getSecurityAttributes(), pCert, szSubjAltName); } } return bRet; } bool SipUserAgent::onTlsEvent(int cause) { bool bRet = true; return bRet; } #endif /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipUserAgentStateless.cpp0000644000175000017500000001306312205613256026142 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipUserAgentStateless::SipUserAgentStateless(int sipTcpPort, int sipUdpPort) : SipUserAgentBase(sipTcpPort, sipUdpPort) { mpMessageObserver = NULL; UtlString localAddress; OsSocket::getHostIp(&localAddress); Url contact; contact.setHostAddress(localAddress.data()); contact.setHostPort(sipUdpPort); contact.toString(mContactAddress); OsDatagramSocket* serverSocket = new OsDatagramSocket(0, NULL,sipUdpPort, NULL); mpUdpServer = new SipClient(serverSocket); mpUdpServer->setUserAgent(this); mpUdpServer->start(); } // Copy constructor SipUserAgentStateless::SipUserAgentStateless(const SipUserAgentStateless& rSipUserAgentStateless) { } // Destructor SipUserAgentStateless::~SipUserAgentStateless() { if(mpUdpServer) delete mpUdpServer; mpUdpServer = NULL; } /* ============================ MANIPULATORS ============================== */ // Assignment operator SipUserAgentStateless& SipUserAgentStateless::operator=(const SipUserAgentStateless& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } UtlBoolean SipUserAgentStateless::handleMessage(OsMsg& eventMessage) { return(TRUE); } void SipUserAgentStateless::addMessageConsumer(OsServerTask* messageConsumer) { mpMessageObserver = messageConsumer; } UtlBoolean SipUserAgentStateless::send(SipMessage& message, OsMsgQ* responseListener, void* responseListenerData) { UtlString sendAddress; UtlString sendProtocol; int sendPort; if(message.isResponse()) { int receivedPort; UtlBoolean receivedSet; UtlBoolean maddrSet; UtlBoolean receivedPortSet; message.getLastVia(&sendAddress, &sendPort, &sendProtocol, &receivedPort, &receivedSet, &maddrSet, &receivedPortSet); if(receivedPortSet && portIsValid(receivedPort)) { sendPort = receivedPort; } } else { UtlString uriString; message.getRequestUri(&uriString); Url uri(uriString); uri.getHostAddress(sendAddress); // Check for maddr UtlString maddr; uri.getUrlParameter("maddr", maddr); if(!maddr.isNull()) { // Use maddr if present sendAddress = maddr; } uri.getUrlParameter("transport", sendProtocol); sendPort = uri.getHostPort(); } UtlBoolean sendOk = sendTo(message, sendAddress.data(), sendProtocol.data(), sendPort); return(sendOk); } UtlBoolean SipUserAgentStateless::sendTo(SipMessage& message, const char* sendAddress, const char* sendProtocol, int sendPort) { UtlBoolean sendOk = FALSE; if(sendAddress && *sendAddress && mpUdpServer) { if (!portIsValid(sendPort)) { sendPort = SIP_PORT; } sendOk = mpUdpServer->sendTo(message, sendAddress, sendPort); } // Log the message if (isMessageLoggingEnabled()) { UtlString messageStatus; char messageChars[200]; if(sendOk) sprintf(messageChars, "Sent message %s port:%d:\n", sendAddress, sendPort); else sprintf(messageChars, "Failed to send message %s port:%d:\n", sendAddress, sendPort); messageStatus = messageChars; UtlString msgBytes; int msgLen; message.getBytes(&msgBytes, &msgLen); msgBytes.insert(0, messageStatus); msgBytes.append("--------------------END--------------------\n"); logMessage(msgBytes.data(), msgBytes.length()); } return(sendOk); } void SipUserAgentStateless::dispatch(SipMessage* message, int messageType) { // Log the message //if(message) //{ // UtlString msgBytes; // int msgLen; // message->getBytes(&msgBytes, &msgLen); // msgBytes.insert(0, "Received message:\n"); // msgBytes.append("++++++++++++++++++++END++++++++++++++++++++\n"); // logMessage(msgBytes.data(), msgBytes.length()); //} if(mpMessageObserver) { SipMessageEvent event(message); event.setMessageStatus(messageType); mpMessageObserver->postMessage(event); } } /* ============================ ACCESSORS ================================= */ void SipUserAgentStateless::logMessage(const char* message, int messageLength) { osPrintf("%s", message); } /* ============================ INQUIRY =================================== */ UtlBoolean SipUserAgentStateless::isMessageLoggingEnabled() { return true ; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SmimeBody.cpp0000644000175000017500000020702112205613256023570 0ustar00danieldaniel00000000000000#ifdef OPENSSL // // // Copyright (C) 2005 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie (dpetrie AT SIPez DOT com) // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include //#define ENABLE_OPENSSL_SMIME #ifdef ENABLE_OPENSSL_SMIME # include # include # include # include # include #endif //#define ENABLE_NSS_SMIME #ifdef ENABLE_NSS_SMIME # include # include # include # include # include # include # include extern "C" CERTCertificate * __CERT_DecodeDERCertificate(SECItem *derSignedCert, PRBool copyDER, char *nickname); #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS #ifdef ENABLE_OPENSSL_SMIME static void dumpOpensslError() { BIO* bioErrorBuf = BIO_new(BIO_s_mem()); ERR_print_errors(bioErrorBuf); BUF_MEM *bioErrorMem; BIO_get_mem_ptr(bioErrorBuf, &bioErrorMem); if(bioErrorMem) { UtlString errorString; errorString.append(bioErrorMem->data, bioErrorMem->length); printf("OPENSSL Error:\n%s\n", errorString.data()); } } #endif /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Default Constructor SmimeBody::SmimeBody() { mContentEncoding = SMIME_ENODING_BINARY; append(CONTENT_SMIME_PKCS7); mClassType = SMIME_BODY_CLASS; mpDecryptedBody = NULL; } // Constructor SmimeBody::SmimeBody(const char* bytes, int length, const char* smimeEncodingType) { bodyLength = length; mBody.append(bytes, length); // Remove to ake sure base class did not already set it remove(0); append(CONTENT_SMIME_PKCS7); mClassType = SMIME_BODY_CLASS; mContentEncoding = SMIME_ENODING_UNKNOWN; if(smimeEncodingType) { UtlString sMimeEncodingString(smimeEncodingType); sMimeEncodingString.toUpper(); if(sMimeEncodingString.compareTo(HTTP_CONTENT_TRANSFER_ENCODING_BINARY, UtlString::ignoreCase) == 0) { mContentEncoding = SMIME_ENODING_BINARY; } else if(sMimeEncodingString.compareTo(HTTP_CONTENT_TRANSFER_ENCODING_BASE64, UtlString::ignoreCase) == 0) { mContentEncoding = SMIME_ENODING_BASE64; } else { // TODO: We could probably put a hack in here to heuristically // determine if the encoding is base64 or not based upon the // byte values. OsSysLog::add(FAC_SIP, PRI_ERR, "Invalid transport encoding for S/MIME content"); } } mpDecryptedBody = NULL; } // Copy constructor SmimeBody::SmimeBody(const SmimeBody& rSmimeBody) { // Copy the base class stuff this->HttpBody::operator=((const HttpBody&)rSmimeBody); mpDecryptedBody = NULL; if(rSmimeBody.mpDecryptedBody) { mpDecryptedBody = HttpBody::copyBody(*(rSmimeBody.mpDecryptedBody)); } mClassType = SMIME_BODY_CLASS; // Remove to ake sure base class did not already set it remove(0); append(CONTENT_SMIME_PKCS7); mContentEncoding = rSmimeBody.mContentEncoding; } // Destructor SmimeBody::~SmimeBody() { if(mpDecryptedBody) { delete mpDecryptedBody; mpDecryptedBody = NULL; } } /* ============================ MANIPULATORS ============================== */ // Assignment operator SmimeBody& SmimeBody::operator=(const SmimeBody& rhs) { if (this == &rhs) // handle the assignment to self case return *this; // Copy the parent *((HttpBody*)this) = rhs; // Set the class type just to play it safe mClassType = SMIME_BODY_CLASS; // Remove the decrypted body if one is attached, // in case we copy over it if(mpDecryptedBody) { delete mpDecryptedBody; mpDecryptedBody = NULL; } // If the source has a body copy it if(rhs.mpDecryptedBody) { mpDecryptedBody = HttpBody::copyBody(*(rhs.mpDecryptedBody)); } mContentEncoding = rhs.mContentEncoding; return *this; } UtlBoolean SmimeBody::decrypt(const char* derPkcs12, int derPkcs12Length, const char* pkcs12Password) { UtlBoolean decryptionSucceeded = FALSE; UtlString decryptedData; #ifdef ENABLE_OPENSSL_SMIME decryptionSucceeded = opensslSmimeDecrypt(derPkcs12, derPkcs12Length, pkcs12Password, (mContentEncoding == SMIME_ENODING_BASE64), mBody.data(), mBody.length(), decryptedData); #elif ENABLE_NSS_SMIME OsSysLog::add(FAC_SIP, PRI_ERR, "NSS S/MIME decrypt not implemented"); #endif // Decryption succeeded, so create a HttpBody for the result if(decryptionSucceeded && decryptedData.length() > 0) { HttpBody* newDecryptedBody = NULL; // Need to read the headers before the real body to see // what the content type of the decrypted body is UtlDList bodyHeaders; int parsedBytes = HttpMessage::parseHeaders(decryptedData.data(), decryptedData.length(), bodyHeaders); UtlString contentTypeName(HTTP_CONTENT_TYPE_FIELD); NameValuePair* contentType = (NameValuePair*) bodyHeaders.find(&contentTypeName); UtlString contentEncodingName(HTTP_CONTENT_TRANSFER_ENCODING_FIELD); NameValuePair* contentEncoding = (NameValuePair*) bodyHeaders.find(&contentEncodingName); const char* realBodyStart = decryptedData.data() + parsedBytes; int realBodyLength = decryptedData.length() - parsedBytes; newDecryptedBody = HttpBody::createBody(realBodyStart, realBodyLength, contentType ? contentType->getValue() : NULL, contentEncoding ? contentEncoding->getValue() : NULL); bodyHeaders.destroyAll(); // If one already exists, delete it. This should not typically // be the case. Infact it might make sense to make this method // a no-op if a decrypted body already exists if(mpDecryptedBody) { delete mpDecryptedBody; mpDecryptedBody = NULL; } mpDecryptedBody = newDecryptedBody; } return(decryptionSucceeded); } UtlBoolean SmimeBody::encrypt(HttpBody* bodyToEncrypt, int numRecipients, const char* derPublicKeyCerts[], int derPubliceKeyCertLengths[]) { UtlBoolean encryptionSucceeded = FALSE; // Clean up an residual decrypted body or encrypted body content. // Should typically not be any. if(mpDecryptedBody) { delete mpDecryptedBody; mpDecryptedBody = NULL; } mBody.remove(0); if(bodyToEncrypt) { UtlString dataToEncrypt; UtlString contentType = bodyToEncrypt->getContentType(); // Add the content-type and content-encoding headers to // the body to be decrypted so that when the otherside // decrypts this body, it can tell what the content is dataToEncrypt ="Content-Type: "; dataToEncrypt.append(contentType); dataToEncrypt.append(END_OF_LINE_DELIMITOR); dataToEncrypt.append("Content-Transfer-Encoding: binary"); dataToEncrypt.append(END_OF_LINE_DELIMITOR); dataToEncrypt.append(END_OF_LINE_DELIMITOR); // Append the real body content const char* dataPtr; int dataLength; bodyToEncrypt->getBytes(&dataPtr, &dataLength); dataToEncrypt.append(dataPtr, dataLength); // Attach the decrypted version of the body for // future reference. mpDecryptedBody = bodyToEncrypt; // We almost always want to use binary for SIP as it is // much more efficient than base64. UtlBoolean encryptedDataInBase64Format = FALSE; #ifdef ENABLE_OPENSSL_SMIME encryptionSucceeded = opensslSmimeEncrypt(numRecipients, derPublicKeyCerts, derPubliceKeyCertLengths, dataToEncrypt.data(), dataToEncrypt.length(), encryptedDataInBase64Format, mBody); #elif ENABLE_NSS_SMIME encryptionSucceeded = nssSmimeEncrypt(numRecipients, derPublicKeyCerts, derPubliceKeyCertLengths, dataToEncrypt.data(), dataToEncrypt.length(), encryptedDataInBase64Format, mBody); #endif // There should always be content if encryption succeeds if(encryptionSucceeded && mBody.length() <= 0) { encryptionSucceeded = FALSE; OsSysLog::add(FAC_SIP, PRI_ERR, "SmimeBody::encrypt no encrypted content"); } } bodyLength = mBody.length(); return(encryptionSucceeded); } #ifdef ENABLE_NSS_SMIME static void nssOutToUtlString(void *sink, const char *data, unsigned long dataLength) { printf("nssOutToUtlString recieved %d bytes\n", dataLength); UtlString* outputSink = (UtlString*) sink; outputSink->append(data, dataLength); } #endif UtlBoolean SmimeBody::nssSmimeEncrypt(int numResipientCerts, const char* derPublicKeyCerts[], int derPublicKeyCertLengths[], const char* dataToEncrypt, int dataToEncryptLength, UtlBoolean encryptedDataInBase64Format, UtlString& encryptedData) { UtlBoolean encryptionSucceeded = FALSE; encryptedData.remove(0); #ifdef ENABLE_NSS_SMIME // nickname can be NULL as we are not putting this in a database char *nickname = NULL; // copyDER = true so we copy the DER format cert passed in so memory // is internally alloc'd and freed PRBool copyDER = true; // Create an envelope or container for the encrypted data SECOidTag algorithm = SEC_OID_DES_EDE3_CBC; // or SEC_OID_AES_128_CBC // Should be able to get the key size from the cert somehow int keysize = 1024; NSSCMSMessage* cmsMessage = NSS_CMSMessage_Create(NULL); NSSCMSEnvelopedData* myEnvelope = NSS_CMSEnvelopedData_Create(cmsMessage, algorithm, keysize); // Do the following for each recipient if there is more than one. // For each recipient: for(int certIndex = 0; certIndex < numResipientCerts; certIndex++) { // Convert the DER to a NSS CERT SECItem derFormatCertItem; SECItem* derFormatCertItemPtr = &derFormatCertItem; derFormatCertItem.data = (unsigned char*) derPublicKeyCerts[certIndex]; derFormatCertItem.len = derPublicKeyCertLengths[certIndex]; CERTCertificate* myCertFromDer = NULL; myCertFromDer = __CERT_DecodeDERCertificate(&derFormatCertItem, copyDER, nickname); // Add just the recipient Subject key Id, if it exists to the envelope // This is the minimal information needed to identify which recipient // the the symetric/session key is encrypted for NSSCMSRecipientInfo* recipientInfo = NULL; // Add the full set of recipient information including // the Cert. issuer location and org. info. recipientInfo = NSS_CMSRecipientInfo_Create(cmsMessage, myCertFromDer); if(recipientInfo) { if(NSS_CMSEnvelopedData_AddRecipient(myEnvelope , recipientInfo) != SECSuccess) { NSS_CMSEnvelopedData_Destroy(myEnvelope); myEnvelope = NULL; NSS_CMSRecipientInfo_Destroy(recipientInfo); } } // No recipientInfo else { NSS_CMSEnvelopedData_Destroy(myEnvelope); myEnvelope = NULL; } } //end for each recipient // Get the content out of the envelop NSSCMSContentInfo* envelopContentInfo = NSS_CMSEnvelopedData_GetContentInfo(myEnvelope); //TODO: why are we copying or setting the content pointer from the envelope into the msg???????? if (NSS_CMSContentInfo_SetContent_Data(cmsMessage, envelopContentInfo, NULL, PR_FALSE) != SECSuccess) { // release cmsg and other stuff NSS_CMSEnvelopedData_Destroy(myEnvelope); myEnvelope = NULL; } //TODO: why are we copying or setting the content pointer from the message and // putting it back into the msg???????? NSSCMSContentInfo* messageContentInfo = NSS_CMSMessage_GetContentInfo(cmsMessage); if(NSS_CMSContentInfo_SetContent_EnvelopedData(cmsMessage, messageContentInfo, myEnvelope) != SECSuccess) { // release cmsg and other stuff NSS_CMSEnvelopedData_Destroy(myEnvelope); myEnvelope = NULL; } if(cmsMessage) { // Create an encoder and context to do the encryption. // The encodedItem will stort the encoded result //SECItem encodedItem; //encodedItem.data = NULL; //encodedItem.len = 0; //SECITEM_AllocItem(NULL, &encodedItem, 0); printf("start encoder\n"); NSSCMSEncoderContext* encoderContext = NSS_CMSEncoder_Start(cmsMessage, nssOutToUtlString, &encryptedData, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); // Add encrypted content printf("update encoder\n"); NSS_CMSEncoder_Update(encoderContext, dataToEncrypt, dataToEncryptLength); // Finished encrypting printf("finish encoder\n"); NSS_CMSEncoder_Finish(encoderContext); myEnvelope = NULL; if(encryptedData.length() > 0) { encryptionSucceeded = TRUE; } // Clean up the message memory, the envelop gets cleaned up // with the message NSS_CMSMessage_Destroy(cmsMessage); cmsMessage = NULL; } #else OsSysLog::add(FAC_SIP, PRI_ERR, "SmimeBody::nssSmimeEncrypt invoked with ENABLE_NSS_SMIME not defined"); #endif return(encryptionSucceeded); } UtlBoolean SmimeBody::nssSmimeDecrypt(const char* derPkcs12, int derPkcs12Length, const char* pkcs12Password, UtlBoolean dataIsInBase64Format, const char* dataToDecrypt, int dataToDecryptLength, UtlString& decryptedData) { UtlBoolean decryptSucceeded = FALSE; decryptedData.remove(0); #ifdef ENABLE_NSS_SMIME OsSysLog::add(FAC_SIP, PRI_ERR, "SmimeBody::nssSmimeDecrypt not implemented"); ////// BEGIN WARNING: THIS CODE HAS NOT BEEN TESTED AT ALL /////// // allocate a temporaty slot in the database PK11SlotInfo *slot = PK11_GetInternalKeySlot(); PRBool swapUnicode = PR_FALSE; SEC_PKCS12DecoderContext *p12Decoder = NULL; // Need to put the pkcs12 password into a SECItem SECItem passwordItem; passwordItem.data = (unsigned char*) pkcs12Password; passwordItem.len = strlen(pkcs12Password); SECItem uniPasswordItem; uniPasswordItem.data = NULL; uniPasswordItem.len = 0; #ifdef IS_LITTLE_ENDIAN swapUnicode = PR_TRUE; #endif // Allocate a temporary internal slot slot = PK11_GetInternalSlot(); if(slot == NULL) { OsSysLog::add(FAC_SIP, PRI_ERR, "unable to use slot in NSS dataqbase for S/MIME decryption"); } else { // Do UNICODE conversion of password based upon the platform // (not sure this is even neccessary in our application). I do not // know how we would get unicode passwords if(0) //P12U_UnicodeConversion(NULL, &uniPasswordItem, passwordItem, PR_TRUE, // swapUnicode) != SECSuccess) { OsSysLog::add(FAC_SIP, PRI_ERR, "NSS Unicode conversion failed for PKCS12 object for S/MIME decryption"); } else { // Initialze the decoder for the PKCS12 container for the private key p12Decoder = SEC_PKCS12DecoderStart(&passwordItem, slot, NULL, NULL, NULL, NULL, NULL, NULL); if(!p12Decoder) { OsSysLog::add(FAC_SIP, PRI_ERR, "failed to initialize PKCS12 decoder to extract private key for S/MIME decryption"); } else { // Add the PKCS12 data to the decoder if(SEC_PKCS12DecoderUpdate(p12Decoder, (unsigned char *) derPkcs12, derPkcs12Length) != SECSuccess || // Validate the decoded PKCS12 SEC_PKCS12DecoderVerify(p12Decoder) != SECSuccess) { OsSysLog::add(FAC_SIP, PRI_ERR, "unable to decrypt PKCS12 for S/MIME decryption. Perhaps invalid PKCS12 or PKCS12 password"); } else { // Import the private key and certificate from the // decoded PKCS12 into the database if(SEC_PKCS12DecoderImportBags(p12Decoder) != SECSuccess) { OsSysLog::add(FAC_SIP, PRI_ERR, "failed to import private key and certificate into NSS database"); } else { // Put the S/MIME data in a SECItem SECItem dataToDecodeItem; dataToDecodeItem.data = (unsigned char *) dataToDecrypt; dataToDecodeItem.len = dataToDecryptLength; if(dataIsInBase64Format) { // TODO: // Use some NSS util. to convert base64 to binary OsSysLog::add(FAC_SIP, PRI_ERR, "NSS decrypt of base64 S/MIME message not implemented"); } else { // Decode the S/MIME blob NSSCMSMessage *cmsMessage = NSS_CMSMessage_CreateFromDER(&dataToDecodeItem, nssOutToUtlString, &decryptedData, NULL, NULL, NULL, NULL); if(cmsMessage && decryptedData.length() > 0) { decryptSucceeded = TRUE; } // TODO: // Remove the temporary private key from the // database using the slot handle } } } } } } // Clean up if(p12Decoder) { SEC_PKCS12DecoderFinish(p12Decoder); } if(uniPasswordItem.data) { SECITEM_ZfreeItem(&uniPasswordItem, PR_FALSE); } ////// END WARNING ///// #else OsSysLog::add(FAC_SIP, PRI_ERR, "SmimeBody::nssSmimeDecrypt invoked with ENABLE_NSS_SMIME not defined"); #endif return(decryptSucceeded); } UtlBoolean SmimeBody::opensslSmimeEncrypt(int numRecipients, const char* derPublicKeyCerts[], int derPublicKeyCertLengths[], const char* dataToEncrypt, int dataToEncryptLength, UtlBoolean encryptedDataInBase64Format, UtlString& encryptedData) { UtlBoolean encryptSucceeded = FALSE; encryptedData.remove(0); #ifdef ENABLE_OPENSSL_SMIME // Convert the DER format Certs. to a stack of X509 STACK_OF(X509)* recipientX509Certs = sk_X509_new_null(); for(int recipIndex = 0; recipIndex < numRecipients; recipIndex++) { X509* oneX509Cert = d2i_X509(NULL, (unsigned char**)&derPublicKeyCerts[recipIndex], derPublicKeyCertLengths[recipIndex]); if(oneX509Cert) { sk_X509_push(recipientX509Certs, oneX509Cert); } else { printf("Invalid DER format cert. Cannot convert to X509 OpenSSL (DER length: %d)\n", derPublicKeyCertLengths[recipIndex]); } } // Put the data to be encryped into a BIO that can be used as input to // the PKCS7 encoder BIO* dataToEncryptBio = BIO_new_mem_buf((void*)dataToEncrypt, dataToEncryptLength); // Use the X509 certs to create a PKCS7 encoder int encodeOpts = 0; if(encryptedDataInBase64Format) { PKCS7_BINARY; // binary format, not base64 } const EVP_CIPHER* cipher = EVP_des_ede3_cbc(); PKCS7* pkcs7Encoder = PKCS7_encrypt(recipientX509Certs, dataToEncryptBio, cipher, encodeOpts); BIO* encryptedDataBio = BIO_new(BIO_s_mem()); if(pkcs7Encoder && encryptedDataBio) { // Get the raw binary encrypted data out of the encoder i2d_PKCS7_bio(encryptedDataBio, pkcs7Encoder); BUF_MEM *encryptedDataBioMem = NULL; BIO_get_mem_ptr(encryptedDataBio, &encryptedDataBioMem); if(encryptedDataBioMem) { encryptSucceeded = TRUE; encryptedData.append(encryptedDataBioMem->data, encryptedDataBioMem->length); BIO_free(encryptedDataBio); encryptedDataBio = NULL; } } else { if(pkcs7Encoder == NULL) { OsSysLog::add(FAC_SIP, PRI_WARNING, "failed to create openssl PKCS12 encoder"); } if(encryptedDataBio) { OsSysLog::add(FAC_SIP, PRI_ERR, "Failed to allocate openssl BIO"); } } if(pkcs7Encoder) { // TODO: free up PKCS7 pkcs7Encoder = NULL; } if(dataToEncryptBio) { BIO_free(dataToEncryptBio); dataToEncryptBio = NULL; } // Free up the cert stack sk_X509_free(recipientX509Certs); #endif return(encryptSucceeded); } UtlBoolean SmimeBody::opensslSmimeDecrypt(const char* derPkcs12, int derPkcs12Length, const char* pkcs12Password, UtlBoolean dataIsInBase64Format, const char* dataToDecrypt, int dataToDecryptLength, UtlString& decryptedData) { UtlBoolean decryptSucceeded = FALSE; decryptedData.remove(0); #ifdef ENABLE_OPENSSL_SMIME EVP_PKEY* privateKey = NULL; X509* publicKeyCert = NULL; // Create the PKCS12 which contains both cert. and private key // from the DER format BIO* pkcs12Bio = BIO_new_mem_buf((void*)derPkcs12, derPkcs12Length); PKCS12 *pkcs12 = d2i_PKCS12_bio(pkcs12Bio, NULL); // The PKCS12 contains both the private key and the cert. which // are protected by symmetric encryption using the given password. PKCS12_parse(pkcs12, pkcs12Password, &privateKey, &publicKeyCert, NULL); PKCS12_free(pkcs12); pkcs12 = NULL; if(privateKey == NULL) { dumpOpensslError(); OsSysLog::add(FAC_SIP, PRI_ERR, "PKCS12 or PKCS12 password invalid or does not contain private key for S/MIME decrypt operation"); } if(publicKeyCert) { dumpOpensslError(); OsSysLog::add(FAC_SIP, PRI_ERR, "PKCS12 or PKCS12 password invalid or does not contain certificate and public key for S/MIME decrypt operation"); } // Create a memory BIO to put the body into BIO* encryptedBodyBioBuf = BIO_new_mem_buf((void*)dataToDecrypt, dataToDecryptLength); // Create the pkcs7 structure // The clearTextSignatureBio only gets set if it // is provided. BIO* decryptedBodyBioBuf = BIO_new(BIO_s_mem()); PKCS7* pkcs7 = NULL; if(dataIsInBase64Format) // base64 { BIO* clearTextSignatureBio = NULL; pkcs7 = SMIME_read_PKCS7(encryptedBodyBioBuf, &clearTextSignatureBio); if(clearTextSignatureBio) { BIO_free(clearTextSignatureBio); } } else // binary { pkcs7 = d2i_PKCS7_bio(encryptedBodyBioBuf, 0); } if(pkcs7 == NULL) { // Unable to initialize PKCS7 OsSysLog::add(FAC_SIP, PRI_ERR, "Unable to create OpenSSL PKCS7 context for S/MIME decrypt operation\n"); } if(pkcs7 && privateKey && publicKeyCert && decryptedBodyBioBuf) { // Decrypt the pkcs7 structure into a memory BIO int decryptOk = PKCS7_decrypt(pkcs7, privateKey, publicKeyCert, decryptedBodyBioBuf, 0); // Unable to decrypt if(!decryptOk) { OsSysLog::add(FAC_SIP, PRI_ERR, "Unable to decrypt S/MIME message using OpenSSL\n"); } else { // Get the data from the decrypted BIO BUF_MEM *bioMemoryStructure; BIO_get_mem_ptr(decryptedBodyBioBuf, &bioMemoryStructure); if (bioMemoryStructure) { decryptedData.append(bioMemoryStructure->data, bioMemoryStructure->length); decryptSucceeded = TRUE; } } } // Free up the BIOs if(encryptedBodyBioBuf) { BIO_free(encryptedBodyBioBuf); encryptedBodyBioBuf = NULL; } if(decryptedBodyBioBuf) { BIO_free(decryptedBodyBioBuf); decryptedBodyBioBuf; } #else OsSysLog::add(FAC_SIP, PRI_ERR, "SmimeBody::opensslSmimeDecrypt invoked with ENABLE_OPENSSL_SMIME not defined"); #endif return(decryptSucceeded); } UtlBoolean SmimeBody::convertPemToDer(UtlString& pemData, UtlString& derData) { UtlBoolean conversionSucceeded = FALSE; derData.remove(0); #ifdef ENABLE_OPENSSL_SMIME // Convert PEM to openssl X509 BIO* certPemBioBuf = BIO_new_mem_buf((void*)pemData.data(), pemData.length()); if(certPemBioBuf) { X509* x509 = PEM_read_bio_X509(certPemBioBuf, NULL, NULL, NULL); BIO* certDerBio = BIO_new(BIO_s_mem()); if(x509 && certDerBio) { // Convert the X509 to a DER buffer i2d_X509_bio(certDerBio, x509); BUF_MEM* certDerBioMem = NULL; BIO_get_mem_ptr(certDerBio, &certDerBioMem); if(certDerBioMem && certDerBioMem->data && certDerBioMem->length > 0) { derData.append(certDerBioMem->data, certDerBioMem->length); } BIO_free(certDerBio); certDerBio = NULL; X509_free(x509); x509 = NULL; } BIO_free(certPemBioBuf); certPemBioBuf = NULL; } #elif ENABLE_NSS_SMIME // Code from NSS secutil.c char* body = NULL; char* pemDataPtr = (char*) pemData.data(); /* check for headers and trailers and remove them */ if ((body = strstr(pemDataPtr, "-----BEGIN")) != NULL) { char *trailer = NULL; pemData = body; body = PORT_Strchr(body, '\n'); if (!body) body = PORT_Strchr(pemDataPtr, '\r'); /* maybe this is a MAC file */ if (body) trailer = strstr(++body, "-----END"); if (trailer != NULL) { *trailer = '\0'; } else { OsSysLog::add(FAC_SIP, PRI_ERR, "input has header but no trailer\n"); } } else { body = pemDataPtr; } /* Convert to binary */ SECItem derItem; derItem.data = NULL; derItem.len = 0; if(ATOB_ConvertAsciiToItem(&derItem, body)) { OsSysLog::add(FAC_SIP, PRI_ERR, "error converting PEM base64 data to binary"); } else { derData.append(((char*)derItem.data), derItem.len); conversionSucceeded = TRUE; } #else OsSysLog::add(FAC_SIP, PRI_ERR, "SmimeBody::convertPemToDer implemented with NSS and OpenSSL disabled"); #endif return(conversionSucceeded); } /* ============================ ACCESSORS ================================= */ const HttpBody* SmimeBody::getDecyptedBody() const { return(mpDecryptedBody); } /* ============================ INQUIRY =================================== */ UtlBoolean SmimeBody::isDecrypted() const { return(mpDecryptedBody != NULL); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ TESTING =================================== */ /* ============================ FUNCTIONS ================================= */ #else // NSS // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie (dpetrie AT SIPez DOT com) // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #ifdef SIP_TLS #include #endif #ifdef HAVE_NSS extern "C" CERTCertificate * __CERT_DecodeDERCertificate(SECItem *derSignedCert, PRBool copyDER, char *nickname); static char * PR_CALLBACK pk11Passwordcallback(PK11SlotInfo *slot, PRBool retry, void *arg); #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define MAX_SMIME_BODY_SIZE 8192 #define MAX_RECIPIENTS 64 // STATIC VARIABLE INITIALIZATIONS /*SECStatus P12U_UnicodeConversion(PRArenaPool *arena, SECItem *dest, SECItem *src, PRBool toUnicode, PRBool swapBytes); */ /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SmimeBody::SmimeBody(const char* bytes, int length, const char* smimeEncodingType) : mpSmimeSink(NULL) { bodyLength = length; mBody.append(bytes, length); mContentEncoding = SMIME_ENODING_UNKNOWN; if(smimeEncodingType) { UtlString sMimeEncodingString(smimeEncodingType); sMimeEncodingString.toUpper(); if(sMimeEncodingString.compareTo(HTTP_CONTENT_TRANSFER_ENCODING_BINARY, UtlString::ignoreCase) == 0) { mContentEncoding = SMIME_ENODING_BINARY; } else if(sMimeEncodingString.compareTo(HTTP_CONTENT_TRANSFER_ENCODING_BASE64, UtlString::ignoreCase) == 0) { mContentEncoding = SMIME_ENODING_BASE64; } else { // TODO: We could probably put a hack in here to heuristically // determine if the encoding is base64 or not based upon the // byte values. OsSysLog::add(FAC_SIP, PRI_ERR, "Invalid transport encoding for S/MIME content"); } } mpDecryptedBody = NULL; } // Copy constructor SmimeBody::SmimeBody(const SmimeBody& rSmimeBody) : HttpBody(rSmimeBody) { mpDecryptedBody = NULL; if(rSmimeBody.mpDecryptedBody) { mpDecryptedBody = HttpBody::copyBody(*(rSmimeBody.mpDecryptedBody)); } mContentEncoding = rSmimeBody.mContentEncoding; } // Destructor SmimeBody::~SmimeBody() { if(mpDecryptedBody) { delete mpDecryptedBody; mpDecryptedBody = NULL; } } /* ============================ MANIPULATORS ============================== */ // Assignment operator SmimeBody& SmimeBody::operator=(const SmimeBody& rhs) { if (this == &rhs) // handle the assignment to self case return *this; // Copy the parent *((HttpBody*)this) = rhs; // Remove the decrypted body if one is attached, // in case we copy over it if(mpDecryptedBody) { delete mpDecryptedBody; mpDecryptedBody = NULL; } // If the source has a body copy it if(rhs.mpDecryptedBody) { mpDecryptedBody = HttpBody::copyBody(*(rhs.mpDecryptedBody)); } mContentEncoding = rhs.mContentEncoding; return *this; } UtlBoolean SmimeBody::decrypt(const char* derPkcs12, int derPkcs12Length, const char* pkcs12Password, const char* certDbPassword, const char* signerCertDER, int signerCertDERLength, ISmimeNotifySink* pSink) { UtlBoolean decryptionSucceeded = FALSE; mpSmimeSink = pSink; UtlString decryptedData; decryptionSucceeded = nssSmimeDecrypt(derPkcs12, derPkcs12Length, pkcs12Password, certDbPassword, signerCertDER, signerCertDERLength, (mContentEncoding == SMIME_ENODING_BASE64), mBody.data(), mBody.length(), decryptedData, pSink); // Decryption succeeded, so create a HttpBody for the result if(decryptionSucceeded && decryptedData.length() > 0) { HttpBody* newDecryptedBody = NULL; // Need to read the headers before the real body to see // what the content type of the decrypted body is UtlDList bodyHeaders; int parsedBytes = HttpMessage::parseHeaders(decryptedData.data(), decryptedData.length(), bodyHeaders); UtlString contentTypeName(HTTP_CONTENT_TYPE_FIELD); NameValuePair* contentType = (NameValuePair*) bodyHeaders.find(&contentTypeName); UtlString contentEncodingName(HTTP_CONTENT_TRANSFER_ENCODING_FIELD); NameValuePair* contentEncoding = (NameValuePair*) bodyHeaders.find(&contentEncodingName); const char* realBodyStart = decryptedData.data() + parsedBytes; int realBodyLength = decryptedData.length() - parsedBytes; newDecryptedBody = HttpBody::createBody(realBodyStart, realBodyLength, contentType ? contentType->getValue() : NULL, contentEncoding ? contentEncoding->getValue() : NULL); bodyHeaders.destroyAll(); // If one already exists, delete it. This should not typically // be the case. Infact it might make sense to make this method // a no-op if a decrypted body already exists if(mpDecryptedBody) { delete mpDecryptedBody; mpDecryptedBody = NULL; } mpDecryptedBody = newDecryptedBody; } return(decryptionSucceeded); } UtlBoolean SmimeBody::encrypt(HttpBody* bodyToEncrypt, int numRecipients, const char* derPublicKeyCerts[], int derPubliceKeyCertLengths[], const char* szMyCertNickname, const char* szCertDbPassword, ISmimeNotifySink* pSink) { UtlBoolean encryptionSucceeded = FALSE; mpSmimeSink = pSink; // Clean up an residual decrypted body or encrypted body content. // Should typically not be any. if(mpDecryptedBody) { delete mpDecryptedBody; mpDecryptedBody = NULL; } mBody.remove(0); if(bodyToEncrypt) { UtlString dataToEncrypt; UtlString contentType = bodyToEncrypt->getContentType(); // We almost always want to use binary for SIP as it is // much more efficient than base64. UtlBoolean encryptedDataInBase64Format = FALSE; // Add the content-type and content-encoding headers to // the body to be decrypted so that when the otherside // decrypts this body, it can tell what the content is dataToEncrypt ="Content-Type: "; dataToEncrypt.append(contentType); dataToEncrypt.append(END_OF_LINE_DELIMITOR); dataToEncrypt.append("Content-Transfer-Encoding: binary"); dataToEncrypt.append(END_OF_LINE_DELIMITOR); dataToEncrypt.append(END_OF_LINE_DELIMITOR); // Append the real body content const char* dataPtr; int dataLength; bodyToEncrypt->getBytes(&dataPtr, &dataLength); dataToEncrypt.append(dataPtr, dataLength); // Attach the decrypted version of the body for // future reference. mpDecryptedBody = bodyToEncrypt; UtlString encryptedData; encryptionSucceeded = nssSmimeEncrypt(numRecipients, derPublicKeyCerts, derPubliceKeyCertLengths, szMyCertNickname, szCertDbPassword, dataToEncrypt.data(), dataToEncrypt.length(), encryptedDataInBase64Format, mBody, pSink); encryptedData = mBody; bodyLength = mBody.length(); // There should always be content if encryption succeeds if(encryptionSucceeded && encryptedData.length() <= 0) { encryptionSucceeded = FALSE; OsSysLog::add(FAC_SIP, PRI_ERR, "SmimeBody::encrypt no encrypted content"); } } return(encryptionSucceeded); } #ifdef HAVE_NSS void SmimeBody::getSubjAltName(char* szSubjAltName, const CERTCertificate* pCert, const size_t length) { CERTCertExtension** extensions = pCert->extensions; if (extensions) { while (*extensions) { SECItem *ext_oid = &(*extensions)->id; SECItem *ext_critical = &(*extensions)->critical; SECItem *ext_value = &(*extensions)->value; /* id attribute of the extension */ SECOidData *oiddata = SECOID_FindOID(ext_oid); /* value attribute of the extension */ /* SECItem ext_value has type (SECItemType), data (unsigned char *) and len (unsigned int) fields - the application interprets these */ SECOidTag oidtag = SECOID_FindOIDTag(ext_oid); if (oidtag == SEC_OID_X509_SUBJECT_ALT_NAME) // this is the subject alt name { strncpy(szSubjAltName, (const char*)ext_value->data, sipx_min(ext_value->len, length)); break; } extensions++; } } } #endif static void nssOutToUtlString(void *sink, const char *data, unsigned long dataLength) { // printf("nssOutToUtlString recieved %d bytes\n", dataLength); UtlString* outputSink = (UtlString*) sink; outputSink->append(data, dataLength); } static void nssSignedDataToUtlString(void *sink, const char *data, unsigned long dataLength) { // printf("nssOutToUtlString recieved %d bytes\n", dataLength); UtlString* outputSink = (UtlString*) sink; outputSink->append(data, dataLength); } UtlBoolean SmimeBody::nssSmimeEncrypt(int numResipientCerts, const char* derPublicKeyCerts[], int derPublicKeyCertLengths[], const char* szMyCertNickname, const char* szCertDbPassword, const char* dataToEncrypt, int dataToEncryptLength, UtlBoolean encryptedDataInBase64Format, UtlString& encryptedData, ISmimeNotifySink* pSmimeSink) { UtlBoolean encryptionSucceeded = FALSE; #ifdef HAVE_NSS bool bFoundRecipient = false; encryptedData.remove(0); //errorCode = SMIME_ENCRYPT_FAILURE_INVALID_PARAMETER; // nickname can be NULL as we are not putting this in a database char *nickname = NULL; // copyDER = true so we copy the DER format cert passed in so memory // is internally alloc'd and freed PRBool copyDER = PR_TRUE; // Create an envelope or container for the encrypted data SECOidTag algorithm = SEC_OID_DES_EDE3_CBC; // or SEC_OID_AES_128_CBC // Should be able to get the key size from the cert somehow int keysize = 192; NSSCMSMessage* cmsMessage = NSS_CMSMessage_Create(NULL); CERTCertificate* myCert = PK11_FindCertFromNickname((char*)szMyCertNickname, NULL);//szMyCertNickname, NULL); NSSCMSSignedData* sigd = NULL; if (CERT_CheckCertUsage (myCert, KU_DIGITAL_SIGNATURE) != SECSuccess) { // should fail out here } UtlString signedData = createSignedData(myCert, dataToEncrypt, dataToEncryptLength, sigd, (char*)szCertDbPassword); NSSCMSEnvelopedData* myEnvelope = NSS_CMSEnvelopedData_Create(cmsMessage, algorithm, keysize); // Do the following for each recipient if there is more than one. // For each recipient: NSSCMSRecipientInfo* recipientInfo[MAX_RECIPIENTS]; memset(recipientInfo, 0, sizeof(recipientInfo)); for(int certIndex = 0; certIndex < numResipientCerts; certIndex++) { // Convert the DER to a NSS CERT SECItem derFormatCertItem; derFormatCertItem.data = (unsigned char*)derPublicKeyCerts[certIndex]; derFormatCertItem.len = derPublicKeyCertLengths[certIndex]; //SECITEM_AllocItem(NULL, &derFormatCertItem, 0); // memcpy(&derFormatCertItem.data, derPublicKeyCerts[certIndex], derPublicKeyCertLengths[certIndex]) ; CERTCertificate* recipCertFromDer = NULL; recipCertFromDer = __CERT_DecodeDERCertificate(&derFormatCertItem, copyDER, nickname); int x = PR_GetError(); if (!recipCertFromDer) { if (pSmimeSink) pSmimeSink->OnError(SECURITY_ENCRYPT, SECURITY_CAUSE_ENCRYPT_FAILURE_BAD_PUBLIC_KEY); //errorCode = SMIME_ENCRYPT_FAILURE_BAD_PUBLIC_KEY; continue; } // Add just the recipient Subject key Id, if it exists to the envelope // This is the minimal information needed to identify which recipient // the the symetric/session key is encrypted for // Add the full set of recipient information including // the Cert. issuer location and org. info. recipientInfo[certIndex] = NSS_CMSRecipientInfo_Create(cmsMessage, recipCertFromDer); if(recipientInfo[certIndex]) { if(NSS_CMSEnvelopedData_AddRecipient(myEnvelope , recipientInfo[certIndex]) != SECSuccess) { NSS_CMSEnvelopedData_Destroy(myEnvelope); myEnvelope = NULL; NSS_CMSRecipientInfo_Destroy(recipientInfo[certIndex]); } else { bFoundRecipient = true; } } else { // No recipientInfo NSS_CMSEnvelopedData_Destroy(myEnvelope); myEnvelope = NULL; } if (recipCertFromDer) { CERT_DestroyCertificate(recipCertFromDer); } } //end for each recipient if (bFoundRecipient) { // Get the content out of the envelop NSSCMSContentInfo* envelopContentInfo = NSS_CMSEnvelopedData_GetContentInfo(myEnvelope); //TODO: why are we copying or setting the content pointer from the envelope into the msg???????? if (NSS_CMSContentInfo_SetContent_Data(cmsMessage, envelopContentInfo, NULL, PR_FALSE) != SECSuccess) { // release cmsg and other stuff NSS_CMSEnvelopedData_Destroy(myEnvelope); myEnvelope = NULL; } //TODO: why are we copying or setting the content pointer from the message and // putting it back into the msg???????? NSSCMSContentInfo* messageContentInfo = NSS_CMSMessage_GetContentInfo(cmsMessage); if(NSS_CMSContentInfo_SetContent_EnvelopedData(cmsMessage, messageContentInfo, myEnvelope) != SECSuccess) { // release cmsg and other stuff NSS_CMSEnvelopedData_Destroy(myEnvelope); myEnvelope = NULL; } if(cmsMessage) { // Create an encoder and context to do the encryption. // The encodedItem will store the encoded result NSSCMSEncoderContext* encoderContext = NSS_CMSEncoder_Start(cmsMessage, nssOutToUtlString, &encryptedData, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); // Add encrypted content NSS_CMSEncoder_Update(encoderContext, signedData.data(), signedData.length()); // Finished encrypting NSS_CMSEncoder_Finish(encoderContext); if(encryptedData.length() > 0) { encryptionSucceeded = TRUE; if (pSmimeSink) pSmimeSink->OnError(SECURITY_ENCRYPT, SECURITY_CAUSE_ENCRYPT_SUCCESS); } // Clean up the message memory, the envelop gets cleaned up // with the message NSS_CMSMessage_Destroy(cmsMessage); cmsMessage = NULL; } } // if bFoundRecipient #endif return(encryptionSucceeded); } #ifdef HAVE_NSS UtlString SmimeBody::createSignedData(CERTCertificate *cert, const char* dataToSign, const int dataToSignLength, NSSCMSSignedData*& sigd, char* szCertDbPassword) { NSSCMSMessage* cmsg = NULL; NSSCMSContentInfo* cinfo = NULL; NSSCMSSignerInfo *signerinfo = NULL; CERTCertificate *ekpcert = NULL; UtlString signedData(""); cmsg = NSS_CMSMessage_Create(NULL); /* * build chain of objects: message->signedData->data */ if ((sigd = NSS_CMSSignedData_Create(cmsg)) == NULL) { fprintf(stderr, "ERROR: cannot create CMS signedData object.\n"); goto loser; } cinfo = NSS_CMSSignedData_GetContentInfo(sigd); if (NSS_CMSContentInfo_SetContent_Data(cmsg, cinfo, NULL, false) != SECSuccess) { goto loser; } /* * create & attach signer information */ signerinfo = NSS_CMSSignerInfo_Create(cmsg, cert, SEC_OID_SHA1); if (signerinfo == NULL) { fprintf(stderr, "ERROR: cannot create CMS signerInfo object.\n"); goto loser; } if (NSS_CMSSignerInfo_AddSigningTime(signerinfo, PR_Now()) != SECSuccess) { fprintf(stderr, "ERROR: cannot add signingTime attribute.\n"); goto loser; } /* if (NSS_CMSSignerInfo_AddSMIMECaps(signerinfo) != SECSuccess) { fprintf(stderr, "ERROR: cannot add SMIMECaps attribute.\n"); goto loser; } */ /* add signing cert as EncryptionKeyPreference */ /* if (NSS_CMSSignerInfo_AddSMIMEEncKeyPrefs(signerinfo, cert, signOptions->options->certHandle) != SECSuccess) { fprintf(stderr, "ERROR: cannot add default SMIMEEncKeyPrefs attribute.\n"); goto loser; } */ if (NSS_CMSSignedData_AddSignerInfo(sigd, signerinfo) != SECSuccess) { fprintf(stderr, "ERROR: cannot add CMS signerInfo object.\n"); goto loser; } SECItem* digItem; digItem = SECITEM_AllocItem(NULL, NULL, SHA1_LENGTH); PK11_HashBuf(SEC_OID_SHA1, digItem->data, (unsigned char*)dataToSign, dataToSignLength); NSS_CMSSignedData_SetDigestValue(sigd, SEC_OID_SHA1, digItem); cinfo = NSS_CMSMessage_GetContentInfo(cmsg); NSSCMSContentInfo* signedInfo = NSS_CMSSignedData_GetContentInfo(sigd); NSS_CMSContentInfo_SetContent_SignedData(cmsg, cinfo, sigd); SECItem secData; secData.data = (unsigned char*)dataToSign; secData.len = dataToSignLength; if (NSS_CMSContentInfo_SetContent_Data(cmsg, signedInfo, NULL, PR_FALSE) != SECSuccess) { goto loser; } SECStatus status; char* prPass = (char*)PR_Malloc(1024); strncpy(prPass, szCertDbPassword, 256); NSSCMSEncoderContext* encoderContext = NSS_CMSEncoder_Start(cmsg, nssSignedDataToUtlString, &signedData, NULL, NULL, pk11Passwordcallback, (void*)prPass, NULL, NULL, NULL, NULL); // Add encrypted content status = NSS_CMSEncoder_Update(encoderContext, dataToSign, dataToSignLength); // Finished encrypting status = NSS_CMSEncoder_Finish(encoderContext); int x = PR_GetError(); /* SECItem secDerIn; secDerIn.data = (unsigned char*)signedData.data(); secDerIn.len = signedData.length(); SECItem secDerOut; secDerOut.data = NULL; secDerOut.len = 0; PLArenaPool *tmparena = PORT_NewArena(secDerIn.len *2); status = NSS_CMSDEREncode(cmsg, &secDerIn, &secDerOut, tmparena); PORT_Free(prPass); return UtlString((const char*)secDerOut.data, secDerOut.len); */ return signedData; loser: if (cert) { CERT_DestroyCertificate(cert); } return ""; } #endif UtlBoolean SmimeBody::nssSmimeDecrypt(const char* derPkcs12, int derPkcs12Length, const char* pkcs12Password, const char* certDbPassword, const char* signerCertDER, int signerCertDERLength, UtlBoolean dataIsInBase64Format, const char* dataToDecrypt, int dataToDecryptLength, UtlString& decryptedData, ISmimeNotifySink* pSmimeSink) { UtlBoolean decryptSucceeded = FALSE; #ifdef HAVE_NSS decryptedData.remove(0); char* szDbPassword; //errorCode = SMIME_DECRYPT_FAILURE_INVALID_PARAMETER; szDbPassword = (char*)PR_Malloc(256); strncpy(szDbPassword, certDbPassword, 255); SECItem decryptedEnvelope; decryptedEnvelope.data = NULL; decryptedEnvelope.len = 0; SECITEM_AllocItem(NULL, &decryptedEnvelope, 0); decryptedEnvelope.data = new unsigned char [MAX_SMIME_BODY_SIZE]; memset(decryptedEnvelope.data, 0, MAX_SMIME_BODY_SIZE); SECItem decryptedContent; decryptedContent.data = NULL; decryptedContent.len = 0; SECITEM_AllocItem(NULL, &decryptedContent, 0); decryptedContent.data = new unsigned char [MAX_SMIME_BODY_SIZE]; memset(decryptedContent.data, 0, MAX_SMIME_BODY_SIZE); PRBool swapUnicode = PR_FALSE; SEC_PKCS12DecoderContext *p12Decoder = NULL; SECItem slotPwd; memset(&slotPwd, 0, sizeof(SECItem)); slotPwd.data = (unsigned char*)PL_strdup(certDbPassword); slotPwd.len = strlen(certDbPassword); // Allocate a temporary internal slot PK11SlotInfo *slot = PK11_GetInternalKeySlot(); if(slot == NULL) { if (pSmimeSink) { pSmimeSink->OnError(SECURITY_DECRYPT, SECURITY_CAUSE_DECRYPT_FAILURE_DB_INIT); } OsSysLog::add(FAC_SIP, PRI_ERR, "unable to use slot in NSS dataqbase for S/MIME decryption\n"); } else { // first, decrypt the enveloped data SECItem dataToDecodeItem; dataToDecodeItem.data = (unsigned char *) dataToDecrypt; dataToDecodeItem.len = dataToDecryptLength; // Decode the S/MIME blob // mnCallbackDataLength = 0; NSSCMSMessage *cmsMessageEnveloped = NSS_CMSMessage_CreateFromDER(&dataToDecodeItem, nssOutToUtlString, &decryptedEnvelope, pk11Passwordcallback, (void*)szDbPassword, NULL, NULL); // now decode to get the signed data // Prepare to decode the message NSSCMSDecoderContext* decoder = NSS_CMSDecoder_Start(NULL, nssSignedDataToUtlString, &decryptedData, pk11Passwordcallback, (void*)szDbPassword, NULL, NULL); if (!decoder) { return FALSE; } NSS_CMSDecoder_Update(decoder, (const char*)decryptedEnvelope.data, decryptedEnvelope.len); NSSCMSMessage* cmsMsg = NSS_CMSDecoder_Finish(decoder); int x = PR_GetError(); if (!cmsMsg || !NSS_CMSMessage_IsSigned(cmsMsg)) { if (pSmimeSink) { pSmimeSink->OnError(SECURITY_DECRYPT, SECURITY_CAUSE_DECRYPT_MISSING_SIGNATURE); } // we only accept signed messages return FALSE; } if (!cmsMessageEnveloped) { // TODO - check for a bad password, then set the error // code, if it is a bad password //errorCode = SMIME_DECRYPT_FAILURE_BAD_DB_PASSWORD; } int nlevels = NSS_CMSMessage_ContentLevelCount(cmsMsg); for (int i = 0; i < nlevels; i++) { NSSCMSContentInfo *cinfo; SECOidTag typetag; cinfo = NSS_CMSMessage_ContentLevel(cmsMsg, i); typetag = NSS_CMSContentInfo_GetContentTypeTag(cinfo); if (SEC_OID_PKCS7_SIGNED_DATA == typetag) { NSSCMSSignedData *sigd = NULL; sigd = (NSSCMSSignedData *)NSS_CMSContentInfo_GetContent(cinfo); if (sigd == NULL) { pSmimeSink->OnError(SECURITY_DECRYPT, SECURITY_CAUSE_DECRYPT_MISSING_SIGNATURE); } else { NSSCMSSignerInfo *si; si = NSS_CMSSignedData_GetSignerInfo(sigd, 0); // send the signature up to the user CERTCertificate* pCert = NSS_CMSSignerInfo_GetSigningCertificate(si, CERT_GetDefaultCertDB()); char szSubjAltName[256]; memset(szSubjAltName, 0, sizeof(szSubjAltName)); getSubjAltName(szSubjAltName, pCert, sizeof(szSubjAltName)); if (!pCert || !pSmimeSink->OnSignature((void*)pCert, szSubjAltName)) { if (pCert) { pSmimeSink->OnError(SECURITY_DECRYPT, SECURITY_CAUSE_DECRYPT_SIGNATURE_REJECTED); } else { pSmimeSink->OnError(SECURITY_DECRYPT, SECURITY_CAUSE_DECRYPT_MISSING_SIGNATURE); } decryptSucceeded = false; decryptedData = ""; } else { // Verify the signature HRESULT hr = S_OK; if (NSS_CMSSignedData_VerifySignerInfo(sigd, 0, CERT_GetDefaultCertDB(), certUsageEmailSigner) != SECSuccess) { switch (PORT_GetError()) { case SEC_ERROR_PKCS7_BAD_SIGNATURE: case SEC_ERROR_BAD_SIGNATURE: decryptSucceeded = false; if (pSmimeSink) { pSmimeSink->OnError(SECURITY_DECRYPT, SECURITY_CAUSE_DECRYPT_BAD_SIGNATURE); } break; case SEC_ERROR_UNTRUSTED_ISSUER: case SEC_ERROR_UNTRUSTED_CERT: #ifndef SIP_TLS_TEST decryptSucceeded = false; if (pSmimeSink) { pSmimeSink->OnError(SECURITY_DECRYPT, SECURITY_CAUSE_DECRYPT_BAD_SIGNATURE); } #endif break; default: // Perhaps there was en error with the certificate itself, // let's verify it and see what if it's suspect. int x = PR_GetError(); } } } } } // end for } if(decryptedData.length() > 0) { decryptSucceeded = true; if (pSmimeSink) { pSmimeSink->OnError(SECURITY_DECRYPT, SECURITY_CAUSE_DECRYPT_SUCCESS); } } if (cmsMessageEnveloped) { NSS_CMSMessage_Destroy(cmsMessageEnveloped); } } if (slot) PK11_FreeSlot(slot); if (decryptedEnvelope.data) { delete[] decryptedEnvelope.data; decryptedEnvelope.data = NULL; } if (decryptedContent.data) { delete[] decryptedContent.data; decryptedContent.data = NULL; } SECITEM_FreeItem(&decryptedEnvelope, PR_FALSE); SECITEM_FreeItem(&decryptedContent, PR_FALSE); // if (secuPwd.data) // PR_Free(secuPwd.data); if (slotPwd.data) PR_Free(slotPwd.data); #endif return(decryptSucceeded); } bool SmimeBody::importPKCS12Object(const char* derPkcs12, int derPkcs12Length, const char* pkcs12Password, const char* certDbLocation, const char* certDbPassword) { bool bRet = false; #ifdef HAVE_NSS if (P12Wrapper_Init((char*)certDbLocation, "")) { PRBool swapUnicode = PR_FALSE; SEC_PKCS12DecoderContext *p12Decoder = NULL; SECItem secuPwd; memset(&secuPwd, 0, sizeof(SECItem)); secuPwd.data = (unsigned char*)PL_strdup(pkcs12Password); secuPwd.len = strlen(pkcs12Password); SECItem slotPwd; memset(&slotPwd, 0, sizeof(SECItem)); slotPwd.data = (unsigned char*)PL_strdup(certDbPassword); slotPwd.len = strlen(certDbPassword); // Allocate a temporary internal slot PK11SlotInfo *slot = PK11_GetInternalKeySlot(); if(slot == NULL) { OsSysLog::add(FAC_SIP, PRI_ERR, "unable to use slot in NSS dataqbase for S/MIME decryption\n"); } else { UtlString derPkcs12(derPkcs12, derPkcs12Length); // import the pkcs12 into the db int pkcs12_rc = P12Wrapper_ImportPKCS12ObjectFromBuffer((char*)derPkcs12.data(), derPkcs12Length, slot, &slotPwd, &secuPwd); if (pkcs12_rc == 0) { bRet = true; } } if (slot) PK11_FreeSlot(slot); if (slotPwd.data) PR_Free(slotPwd.data); } #endif return bRet; } UtlBoolean SmimeBody::opensslSmimeDecrypt(const char* derPkcs12, int derPkcs12Length, const char* pkcs12Password, UtlBoolean dataIsInBase64Format, const char* dataToDecrypt, int dataToDecryptLength, UtlString& decryptedData) { UtlBoolean decryptSucceeded = FALSE; decryptedData.remove(0); #ifdef ENABLE_OPENSSL_SMIME EVP_PKEY* privateKey = NULL; X509* publicKeyCert = NULL; // Create the PKCS12 which contains both cert. and private key // from the DER format BIO* pkcs12Bio = BIO_new_mem_buf((void*)derPkcs12, derPkcs12Length); PKCS12 *pkcs12 = d2i_PKCS12_bio(pkcs12Bio, NULL); // The PKCS12 contains both the private key and the cert. which // are protected by symmetric encryption using the given password. PKCS12_parse(pkcs12, pkcs12Password, &privateKey, &publicKeyCert, NULL); PKCS12_free(pkcs12); pkcs12 = NULL; if(privateKey == NULL) { OsSysLog::add(FAC_SIP, PRI_ERR, "PKCS12 or PKCS12 password invalid or does not contain private key for S/MIME decrypt operation"); } if(publicKeyCert) { OsSysLog::add(FAC_SIP, PRI_ERR, "PKCS12 or PKCS12 password invalid or does not contain certificate and public key for S/MIME decrypt operation"); } // Create a memory BIO to put the body into BIO* encryptedBodyBioBuf = BIO_new_mem_buf((void*)dataToDecrypt, dataToDecryptLength); // Create the pkcs7 structure // The clearTextSignatureBio only gets set if it // is provided. BIO* decryptedBodyBioBuf = BIO_new(BIO_s_mem()); PKCS7* pkcs7 = NULL; if(dataIsInBase64Format) // base64 { BIO* clearTextSignatureBio = NULL; pkcs7 = SMIME_read_PKCS7(encryptedBodyBioBuf, &clearTextSignatureBio); if(clearTextSignatureBio) { BIO_free(clearTextSignatureBio); } } else // binary { pkcs7 = d2i_PKCS7_bio(encryptedBodyBioBuf, 0); } if(pkcs7 == NULL) { // Unable to initialize PKCS7 OsSysLog::add(FAC_SIP, PRI_ERR, "Unable to create OpenSSL PKCS7 context for S/MIME decrypt operation\n"); } if(pkcs7 && privateKey && publicKeyCert && decryptedBodyBioBuf) { // Decrypt the pkcs7 structure into a memory BIO int decryptOk = PKCS7_decrypt(pkcs7, privateKey, publicKeyCert, decryptedBodyBioBuf, 0); // Unable to decrypt if(!decryptOk) { OsSysLog::add(FAC_SIP, PRI_ERR, "Unable to decrypt S/MIME message using OpenSSL\n"); } else { // Get the data from the decrypted BIO BUF_MEM *bioMemoryStructure; BIO_get_mem_ptr(decryptedBodyBioBuf, &bioMemoryStructure); if (bioMemoryStructure) { decryptedData.append(bioMemoryStructure->data, bioMemoryStructure->length); decryptSucceeded = TRUE; } } } // Free up the BIOs if(encryptedBodyBioBuf) { BIO_free(encryptedBodyBioBuf); encryptedBodyBioBuf = NULL; } if(decryptedBodyBioBuf) { BIO_free(decryptedBodyBioBuf); decryptedBodyBioBuf; } #else OsSysLog::add(FAC_SIP, PRI_ERR, "SmimeBody::opensslSmimeDecrypt invoked with ENABLE_OPENSSL_SMIME not defined"); #endif return(decryptSucceeded); } UtlBoolean SmimeBody::convertPemToDer(UtlString& pemData, UtlString& derData) { UtlBoolean conversionSucceeded = FALSE; #ifdef HAVE_NSS derData.remove(0); // Code from NSS secutil.c char* body = NULL; char* pemDataPtr = (char*) pemData.data(); char* pemDataCopy = NULL; /* check for headers and trailers and remove them */ if ((body = strstr(pemDataPtr, "-----BEGIN")) != NULL) { char *trailer = NULL; pemDataCopy = strdup(body); pemData = pemDataCopy; body = PORT_Strchr(body, '\n'); if (!body) body = PORT_Strchr(pemDataPtr, '\r'); /* maybe this is a MAC file */ if (body) trailer = strstr(++body, "-----END"); if (trailer != NULL) { *trailer = '\0'; } else { OsSysLog::add(FAC_SIP, PRI_ERR, "input has header but no trailer\n"); } } else { body = pemDataPtr; } /* Convert to binary */ SECItem derItem; derItem.data = NULL; derItem.len = 0; if(ATOB_ConvertAsciiToItem(&derItem, body)) { OsSysLog::add(FAC_SIP, PRI_ERR, "error converting PEM base64 data to binary"); } else { derData.append(((char*)derItem.data), derItem.len); SECITEM_FreeItem(&derItem, false); if (pemDataCopy) free(pemDataCopy); conversionSucceeded = TRUE; } #endif return(conversionSucceeded); } /* ============================ ACCESSORS ================================= */ const HttpBody* SmimeBody::getDecryptedBody() const { return(mpDecryptedBody); } /* ============================ INQUIRY =================================== */ UtlBoolean SmimeBody::isDecrypted() const { return(mpDecryptedBody != NULL); } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ TESTING =================================== */ /* ============================ FUNCTIONS ================================= */ #ifdef HAVE_NSS char * PR_CALLBACK pk11Passwordcallback(PK11SlotInfo *slot, PRBool retry, void *arg) { return (char*)arg; } #endif #endifsipxtapi-3.3.0~test17/sipXtackLib/src/net/StateChangeNotifier.cpp0000644000175000017500000000234512205613256025570 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor StateChangeNotifier::StateChangeNotifier() { } // Destructor StateChangeNotifier::~StateChangeNotifier() { } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/TapiMgr.cpp0000644000175000017500000001011712205613256023241 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "net/TapiMgr.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS TapiMgr TapiMgr::sTapiMgr; // Constructor - private, this is a singleton TapiMgr::TapiMgr() : sipxCallEventCallbackPtr(NULL), sipxLineEventCallbackPtr(NULL), sipxMediaCallbackPtr(NULL) { } // destructor - private TapiMgr::~TapiMgr() { } // static accessor for the singleton instance TapiMgr& TapiMgr::getInstance() { return sTapiMgr; } // setting the Call event callback pointer void TapiMgr::setTapiCallCallback(sipxCallEventCallbackFn fp) { sipxCallEventCallbackPtr = fp; } void TapiMgr::setTapiMediaCallback(sipxMediaCallbackFn fp) { sipxMediaCallbackPtr = fp; } // setting the Line event callback pointer void TapiMgr::setTapiLineCallback(sipxLineEventCallbackFn fp) { sipxLineEventCallbackPtr = fp; } void TapiMgr::setTapiCallback(sipxEventCallbackFn fp) { sipxEventCallbackPtr = fp; } void TapiMgr::fireCallEvent(const void* pSrc, const char* szCallId, SipSession* pSession, const char* szRemoteAddress, SIPX_CALLSTATE_EVENT event, SIPX_CALLSTATE_CAUSE cause, void* pEventData, const char* remoteAssertedIdentity) { static SIPX_CALLSTATE_EVENT lastEvent = CALLSTATE_UNKNOWN; static SIPX_CALLSTATE_CAUSE lastCause = CALLSTATE_CAUSE_UNKNOWN; static char szLastCallId[256] = { 0 }; static char szLastRemoteAddress[256] = { 0 }; static SipSession* pLastSession = NULL; if (sipxCallEventCallbackPtr) { if (lastEvent == event && lastCause == cause && strcmp(szLastRemoteAddress, szRemoteAddress) == 0 && strcmp(szLastCallId, szCallId) == 0 ) { // don't fire } else { (*sipxCallEventCallbackPtr)(pSrc, szCallId, pSession, szRemoteAddress, event, cause, pEventData, remoteAssertedIdentity); lastEvent = event; lastCause = cause; strncpy(szLastCallId, szCallId, sizeof(szLastCallId)); strncpy(szLastRemoteAddress, szCallId, sizeof(szLastRemoteAddress)); pLastSession = pSession; } } return; } void TapiMgr::fireMediaEvent(const void* pSrc, const char* szCallId, const char* szRemoteAddress, SIPX_MEDIA_EVENT event, SIPX_MEDIA_CAUSE cause, SIPX_MEDIA_TYPE type, void* pEventData) { if (sipxMediaCallbackPtr) { (*sipxMediaCallbackPtr)(pSrc, szCallId, szRemoteAddress, event, cause, type, pEventData); } } void TapiMgr::fireLineEvent(const void* pSrc, const char* szLineIdentifier, SIPX_LINESTATE_EVENT event, SIPX_LINESTATE_CAUSE cause, const char *bodyBytes ) { if (sipxLineEventCallbackPtr) { (*sipxLineEventCallbackPtr)(pSrc, szLineIdentifier, event, cause, bodyBytes); } } bool TapiMgr::fireEvent(const void* pSrc, const SIPX_EVENT_CATEGORY event, void *pInfo) { if (sipxEventCallbackPtr) { return (*sipxEventCallbackPtr)(pSrc, event, pInfo); } else { return false; } } sipxtapi-3.3.0~test17/sipXtackLib/src/net/Url.cpp0000644000175000017500000014261612205617431022451 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #ifdef __pingtel_on_posix__ #include #endif // APPLICATION INCLUDES #include "os/OsDefs.h" #include "os/OsSysLog.h" #include "utl/UtlDListIterator.h" #include "utl/UtlRegex.h" #include "net/Url.h" #include "utl/UtlNameValueTokenizer.h" #include "net/NameValuePair.h" #include "net/NameValuePairInsensitive.h" #include "net/SipMessage.h" #include "net/HttpRequestContext.h" #undef TIME_PARSE #if TIME_PARSE # include "os/OsTimeLog.h" # define LOG_TIME(x) timeLog.addEvent(x) #else # define LOG_TIME(x) /* x */ #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS /* ========================================================================= * IMPORTANT NOTE: * If you change any of the following regular expressions, enable the * verbose form of the PARSE macro in ../test/net/UrlTest.cpp and check * to see if the parsing times are reasonable. It's pretty easy to * cause very deep recursions, which can be both a performance problem * and can cause crashes due to stack overflow. * ========================================================================= */ #define DQUOTE "\"" #define LWS "\\s+" #define SWS "\\s*" #define SLASH "\\" #define SIP_TOKEN "[a-zA-Z0-9.!%*#_+`'~-]++" // SipTokenSequenceOrQuoted - used to validate display name values in setDisplayName // does not capture any substrings - this is important to avoid recursion const RegEx SipTokenSequenceOrQuoted("^(?:" SIP_TOKEN "(?:" LWS SIP_TOKEN ")*" \ "|" DQUOTE "(?:[^" SLASH DQUOTE "]++" \ "|" SLASH DQUOTE \ "|" SLASH SLASH \ ")*" \ DQUOTE \ ")$"); // DisplayName - used to parse display name from a url string // $1 matches an unquoted string // $2 matches a quoted string but without the quotes // Do Not Change This To Include The Quotes - that causes the regex // processor to recurse, possibly very very deeply. // Instead, we add the quotes back in explicitly below. // neither includes any leading or trailing whitespace const RegEx DisplayName( SWS "(?:(" SIP_TOKEN "(?:" LWS SIP_TOKEN ")*)" "|" DQUOTE "((?:[^" SLASH DQUOTE "]++" "|" SLASH DQUOTE "|" SLASH SLASH ")*)" DQUOTE ")" "(?=" SWS "<)" ); // AngleBrackets // allows and matches leading whitespace // $0 matches any leading whitespace, the angle brackets, and the contents // $1 matches just the contents const RegEx AngleBrackets( SWS "<([^>]+)>" ); /* SupportedSchemes - matches any supported scheme name followed by ':' * allows leading whitespace * $0 matches the scheme name with the colon and any leading whitespace * $1 matches the scheme name without the colon * * IMPORTANT * The number and order of the strings in the following two constants MUST match the * the number and order of the enum values in the Url::Scheme type. * * The value SupportedSchemes.Matches()-1 is used to assign the Scheme in Url::Scheme, * so if the above rule is broken, the scheme recognition will not work. * * Similarly, the Scheme value is used as an index into SchemeName, so the translation * to a string will be wrong if that is not kept correct. */ #define SUPPORTED_SCHEMES "(?i:(sip)|(sips)|(http)|(https)|(ftp)|(file)|(mailto)|(rtsp))" const RegEx SupportedScheme( SWS SUPPORTED_SCHEMES SWS ":" ); const RegEx SupportedSchemeExact( "^" SUPPORTED_SCHEMES "$" ); const char* SchemeName[ Url::NUM_SUPPORTED_URL_SCHEMES ] = { "UNKNOWN-URL-SCHEME", "sip", "sips", "http", "https", "ftp", "file", "mailto", "rtsp" }; // UsernameAndPassword // requires and matches the trailing '@' // $1 matches user // $2 matches password const RegEx UsernameAndPassword( "(" "(?:" "[a-zA-Z0-9_.!~*#'()&=+$,;?/-]++" "|" "%[0-9a-fA-F]{2}" ")+" ")" "(?:" ":" "(" "(?:" "[a-zA-Z0-9_.!~*#'()&=+$,-]++" "|" "%[0-9a-fA-F]{2}" ")*" ")" ")?" "@" ); // Host Address and Port // does not allow leading whitespace // $0 matches host:port // $1 matches host // $2 matches port #define DOMAIN_LABEL "(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)" const RegEx HostAndPort( "(" "(?:" DOMAIN_LABEL "\\.)*" DOMAIN_LABEL "\\.?" // DNS name "|" "(?:[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})" // IPv4 address "|" "(?:\\[[0-9a-fA-F:.]++\\])" // IPv6 address ")" "(?:" ":" "([0-9]{1,6}))?" // port number ); // UrlPath // does not allow whitespace // does not require, but matches a trailing '?' // $0 matches path? // $1 matches path const RegEx UrlPath( "([^?\\s]++)\\??" ); // UrlParams // allows leading whitespace // is terminated by but does not require a trailing '?' or '>' // $0 matches ;params // $1 matches params const RegEx UrlParams( SWS ";([^?>]++)" ); // FieldParams // allows leading whitespace // is terminated by end of string // $0 matches ;params // $1 matches params const RegEx FieldParams( SWS ";(.+)$" ); // HeaderOrQueryParams // allows leading whitespace // is terminated by but does not require a trailing '>' // $0 matches ?params // $1 matches params const RegEx HeaderOrQueryParams( SWS "\\?([^>]++)>?" ); // AllDigits const RegEx AllDigits("^\\+?[0-9*]++$"); // The end of the value (allowing optional whitespace) const RegEx TheEnd("^" SWS "$"); // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor Url::Url(const char* urlString, UtlBoolean isAddrSpec) : mpUrlParameters(NULL), mpHeaderOrQueryParameters(NULL), mpFieldParameters(NULL) { reset(); if (urlString && *urlString) { parseString(urlString ,isAddrSpec); } } void Url::fromString(const UtlString& urlString, UtlBoolean isAddrSpec ) { reset(); parseString(urlString.data(), isAddrSpec); } // Copy constructor Url::Url(const Url& rUrl) : mpUrlParameters(NULL), mpHeaderOrQueryParameters(NULL), mpFieldParameters(NULL) { reset(); *this = rUrl; } // Destructor Url::~Url() { removeParameters(); } void Url::removeParameters() { removeUrlParameters(); removeFieldParameters(); removeHeaderParameters(); } void Url::reset() { mScheme = SipUrlScheme; mDisplayName.remove(0); mUserId.remove(0); mPassword.remove(0); mPasswordSet = FALSE; mHostAddress.remove(0); mHostPort = PORT_NONE; mPath.remove(0); mAngleBracketsIncluded = FALSE; removeParameters(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator Url& Url::operator=(const Url& rhs) { if (this != &rhs) // handle the assignment to self case { reset(); // Copy the members mScheme = rhs.mScheme; mDisplayName = rhs.mDisplayName; mUserId = rhs.mUserId; mPassword = rhs.mPassword; mPasswordSet = rhs.mPasswordSet; mHostAddress = rhs.mHostAddress; mHostPort = rhs.mHostPort; mPath = rhs.mPath; mAngleBracketsIncluded = rhs.mAngleBracketsIncluded; if (rhs.mpUrlParameters) { mpUrlParameters = new UtlDList; UtlDListIterator paramIterator(*rhs.mpUrlParameters); NameValuePair* rhsParam; while ((rhsParam = (NameValuePair*) paramIterator())) { mpUrlParameters->append(new NameValuePair(*rhsParam)); } } else { mRawUrlParameters = rhs.mRawUrlParameters; } if (rhs.mpHeaderOrQueryParameters) { mpHeaderOrQueryParameters = new UtlDList; UtlDListIterator paramIterator(*rhs.mpHeaderOrQueryParameters); NameValuePair* rhsParam; while ((rhsParam = (NameValuePair*) paramIterator())) { mpHeaderOrQueryParameters->append(new NameValuePair(*rhsParam)); } } else { mRawHeaderOrQueryParameters = rhs.mRawHeaderOrQueryParameters; } if (rhs.mpFieldParameters) { mpFieldParameters = new UtlDList; UtlDListIterator paramIterator(*rhs.mpFieldParameters); NameValuePair* rhsParam; while ((rhsParam = (NameValuePair*) paramIterator())) { mpFieldParameters->append(new NameValuePair(*rhsParam)); } } else { mRawFieldParameters = rhs.mRawFieldParameters; } } return *this; } Url& Url::operator=(const char* urlString) { reset(); if (urlString && *urlString) { parseString(urlString,FALSE); } return *this; } /* ============================ ACCESSORS ================================= */ Url::Scheme Url::getScheme() const { return mScheme; } void Url::getUrlType(UtlString& urlProtocol) const { urlProtocol = SchemeName[mScheme]; } void Url::setScheme(Url::Scheme scheme) { mScheme = scheme; } void Url::setUrlType(const char* urlProtocol) { if (urlProtocol) { UtlString schemeName(urlProtocol); mScheme = scheme(schemeName); if ( UnknownUrlScheme == mScheme ) { OsSysLog::add(FAC_SIP, PRI_ERR, "Url::setUrlType unsupported Url scheme '%s'", urlProtocol ); } } else { // no urlProtocol value passed OsSysLog::add(FAC_SIP, PRI_CRIT, "Url::setUrlType Url scheme NULL"); assert(urlProtocol); mScheme = UnknownUrlScheme; } } void Url::getDisplayName(UtlString& displayName) const { displayName = mDisplayName; if (isDigitString(mDisplayName.data())) { displayName.strip(UtlString::both, '\"'); } } void Url::setDisplayName(const char* displayName) { mDisplayName.remove(0); if (displayName && strlen(displayName)) { RegEx tokenSequenceOrQuoted(SipTokenSequenceOrQuoted); if (tokenSequenceOrQuoted.Search(displayName)) { mDisplayName = displayName; } else { assert(FALSE); // invalid display name value } } } void Url::getUserId(UtlString& userId) const { userId = mUserId; } void Url::setUserId(const char* userId) { if (userId) { mUserId = userId; } else { mUserId.remove(0); } } UtlBoolean Url::getPassword(UtlString& password) const { password = mPassword; return(mPasswordSet); } void Url::setPassword(const char* password) { if (password) { mPassword = password; mPasswordSet = TRUE; } else { mPassword.remove(0); mPasswordSet = FALSE; } } void Url::getHostAddress(UtlString& address) const { address = mHostAddress; } void Url::getHostWithPort(UtlString& domain) const { getHostAddress(domain); if (mHostPort != PORT_NONE) { char portNum[7]; sprintf(portNum, ":%d", mHostPort); domain.append(portNum); } } void Url::setPath(const char* path) { if (path) { mPath = path; } else { mPath.remove(0); } } UtlBoolean Url::getPath(UtlString& path, UtlBoolean getStyle) { path = mPath; // If the desire is to have an HTTP GET style path with CGI variables if(getStyle) { if ( ( mpHeaderOrQueryParameters || const_cast(this)->parseHeaderOrQueryParameters() ) && mpHeaderOrQueryParameters->entries() ) { UtlDListIterator headerParamIterator(*mpHeaderOrQueryParameters); NameValuePair* headerParam = NULL; UtlString headerParamValue ; UtlBoolean firstHeader = TRUE; while ((headerParam = (NameValuePair*) headerParamIterator())) { // Add separator for first header parameter if(firstHeader) { path.append("?", 1); firstHeader = FALSE; } else { path.append("&", 1); } path.append(*headerParam); headerParamValue = headerParam->getValue(); if(!headerParamValue.isNull()) { path.append("=", 1); HttpMessage::escape(headerParamValue); path.append(headerParamValue); } } } // endif mpHeaderOrQueryParameters } return(!mPath.isNull()); } void Url::setHostAddress(const char* address) { if (address) mHostAddress = address; else mHostAddress.remove(0); } int Url::getHostPort() const { return(mHostPort); } void Url::setHostPort(int port) { mHostPort = port; } UtlBoolean Url::getUrlParameter(const char* name, UtlString& value, int index) { int foundIndex = 0; UtlBoolean found = FALSE; value = ""; if(mpUrlParameters || parseUrlParameters()) { UtlDListIterator urlParamIterator(*mpUrlParameters); NameValuePair* urlParam = NULL; UtlString paramName; while ((urlParam = (NameValuePair*) urlParamIterator())) { paramName = *urlParam; if(paramName.compareTo(name, UtlString::ignoreCase) == 0) { if(index == foundIndex) { found = TRUE; value = urlParam->getValue(); break; } foundIndex++; } } } return(found); } UtlBoolean Url::getUrlParameter(int urlIndex, UtlString& name, UtlString& value) { NameValuePair* url = NULL; if ( (urlIndex >= 0) && (mpUrlParameters || parseUrlParameters()) && (((int)(mpUrlParameters->entries())) > urlIndex) ) { url = (NameValuePair*) mpUrlParameters->at(urlIndex); } if(url) { name = *url; value = url->getValue(); } return(NULL != url); } UtlBoolean Url::getUrlParameters(int iMaxReturn, UtlString* pNames, UtlString *pValues, int& iActualReturn) { if(! (mpUrlParameters || parseUrlParameters())) { iActualReturn = 0; } // If the pNames or pValue is null, return false and set the actual return // to the actual number of items. else if ((pNames == NULL) || (pValues == NULL)) { iActualReturn = mpUrlParameters->entries() ; return FALSE ; } else { iActualReturn = sipx_min(iMaxReturn, ((int)(mpUrlParameters->entries()))) ; for (int i=0; iat(i) ; pNames[i] = *pair; pValues[i] = pair->getValue() ; } } return (iActualReturn > 0) ; } void Url::setUrlParameter(const char* name, const char* value) { NameValuePair* nv = new NameValuePair(name ? name : "", value ? value : ""); // ensure that mpUrlParameters is initialized if (! (mpUrlParameters || parseUrlParameters())) { mpUrlParameters = new UtlDList; } NameValuePair* existingParam = static_cast(mpUrlParameters->find(nv)); if (existingParam) { existingParam->setValue(value); } else { mpUrlParameters->append(nv); } } UtlBoolean Url::getHeaderParameter(const char* name, UtlString& value, int index) { int foundIndex = 0; UtlBoolean found = FALSE; value = ""; if(mpHeaderOrQueryParameters || parseHeaderOrQueryParameters()) { UtlDListIterator headerParamIterator(*mpHeaderOrQueryParameters); NameValuePair* headerParam = NULL; UtlString paramName; while ((headerParam = (NameValuePair*) headerParamIterator())) { paramName = *headerParam; if(paramName.compareTo(name, UtlString::ignoreCase) == 0) { if(index == foundIndex) { found = TRUE; value = headerParam->getValue(); break; } foundIndex++; } } } return(found); } UtlBoolean Url::getHeaderParameters(int iMaxReturn, UtlString* pNames, UtlString *pValues, int& iActualReturn) { if(!(mpHeaderOrQueryParameters || parseHeaderOrQueryParameters())) { iActualReturn = 0; } // If the pValue is null, return false and set the actual return to the actual // number of items. else if (pValues == NULL || pNames == NULL) { iActualReturn = mpHeaderOrQueryParameters->entries() ; return FALSE ; } else { iActualReturn = sipx_min(iMaxReturn, ((int)(mpHeaderOrQueryParameters->entries()))) ; for (int i=0; iat(i) ; pNames[i] = *pair; pValues[i] = pair->getValue() ; } } return (iActualReturn > 0) ; } void Url::removeUrlParameters() { if(mpUrlParameters) { mpUrlParameters->destroyAll(); delete mpUrlParameters; mpUrlParameters = NULL; } else { mRawUrlParameters.remove(0); } } void Url::removeUrlParameter(const char* name) { if(mpUrlParameters || parseUrlParameters()) { NameValuePairInsensitive nv(name ? name : "", NULL); UtlDListIterator iterator(*mpUrlParameters); UtlContainable* matchingParam; while((matchingParam = iterator.findNext(&nv))) { mpUrlParameters->destroy(matchingParam); } } } void Url::getUri(UtlString& urlString) { // Insert the scheme urlString = schemeName(mScheme); urlString.append(":",1); switch(mScheme) { case FileUrlScheme: case FtpUrlScheme: case HttpUrlScheme: case HttpsUrlScheme: case RtspUrlScheme: urlString.append("//",2); break; case SipUrlScheme: case SipsUrlScheme: case MailtoUrlScheme: default: break; } // Add the user if (FileUrlScheme != mScheme) // no user defined in a file url { if(!mUserId.isNull()) { urlString.append(mUserId); if(!mPassword.isNull() || mPasswordSet) { urlString.append(":", 1); urlString.append(mPassword); } urlString.append("@", 1); } } // Add the host urlString.append(mHostAddress); if(mHostPort > 0) { char portBuffer[20]; sprintf(portBuffer, ":%d", mHostPort); urlString.append(portBuffer); } // Add the path switch(mScheme) { case FileUrlScheme: case FtpUrlScheme: case HttpUrlScheme: case HttpsUrlScheme: case RtspUrlScheme: if(!mPath.isNull()) { urlString.append(mPath); } break; case SipUrlScheme: case SipsUrlScheme: case MailtoUrlScheme: default: break; } // Add the URL parameters if ( ( mpUrlParameters || const_cast(this)->parseUrlParameters() ) && mpUrlParameters->entries() ) { UtlDListIterator urlParamIterator(*mpUrlParameters); NameValuePair* urlParam = NULL; UtlString urlParamValue; while ((urlParam = (NameValuePair*) urlParamIterator())) { urlString.append(";", 1); urlString.append(*urlParam); urlParamValue = urlParam->getValue(); if(!urlParamValue.isNull()) { urlString.append("=", 1); HttpMessage::escape(urlParamValue); urlString.append(urlParamValue); } } } // Add the header parameters if ( ( mpHeaderOrQueryParameters || const_cast(this)->parseHeaderOrQueryParameters() ) && mpHeaderOrQueryParameters->entries() ) { UtlDListIterator headerParamIterator(*mpHeaderOrQueryParameters); NameValuePairInsensitive* headerParam = NULL; UtlString headerParamValue; UtlBoolean firstHeader = TRUE; while ((headerParam = static_cast(headerParamIterator()))) { // Add separator for first header parameter if(firstHeader) { urlString.append("?", 1); firstHeader = FALSE; } else { urlString.append("&", 1); } urlString.append(*headerParam); headerParamValue = headerParam->getValue(); if(!headerParamValue.isNull()) { urlString.append("=", 1); HttpMessage::escape(headerParamValue); urlString.append(headerParamValue); } } } } void Url::setHeaderParameter(const char* name, const char* value) { if ( name && *name ) { NameValuePairInsensitive* nv = new NameValuePairInsensitive(name, value ? value : ""); // ensure that mpHeaderOrQueryParameters is initialized if (! (mpHeaderOrQueryParameters || parseHeaderOrQueryParameters())) { mpHeaderOrQueryParameters = new UtlDList; } if ( ( SipUrlScheme == mScheme || SipsUrlScheme == mScheme ) && ( SipMessage::isUrlHeaderUnique(name) ) ) { removeHeaderParameter(name); } // for all other cases, assume that duplicate query parameters are ok mpHeaderOrQueryParameters->append(nv); } } UtlBoolean Url::getHeaderParameter(int headerIndex, UtlString& name, UtlString& value) { NameValuePair* header = NULL; if ( (headerIndex >= 0) && (mpHeaderOrQueryParameters || parseHeaderOrQueryParameters()) && (((int)(mpHeaderOrQueryParameters->entries())) > headerIndex) ) { header = static_cast(mpHeaderOrQueryParameters->at(headerIndex)); } if(header) { name = *header; value = header->getValue(); } return(NULL != header); } void Url::removeHeaderParameters() { if(mpHeaderOrQueryParameters) { mpHeaderOrQueryParameters->destroyAll(); delete mpHeaderOrQueryParameters; mpHeaderOrQueryParameters = NULL; } mRawHeaderOrQueryParameters.remove(0); } void Url::removeHeaderParameter(const char* name) { if(mpHeaderOrQueryParameters || parseHeaderOrQueryParameters()) { NameValuePairInsensitive nv(name ? name : "", NULL); UtlDListIterator iterator(*mpHeaderOrQueryParameters); UtlContainable* matchingParam; while((matchingParam=iterator.findNext(&nv))) { mpHeaderOrQueryParameters->destroy(matchingParam); } } } UtlBoolean Url::getFieldParameter(const char* name, UtlString& value, int index) const { int foundIndex = 0; UtlBoolean found = FALSE; value = ""; if(mpFieldParameters || const_cast(this)->parseFieldParameters()) { UtlDListIterator fieldParamIterator(*mpFieldParameters); NameValuePair* fieldParam = NULL; UtlString paramName; while ((fieldParam = (NameValuePair*) fieldParamIterator())) { paramName = *fieldParam; if(paramName.compareTo(name, UtlString::ignoreCase) == 0) { if(index == foundIndex) { found = TRUE; value = fieldParam->getValue(); break; } foundIndex++; } } } return(found); } UtlBoolean Url::getFieldParameter(int fieldIndex, UtlString& name, UtlString& value) { NameValuePair* field = NULL; if ( fieldIndex >= 0 && (mpFieldParameters || parseFieldParameters()) && ((int)(mpFieldParameters->entries())) > fieldIndex ) { field = (NameValuePair*) mpFieldParameters->at(fieldIndex); } if(field) { name = *field; value = field->getValue(); } return(NULL != field); } UtlBoolean Url::getFieldParameters(int iMaxReturn, UtlString* pNames, UtlString *pValues, int& iActualReturn) { if(!(mpFieldParameters || parseFieldParameters())) { iActualReturn = 0; } // If the pValue is null, return false and set the actual return to the actual // number of items. else if (pNames == NULL || pValues == NULL) { iActualReturn = mpFieldParameters->entries() ; return FALSE ; } else { iActualReturn = sipx_min(iMaxReturn, ((int)(mpFieldParameters->entries()))) ; for (int i=0; iat(i) ; pNames[i] = *pair; pValues[i] = pair->getValue() ; } } return (iActualReturn > 0) ; } void Url::setFieldParameter(const char* name, const char* value) { NameValuePair* nv = new NameValuePair(name ? name : "", value ? value : ""); // ensure that mpFieldParameters is initialized if (! (mpFieldParameters || parseFieldParameters())) { mpFieldParameters = new UtlDList; } NameValuePair* existingParam = static_cast(mpFieldParameters->find(nv)); if (existingParam) { existingParam->setValue(value); delete nv; } else { mpFieldParameters->append(nv); } } void Url::removeFieldParameters() { if(mpFieldParameters) { mpFieldParameters->destroyAll(); delete mpFieldParameters; mpFieldParameters = NULL; } mRawFieldParameters.remove(0); } void Url::removeFieldParameter(const char* name) { if(mpFieldParameters || parseFieldParameters()) { NameValuePairInsensitive nv(name ? name : "", NULL); UtlDListIterator iterator(*mpFieldParameters); UtlContainable* matchingParam; while((matchingParam=iterator.findNext(&nv))) { mpFieldParameters->destroy(matchingParam); } } } void Url::includeAngleBrackets() { mAngleBracketsIncluded = TRUE; } void Url::removeAngleBrackets() { mAngleBracketsIncluded = FALSE; } UtlString Url::toString() const { UtlString str; toString(str); return str; } void Url::toString(UtlString& urlString) const { UtlBoolean isNameAddr = FALSE; // This is a replace operation; clear the storage string urlString.remove(0); if ( !mDisplayName.isNull() ) { urlString.append(mDisplayName); isNameAddr = TRUE; } bool haveUrlParams = ( ( mpUrlParameters || const_cast(this)->parseUrlParameters() ) && mpUrlParameters->entries() ); bool haveHdrParams = ( ( mpHeaderOrQueryParameters || const_cast(this)->parseHeaderOrQueryParameters() ) && mpHeaderOrQueryParameters->entries() ); bool haveFldParams = ( ( mpFieldParameters || const_cast(this)->parseFieldParameters() ) && mpFieldParameters->entries() ); // If this should be nameAddr as opposed to addrSpec // (i.e. do we need anglebrackets) if ( isNameAddr // There was a Display name || mAngleBracketsIncluded // Explicit setting from the caller || haveFldParams || ( ( SipUrlScheme == mScheme || SipsUrlScheme == mScheme ) && ( haveUrlParams || haveHdrParams ) ) ) { urlString.append("<", 1); isNameAddr = TRUE; } UtlString theAddrSpec; const_cast(this)->getUri(theAddrSpec); urlString.append(theAddrSpec); // Add the terminating angle bracket if(isNameAddr) { urlString.append(">", 1); } // Add the field parameters if(haveFldParams) { UtlDListIterator fieldParamIterator(*mpFieldParameters); NameValuePair* fieldParam = NULL; UtlString fieldParamValue; while ((fieldParam = (NameValuePair*) fieldParamIterator())) { urlString.append(";", 1); urlString.append(*fieldParam); fieldParamValue = fieldParam->getValue(); if(!fieldParamValue.isNull()) { urlString.append("=", 1); Url::gen_value_escape(fieldParamValue); urlString.append(fieldParamValue); } } } } void Url::dump() { UtlString proto; getUrlType(proto); printf("Url type: '%s'\n", proto.data()); UtlString disp; getDisplayName(disp); printf("DisplayName: '%s'\n", disp.data()); UtlString user; getUserId(user); printf("UserId: '%s'\n", user.data()); UtlString pwd; getPassword(pwd); printf("Password: '%s'\n", pwd.data()); UtlString server; getHostAddress(server); printf("Address: '%s'\n", server.data()); int port = getHostPort(); printf("Port: %d\n", port); UtlString callId; getHeaderParameter("call-id", callId); printf("Call-Id: '%s'\n", callId.data()); UtlString name; UtlString value; int index = 0; printf("\nHeader Parameters:\n"); while(getHeaderParameter(index, name, value)) { printf("'%s'='%s'\n", name.data(), value.data()); index++; } index = 0; printf("\nField Parameters:\n"); while(getFieldParameter(index, name, value)) { printf("'%s'='%s'\n", name.data(), value.data()); index++; } index = 0; printf("\nURL Parameters:\n"); while(getUrlParameter(index, name, value)) { printf("'%s'='%s'\n", name.data(), value.data()); index++; } } /* ============================ INQUIRY =================================== */ UtlBoolean Url::isDigitString(const char* dialedCharacters) { // Must be digits or * RegEx allDigits(AllDigits); return allDigits.Search(dialedCharacters); } UtlBoolean Url::isIncludeAngleBracketsSet() const { return mAngleBracketsIncluded ; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ void Url::parseString(const char* urlString, UtlBoolean isAddrSpec) { // If isAddrSpec: // userinfo@hostport;uriParameters?headerParameters // If !isAddrSpec: // DisplayName;fieldParameters # ifdef TIME_PARSE OsTimeLog timeLog; LOG_TIME("start "); # endif // Try to catch when a name-addr is passed but we are expecting an // addr-spec -- many name-addr's start with '<' or '"'. if (isAddrSpec && (urlString[0] == '<' || urlString[0] == '"')) { OsSysLog::add(FAC_SIP, PRI_ERR, "Url::parseString Invalid addr-spec found (probably name-addr format): '%s'", urlString); } int workingOffset = 0; // begin at the beginning... size_t afterAngleBrackets = UTL_NOT_FOUND; if (isAddrSpec) { mAngleBracketsIncluded = FALSE; } else // ! addr-spec { // Is there a display name on the front? mDisplayName.remove(0); LOG_TIME("display <"); RegEx displayName(DisplayName); if (displayName.SearchAt(urlString, workingOffset)) { LOG_TIME("display > "); switch (displayName.Matches() /* number of substrings that matched */) { case 2: // matched unquoted sequence of tokens displayName.MatchString(&mDisplayName, 1); break; case 3: // matched a double quoted string // see performance note on DisplayName mDisplayName.append("\""); displayName.MatchString(&mDisplayName, 2); mDisplayName.append("\""); break; default: assert(false); } // does not include whitespace or the '<' workingOffset = displayName.AfterMatch(0); } // Are there angle brackets around the URI? LOG_TIME("angles < "); RegEx angleBrackets(AngleBrackets); if (angleBrackets.SearchAt(urlString, workingOffset)) { LOG_TIME("angles > "); // yes, there are angle brackets workingOffset = angleBrackets.MatchStart(1); // inside the angle brackets afterAngleBrackets = angleBrackets.AfterMatch(0); // following the '>' /* * Note: We do not set mAngleBracketsIncluded just because we saw them * That is only used for explicit control from the outside. * The local knowledge of whether or not there are angle brackets * is whether or not afterAngleBrackets == UTL_NOT_FOUND */ } } /* * AMBIGUITY - there is a potential ambiguity when parsing real URLs. * * Consider the url 'foo:333' - it could be: * scheme 'foo' host '333' ('333' is a valid local host name - bad idea, but legal) * or host 'foo' port '333' (and scheme 'sip' is implied) * * Now make it worse by using 'sips' as a hostname: * 'sips:333' * scheme 'sips' host '333' * or host 'sips' port '333' (and scheme 'sip' is implied) * * We resolve the first case by treating anything left of the colon as a scheme if * it is one of the supported schemes. Otherwise, we set the scheme to the * default (sip) and go on so that it will be parsed as a hostname. This does not * do the right thing for the (scheme 'sips' host '333') case, but they get what * they deserve. */ // Parse the scheme (aka url type) LOG_TIME("scheme < "); RegEx supportedScheme(SupportedScheme); if ( (supportedScheme.SearchAt(urlString,workingOffset)) && (supportedScheme.MatchStart(0) == workingOffset) ) { LOG_TIME("scheme > "); // the scheme name matches one of the supported schemes mScheme = static_cast(supportedScheme.Matches()-1); workingOffset = supportedScheme.AfterMatch(0); // past the ':' } else { /* * It did not match one of the supported scheme names * so proceed on the assumption that it's a host and "sip:" is implied * Leave the workingOffset where it is (before the token). * The code below, through the parsing of host and port * treats this as an implicit 'sip:' url; if it parses ok * up to that point, it resets the scheme to SipsUrlScheme */ mScheme = UnknownUrlScheme; } // skip over any '//' following the scheme for the ones we know use that switch (mScheme) { case FileUrlScheme: case FtpUrlScheme: case HttpUrlScheme: case HttpsUrlScheme: case RtspUrlScheme: if (0==strncmp("//", urlString+workingOffset, 2)) { workingOffset += 2; } break; case UnknownUrlScheme: case SipUrlScheme: case SipsUrlScheme: case MailtoUrlScheme: default: break; } if (FileUrlScheme != mScheme) // no user part in file urls { // Parse the username and password LOG_TIME("userpass < "); RegEx usernameAndPassword(UsernameAndPassword); if ( (usernameAndPassword.SearchAt(urlString, workingOffset)) && usernameAndPassword.MatchStart(0) == workingOffset ) { LOG_TIME("userpass > "); usernameAndPassword.MatchString(&mUserId, 1); usernameAndPassword.MatchString(&mPassword, 2); workingOffset = usernameAndPassword.AfterMatch(0); } else { // username and password are optional, so not finding them is ok // leave workingOffset where it is } } // Parse the hostname and port LOG_TIME("hostport < "); RegEx hostAndPort(HostAndPort); if ( (hostAndPort.SearchAt(urlString,workingOffset)) && (hostAndPort.MatchStart(0) == workingOffset) ) { LOG_TIME("hostport > "); hostAndPort.MatchString(&mHostAddress,1); UtlString portStr; if (hostAndPort.MatchString(&portStr,2)) { mHostPort = atoi(portStr.data()); } workingOffset = hostAndPort.AfterMatch(0); if (UnknownUrlScheme == mScheme) { /* * Resolve AMBIGUITY * Since we were able to parse this as a host and port, it is now safe to * set the scheme to the implied 'sip:'. */ mScheme = SipUrlScheme; } } else { if (FileUrlScheme != mScheme) // no host is ok in a file URL { /* * This is not a file URL, so not having a recognized host name is invalid. * * Since we may have been called from a constructor, there is no way to * return an error, but at this point we know this is bad, so instead * we just log an error and set the scheme to the unknown url type and * clear any components that might have been set. */ OsSysLog::add(FAC_SIP, PRI_ERR, "Url::parseString no valid host found at char %d in '%s', " "isAddrSpec = %d", workingOffset, urlString, isAddrSpec ); mScheme = UnknownUrlScheme; mDisplayName.remove(0); mUserId.remove(0); mPassword.remove(0); } } // Next is a path if http, https, or ftp, // OR url parameters if sip or sips. // There can be no Url parameters for http, https, or ftp // because semicolon is a valid part of the path value switch ( mScheme ) { case FileUrlScheme: case FtpUrlScheme: case HttpUrlScheme: case HttpsUrlScheme: case RtspUrlScheme: { // this is an http, https, or ftp URL, so get the path LOG_TIME("path < "); RegEx urlPath(UrlPath); if ( (urlPath.SearchAt(urlString, workingOffset)) && (urlPath.MatchStart(0) == workingOffset) ) { LOG_TIME("path > "); urlPath.MatchString(&mPath,1); workingOffset = urlPath.AfterMatch(1); } } break; case SipUrlScheme: case SipsUrlScheme: { // it may have url parameters of the form ";" param "=" value ... // if it meets the right conditions: if ( isAddrSpec // in addr-spec, any param is a url param || afterAngleBrackets != UTL_NOT_FOUND // inside angle brackets there may be a url param ) { LOG_TIME("urlparm < "); RegEx urlParams(UrlParams); if ( (urlParams.SearchAt(urlString, workingOffset)) && (urlParams.MatchStart(0) == workingOffset) ) { LOG_TIME("urlparm > "); urlParams.MatchString(&mRawUrlParameters, 1); workingOffset = urlParams.AfterMatch(1); // actual parsing of the parameters is in parseUrlParameters // so that it only happens if someone asks for them. } } } break; case MailtoUrlScheme: default: // no path component break; } if (UnknownUrlScheme != mScheme) { // Parse any header or query parameters LOG_TIME("hdrparm < "); RegEx headerOrQueryParams(HeaderOrQueryParams); if( (headerOrQueryParams.SearchAt(urlString, workingOffset)) && (headerOrQueryParams.MatchStart(0) == workingOffset) ) { LOG_TIME("hdrparm > "); headerOrQueryParams.MatchString(&mRawHeaderOrQueryParameters, 1); workingOffset = headerOrQueryParams.AfterMatch(0); // actual parsing of the parameters is in parseHeaderOrQueryParameters // so that it only happens if someone asks for them. } // Parse the field parameters if (!isAddrSpec) // can't have field parameters in an addrspec { if (afterAngleBrackets != UTL_NOT_FOUND) { workingOffset = afterAngleBrackets; } LOG_TIME("fldparm < "); RegEx fieldParameters(FieldParams); if ( (fieldParameters.SearchAt(urlString, workingOffset)) && (fieldParameters.MatchStart(0) == workingOffset) ) { LOG_TIME("fldparm > "); fieldParameters.MatchString(&mRawFieldParameters, 1); // actual parsing of the parameters is in parseFieldParameters // so that it only happens if someone asks for them. } } } # ifdef TIME_PARSE UtlString timeDump; timeLog.getLogString(timeDump); printf("\n%s\n", timeDump.data()); # endif } UtlBoolean Url::isUserHostPortEqual(const Url &url, int impliedPort ) const { int otherPort; int myPort; if (impliedPort == PORT_NONE) { // strict checking - no implied port values otherPort = url.mHostPort; myPort = mHostPort; } else { // sloppy checking - an unspecified port is considered to be impliedPort otherPort = ( url.mHostPort == PORT_NONE ) ? impliedPort : url.mHostPort; myPort = ( mHostPort == PORT_NONE ) ? impliedPort : mHostPort; } return ((myPort == otherPort) && isUserHostEqual(url)); } UtlBoolean Url::isUserHostEqual(const Url &url) const { return ( (mHostAddress.compareTo(url.mHostAddress, UtlString::ignoreCase) == 0) && (mUserId.compareTo(url.mUserId) == 0)); } void Url::getIdentity(UtlString &identity) const { identity.remove(0); identity.append(mUserId); identity.append("@", 1); UtlString lowerHostAddress(mHostAddress); lowerHostAddress.toLower(); identity.append(lowerHostAddress); // If the port designates an actual port, it must be specified. if(portIsValid(mHostPort)) { char portBuffer[20]; sprintf(portBuffer, ":%d", mHostPort); identity.append(portBuffer); } } /// Translate a scheme string (not including the terminating colon) to a Scheme enum. Url::Scheme Url::scheme( const UtlString& schemeName ) { Scheme theScheme; RegEx supportedSchemeExact(SupportedSchemeExact); if (supportedSchemeExact.Search(schemeName.data())) { theScheme = static_cast(supportedSchemeExact.Matches()-1); } else { theScheme = UnknownUrlScheme; } return theScheme; } /// Get the canonical (lowercase) name of a supported Scheme. const char* Url::schemeName( Url::Scheme scheme ) { const char* theName; if (scheme > UnknownUrlScheme && scheme < NUM_SUPPORTED_URL_SCHEMES) { theName = SchemeName[scheme]; } else { theName = SchemeName[UnknownUrlScheme]; } return theName; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ bool Url::parseUrlParameters() { if (!mpUrlParameters && !mRawUrlParameters.isNull()) { mpUrlParameters = new UtlDList(); HttpRequestContext::parseCgiVariables(mRawUrlParameters, *mpUrlParameters, ";", "=", TRUE, &HttpMessage::unescape); mRawUrlParameters.remove(0); } return mpUrlParameters != NULL; } bool Url::parseHeaderOrQueryParameters() { if (!mpHeaderOrQueryParameters && !mRawHeaderOrQueryParameters.isNull()) { mpHeaderOrQueryParameters = new UtlDList(); HttpRequestContext::parseCgiVariables(mRawHeaderOrQueryParameters, *mpHeaderOrQueryParameters, "&", "=", TRUE, &HttpMessage::unescape); mRawHeaderOrQueryParameters.remove(0); } return mpHeaderOrQueryParameters != NULL; } bool Url::parseFieldParameters() { if (!mpFieldParameters && !mRawFieldParameters.isNull()) { mpFieldParameters = new UtlDList(); #if 0 printf("Url::parseFieldParameters mRawFieldParameters = '%s'\n", mRawFieldParameters.data()); #endif HttpRequestContext::parseCgiVariables(mRawFieldParameters, *mpFieldParameters, ";", "=", TRUE, &Url::gen_value_unescape); mRawFieldParameters.remove(0); } return mpFieldParameters != NULL; } void Url::gen_value_unescape(UtlString& escapedText) { #if 0 printf("Url::gen_value_unescape before escapedText = '%s'\n", escapedText.data()); #endif //UtlString unescapedText; int numUnescapedChars = 0; const char* unescapedTextPtr = escapedText; // The number of unescaped characters is always less than // or equal to the number of escaped characters. Therefore // we will cheat a little and used the escapedText as // the destiniation to directly write characters in place // as the append method is very expensive char* resultPtr = new char[escapedText.length() + 1]; // Skip initial whitespace, which may be before the starting double-quote // of a quoted string. Tokens and hosts are not allowed to start with // whitespace. while (*unescapedTextPtr && (*unescapedTextPtr == ' ' || *unescapedTextPtr == '\t')) { // Consume the whitespace character. unescapedTextPtr++; numUnescapedChars++; } // Examine the first character to see if it is a double-quote. if (*unescapedTextPtr == '"') { // Skip the initial double-quote. unescapedTextPtr++; while (*unescapedTextPtr) { // Substitute a (backslash-)quoted-pair. if (*unescapedTextPtr == '\\') { // Get the next char. unescapedTextPtr++; // Don't get deceived if there is no next character. if (*unescapedTextPtr) { // The next character is copied unchanged. resultPtr[numUnescapedChars] = *unescapedTextPtr; numUnescapedChars++; } } // A double-quote without backslash ends the string. else if (*unescapedTextPtr == '"') { break; } // Char is face value. else { resultPtr[numUnescapedChars] = *unescapedTextPtr; numUnescapedChars++; } // Go to the next character unescapedTextPtr++; } } else { // It is a token or host, and can be copied unchanged. while (*unescapedTextPtr) { resultPtr[numUnescapedChars] = *unescapedTextPtr; numUnescapedChars++; // Go to the next character unescapedTextPtr++; } } // Copy back into the UtlString. resultPtr[numUnescapedChars] = '\0'; escapedText.replace(0, numUnescapedChars, resultPtr); escapedText.remove(numUnescapedChars); delete[] resultPtr; #if 0 printf("Url::gen_value_unescape after escapedText = '%s'\n", escapedText.data()); #endif } void Url::gen_value_escape(UtlString& unEscapedText) { // Check if there are any characters in unEscapedText that need to be // escaped in a field parameter value. if (strspn(unEscapedText.data(), // Alphanumerics "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789" // Characters allowed in tokens "-.!%*_+`'~" // Additional characters allowed by the syntax of "host" "[]:") != unEscapedText.length()) { // Temporary string to construct the escaped value in. UtlString escapedText; // Pre-size it to the size of the un-escaped test, plus 2 for // the starting and ending double-quotes. escapedText.capacity((size_t) unEscapedText.length() + 2); const char* unescapedTextPtr = unEscapedText.data(); // Start with double-quote. escapedText.append("\""); // Process each character of the un-escaped value. while(*unescapedTextPtr) { char unEscapedChar = *unescapedTextPtr; if (unEscapedChar == '"' || unEscapedChar == '\\') { // Construct a little 2-character string and append it. char escapedChar[2]; escapedChar[0] = '\\'; escapedChar[1] = *unescapedTextPtr; escapedText.append(&unEscapedChar, 2); } else { // Append the character directly. escapedText.append(&unEscapedChar, 1); } // Consider the next character. unescapedTextPtr++; } // End with double-quote. escapedText.append("\""); // Write the escaped string into the argumemt. unEscapedText = escapedText; } } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/XmlRpcBody.cpp0000644000175000017500000001222512205613256023723 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2005 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor XmlRpcBody::XmlRpcBody() { mBody = XML_VERSION_1_0; } // Destructor XmlRpcBody::~XmlRpcBody() { } /* ============================ MANIPULATORS ============================== */ void XmlRpcBody::append(const char* string) { mBody.append(string); } /* ============================ ACCESSORS ================================= */ int XmlRpcBody::getLength() const { return (mBody.length()); } void XmlRpcBody::getBytes(const char** bytes, int* length) const { // This version of getBytes exists so that a caller who is // calling this method through an HttpBody will get the right // thing - we fill in the mBody string and then return that. UtlString tempBody; getBytes( &tempBody, length ); ((XmlRpcBody*)this)->mBody = tempBody.data(); *bytes = mBody.data(); } void XmlRpcBody::getBytes(UtlString* bytes, int* length) const { *bytes = mBody; *length = bytes->length(); } bool XmlRpcBody::addValue(UtlContainable* value) { bool result = false; UtlString paramValue; // UtlInt if (value->isInstanceOf(UtlInt::TYPE)) { UtlInt* pValue = (UtlInt *)value; // allow room for the widest possible value, INT_MIN = -2147483648 char temp[11]; sprintf(temp, "%d", pValue->getValue()); paramValue.append(BEGIN_INT); paramValue.append(temp); paramValue.append(END_INT); result = true; } // UtlLongLongInt else if (value->isInstanceOf(UtlLongLongInt::TYPE)) { UtlLongLongInt* pValue = (UtlLongLongInt *)value; // always encode these in hex - more readable for values this big char temp[19]; sprintf(temp, "%0#16"PRIx64, pValue->getValue()); paramValue.append(BEGIN_I8); paramValue.append(temp); paramValue.append(END_I8); result = true; } else if (value->isInstanceOf(UtlBool::TYPE)) { UtlBool* pValue = (UtlBool *)value; paramValue.append(BEGIN_BOOLEAN); paramValue.append(pValue->getValue() ? "1" : "0"); paramValue.append(END_BOOLEAN); result = true; } else if (value->isInstanceOf(UtlString::TYPE)) { UtlString* pValue = (UtlString *)value; // Fix XSL-116: XML-RPC must escape special chars in string values result = XmlEscape(paramValue, *pValue); paramValue.insert(0, BEGIN_STRING); paramValue.append(END_STRING); } else if (value->isInstanceOf(UtlDateTime::TYPE)) { UtlDateTime* pTime = (UtlDateTime *)value; OsDateTime time; pTime->getTime(time); UtlString isoTime; time.getIsoTimeStringZ(isoTime); paramValue = BEGIN_TIME + isoTime + END_TIME; result = true; } else if (value->isInstanceOf(UtlHashMap::TYPE)) { result = addStruct((UtlHashMap *)value); } else if (value->isInstanceOf(UtlSList::TYPE)) { result = addArray((UtlSList *)value); } else { assert(false); // unsupported type } mBody.append(paramValue); return result; } bool XmlRpcBody::addArray(UtlSList* array) { bool result = false; mBody.append(BEGIN_ARRAY); UtlSListIterator iterator(*array); UtlContainable* pObject; while ( (pObject = iterator()) && (result = addValue(pObject)) ) { } mBody.append(END_ARRAY); return result; } bool XmlRpcBody::addStruct(UtlHashMap* members) { bool result = true; mBody.append(BEGIN_STRUCT); UtlHashMapIterator iterator(*members); UtlString* pName; UtlContainable* pObject; UtlString structName; while (result && (pName = (UtlString *)iterator())) { mBody.append(BEGIN_MEMBER); structName = BEGIN_NAME + *pName + END_NAME; mBody.append(structName); pObject = members->findValue(pName); result = addValue(pObject); mBody.append(END_MEMBER); } mBody.append(END_STRUCT); return result; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/XmlRpcDispatch.cpp0000644000175000017500000007637112205613256024601 0ustar00danieldaniel00000000000000// // Copyright (C) 2005-2012 SIPez LLC. All rights reserved. // // Copyright (C) 2005 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_SSL # include #endif #include #include #include #include "net/XmlRpcDispatch.h" // STATIC VARIABLE DEFINITIONS const UtlContainableType XmlRpcMethodContainer::TYPE = "XmlRpcMethod"; #undef TEST_HTTP /* turn on to log raw http messages */ XmlRpcMethodContainer::XmlRpcMethodContainer() { mpUserData = NULL; mpMethod = NULL; } XmlRpcMethodContainer::~XmlRpcMethodContainer() { } int XmlRpcMethodContainer::compareTo(const UtlContainable *b) const { return ((mpUserData == ((XmlRpcMethodContainer *)b)->mpUserData) && (mpMethod == ((XmlRpcMethodContainer *)b)->mpMethod)); } unsigned int XmlRpcMethodContainer::hash() const { return (uintptr_t) mpUserData; } const UtlContainableType XmlRpcMethodContainer::getContainableType() const { return TYPE; } void XmlRpcMethodContainer::setData(XmlRpcMethod::Get* method, void* userData) { mpMethod = method; mpUserData = userData; } void XmlRpcMethodContainer::getData(XmlRpcMethod::Get*& method, void*& userData) { method = mpMethod; userData = mpUserData; } // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS const char* XmlRpcDispatch::DEFAULT_URL_PATH = "/RPC2"; /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor XmlRpcDispatch::XmlRpcDispatch(int httpServerPort, bool isSecureServer, const char* uriPath, const char* httpBindAddress) : mLock(OsBSem::Q_PRIORITY, OsBSem::FULL) { UtlString osBaseUriDirectory ; OsPath workingDirectory; OsPath path; OsFileSystem::getWorkingDirectory(path); path.getNativePath(workingDirectory); osBaseUriDirectory = workingDirectory + OsPathBase::separator; // Create a HTTPS Server OsServerSocket* pServerSocket = NULL; if (isSecureServer) { #ifdef HAVE_SSL // OsSSLServerSocket currently only binds on all addresses. Need to add argument to // OsSSLServerSocket constructor assert(httpBindAddress == NULL); pServerSocket = new OsSSLServerSocket(50, httpServerPort); #else assert(0); #endif } else { pServerSocket = new OsServerSocket(50, httpServerPort, httpBindAddress); } mpHttpServer = new HttpServer(pServerSocket, NULL, // no password database NULL, // no http authentication realm NULL, // no valid ip address list true // use persistent http connections ); // Set the http server root to the current directory mpHttpServer->allowFileAccess(false); mpHttpServer->addUriMap("/", osBaseUriDirectory.data()); mpHttpServer->start(); // Add the XmlRpcDispatch to the HttpServer mpHttpServer->addHttpService(uriPath, (HttpService*)this); } // Copy constructor NOT IMPLEMENTED XmlRpcDispatch::XmlRpcDispatch(const XmlRpcDispatch& rXmlRpcDispatch) : mLock(OsBSem::Q_PRIORITY, OsBSem::FULL) { } // Destructor XmlRpcDispatch::~XmlRpcDispatch() { // HTTP server shutdown if (mpHttpServer) { mpHttpServer->requestShutdown(); delete mpHttpServer; mpHttpServer = NULL; } } /* ============================ MANIPULATORS ============================== */ // Assignment operator XmlRpcDispatch& XmlRpcDispatch::operator=(const XmlRpcDispatch& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } void XmlRpcDispatch::processRequest(const HttpRequestContext& requestContext, const HttpMessage& request, HttpMessage*& response ) { # ifdef TEST_HTTP int len; UtlString httpString; request.getBytes(&httpString , &len); OsSysLog::add(FAC_SIP, PRI_DEBUG, "XmlRpcDispatch::processRequest HttpEvent = \n%s", httpString.data()); # endif // Create a response response = new HttpMessage(); response->setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION_1_1, HTTP_OK_CODE, HTTP_OK_TEXT); UtlString bodyString; int bodyLength; const HttpBody* requestBody = request.getBody(); requestBody->getBytes(&bodyString, &bodyLength); XmlRpcResponse responseBody; XmlRpcMethodContainer* methodContainer = NULL; UtlSList params; parseXmlRpcRequest(bodyString, methodContainer, params, responseBody); XmlRpcMethod::ExecutionStatus status; if (methodContainer) { XmlRpcMethod::Get* methodGet; void* userData; methodContainer->getData(methodGet, userData); XmlRpcMethod* method = methodGet(); OsSysLog::add(FAC_SIP, PRI_DEBUG, "XmlRpcDispatch::processRequest start to execute the request ..."); method->execute(requestContext, params, userData, responseBody, status); // Delete the instance of the method if (method) { delete method; } // Clean up the memory allocated in params cleanUp(¶ms); } if (status == XmlRpcMethod::REQUIRE_AUTHENTICATION) { // Create an authentication challenge response OsSysLog::add(FAC_SIP, PRI_WARNING, "XmlRpcDispatch::processRequest request does not have authentication." ); responseBody.setFault(AUTHENTICATION_REQUIRED_FAULT_CODE, AUTHENTICATION_REQUIRED_FAULT_STRING); } // Send the response back responseBody.getBody()->getBytes(&bodyString, &bodyLength); OsSysLog::add(FAC_SIP, PRI_DEBUG, "XmlRpcDispatch::processRequest request returned %s\n%s", ( status == XmlRpcMethod::OK ? "OK" : "FAILED" ), bodyString.data() ); response->setBody(new HttpBody(bodyString.data(), bodyLength)); response->setContentType(CONTENT_TYPE_TEXT_XML); response->setContentLength(bodyLength); } /* ============================ ACCESSORS ================================= */ void XmlRpcDispatch::addMethod(const char* methodName, XmlRpcMethod::Get* method, void* userData) { mLock.acquire(); UtlString name(methodName); if (mMethods.findValue(&name) == NULL) { XmlRpcMethodContainer *methodContainer = new XmlRpcMethodContainer(); methodContainer->setData(method, userData); mMethods.insertKeyAndValue(new UtlString(methodName), methodContainer); } mLock.release(); } void XmlRpcDispatch::removeMethod(const char* methodName) { mLock.acquire(); UtlString key = methodName; if(! mMethods.destroy(&key)) { OsSysLog::add(FAC_NET, PRI_ERR, "XmlRpcDispatch::removeMethod key: %s not removed or deleted", methodName); } mLock.release(); } /// Return the HTTP server that services RPC requests HttpServer* XmlRpcDispatch::getHttpServer() { return mpHttpServer; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ bool XmlRpcDispatch::parseXmlRpcRequest(UtlString& requestContent, XmlRpcMethodContainer*& methodContainer, UtlSList& params, XmlRpcResponse& response) { bool result = false; OsSysLog::add(FAC_SIP, PRI_DEBUG, "XmlRpcDispatch::parseXmlRpcRequest requestBody = \n%s", requestContent.data()); // Parse the XML-RPC response TiXmlDocument doc("XmlRpcRequest.xml"); doc.Parse(requestContent); if (!doc.Error()) { TiXmlNode* rootNode = doc.FirstChild ("methodCall"); if (rootNode != NULL) { // Positive response example // // // examples.getStateName // // // 41 // // // TiXmlNode* methodNode = rootNode->FirstChild("methodName"); if (methodNode) { // Check whether the method exists or not. If not, send back a fault response UtlString methodCall = methodNode->FirstChild()->Value(); methodContainer = (XmlRpcMethodContainer*) mMethods.findValue(&methodCall); if (methodContainer) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "XmlRpcDispatch::parseXmlRpcRequest requestMethod = %s", methodCall.data()); TiXmlNode* paramsNode = rootNode->FirstChild("params"); if (paramsNode) { int index = 0; for (TiXmlNode* paramNode = paramsNode->FirstChild("param"); paramNode; paramNode = paramNode->NextSibling("param")) { TiXmlNode* subNode = paramNode->FirstChild("value"); if (subNode) { result = parseValue(subNode, index, params); if (!result) { OsSysLog::add(FAC_SIP, PRI_ERR, "XmlRpcDispatch::parseXmlRpcRequest ill-formed XML contents in %s.", requestContent.data()); response.setFault(EMPTY_PARAM_VALUE_FAULT_CODE, EMPTY_PARAM_VALUE_FAULT_STRING); break; } index++; } } } } else { OsSysLog::add(FAC_SIP, PRI_ERR, "XmlRpcDispatch::parseXmlRpcRequest no method named %s is registered", methodCall.data()); response.setFault(UNREGISTERED_METHOD_FAULT_CODE, UNREGISTERED_METHOD_FAULT_STRING); result = false; } } else { OsSysLog::add(FAC_SIP, PRI_ERR, "XmlRpcDispatch::parseXmlRpcRequest method name does not exist"); response.setFault(METHOD_NAME_FAULT_CODE, METHOD_NAME_FAULT_STRING); result = false; } } } else { OsSysLog::add(FAC_SIP, PRI_ERR, "XmlRpcDispatch::parseXmlRpcRequest ill-formed XML contents in %s. Parsing error = %s", requestContent.data(), doc.ErrorDesc()); response.setFault(ILL_FORMED_CONTENTS_FAULT_CODE, ILL_FORMED_CONTENTS_FAULT_STRING); result = false; } return result; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ bool XmlRpcDispatch::parseValue(TiXmlNode* subNode, int index, UtlSList& params) { bool result = false; UtlString paramValue; // four-byte signed integer TiXmlNode* valueNode = subNode->FirstChild("i4"); if (valueNode) { if (valueNode->FirstChild()) { paramValue = valueNode->FirstChild()->Value(); params.insertAt(index, new UtlInt(atoi(paramValue))); result = true; } else { result = false; } } else { valueNode = subNode->FirstChild("int"); if (valueNode) { if (valueNode->FirstChild()) { paramValue = valueNode->FirstChild()->Value(); params.insertAt(index, new UtlInt(atoi(paramValue))); result = true; } else { result = false; } } else { valueNode = subNode->FirstChild("i8"); if (valueNode) { if (valueNode->FirstChild()) { paramValue = valueNode->FirstChild()->Value(); params.insertAt(index, new UtlLongLongInt(UtlLongLongInt::stringToLongLong(paramValue))); result = true; } else { result = false; } } else { valueNode = subNode->FirstChild("boolean"); if (valueNode) { if (valueNode->FirstChild()) { paramValue = valueNode->FirstChild()->Value(); params.insertAt(index, new UtlBool((atoi(paramValue)==1))); result = true; } else { result = false; } } else { // string // Note: In the string case, we allow a null string valueNode = subNode->FirstChild("string"); if (valueNode) { if (valueNode->FirstChild()) { paramValue = valueNode->FirstChild()->Value(); params.insertAt(index, new UtlString(paramValue)); } else { params.insertAt(index, new UtlString()); } result = true; } else { // dateTime.iso8601 valueNode = subNode->FirstChild("dateTime.iso8601"); if (valueNode) { if (valueNode->FirstChild()) { paramValue = valueNode->FirstChild()->Value(); // need to change to UtlDateTime params.insertAt(index, new UtlString(paramValue)); result = true; } else { result = false; } } else { // struct valueNode = subNode->FirstChild("struct"); if (valueNode) { UtlHashMap* members = NULL; if (parseStruct(valueNode, members)) { params.insertAt(index, members); result = true; } } else { // array valueNode = subNode->FirstChild("array"); if (valueNode) { UtlSList* array = NULL; if (parseArray(valueNode, array)) { params.insertAt(index, array); result = true; } } else { // Default case for string if (subNode->FirstChild()) { paramValue = subNode->FirstChild()->Value(); params.insertAt(index, new UtlString(paramValue)); } else { params.insertAt(index, new UtlString()); } result = true; } } } } } } } } return result; } bool XmlRpcDispatch::parseStruct(TiXmlNode* subNode, UtlHashMap*& members) { bool result = false; // struct UtlString name; UtlString paramValue; TiXmlNode* memberValue; UtlHashMap* pMembers = new UtlHashMap(); for (TiXmlNode* memberNode = subNode->FirstChild("member"); memberNode; memberNode = memberNode->NextSibling("member")) { TiXmlNode* memberName = memberNode->FirstChild("name"); if (memberName) { if (memberName->FirstChild()) { name = memberName->FirstChild()->Value(); } else { result = false; break; } memberValue = memberNode->FirstChild("value"); if (memberValue) { // four-byte signed integer TiXmlNode* valueElement = memberValue->FirstChild("i4"); if (valueElement) { if (valueElement->FirstChild()) { paramValue = valueElement->FirstChild()->Value(); pMembers->insertKeyAndValue(new UtlString(name), new UtlInt(atoi(paramValue))); result = true; } else { result = false; break; } } else { valueElement = memberValue->FirstChild("int"); if (valueElement) { if (valueElement->FirstChild()) { paramValue = valueElement->FirstChild()->Value(); pMembers->insertKeyAndValue(new UtlString(name), new UtlInt(atoi(paramValue))); result = true; } else { result = false; break; } } else { valueElement = memberValue->FirstChild("i8"); if (valueElement) { if (valueElement->FirstChild()) { paramValue = valueElement->FirstChild()->Value(); pMembers->insertKeyAndValue(new UtlString(name), new UtlLongLongInt(UtlLongLongInt::stringToLongLong(paramValue))); result = true; } else { result = false; break; } } else { valueElement = memberValue->FirstChild("boolean"); if (valueElement) { if (valueElement->FirstChild()) { paramValue = valueElement->FirstChild()->Value(); pMembers->insertKeyAndValue(new UtlString(name), new UtlBool((atoi(paramValue)==1))); result = true; } else { result = false; break; } } else { valueElement = memberValue->FirstChild("string"); if (valueElement) { if (valueElement->FirstChild()) { paramValue = valueElement->FirstChild()->Value(); pMembers->insertKeyAndValue(new UtlString(name), new UtlString(paramValue)); } else { pMembers->insertKeyAndValue(new UtlString(name), new UtlString()); } result = true; } else { valueElement = memberValue->FirstChild("dateTime.iso8601"); if (valueElement) { if (valueElement->FirstChild()) { paramValue = valueElement->FirstChild()->Value(); pMembers->insertKeyAndValue(new UtlString(name), new UtlString(paramValue)); result = true; } else { result = false; break; } } else { valueElement = memberValue->FirstChild("struct"); if (valueElement) { UtlHashMap* members; if (parseStruct(valueElement, members)) { pMembers->insertKeyAndValue(new UtlString(name), members); result = true; } } else { valueElement = memberValue->FirstChild("array"); if (valueElement) { UtlSList* subArray; if (parseArray(valueElement, subArray)) { pMembers->insertKeyAndValue(new UtlString(name), subArray); result = true; } } else { // default for string if (memberValue->FirstChild()) { paramValue = memberValue->FirstChild()->Value(); pMembers->insertKeyAndValue(new UtlString(name), new UtlString(paramValue)); } else { pMembers->insertKeyAndValue(new UtlString(name), new UtlString()); } result = true; } } } } } } } } } } } members = pMembers; return result; } bool XmlRpcDispatch::parseArray(TiXmlNode* subNode, UtlSList*& array) { bool result = false; // array UtlString paramValue; TiXmlNode* dataNode = subNode->FirstChild("data"); if (dataNode) { UtlSList* pList = new UtlSList(); for (TiXmlNode* valueNode = dataNode->FirstChild("value"); valueNode; valueNode = valueNode->NextSibling("value")) { // four-byte signed integer TiXmlNode* arrayElement = valueNode->FirstChild("i4"); if (arrayElement) { if (arrayElement->FirstChild()) { paramValue = arrayElement->FirstChild()->Value(); pList->insert(new UtlInt(atoi(paramValue))); result = true; } else { result = false; break; } } else { arrayElement = valueNode->FirstChild("int"); if (arrayElement) { if (arrayElement->FirstChild()) { paramValue = arrayElement->FirstChild()->Value(); pList->insert(new UtlInt(atoi(paramValue))); result = true; } else { result = false; break; } } else { arrayElement = valueNode->FirstChild("i8"); if (arrayElement) { if (arrayElement->FirstChild()) { paramValue = arrayElement->FirstChild()->Value(); pList->insert(new UtlLongLongInt(UtlLongLongInt::stringToLongLong(paramValue))); result = true; } else { result = false; break; } } else { arrayElement = valueNode->FirstChild("boolean"); if (arrayElement) { if (arrayElement->FirstChild()) { paramValue = arrayElement->FirstChild()->Value(); pList->insert(new UtlBool((atoi(paramValue)==1))); result = true; } else { result = false; break; } } else { arrayElement = valueNode->FirstChild("string"); if (arrayElement) { if (arrayElement->FirstChild()) { paramValue = arrayElement->FirstChild()->Value(); pList->insert(new UtlString(paramValue)); } else { pList->insert(new UtlString()); } result = true; } else { arrayElement = valueNode->FirstChild("dateTime.iso8601"); if (arrayElement) { if (arrayElement->FirstChild()) { paramValue = arrayElement->FirstChild()->Value(); pList->insert(new UtlString(paramValue)); result = true; } else { result = false; break; } } else { arrayElement = valueNode->FirstChild("struct"); if (arrayElement) { UtlHashMap* members; if (parseStruct(arrayElement, members)) { pList->insert(members); result = true; } } else { arrayElement = valueNode->FirstChild("array"); if (arrayElement) { UtlSList* subArray; if (parseArray(arrayElement, subArray)) { pList->insert(subArray); result = true; } } else { // default for string if (valueNode->FirstChild()) { paramValue = valueNode->FirstChild()->Value(); pList->insert(new UtlString(paramValue)); } else { pList->insert(new UtlString()); } result = true; } } } } } } } } } array = pList; } return result; } void XmlRpcDispatch::cleanUp(UtlHashMap* map) { UtlHashMapIterator iterator(*map); UtlString* pName; UtlContainable *key; UtlContainable *value; while ((pName = (UtlString *) iterator())) { key = map->removeKeyAndValue(pName, value); UtlString paramType(value->getContainableType()); if (paramType.compareTo("UtlHashMap") == 0) { UtlHashMap* pMap = (UtlHashMap *) value; cleanUp(pMap); delete pMap; } else { if (paramType.compareTo("UtlSList") == 0) { UtlSList* pList = (UtlSList *) value; cleanUp(pList); delete pList; } else { delete value; } } delete pName; } } void XmlRpcDispatch::cleanUp(UtlSList* array) { UtlSListIterator iterator(*array); UtlContainable *value; while ((value = iterator())) { value = array->remove(value); UtlString paramType(value->getContainableType()); if (paramType.compareTo("UtlHashMap") == 0) { UtlHashMap* pMap = (UtlHashMap *) value; cleanUp(pMap); delete pMap; } else { if (paramType.compareTo("UtlSList") == 0) { UtlSList* pList = (UtlSList *) value; cleanUp(pList); delete pList; } else { delete value; } } } } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/XmlRpcMethod.cpp0000644000175000017500000000247212205613256024251 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ XmlRpcMethod* XmlRpcMethod::get() { assert(0); return NULL; } // Destructor XmlRpcMethod::~XmlRpcMethod() { } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ // Constructor XmlRpcMethod::XmlRpcMethod() { } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/XmlRpcRequest.cpp0000644000175000017500000001037312205617431024457 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include "net/XmlRpcRequest.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor XmlRpcRequest::XmlRpcRequest(Url& uri, const char* methodName) { mUrl = uri; // Start to construct the HTTP message mpHttpRequest = new HttpMessage(); mpHttpRequest->setFirstHeaderLine(HTTP_POST_METHOD, "/RPC2", HTTP_PROTOCOL_VERSION_1_1); mpHttpRequest->addHeaderField("Accept", "text/xml"); mpHttpRequest->setUserAgentField("XML-RPC client"); // Start to construct the XML-RPC body mpRequestBody = new XmlRpcBody(); OsSysLog::add(FAC_SIP, PRI_DEBUG, "XmlRpcRequest::XmlRpcRequest creating a XmlRpcBody %p", mpRequestBody); mpRequestBody->append(BEGIN_METHOD_CALL); UtlString methodCall = BEGIN_METHOD_NAME + UtlString(methodName) + END_METHOD_NAME; mpRequestBody->append(methodCall); mpRequestBody->append(BEGIN_PARAMS); } // Destructor XmlRpcRequest::~XmlRpcRequest() { if (mpHttpRequest) { delete mpHttpRequest; } } bool XmlRpcRequest::execute(XmlRpcResponse& response, int timeoutMilliSeconds, UtlBoolean usePersistentConnections) { bool result = false; // End of constructing the XML-RPC body mpRequestBody->append(END_PARAMS); mpRequestBody->append(END_METHOD_CALL); UtlString bodyString; int bodyLength; mpRequestBody->getBytes(&bodyString, &bodyLength); OsSysLog::add(FAC_SIP, PRI_DEBUG, "XmlRpcRequest::execute XML-RPC request message = \n%s\n", bodyString.data()); mpHttpRequest->setBody(mpRequestBody); mpHttpRequest->setContentType(CONTENT_TYPE_TEXT_XML); mpHttpRequest->setContentLength(bodyLength); // Create an empty response object and sent the built up request // to the XML-RPC server HttpMessage *pResponse = new HttpMessage(); int statusCode = pResponse->get(mUrl, *mpHttpRequest, timeoutMilliSeconds, (usePersistentConnections == TRUE)); if (statusCode/100 == 2) { const HttpBody* pResponseBody = pResponse->getBody(); pResponseBody->getBytes(&bodyString, &bodyLength); OsSysLog::add(FAC_SIP, PRI_DEBUG, "XmlRpcRequest::execute XML-RPC message = %s\n", bodyString.data()); if (response.parseXmlRpcResponse(bodyString)) { result = true; } } else if (statusCode == -1) { response.setFault(XmlRpcResponse::ConnectionFailure, CONNECTION_FAILURE_FAULT_STRING); OsSysLog::add(FAC_SIP, PRI_WARNING, "XmlRpcRequest::execute http connection failed\n"); } else { UtlString statusText; pResponse->getResponseStatusText(&statusText); response.setFault(XmlRpcResponse::HttpFailure, statusText.data()); OsSysLog::add(FAC_SIP, PRI_DEBUG, "XmlRpcRequest::execute failed with status = %d %s\n", statusCode, statusText.data()); } delete pResponse; return result; } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ bool XmlRpcRequest::addParam(UtlContainable* value) { bool result = false; mpRequestBody->append(BEGIN_PARAM); result = mpRequestBody->addValue(value); mpRequestBody->append(END_PARAM); return result; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/XmlRpcResponse.cpp0000644000175000017500000006516512205613256024637 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include #include #include #include #include #include "net/XmlRpcResponse.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor XmlRpcResponse::XmlRpcResponse() : mpResponseBody(NULL), mResponseValue(NULL), mFaultCode(ILL_FORMED_CONTENTS_FAULT_CODE), mFaultString(ILL_FORMED_CONTENTS_FAULT_STRING) { } // Destructor XmlRpcResponse::~XmlRpcResponse() { // Clean up the memory in mResponseValue if (mResponseValue) { cleanUp(mResponseValue); mResponseValue = NULL; } if (mpResponseBody) { delete mpResponseBody; mpResponseBody = NULL; } } bool XmlRpcResponse::parseXmlRpcResponse(UtlString& responseContent) { bool result = false; // Parse the XML-RPC response TiXmlDocument doc("XmlRpcResponse.xml"); doc.Parse(responseContent); if (!doc.Error()) { TiXmlNode* rootNode = doc.FirstChild ("methodResponse"); if (rootNode != NULL) { // Positive response example // // // // // South Dakota // // // TiXmlNode* paramsNode = rootNode->FirstChild("params"); if (paramsNode != NULL) { TiXmlNode* paramNode = paramsNode->FirstChild("param"); if (paramNode) { TiXmlNode* subNode = paramNode->FirstChild("value"); if (subNode) { result = parseValue(subNode); } } } else { // Fault response example // // // // // // // faultCode // 4 // // // faultString // Too many parameters. // // // // // TiXmlNode* faultNode = rootNode->FirstChild("fault"); if (faultNode != NULL) { TiXmlNode* subNode = faultNode->FirstChild("value"); if (subNode != NULL) { subNode = subNode->FirstChild("struct"); if (subNode != NULL) { for (TiXmlNode* memberNode = subNode->FirstChild("member"); memberNode; memberNode = memberNode->NextSibling("member")) { UtlString nameValue; if (memberNode->FirstChild("name") && (memberNode->FirstChild("name"))->FirstChild()) { nameValue = (memberNode->FirstChild("name"))->FirstChild()->Value(); if (nameValue.compareTo("faultCode") == 0) { if (memberNode->FirstChild("value")) { TiXmlNode* valueNode = (memberNode->FirstChild("value"))->FirstChild("int"); if (valueNode && valueNode->FirstChild()) { mFaultCode = atoi(valueNode->FirstChild()->Value()); } valueNode = (memberNode->FirstChild("value"))->FirstChild("i4"); if (valueNode && valueNode->FirstChild()) { mFaultCode = atoi(valueNode->FirstChild()->Value()); } } } if (nameValue.compareTo("faultString") == 0) { TiXmlNode* valueNode = memberNode->FirstChild("value"); if (valueNode) { TiXmlNode* stringNode = valueNode->FirstChild("string"); if (stringNode && stringNode->FirstChild()) { mFaultString = stringNode->FirstChild()->Value(); } else { if (valueNode->FirstChild()) { mFaultString = valueNode->FirstChild()->Value(); } else { mFaultString = NULL; } } } } } } } } } } } } else { OsSysLog::add(FAC_SIP, PRI_ERR, "XmlRpcResponse::parseXmlRpcResponse ill formatted xml contents in %s. Parsing error = %s", responseContent.data(), doc.ErrorDesc()); result = false; } return result; } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ bool XmlRpcResponse::setResponse(UtlContainable* value) { bool result = false; assert(mpResponseBody == NULL); // response body should only be created once // Start to construct the XML-RPC body mpResponseBody = new XmlRpcBody(); assert(mpResponseBody != NULL); // if not true, allocation failed mpResponseBody->append(BEGIN_RESPONSE); mpResponseBody->append(BEGIN_PARAMS); mpResponseBody->append(BEGIN_PARAM); result = mpResponseBody->addValue(value); mpResponseBody->append(END_PARAM); mpResponseBody->append(END_PARAMS); mpResponseBody->append(END_RESPONSE); UtlString bodyString; int bodyLength; mpResponseBody->getBytes(&bodyString, &bodyLength); OsSysLog::add(FAC_SIP, PRI_DEBUG, "mpResponseBody::setResponse XML-RPC response message = \n%s", bodyString.data()); return result; } bool XmlRpcResponse::setFault(int faultCode, const char* faultString) { bool result = true; mFaultCode = faultCode; mFaultString = faultString; // Start to construct the XML-RPC body for fault response assert(mpResponseBody == NULL); // response body should only be created once mpResponseBody = new XmlRpcBody(); assert(mpResponseBody != NULL); // if not true, allocation failed // Fault response example // // // // // // // faultCode // 4 // // // faultString // Too many parameters. // // // // // mpResponseBody->append(BEGIN_RESPONSE); mpResponseBody->append(BEGIN_FAULT); mpResponseBody->append(BEGIN_STRUCT); mpResponseBody->append(BEGIN_MEMBER); mpResponseBody->append(FAULT_CODE); char temp[10]; sprintf(temp, "%d", mFaultCode); UtlString paramValue = BEGIN_INT + UtlString(temp) + END_INT; mpResponseBody->append(paramValue); mpResponseBody->append(END_MEMBER); mpResponseBody->append(BEGIN_MEMBER); mpResponseBody->append(FAULT_STRING); paramValue = BEGIN_STRING + mFaultString + END_STRING; mpResponseBody->append(paramValue); mpResponseBody->append(END_MEMBER); mpResponseBody->append(END_STRUCT); mpResponseBody->append(END_FAULT); mpResponseBody->append(END_RESPONSE); UtlString bodyString; int bodyLength; mpResponseBody->getBytes(&bodyString, &bodyLength); OsSysLog::add(FAC_SIP, PRI_DEBUG, "mpResponseBody::setFault XML-RPC response message = \n%s", bodyString.data()); return result; } bool XmlRpcResponse::getResponse(UtlContainable*& value) { bool result = false; value = mResponseValue; if (value) { result = true; } else { result = false; } return result; } void XmlRpcResponse::getFault(int* faultCode, UtlString& faultString) { *faultCode = mFaultCode; faultString = mFaultString; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ bool XmlRpcResponse::parseValue(TiXmlNode* subNode) { bool result = false; // Clean up the memory in mResponseValue if (mResponseValue) { cleanUp(mResponseValue); mResponseValue = NULL; } UtlString paramValue; // four-byte signed integer TiXmlNode* valueNode = subNode->FirstChild("i4"); if (valueNode) { if (valueNode->FirstChild()) { paramValue = valueNode->FirstChild()->Value(); mResponseValue = new UtlInt(atoi(paramValue)); result = true; } else { result = false; } } else { valueNode = subNode->FirstChild("int"); if (valueNode) { if (valueNode->FirstChild()) { paramValue = valueNode->FirstChild()->Value(); mResponseValue = new UtlInt(atoi(paramValue)); result = true; } else { result = false; } } else { valueNode = subNode->FirstChild("i8"); if (valueNode) { if (valueNode->FirstChild()) { paramValue = valueNode->FirstChild()->Value(); mResponseValue = new UtlLongLongInt(UtlLongLongInt::stringToLongLong(paramValue)); result = true; } else { result = false; } } else { // boolean valueNode = subNode->FirstChild("boolean"); if (valueNode) { if (valueNode->FirstChild()) { paramValue = valueNode->FirstChild()->Value(); mResponseValue = new UtlBool((atoi(paramValue)==1)); result = true; } else { result = false; } } else { // string valueNode = subNode->FirstChild("string"); if (valueNode) { if (valueNode->FirstChild()) { paramValue = valueNode->FirstChild()->Value(); mResponseValue = new UtlString(paramValue); } else { mResponseValue = NULL; } result = true; } else { // dateTime.iso8601 valueNode = subNode->FirstChild("dateTime.iso8601"); if (valueNode) { if (valueNode->FirstChild()) { paramValue = valueNode->FirstChild()->Value(); //mResponseValue = new UtlDateTime(paramValue); result = true; } else { result = false; } } else { // struct valueNode = subNode->FirstChild("struct"); if (valueNode) { UtlHashMap* map = new UtlHashMap(); if (parseStruct(valueNode, map)) { mResponseValue = map; result = true; } } else { // array valueNode = subNode->FirstChild("array"); if (valueNode) { UtlSList* list = new UtlSList(); if (parseArray(valueNode, list)) { mResponseValue = list; result = true; } } else { // default as string valueNode = subNode->FirstChild(); if (valueNode) { paramValue = valueNode->Value(); mResponseValue = new UtlString(paramValue); } else { mResponseValue = NULL; } result = true; } } } } } } } } return result; } bool XmlRpcResponse::parseStruct(TiXmlNode* subNode, UtlHashMap* members) { bool result = false; // struct UtlString name; UtlString paramValue; TiXmlNode* memberValue; for (TiXmlNode* memberNode = subNode->FirstChild("member"); memberNode; memberNode = memberNode->NextSibling("member")) { TiXmlNode* memberName = memberNode->FirstChild("name"); if (memberName) { if (memberName->FirstChild()) { name = memberName->FirstChild()->Value(); } else { result = false; break; } memberValue = memberNode->FirstChild("value"); if (memberValue) { // four-byte signed integer TiXmlNode* valueElement = memberValue->FirstChild("i4"); if (valueElement) { if (valueElement->FirstChild()) { paramValue = valueElement->FirstChild()->Value(); members->insertKeyAndValue(new UtlString(name), new UtlInt(atoi(paramValue))); result = true; } else { result = false; break; } } else { valueElement = memberValue->FirstChild("int"); if (valueElement) { if (valueElement->FirstChild()) { paramValue = valueElement->FirstChild()->Value(); members->insertKeyAndValue(new UtlString(name), new UtlInt(atoi(paramValue))); result = true; } else { result = false; break; } } else { valueElement = memberValue->FirstChild("i8"); if (valueElement) { if (valueElement->FirstChild()) { paramValue = valueElement->FirstChild()->Value(); members->insertKeyAndValue(new UtlString(name), new UtlLongLongInt(UtlLongLongInt::stringToLongLong(paramValue))); result = true; } else { result = false; break; } } else { valueElement = memberValue->FirstChild("boolean"); if (valueElement) { if (valueElement->FirstChild()) { paramValue = valueElement->FirstChild()->Value(); members->insertKeyAndValue(new UtlString(name), new UtlBool((atoi(paramValue)==1))); result = true; } else { result = false; break; } } else { valueElement = memberValue->FirstChild("string"); if (valueElement) { if (valueElement->FirstChild()) { paramValue = valueElement->FirstChild()->Value(); members->insertKeyAndValue(new UtlString(name), new UtlString(paramValue)); } else { members->insertKeyAndValue(new UtlString(name), new UtlString()); } result = true; } else { valueElement = memberValue->FirstChild("dateTime.iso8601"); if (valueElement) { if (valueElement->FirstChild()) { paramValue = valueElement->FirstChild()->Value(); members->insertKeyAndValue(new UtlString(name), new UtlString(paramValue)); result = true; } else { result = false; break; } } else { valueElement = memberValue->FirstChild("struct"); if (valueElement) { UtlHashMap* members = new UtlHashMap(); if (parseStruct(valueElement, members)) { members->insertKeyAndValue(new UtlString(name), members); result = true; } } else { valueElement = memberValue->FirstChild("array"); if (valueElement) { UtlSList* subArray = new UtlSList(); if (parseArray(valueElement, subArray)) { members->insertKeyAndValue(new UtlString(name), subArray); result = true; } } else { // default for string if (memberValue->FirstChild()) { paramValue = memberValue->FirstChild()->Value(); members->insertKeyAndValue(new UtlString(name), new UtlString(paramValue)); } else { members->insertKeyAndValue(new UtlString(name), new UtlString()); } result = true; } } } } } } } } } } } return result; } bool XmlRpcResponse::parseArray(TiXmlNode* subNode, UtlSList* array) { bool result = false; // array UtlString paramValue; TiXmlNode* dataNode = subNode->FirstChild("data"); if (dataNode) { result = true; // an empty list is ok // see if there are values... for (TiXmlNode* valueNode = dataNode->FirstChild("value"); result && valueNode; valueNode = valueNode->NextSibling("value") ) { // four-byte signed integer TiXmlNode* arrayElement;; if ((arrayElement = valueNode->FirstChild("i4"))) { if (arrayElement->FirstChild()) { paramValue = arrayElement->FirstChild()->Value(); array->insert(new UtlInt(atoi(paramValue))); } else { result = false; } } else if ((arrayElement = valueNode->FirstChild("int"))) { if (arrayElement->FirstChild()) { paramValue = arrayElement->FirstChild()->Value(); array->insert(new UtlInt(atoi(paramValue))); } else { result = false; } } else if ((arrayElement = valueNode->FirstChild("i8"))) { if (arrayElement->FirstChild()) { paramValue = arrayElement->FirstChild()->Value(); array->insert(new UtlLongLongInt(UtlLongLongInt::stringToLongLong(paramValue))); } else { result = false; } } else if ((arrayElement = valueNode->FirstChild("boolean"))) { if (arrayElement->FirstChild()) { paramValue = arrayElement->FirstChild()->Value(); array->insert(new UtlBool((atoi(paramValue)==1))); } else { result = false; } } else if ((arrayElement = valueNode->FirstChild("string"))) { if (arrayElement->FirstChild()) { paramValue = arrayElement->FirstChild()->Value(); array->insert(new UtlString(paramValue)); } else { array->insert(new UtlString()); } } else if ((arrayElement = valueNode->FirstChild("dateTime.iso8601"))) { if (arrayElement->FirstChild()) { paramValue = arrayElement->FirstChild()->Value(); array->insert(new UtlString(paramValue)); } else { result = false; } } else if ((arrayElement = valueNode->FirstChild("struct"))) { UtlHashMap* members = new UtlHashMap(); if (parseStruct(arrayElement, members)) { array->insert(members); } } else if ((arrayElement = valueNode->FirstChild("array"))) { UtlSList* subArray = new UtlSList(); if (parseArray(arrayElement, subArray)) { array->insert(subArray); } } else { // default for string if (valueNode->FirstChild()) { paramValue = valueNode->FirstChild()->Value(); array->insert(new UtlString(paramValue)); } else { array->insert(new UtlString()); } } } // end of for loop over values } return result; } void XmlRpcResponse::cleanUp(UtlContainable* value) { if (value) { if (value->isInstanceOf(UtlHashMap::TYPE)) { UtlHashMap* map = dynamic_cast(value); UtlHashMapIterator iterator(*map); UtlString* key; while ((key = dynamic_cast(iterator()))) { UtlContainable *pName; UtlContainable *member; pName = map->removeKeyAndValue(key, member); delete pName; cleanUp(member); } } else if (value->isInstanceOf(UtlSList::TYPE)) { UtlSList* array = dynamic_cast(value); UtlContainable *element; while ((element = array->get()/* pop */)) { cleanUp(element); } } delete value; } } /// Get the content of the response XmlRpcBody* XmlRpcResponse::getBody() { assert(mpResponseBody); // if false, no response was set return mpResponseBody; } /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/HttpConnection.cpp0000644000175000017500000001007712205613256024642 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2006-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #ifdef __pingtel_on_posix__ //needed by linux #include #endif #include #include // APPLICATION INCLUDES #include #include #include // Needed for SIP_SHORT_CONTENT_LENGTH_FIELD. #include #include #ifdef HAVE_SSL #include #endif /* HAVE_SSL */ #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define HTTP_READ_TIMEOUT_MSECS 30000 /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor HttpConnection::HttpConnection(OsConnectionSocket* requestSocket, HttpServer* httpServer) : OsTask("HttpConnection-%d"), UtlString("HttpConnection"), mpRequestSocket(requestSocket), mpHttpServer(httpServer), mbToBeDeleted(false) { } // Destructor HttpConnection::~HttpConnection() { // Wait until run exits before clobbering members waitUntilShutDown(); OsSysLog::add(FAC_HTTP, PRI_DEBUG, "Shutting down HttpConnection for socket %p", mpRequestSocket); if (mpRequestSocket) { mpRequestSocket->close(); delete mpRequestSocket; mpRequestSocket = NULL; } } /* ============================ MANIPULATORS ============================== */ int HttpConnection::run(void* runArg) { HttpMessage request; bool bConnected = true; if (!mpRequestSocket || !mpRequestSocket->isOk()) { OsSysLog::add(FAC_HTTP, PRI_ERR, "HttpConnection: port not ok" ); } while(!isShuttingDown() && mpRequestSocket && mpRequestSocket->isOk() && bConnected) { // Read a http request from the socket if (mpRequestSocket->isReadyToRead(HTTP_READ_TIMEOUT_MSECS)) { int bytesRead = request.read(mpRequestSocket); if (bytesRead > 0) { UtlString remoteIp; mpRequestSocket->getRemoteHostIp(&remoteIp); HttpMessage* response = NULL; // If request from Valid IP Address if (mpHttpServer->processRequestIpAddr(remoteIp, request, response)) { // If the request is authorized mpHttpServer->processRequest(request, response, mpRequestSocket); } if(response) { response->setHeaderValue("Connection", "Keep-Alive"); response->write(mpRequestSocket); delete response; response = NULL; } } else { // isReadyToRead indicated readability but the read returned 0 bytes - the peer // must have shut down bConnected = FALSE; OsSysLog::add(FAC_HTTP, PRI_DEBUG, "HttpConnection::run - read 0 bytes, indicating peer shut down"); } } } // If we're here either we're shutting down or the socket went bad. Mark for deletion mbToBeDeleted = true; OsSysLog::add(FAC_HTTP, PRI_DEBUG, "HttpConnection::run exiting"); return(TRUE); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/HttpConnectionMap.cpp0000644000175000017500000001234612205613256025301 0ustar00danieldaniel00000000000000// // Copyright (C) 2006-2010 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2006-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include #include #ifdef __pingtel_on_posix__ //needed by linux #include #endif #include #include // APPLICATION INCLUDES #include #include #include // Needed for SIP_SHORT_CONTENT_LENGTH_FIELD. #include #include #include #ifdef HAVE_SSL #include #endif /* HAVE_SSL */ #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS #define HTTP_READ_TIMEOUT_MSECS 30000 HttpConnectionMap* HttpConnectionMap::pInstance = NULL; OsBSem HttpConnectionMap::mLock(OsBSem::Q_FIFO, OsBSem::FULL); /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ HttpConnectionMap* HttpConnectionMap::getHttpConnectionMap() { OsLock lock(mLock); if (pInstance == NULL) { pInstance = new HttpConnectionMap(); } return pInstance; } void HttpConnectionMap::releaseHttpConnectionMap() { OsLock lock(mLock); if (pInstance) { delete pInstance; pInstance = NULL; } } void HttpConnectionMap::clearHttpConnectionMap() { destroyAll(); } /* ============================ MANIPULATORS ============================== */ HttpConnectionMapEntry* HttpConnectionMap::getPersistentConnection(const Url& url, OsConnectionSocket*& socket) { UtlString keyString; socket = NULL; getPersistentUriKey(url, keyString); HttpConnectionMapEntry* pEntry; { // table lock scope OsLock lock(mLock); pEntry = static_cast(findValue(&keyString)); if (!pEntry) { // Now create a new one pEntry = new HttpConnectionMapEntry("ConnectionMapEntry-%d"); if (pEntry) { if (insertKeyAndValue(new UtlString(keyString.data()), pEntry) != NULL) { OsSysLog::add(FAC_HTTP, PRI_DEBUG, "HttpConnectionMap::getPersistentConnection " "- Adding %s for %s", pEntry->data(), keyString.data()); } else { OsSysLog::add(FAC_HTTP, PRI_ERR, "HttpConnectionMap::getPersistentConnection " "- adding %s (entry %s) failed)", keyString.data(), pEntry->data()); delete pEntry; pEntry = NULL; } } } } // end of table lock if (pEntry) { pEntry->mLock.acquire(); socket = pEntry->mpSocket; pEntry->mbInUse = true; OsSysLog::add(FAC_HTTP, PRI_DEBUG, "HttpConnectionMap::getPersistentConnection - Found %s for %s, socket %p", pEntry->data(), keyString.data(), socket); } return pEntry; } void HttpConnectionMap::getPersistentUriKey(const Url& url, UtlString& key) { UtlString urlType; UtlString httpHost; UtlString httpPort; url.getUrlType(urlType); url.getHostAddress(httpHost); int tempPort = url.getHostPort(); UtlString httpType = (url.getScheme() == Url::HttpsUrlScheme) ? "https" : "http"; if (tempPort == PORT_NONE) { if (httpType == "https") { httpPort = "443"; } else { httpPort = "80"; } } else { char t[10]; sprintf(t, "%d", tempPort); httpPort = t; } key = httpType + ":" + httpHost + ":" + httpPort; key.toLower(); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ HttpConnectionMap::HttpConnectionMap() { } HttpConnectionMap::~HttpConnectionMap() { clearHttpConnectionMap(); } int HttpConnectionMapEntry::count = 0; HttpConnectionMapEntry::HttpConnectionMapEntry(const UtlString& name) : mLock(OsBSem::Q_FIFO, OsBSem::FULL), mbInUse(true) { char nameBuffer[256]; sprintf(nameBuffer, name.data(), count++); this->append(nameBuffer); mpSocket = NULL; } HttpConnectionMapEntry::~HttpConnectionMapEntry() { //OsSysLog::add(FAC_HTTP, PRI_DEBUG, // "HttpConnectionMapEntry::destructor %s", this->data()); if (mpSocket) { delete mpSocket; mpSocket = NULL; } } sipxtapi-3.3.0~test17/sipXtackLib/src/net/PidfBody.cpp0000644000175000017500000002676412205613256023415 0ustar00danieldaniel00000000000000// // Copyright (C) 2005 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2005 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie (dpetrie AT SIPez DOT com) // SYSTEM INCLUDES // APPLICATION INCLUDES #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // PRIVATE CLASSES class PidfTuple : public UtlString { public: PidfTuple(){}; PidfTuple(const PidfTuple& rPidfTuple); virtual ~PidfTuple(){}; PidfTuple& operator=(const PidfTuple& rhs); UtlBoolean mTupleStatusBasic; UtlString mTupleContact; // TODO: should be an array UtlString mTupleNote; }; // Copy constructor PidfTuple::PidfTuple(const PidfTuple& rPidfTuple) { append(rPidfTuple); mTupleStatusBasic = rPidfTuple.mTupleStatusBasic; mTupleContact = rPidfTuple.mTupleContact; mTupleNote = rPidfTuple.mTupleNote; } // Assignment operator PidfTuple& PidfTuple::operator=(const PidfTuple& rPidfTuple) { if(this != &rPidfTuple) { remove(0); append(rPidfTuple); mTupleStatusBasic = rPidfTuple.mTupleStatusBasic; mTupleContact = rPidfTuple.mTupleContact; mTupleNote = rPidfTuple.mTupleNote; } return(*this); } /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Default constructor PidfBody::PidfBody(const char* resourceAor) : HttpBody() { if(resourceAor) { mEntityAor = resourceAor; } mClassType = PIDF_BODY_CLASS; mRendered = FALSE; // Remove to make sure base class did not already set it remove(0); append(CONTENT_TYPE_PIDF); } // Constructor PidfBody::PidfBody(const char* bytes, int length, const char* contentEncodingValueString) : HttpBody() { mClassType = PIDF_BODY_CLASS; parseXmlToPidfProperties(bytes, length, contentEncodingValueString, mEntityAor, mTuples); mRendered = TRUE; mBody.append(bytes, length); bodyLength = length; // Remove to make sure base class did not already set it remove(0); append(CONTENT_TYPE_PIDF); } // Copy constructor PidfBody::PidfBody(const PidfBody& rPidfBody) { // Copy the parent *((HttpBody*)this) = rPidfBody; // Remove to make sure base class did not already set it remove(0); append(CONTENT_TYPE_PIDF); mClassType = PIDF_BODY_CLASS; mEntityAor = rPidfBody.mEntityAor; copyTuples(rPidfBody.mTuples, mTuples); mRendered = rPidfBody.mRendered; } // Destructor PidfBody::~PidfBody() { // Delete any Tuples in the list mTuples.destroyAll(); } /* ============================ MANIPULATORS ============================== */ // Assignment operator PidfBody& PidfBody::operator=(const PidfBody& rPidfBody) { if (this != &rPidfBody) // do not copy self { // Copy the parent *((HttpBody*)this) = rPidfBody; // Set the class type just mClassType = PIDF_BODY_CLASS; *this = CONTENT_TYPE_PIDF; mClassType = PIDF_BODY_CLASS; mEntityAor = rPidfBody.mEntityAor; mTuples.destroyAll(); copyTuples(rPidfBody.mTuples, mTuples); } return(*this); } void PidfBody::render() { mBody.remove(0); // Add the common PIDF XML header renderPidfXmlHeader(mEntityAor); UtlDListIterator iterator(mTuples); // Loop through the Tuples and add to the body PidfTuple* tuple = NULL; while((tuple = (PidfTuple*) iterator())) { renderPidfTuple(*tuple, tuple->mTupleStatusBasic, tuple->mTupleContact, tuple->mTupleNote); } // Add the common PIDF footer renderPidfXmlFooter(); mRendered = TRUE; } int PidfBody::parseXmlToPidfProperties(const char* bytes, int length, const char* contentEncodingValueString, UtlString& entityAor, UtlDList& tuples) { int tupleCount = 0; entityAor.remove(0); tuples.destroyAll(); // Make sure we have a null terminated string UtlString byteString; byteString.append(bytes, length); // TODO: should pay attention to contentEncodingValueString TiXmlDocument pidfXmlDocument; pidfXmlDocument.Parse(byteString); // TODO: need to check for name spaces // Get the presense element and the AOR attribute TiXmlNode* presenceNode = pidfXmlDocument.FirstChild ("presence"); if(presenceNode) { TiXmlElement* presenceElement = presenceNode->ToElement(); if(presenceElement) { entityAor = presenceElement->Attribute("entity"); } TiXmlNode *tupleNode = presenceNode->FirstChild("tuple"); while(tupleNode) { PidfTuple* tuple = new PidfTuple; // Get the tuple id attribute TiXmlElement* tupleElement = tupleNode->ToElement(); if(tupleElement) { tuple->append(tupleElement->Attribute("id")); } // The tuple should contain a , one or more // and optionally a TiXmlNode* statusNode = tupleNode->FirstChild("status"); if(statusNode) { TiXmlNode* basicNode = statusNode->FirstChild("basic"); if(basicNode) { UtlString basicString; basicString = basicNode->FirstChild()->Value(); tuple->mTupleStatusBasic = FALSE; if(basicString.compareTo("open", UtlString::ignoreCase) == 0) { tuple->mTupleStatusBasic = TRUE; } } } TiXmlNode* contactNode = tupleNode->FirstChild("contact"); if(contactNode) { tuple->mTupleContact = contactNode->FirstChild()->Value(); } TiXmlNode* noteNode = tupleNode->FirstChild("note"); if(noteNode) { tuple->mTupleNote = noteNode->FirstChild()->Value(); } // Add the tuple to the list tuples.append(tuple); // check for next tuple tupleNode = presenceNode->NextSibling("tuple"); } } return(tupleCount); } /* ============================ ACCESSORS ================================= */ void PidfBody::getEntityAor(UtlString& entityAor) const { entityAor = mEntityAor; } void PidfBody::getBytes(const char** bytes, int* length) const { if(!mRendered) { (*((PidfBody*)this)).render(); } HttpBody::getBytes(bytes, length); } void PidfBody::getBytes(UtlString* bytes, int* length) const { if(!mRendered) { (*((PidfBody*)this)).render(); } HttpBody::getBytes(bytes, length); } UtlBoolean PidfBody::getBasicStatus(int tupleIndex, UtlString& tupleId, UtlBoolean& isTupleStatusBasicOpen, UtlString& contact, UtlString& tupleNote) const { PidfTuple* tuple = (PidfTuple*) mTuples.at(tupleIndex); if(tuple) { tupleId = *tuple; isTupleStatusBasicOpen = tuple->mTupleStatusBasic; contact = tuple->mTupleContact; tupleNote = tuple->mTupleNote; } else { isTupleStatusBasicOpen = FALSE; contact = ""; tupleNote = ""; } return(tuple != NULL); } UtlBoolean PidfBody::changeBasicStatus(int tupleIndex, UtlBoolean isTupleStatusBasicOpen) { PidfTuple* tuple = (PidfTuple*) mTuples.at(tupleIndex); if(tuple) { tuple->mTupleStatusBasic = isTupleStatusBasicOpen; mRendered = FALSE; } return(tuple != NULL); } void PidfBody::addBasicStatus(const UtlString& tupleId, const UtlBoolean& isTupleStatusBasicOpen, const UtlString& contact, const UtlString& tupleNote) { PidfTuple* tuple = new PidfTuple(); tuple->append(tupleId); tuple->mTupleStatusBasic = isTupleStatusBasicOpen; tuple->mTupleContact = contact; tuple->mTupleNote = tupleNote; mTuples.append(tuple); mRendered = FALSE; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* open tel:+09012345678 , using a default XML namespace: open tel:+09012345678 */ // Quick and dirty implementation of XML rendering void PidfBody::renderPidfXmlHeader(const UtlString& entityAor) { mBody = "\n\n"); bodyLength = mBody.length(); } void PidfBody::renderPidfTuple(const UtlString& tupleId, const UtlBoolean isTupleStatusBasicOpen, const UtlString& tupleContact, const UtlString& tupleNote) { mBody.append(" \n \n "); // status basic if(isTupleStatusBasicOpen) { mBody.append("open"); } else { mBody.append("closed"); } mBody.append("\n \n "); // contact if(!tupleContact.isNull()) { mBody.append(" "); mBody.append(tupleContact); mBody.append("\n"); } // note if(!tupleNote.isNull()) { mBody.append(" "); mBody.append(tupleNote); mBody.append(" \n"); } // End tuple mBody.append(" \n"); bodyLength = mBody.length(); } void PidfBody::renderPidfXmlFooter() { mBody.append("\n"); bodyLength = mBody.length(); } void PidfBody::copyTuples(const UtlDList& sourceList, UtlDList& targetList) { UtlDListIterator iterator(sourceList); // Loop through the Tuples copy to target list PidfTuple* tuple = NULL; while((tuple = (PidfTuple*) iterator())) { PidfTuple* tupleCopy = new PidfTuple(*tuple); targetList.append(tupleCopy); } } /* ============================ TESTING =================================== */ /* ============================ FUNCTIONS ================================= */ sipxtapi-3.3.0~test17/sipXtackLib/src/net/SipTlsServer.cpp0000644000175000017500000002531412205613256024310 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifdef SIP_TLS // SYSTEM INCLUDES #include // APPLICATION INCLUDES #include #include #include #ifdef SIP_TLS # include # ifdef SIP_TLS_NSS # else # include # include # endif #endif #include #include #include #include // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS //#define TEST_PRINT // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor SipTlsServer::SipTlsServer(int port, SipUserAgent* userAgent, UtlBoolean bUseNextAvailablePort, UtlString certNickname, UtlString certPassword, UtlString dbLocation, const char* szBindAddr) : SipProtocolServerBase(userAgent, "TLS", "SipTlsServer %d"), mCertNickname(certNickname), mCertPassword(certPassword), mDbLocation(dbLocation), mTlsInitCode(OS_SUCCESS) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTlsServer::_ port = %d, bUseNextAvailablePort = %d", port, bUseNextAvailablePort); mServerPort = port ; mpServerBrokerListener = new SipServerBrokerListener(this); #ifdef _DISABLE_MULTIPLE_INTERFACE_SUPPORT szBindAddr = "0.0.0.0" ; #endif OsSysLog::add(FAC_SIP,PRI_DEBUG,"SipTlsServer::~ port %d", port); if (szBindAddr && 0 != strcmp(szBindAddr, "0.0.0.0")) { mDefaultIp = szBindAddr; createServerSocket(szBindAddr, mServerPort, bUseNextAvailablePort); } else { int numAddresses = MAX_IP_ADDRESSES; const HostAdapterAddress* adapterAddresses[MAX_IP_ADDRESSES]; getAllLocalHostIps(adapterAddresses, numAddresses); for (int i = 0; i < numAddresses; i++) { createServerSocket(adapterAddresses[i]->mAddress.data(), mServerPort, bUseNextAvailablePort); if (0 == i) { // use the first IP address in the array // for the 'default ip' mDefaultIp = adapterAddresses[i]->mAddress.data(); } delete adapterAddresses[i]; } } mDefaultPort = SIP_TLS_PORT; } UtlBoolean SipTlsServer::startListener() { UtlBoolean bRet(FALSE); # ifdef TEST_PRINT osPrintf("SIP Server binding to port %d\n", serverPort); # endif // iterate over the SipServerBroker map and call start UtlHashMapIterator iterator(mServerBrokers); UtlVoidPtr* pBrokerContainer = NULL; SipServerBroker* pBroker = NULL; UtlString* pKey = NULL; while(pKey = (UtlString*)iterator()) { pBrokerContainer = (UtlVoidPtr*) iterator.value(); if (pBrokerContainer) { pBroker = (SipServerBroker*)pBrokerContainer->getValue(); if (pBroker) { pBroker->start(); bRet = TRUE; } } } return bRet; } OsStatus SipTlsServer::createServerSocket(const char* szBindAddr, int& port, const UtlBoolean& bUseNextAvailablePort) { OsStatus rc = OS_FAILED; if(portIsValid(port)) { #ifdef SIP_TLS # ifdef SIP_TLS_NSS // TODO - create a new OpenTLSServerSocket OsServerSocket* pServerSocket = new OsTLSServerSocket(64, port, mCertNickname, mCertPassword, mDbLocation, szBindAddr); if (pServerSocket) { } # else OsServerSocket* pServerSocket = new OsSSLServerSocket(64, port); # endif #else OsServerSocket* pServerSocket = new OsServerSocket(64, port); #endif // If the socket is busy or unbindable and the user requested using the // next available port, try the next SIP_MAX_PORT_RANGE ports. if (bUseNextAvailablePort && !pServerSocket->isOk()) { for (int i=1; i<=SIP_MAX_PORT_RANGE; i++) { delete pServerSocket ; #ifdef SIP_TLS # ifdef SIP_TLS_NSS pServerSocket = new OsTLSServerSocket(64, port+i, mCertNickname, mCertPassword, mDbLocation); # else pServerSocket = new OsSSLServerSocket(64, port+i); # endif #else pServerSocket = new OsServerSocket(64, port+i); #endif if (pServerSocket->isOk()) { break ; } } } if (pServerSocket && pServerSocket->isOk()) { mServerPort = pServerSocket->getLocalHostPort() ; port = pServerSocket->getLocalHostPort(); SIPX_CONTACT_ADDRESS contact; strcpy(contact.cIpAddress, szBindAddr); contact.iPort = port; contact.eContactType = CONTACT_LOCAL; char szAdapterName[16]; memset((void*)szAdapterName, 0, sizeof(szAdapterName)); // null out the string getContactAdapterName(szAdapterName, contact.cIpAddress, false); strcpy(contact.cInterface, szAdapterName); contact.eTransportType = TRANSPORT_TLS; mSipUserAgent->addContactAddress(contact); // add address and port to the maps mServerSocketMap.insertKeyAndValue(new UtlString(szBindAddr), new UtlVoidPtr((void*)pServerSocket)); mServerPortMap.insertKeyAndValue(new UtlString(szBindAddr), new UtlInt(pServerSocket->getLocalHostPort())); mServerBrokers.insertKeyAndValue(new UtlString(szBindAddr), new UtlVoidPtr(new SipServerBroker((OsServerTask*)mpServerBrokerListener, pServerSocket))); rc = OS_SUCCESS; # ifdef SIP_TLS_NSS TlsInitCodes tlsInitCode = ((OsTLSServerSocket*)pServerSocket)->getTlsInitCode(); if (tlsInitCode != TLS_INIT_SUCCESS) { switch (tlsInitCode) { case TLS_INIT_DATABASE_FAILURE: mTlsInitCode = OS_TLS_INIT_DATABASE_FAILURE; break; case TLS_INIT_BAD_PASSWORD: mTlsInitCode = OS_TLS_INIT_BAD_PASSWORD; break; case TLS_INIT_TCP_IMPORT_FAILURE: mTlsInitCode = OS_TLS_INIT_TCP_IMPORT_FAILURE; break; case TLS_INIT_NSS_FAILURE: mTlsInitCode = OS_TLS_INIT_NSS_FAILURE; break; default: mTlsInitCode = OS_TLS_INIT_NSS_FAILURE; break; } OsSysLog::add(FAC_SIP, PRI_ERR, "SipTlsServer - init failure = %d", mTlsInitCode); } # endif } } return rc; } void SipTlsServer::shutdownListener() { requestShutdown(); shutdownClients(); } int SipTlsServer::run(void* runArgument) { while (!isShuttingDown()) { OsTask::delay(500); // this method really shouldn't do anything } return(0); } // Destructor SipTlsServer::~SipTlsServer() { waitUntilShutDown(); if (mpServerBrokerListener) { mpServerBrokerListener->requestShutdown(); delete mpServerBrokerListener; } { SipServerBroker* pBroker = NULL; UtlHashMapIterator iterator(this->mServerBrokers); UtlVoidPtr* pBrokerContainer = NULL; UtlString* pKey = NULL; while (pKey = (UtlString*)iterator()) { pBrokerContainer = (UtlVoidPtr*)iterator.value(); if (pBrokerContainer) { pBroker = (SipServerBroker*)pBrokerContainer->getValue(); if (pBroker) { pBroker->requestShutdown(); delete pBroker; } } } mServerBrokers.destroyAll(); } /* { OsSocket* pSocket = NULL; UtlHashMapIterator iterator(mServerSocketMap); UtlVoidPtr* pSocketContainer = NULL; UtlString* pKey = NULL; while (pKey = (UtlString*)iterator()) { pSocketContainer = (UtlVoidPtr*)iterator.value(); if (pSocketContainer) { pSocket = (OsSocket*)pSocketContainer->getValue(); if (pSocket) { delete pSocket; } } } mServerSocketMap.destroyAll(); } */ mServerSocketMap.destroyAll(); mServerPortMap.destroyAll(); } /* ============================ MANIPULATORS ============================== */ OsSocket* SipTlsServer::buildClientSocket(int hostPort, const char* hostAddress, const char* localIp) { OsSocket* socket = NULL; #ifdef SIP_TLS # ifdef SIP_TLS_NSS socket = new OsTLSClientConnectionSocket(hostPort, hostAddress, mCertNickname, mCertPassword, mDbLocation, 0, localIp, mSipUserAgent); # else socket = new OsSSLConnectionSocket(hostPort, hostAddress); # endif #else // Create the socket in non-blocking mode so it does not block // while conecting socket = new OsConnectionSocket(hostPort, hostAddress, FALSE, localIp); #endif if (socket) { socket->makeBlocking(); } return(socket); } /* ============================ ACCESSORS ================================= */ // The the local server port for this server int SipTlsServer::getServerPort() const { return mServerPort ; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ #endif sipxtapi-3.3.0~test17/sipXtackLib/src/resparse/0000755000175000017500000000000012321445027022226 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXtackLib/src/resparse/wnt/0000755000175000017500000000000012321445027023036 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXtackLib/src/resparse/wnt/inet_addr.c0000644000175000017500000001555312205613256025146 0ustar00danieldaniel00000000000000/* * ++Copyright++ 1983, 1990, 1993 * - * Copyright (c) 1983, 1990, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * - * Portions Copyright (c) 1993 by Digital Equipment Corporation. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies, and that * the name of Digital Equipment Corporation not be used in advertising or * publicity pertaining to distribution of the document or software without * specific, written prior permission. * * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. * - * --Copyright-- */ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)inet_addr.c 8.1 (Berkeley) 6/17/93"; static char rcsid[] = ""; #endif /* LIBC_SCCS and not lint */ #if defined (_WIN32) /* Use Columbia versions for win32 only --GAT */ # include # include # include #endif #include /* Following unneeded, already replaced/included in.h for win32 --GAT */ /*#include *//* Use sysdep.h instead of winsock2.h */ #include "resparse/types.h" #if !defined(isascii) /* XXX - could be a function */ # define isascii(c) (!(c & 0200)) #endif /* * Check whether "cp" is a valid ascii representation * of an Internet address and convert to a binary address. * Returns 1 if the address is valid, 0 if not. * This replaces inet_addr, the return value from which * cannot distinguish between failure and a local broadcast address. */ int inet_aton(cp, addr) register const char *cp; struct in_addr *addr; { register u_long val; register int base, n; register char c; u_int parts[4]; register u_int *pp = parts; c = *cp; for (;;) { /* * Collect number up to ``.''. * Values are specified as for C: * 0x=hex, 0=octal, isdigit=decimal. */ if (!isdigit(c)) return (0); val = 0; base = 10; if (c == '0') { c = *++cp; if (c == 'x' || c == 'X') base = 16, c = *++cp; else base = 8; } for (;;) { if (isascii(c) && isdigit(c)) { val = (val * base) + (c - '0'); c = *++cp; } else if (base == 16 && isascii(c) && isxdigit(c)) { val = (val << 4) | (c + 10 - (islower(c) ? 'a' : 'A')); c = *++cp; } else break; } if (c == '.') { /* * Internet format: * a.b.c.d * a.b.c (with c treated as 16 bits) * a.b (with b treated as 24 bits) */ if (pp >= parts + 3) return (0); *pp++ = val; c = *++cp; } else break; } /* * Check for trailing characters. */ if (c != '\0' && (!isascii(c) || !isspace(c))) return (0); /* * Concoct the address according to * the number of parts specified. */ n = pp - parts + 1; switch (n) { case 0: return (0); /* initial nondigit */ case 1: /* a -- 32 bits */ break; case 2: /* a.b -- 8.24 bits */ if (val > 0xffffff) return (0); val |= parts[0] << 24; break; case 3: /* a.b.c -- 8.8.16 bits */ if (val > 0xffff) return (0); val |= (parts[0] << 24) | (parts[1] << 16); break; case 4: /* a.b.c.d -- 8.8.8.8 bits */ if (val > 0xff) return (0); val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8); break; } if (addr) addr->s_addr = htonl(val); return (1); } sipxtapi-3.3.0~test17/sipXtackLib/src/resparse/wnt/writev.c0000644000175000017500000000166612205613256024535 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #include #include /* writev() emulation for WIN32 environment */ int writev(int fd, const struct iovec *vector, int count) { int block; void *iov_base; unsigned int iov_len; unsigned int write_count, total_write_count; total_write_count = 0; for (block = 0; block < count; block++) { iov_base = vector[block].iov_base; iov_len = (unsigned int)vector[block].iov_len; if (WriteFile((HANDLE)fd, (char *)iov_base, iov_len, (unsigned int *)&write_count, NULL) == FALSE) return (-1); total_write_count += write_count; } return(total_write_count); } sipxtapi-3.3.0~test17/sipXtackLib/src/resparse/bzero.c0000644000175000017500000000063412205613256023520 0ustar00danieldaniel00000000000000/* // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// */ #ifndef __pingtel_on_posix__ #define BZERO #include "memset.c" #endif /* __pingtel_on_posix__ */ sipxtapi-3.3.0~test17/sipXtackLib/src/resparse/memset.c0000644000175000017500000001113012205613256023662 0ustar00danieldaniel00000000000000/*- * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Mike Hibler and Chris Torek. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef __pingtel_on_posix__ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)memset.c 8.1 (Berkeley) 6/4/93"; #endif /* LIBC_SCCS and not lint */ #ifdef WINCE # include #else # include #endif #include #include #include "resparse/types.h" #define wsize sizeof(u_int) #define wmask (wsize - 1) #ifdef BZERO #define RETURN return #define VAL 0 #define WIDEVAL 0 /* _local added to function name to avoid name conflict --GAT */ void bzero_local(dst0, length) void *dst0; register size_t length; #else #define RETURN return (dst0) #define VAL c0 #define WIDEVAL c void * res_memset(dst0, c0, length) void *dst0; register int c0; register size_t length; #endif { register size_t t; #ifndef BZERO register u_int c; #endif register u_char *dst; dst = (u_char *)dst0; /* * If not enough words, just fill bytes. A length >= 2 words * guarantees that at least one of them is `complete' after * any necessary alignment. For instance: * * |-----------|-----------|-----------| * |00|01|02|03|04|05|06|07|08|09|0A|00| * ^---------------------^ * dst dst+length-1 * * but we use a minimum of 3 here since the overhead of the code * to do word writes is substantial. */ if (length < 3 * wsize) { while (length != 0) { *dst++ = VAL; --length; } RETURN; } #ifndef BZERO if ((c = (u_char)c0) != 0) { /* Fill the word. */ c = (c << 8) | c; /* u_int is 16 bits. */ #if UINT_MAX > 0xffff c = (c << 16) | c; /* u_int is 32 bits. */ #endif #if UINT_MAX > 0xffffffff c = (c << 32) | c; /* u_int is 64 bits. */ #endif } #endif /* Align destination by filling in bytes. */ if ((t = (long)dst & wmask) != 0) { t = wsize - t; length -= t; do { *dst++ = VAL; } while (--t != 0); } /* Fill words. Length was >= 2*words so we know t >= 1 here. */ t = length / wsize; do { *(u_int *)dst = WIDEVAL; dst += wsize; } while (--t != 0); /* Mop up trailing bytes, if any. */ t = length & wmask; if (t != 0) do { *dst++ = VAL; } while (--t != 0); RETURN; } #endif /* __pingtel_on_posix__ */ sipxtapi-3.3.0~test17/sipXtackLib/src/resparse/ns_name.c0000644000175000017500000005152612205613256024025 0ustar00danieldaniel00000000000000/* * Copyright (c) 1996 by Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ #ifndef __pingtel_on_posix__ /* */ #ifdef WINCE # include #else # include #endif #ifndef WINCE /* no errno.h under WinCE */ #include #endif /* Reordered includes and separated into win/vx --GAT */ #if defined (_WIN32) /* Use Columbia versions for win32 only --GAT */ # include # include # include # include /* DWW removed next line because already defined by errno.h under vc6 # include */ #elif defined (_VXWORKS) # include /* Use local lnameser.h for info missing from VxWorks version --GAT */ /* lnameser.h is a subset of resparse/arpa/nameser.h */ # include # include /* Use local lresolv.h for info missing from VxWorks version --GAT */ /* lresolv.h is a subset of resparse/resolv/resolv.h */ # include # include #endif #include /* #define EMSGSIZE 40 Removed, now in nterrno.h --GAT */ /* Message too long */ #define NS_CMPRSFLGS 0xc0 /* Defined by myself */ #define NS_MAXCDNAME 256 /* Defined by myself */ /* Data. */ static char digits[] = "0123456789"; /* Forward. */ static int special(int); static int printable(int); static int dn_find(const u_char *, const u_char *, const u_char * const *, const u_char * const *); /* Public. */ /* * ns_name_ntop(src, dst, dstsiz) * Convert an encoded domain name to printable ascii as per RFC1035. * return: * Number of bytes written to buffer, or -1 (with errno set) * notes: * The root is returned as "." * All other domains are returned in non absolute form */ int ns_name_ntop(const u_char *src, char *dst, size_t dstsiz) { const u_char *cp; char *dn, *eom; u_char c; u_int n; cp = src; dn = dst; eom = dst + dstsiz; while ((n = *cp++) != 0) { if ((n & NS_CMPRSFLGS) != 0) { /* Some kind of compression pointer. */ errno = EMSGSIZE; return (-1); } if (dn != dst) { if (dn >= eom) { errno = EMSGSIZE; return (-1); } *dn++ = '.'; } if (dn + n >= eom) { errno = EMSGSIZE; return (-1); } for ((void)NULL; n > 0; n--) { c = *cp++; if (special(c)) { if (dn + 1 >= eom) { errno = EMSGSIZE; return (-1); } *dn++ = '\\'; *dn++ = (char)c; } else if (!printable(c)) { if (dn + 3 >= eom) { errno = EMSGSIZE; return (-1); } *dn++ = '\\'; *dn++ = digits[c / 100]; *dn++ = digits[(c % 100) / 10]; *dn++ = digits[c % 10]; } else { if (dn >= eom) { errno = EMSGSIZE; return (-1); } *dn++ = (char)c; } } } if (dn == dst) { if (dn >= eom) { errno = EMSGSIZE; return (-1); } *dn++ = '.'; } if (dn >= eom) { errno = EMSGSIZE; return (-1); } *dn++ = '\0'; return (dn - dst); } /* * ns_name_pton(src, dst, dstsiz) * Convert a ascii string into an encoded domain name as per RFC1035. * return: * -1 if it fails * 1 if string was fully qualified * 0 is string was not fully qualified * notes: * Enforces label and domain length limits. */ int ns_name_pton(const char *src, u_char *dst, size_t dstsiz) { u_char *label, *bp, *eom; int c, n, escaped; char *cp; int ttmp; escaped = 0; bp = dst; eom = dst + dstsiz; label = bp++; while ((c = *src++) != 0) { if (escaped) { if ((cp = strchr(digits, c)) != NULL) { n = (cp - digits) * 100; if ((c = *src++) == 0 || (cp = strchr(digits, c)) == NULL) { errno = EMSGSIZE; return (-1); } n += (cp - digits) * 10; if ((c = *src++) == 0 || (cp = strchr(digits, c)) == NULL) { errno = EMSGSIZE; return (-1); } n += (cp - digits); if (n > 255) { errno = EMSGSIZE; return (-1); } c = n; } escaped = 0; } else if (c == '\\') { escaped = 1; continue; } else if (c == '.') { c = (bp - label - 1); ttmp = NS_CMPRSFLGS; if ((c & NS_CMPRSFLGS) != 0) { /* Label too big. */ errno = EMSGSIZE; return (-1); } if (label >= eom) { errno = EMSGSIZE; return (-1); } *label = c; /* Fully qualified ? */ if (*src == '\0') { if (c != 0) { if (bp >= eom) { errno = EMSGSIZE; return (-1); } *bp++ = '\0'; } if ((bp - dst) > MAXCDNAME) { errno = EMSGSIZE; return (-1); } return (1); } if (c == 0) { errno = EMSGSIZE; return (-1); } label = bp++; continue; } if (bp >= eom) { errno = EMSGSIZE; return (-1); } *bp++ = (u_char)c; } c = (bp - label - 1); ttmp = NS_CMPRSFLGS; if ((c & NS_CMPRSFLGS) != 0) { /* Label too big. */ errno = EMSGSIZE; return (-1); } if (label >= eom) { errno = EMSGSIZE; return (-1); } *label = c; if (c != 0) { if (bp >= eom) { errno = EMSGSIZE; return (-1); } *bp++ = 0; } if ((bp - dst) > MAXCDNAME) { /* src too big */ errno = EMSGSIZE; return (-1); } return (0); } /* * ns_name_unpack(msg, eom, src, dst, dstsiz) * Unpack a domain name from a message, source may be compressed. * return: * -1 if it fails, or consumed octets if it succeeds. */ int ns_name_unpack(const u_char *msg, const u_char *eom, const u_char *src, u_char *dst, size_t dstsiz) { const u_char *srcp, *dstlim; u_char *dstp; int n, len, checked; len = -1; checked = 0; dstp = dst; srcp = src; dstlim = dst + dstsiz; if (srcp < msg || srcp >= eom) { errno = EMSGSIZE; return (-1); } /* Fetch next label in domain name. */ while ((n = *srcp++) != 0) { /* Check for indirection. */ switch (n & NS_CMPRSFLGS) { case 0: /* Limit checks. */ if (dstp + n + 1 >= dstlim || srcp + n >= eom) { errno = EMSGSIZE; return (-1); } checked += n + 1; *dstp++ = n; memcpy(dstp, srcp, n); dstp += n; srcp += n; break; case NS_CMPRSFLGS: if (srcp >= eom) { errno = EMSGSIZE; return (-1); } if (len < 0) len = srcp - src + 1; srcp = msg + (((n & 0x3f) << 8) | (*srcp & 0xff)); if (srcp < msg || srcp >= eom) { /* Out of range. */ errno = EMSGSIZE; return (-1); } checked += 2; /* * Check for loops in the compressed name; * if we've looked at the whole message, * there must be a loop. */ if (checked >= eom - msg) { errno = EMSGSIZE; return (-1); } break; default: errno = EMSGSIZE; return (-1); /* flag error */ } } *dstp = '\0'; if (len < 0) len = srcp - src; return (len); } /* * ns_name_pack(src, dst, dstsiz, dnptrs, lastdnptr) * Pack domain name 'domain' into 'comp_dn'. * return: * Size of the compressed name, or -1. * notes: * 'dnptrs' is an array of pointers to previous compressed names. * dnptrs[0] is a pointer to the beginning of the message. The array * ends with NULL. * 'lastdnptr' is a pointer to the end of the array pointed to * by 'dnptrs'. * Side effects: * The list of pointers in dnptrs is updated for labels inserted into * the message as we compress the name. If 'dnptr' is NULL, we don't * try to compress names. If 'lastdnptr' is NULL, we don't update the * list. */ int ns_name_pack(const u_char *src, u_char *dst, int dstsiz, const u_char **dnptrs, const u_char **lastdnptr) { u_char *dstp; const u_char **cpp, **lpp, *eob, *msg; const u_char *srcp; int n, l; srcp = src; dstp = dst; eob = dstp + dstsiz; lpp = cpp = NULL; if (dnptrs != NULL) { if ((msg = *dnptrs++) != NULL) { for (cpp = dnptrs; *cpp != NULL; cpp++) (void)NULL; lpp = cpp; /* end of list to search */ } } else msg = NULL; /* make sure the domain we are about to add is legal */ l = 0; do { n = *srcp; if ((n & NS_CMPRSFLGS) != 0) { errno = EMSGSIZE; return (-1); } l += n + 1; if (l > MAXCDNAME) { errno = EMSGSIZE; return (-1); } srcp += n + 1; } while (n != 0); srcp = src; do { /* Look to see if we can use pointers. */ n = *srcp; if (n != 0 && msg != NULL) { l = dn_find(srcp, msg, (const u_char * const *)dnptrs, (const u_char * const *)lpp); if (l >= 0) { if (dstp + 1 >= eob) { errno = EMSGSIZE; return (-1); } *dstp++ = (l >> 8) | NS_CMPRSFLGS; *dstp++ = l % 256; return (dstp - dst); } /* Not found, save it. */ if (lastdnptr != NULL && cpp < lastdnptr - 1 && (dstp - msg) < 0x4000) { *cpp++ = dstp; *cpp = NULL; } } /* copy label to buffer */ if (n & NS_CMPRSFLGS) { /* Should not happen. */ errno = EMSGSIZE; return (-1); } if (dstp + 1 + n >= eob) { errno = EMSGSIZE; return (-1); } memcpy(dstp, srcp, n + 1); srcp += n + 1; dstp += n + 1; } while (n != 0); if (dstp > eob) { if (msg != NULL) *lpp = NULL; errno = EMSGSIZE; return (-1); } return (dstp - dst); } /* * ns_name_uncompress(msg, eom, src, dst, dstsiz) * Expand compressed domain name to presentation format. * return: * Number of bytes read out of `src', or -1 (with errno set). * note: * Root domain returns as "." not "". */ int ns_name_uncompress(const u_char *msg, const u_char *eom, const u_char *src, char *dst, size_t dstsiz) { u_char tmp[NS_MAXCDNAME]; int n; if ((n = ns_name_unpack(msg, eom, src, tmp, sizeof tmp)) == -1) return (-1); if (ns_name_ntop(tmp, dst, dstsiz) == -1) return (-1); return (n); } /* * ns_name_compress(src, dst, dstsiz, dnptrs, lastdnptr) * Compress a domain name into wire format, using compression pointers. * return: * Number of bytes consumed in `dst' or -1 (with errno set). * notes: * 'dnptrs' is an array of pointers to previous compressed names. * dnptrs[0] is a pointer to the beginning of the message. * The list ends with NULL. 'lastdnptr' is a pointer to the end of the * array pointed to by 'dnptrs'. Side effect is to update the list of * pointers for labels inserted into the message as we compress the name. * If 'dnptr' is NULL, we don't try to compress names. If 'lastdnptr' * is NULL, we don't update the list. */ int ns_name_compress(const char *src, u_char *dst, size_t dstsiz, const u_char **dnptrs, const u_char **lastdnptr) { u_char tmp[NS_MAXCDNAME]; if (ns_name_pton(src, tmp, sizeof tmp) == -1) return (-1); return (ns_name_pack(tmp, dst, dstsiz, dnptrs, lastdnptr)); } /* * ns_name_skip(ptrptr, eom) * Advance *ptrptr to skip over the compressed name it points at. * return: * 0 on success, -1 (with errno set) on failure. */ int ns_name_skip(const u_char **ptrptr, const u_char *eom) { const u_char *cp; u_int n; cp = *ptrptr; while (cp < eom && (n = *cp++) != 0) { /* Check for indirection. */ switch (n & NS_CMPRSFLGS) { case 0: /* normal case, n == len */ cp += n; continue; case NS_CMPRSFLGS: /* indirection */ cp++; break; default: /* illegal type */ errno = EMSGSIZE; return (-1); } break; } if (cp > eom) { errno = EMSGSIZE; return (-1); } *ptrptr = cp; return (0); } /* Private. */ /* * special(ch) * Thinking in noninternationalized USASCII (per the DNS spec), * is this characted special ("in need of quoting") ? * return: * boolean. */ static int special(int ch) { switch (ch) { case 0x22: /* '"' */ case 0x2E: /* '.' */ case 0x3B: /* ';' */ case 0x5C: /* '\\' */ /* Special modifiers in zone files. */ case 0x40: /* '@' */ case 0x24: /* '$' */ return (1); default: return (0); } } /* * printable(ch) * Thinking in noninternationalized USASCII (per the DNS spec), * is this character visible and not a space when printed ? * return: * boolean. */ static int printable(int ch) { return (ch > 0x20 && ch < 0x7f); } /* * Thinking in noninternationalized USASCII (per the DNS spec), * convert this character to lower case if it's upper case. */ static int mklower(int ch) { if (ch >= 0x41 && ch <= 0x5A) return (ch + 0x20); return (ch); } /* * dn_find(domain, msg, dnptrs, lastdnptr) * Search for the counted-label name in an array of compressed names. * return: * offset from msg if found, or -1. * notes: * dnptrs is the pointer to the first name on the list, * not the pointer to the start of the message. */ static int dn_find(const u_char *domain, const u_char *msg, const u_char * const *dnptrs, const u_char * const *lastdnptr) { const u_char *dn, *cp, *sp; const u_char * const *cpp; u_int n; for (cpp = dnptrs; cpp < lastdnptr; cpp++) { dn = domain; sp = cp = *cpp; while ((n = *cp++) != 0) { /* * check for indirection */ switch (n & NS_CMPRSFLGS) { case 0: /* normal case, n == len */ if (n != *dn++) goto next; for ((void)NULL; n > 0; n--) if (mklower(*dn++) != mklower(*cp++)) goto next; /* Is next root for both ? */ if (*dn == '\0' && *cp == '\0') return (sp - msg); if (*dn) continue; goto next; case NS_CMPRSFLGS: /* indirection */ cp = msg + (((n & 0x3f) << 8) | *cp); break; default: /* illegal type */ errno = EMSGSIZE; return (-1); } } next: ; } errno = ENOENT; return (-1); } #endif /* __pingtel_on_posix__ */ sipxtapi-3.3.0~test17/sipXtackLib/src/resparse/ns_netint.c0000644000175000017500000000360312205613256024377 0ustar00danieldaniel00000000000000/* * Copyright (c) 1996 by Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ #ifndef __pingtel_on_posix__ /* */ /* Import. */ #ifdef WINCE # include #else # include #endif /* Reordered includes and separated into win/vx --GAT */ #if defined (_WIN32) /* Use Columbia versions for win32 only --GAT */ # include # include # include #elif defined(_VXWORKS) # include # include /* Use local lnameser.h for info missing from VxWorks version --GAT */ /* lnameser.h is a subset of resparse/wnt/arpa/nameser.h */ # include # include #endif u_int ns_get16(const u_char *src) { u_int dst; NS_GET16(dst, src); return (dst); } u_long ns_get32(const u_char *src) { u_long dst; NS_GET32(dst, src); return (dst); } void ns_put16(u_int src, u_char *dst) { NS_PUT16(src, dst); } void ns_put32(u_long src, u_char *dst) { NS_PUT32(src, dst); } #endif /* __pingtel_on_posix__ */ sipxtapi-3.3.0~test17/sipXtackLib/src/resparse/res_comp.c0000644000175000017500000002451312205613256024210 0ustar00danieldaniel00000000000000/* * Copyright (c) 1985, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Portions Copyright (c) 1993 by Digital Equipment Corporation. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies, and that * the name of Digital Equipment Corporation not be used in advertising or * publicity pertaining to distribution of the document or software without * specific, written prior permission. * * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ /* * Portions Copyright (c) 1996 by Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ #ifndef __pingtel_on_posix__ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)res_comp.c 8.1 (Berkeley) 6/4/93"; static char orig_rcsid[] = "From: Id: res_comp.c,v 8.11 1997/05/21 19:31:04 halley Exp $"; static char rcsid[] = ""; #endif /* LIBC_SCCS and not lint */ #ifdef WINCE # include #else # include #endif #include /* Reordered includes and separated into win/vx --GAT */ #if defined (_WIN32) /* Use Columbia versions for win32 only --GAT */ # include # include # include # include # include #elif defined(_VXWORKS) # include # include /* Use local lnameser.h for info missing from VxWorks version --GAT */ /* lnameser.h is a subset of resparse/wnt/arpa/nameser.h */ # include # include /* Use local lresolv.h for info missing from VxWorks version --GAT */ /* lresolv.h is a subset of resparse/wnt/resolv/resolv.h */ # include # include # include #endif #include #include #include "resparse/ns_name.h" #define BIND_4_COMPAT /* * Expand compressed domain name 'comp_dn' to full domain name. * 'msg' is a pointer to the begining of the message, * 'eomorig' points to the first location after the message, * 'exp_dn' is a pointer to a buffer of size 'length' for the result. * Return size of compressed name or -1 if there was an error. */ int dn_expand(const u_char *msg, const u_char *eom, const u_char *src, char *dst, int dstsiz) { int n = ns_name_uncompress(msg, eom, src, dst, (size_t)dstsiz); if (n > 0 && dst[0] == '.') dst[0] = '\0'; return (n); } /* * Pack domain name 'exp_dn' in presentation form into 'comp_dn'. * Return the size of the compressed name or -1. * 'length' is the size of the array pointed to by 'comp_dn'. */ int dn_comp(const char *src, u_char *dst, int dstsiz, u_char **dnptrs, u_char **lastdnptr) { return (ns_name_compress(src, dst, (size_t)dstsiz, (const u_char **)dnptrs, (const u_char **)lastdnptr)); } /* Use Columbia version for win32 only to avoid conflict * with libARMSA110gnuvx.a library under VxWorks --GAT */ #if defined (_WIN32) /* * Skip over a compressed domain name. Return the size or -1. */ int dn_skipname(const u_char *ptr, const u_char *eom) { const u_char *saveptr = ptr; if (ns_name_skip(&ptr, eom) == -1) return (-1); return (ptr - saveptr); } #endif /* * Verify that a domain name uses an acceptable character set. */ /* * Note the conspicuous absence of ctype macros in these definitions. On * non-ASCII hosts, we can't depend on string literals or ctype macros to * tell us anything about network-format data. The rest of the BIND system * is not careful about this, but for some reason, we're doing it right here. */ #define PERIOD 0x2e #define hyphenchar(c) ((c) == 0x2d) #define bslashchar(c) ((c) == 0x5c) #define periodchar(c) ((c) == PERIOD) #define asterchar(c) ((c) == 0x2a) #define alphachar(c) (((c) >= 0x41 && (c) <= 0x5a) \ || ((c) >= 0x61 && (c) <= 0x7a)) #define digitchar(c) ((c) >= 0x30 && (c) <= 0x39) #define borderchar(c) (alphachar(c) || digitchar(c)) #define middlechar(c) (borderchar(c) || hyphenchar(c)) #define domainchar(c) ((c) > 0x20 && (c) < 0x7f) #if !defined(_VXWORKS) /* * wdn - it is defined in * * TORNADO2.2\target\src\wrn\coreip\apps\dns\v6\client\res_comp.c */ int res_hnok(dn) const char *dn; { int ppch = '\0', pch = PERIOD, ch = *dn++; while (ch != '\0') { int nch = *dn++; if (periodchar(ch)) { (void)NULL; } else if (periodchar(pch)) { if (!borderchar(ch)) return (0); } else if (periodchar(nch) || nch == '\0') { if (!borderchar(ch)) return (0); } else { if (!middlechar(ch)) return (0); } ppch = pch, pch = ch, ch = nch; } return (1); } #endif /* * hostname-like (A, MX, WKS) owners can have "*" as their first label * but must otherwise be as a host name. */ int res_ownok(dn) const char *dn; { if (asterchar(dn[0])) { if (periodchar(dn[1])) return (res_hnok(dn+2)); if (dn[1] == '\0') return (1); } return (res_hnok(dn)); } /* * SOA RNAMEs and RP RNAMEs can have any printable character in their first * label, but the rest of the name has to look like a host name. */ int res_mailok(dn) const char *dn; { int ch, escaped = 0; /* "." is a valid missing representation */ if (*dn == '\0') return (1); /* otherwise
* * CONNECTED indicates that both RTP is flowing and the call is attached * to the local. This is the normal state for a connected call. * * BRIDGED indicates that RTP is flowing, but the call is out of focus. * This event is generally caused by holding a conference (conference * will bridge by default) or if you accept/place a new call without * explicitly holding the active call. * * REMOTE_HELD indicates that RTP has stopped flowing. This is generally * caused when the remote side places you on hold. The call is still * locally in focus and audio will automatically resume once your are * take off remote hold. * * HELD indicates that both RTP has stopped flowing and the call is out * of focus. * * Developers can also expect media events (e.g. MEDIA_LOCAL_STOP) * whenever RTP is stopped (REMOTE_HELD and HELD). Since media is still * flowing for CONNECTED and BRIDGED, no media stop events are sent. * * NOTE: If this call is part of a conference, sipxCallHold will only * change the remote held state (RTP). You must use * sipxConferenceHold to change call focus. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param bStopRemoteAudio Flag which controls whether sipXtapi takes * the call out of focus (stops engaging local audio microphone * and speaker) or stops sending/receiving audio. Specify true * to stop audio (default) or false to take the call out of * focus. To play audio or generate tones to a remote connection * while on hold, please specify false. This parameter is * ignored (and assumed true) if the call is part of a conference. */ SIPXTAPI_API SIPX_RESULT sipxCallHold(const SIPX_CALL hCall, bool bStopRemoteAudio = true) ; /** * Take the specified call off hold. This API will take the call off * both local hold and remote/full hold. * * @see sipxCallHold for a description of expected events * associated with hold events. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. */ SIPXTAPI_API SIPX_RESULT sipxCallUnhold(const SIPX_CALL hCall) ; /** * Drop/Destroy the specified call. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. */ SIPXTAPI_API SIPX_RESULT sipxCallDestroy(SIPX_CALL& hCall) ; /** * Get the SIP call ID of the call represented by the specified call handle. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szId Buffer to store the ID. A zero-terminated string will be * copied into this buffer on success. * @param iMaxLength Max length of the ID buffer */ SIPXTAPI_API SIPX_RESULT sipxCallGetID(const SIPX_CALL hCall, char* szId, const size_t iMaxLength) ; /** * Get the SIP identity of the local connection. The identity represents * either 1) who was called in the case of a inbound call, or 2) the * line identity used in an outbound call. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szId Buffer to store the ID. A zero-terminated string will be * copied into this buffer on success. * @param iMaxLength Max length of the ID buffer. */ SIPXTAPI_API SIPX_RESULT sipxCallGetLocalID(const SIPX_CALL hCall, char* szId, const size_t iMaxLength) ; /** * Get the line handle for the given call if it has one. * * @param hCall - Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param hLine - handle to call for local side of call. * Note: not all calls have a line handle. Set to SIPX_LINE_NULL if * line handle does not exist for call. */ SIPXTAPI_API SIPX_RESULT sipxCallGetLine(const SIPX_CALL hCall, SIPX_LINE& hLine); /** * Get the SIP identity of the remote connection. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szId Buffer to store the ID. A zero-terminated string will be * copied into this buffer on success. * @param iMaxLength Max length of the ID buffer. */ SIPXTAPI_API SIPX_RESULT sipxCallGetRemoteID(const SIPX_CALL hCall, char* szId, const size_t iMaxLength) ; /** * Get the SIP identity of the contact connection. The identity represents * the originator of the message. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szId Buffer to store the ID. A zero-terminated string will be * copied into this buffer on success. * @param iMaxLength Max length of the ID buffer. */ SIPXTAPI_API SIPX_RESULT sipxCallGetContactID(const SIPX_CALL hCall, char* szId, const size_t iMaxLength) ; /** * Gets the media interface connection ID. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param connectionId Reference to the returned connection identifier. */ SIPXTAPI_API SIPX_RESULT sipxCallGetConnectionId(const SIPX_CALL hCall, int& connectionId); /** * Get the conference handle for the specified call * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * * @param hConf Conference handle for this call (if the call is part of a * conference) */ SIPXTAPI_API SIPX_RESULT sipxCallGetConference(const SIPX_CALL hCall, SIPX_CONF& hConf) ; /** * Get the SIP request URI. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szUri Buffer to store the request URI. A zero-terminated string will * be copied into this buffer on success. * @param iMaxLength Max length of the request URI buffer. */ SIPXTAPI_API SIPX_RESULT sipxCallGetRequestURI(const SIPX_CALL hCall, char* szUri, const size_t iMaxLength) ; /** * Get the SIP remote contact. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szContact Buffer to store the remote contact. A zero-terminated * string will be copied into this buffer on success. * @param iMaxLength Max length of the remote contact buffer. */ SIPXTAPI_API SIPX_RESULT sipxCallGetRemoteContact(const SIPX_CALL hCall, char* szContact, const size_t iMaxLength) ; /** * Get the remote user agent of the call represented by the specified call handle. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szAgent Buffer to store the user agent name. A zero-terminated string * will be copied into this buffer on success. * @param iMaxLength Max length of the buffer */ SIPXTAPI_API SIPX_RESULT sipxCallGetRemoteUserAgent(const SIPX_CALL hCall, char* szAgent, const size_t iMaxLength) ; /** * Play a tone (DTMF, dialtone, ring back, etc) to the local and/or * remote party. See the DTMF_ constants for built-in tones. * If a sipxCallDestroy is attempted while a tone is playing, * sipxCallDestroy will fail with a SIPX_RESULT_BUSY return code. * Call sipxCallStopTone before making the call to * sipxConferenceDestroy. DTMF is sent via RFC 2833 method. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param toneId ID of the tone to play * @param bLocal Should the tone be played locally? * @param bRemote Should the tone be played to the remote party? */ SIPXTAPI_API SIPX_RESULT sipxCallStartTone(const SIPX_CALL hCall, const SIPX_TONE_ID toneId, const bool bLocal, const bool bRemote) ; /** * Stop playing a tone (DTMF, dialtone, ring back, etc). to local * and remote parties. Under a GIPS VoiceEngine build, this method * is a NOP -- VoiceEngine only plays tones for a specific time * interval. * If a sipxCallDestroy is attempted while a tone is playing, * sipxCallDestroy will fail with a SIPX_RESULT_BUSY return code. * Call sipxCallStopTone before making the call to * sipxConferenceDestroy. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. */ SIPXTAPI_API SIPX_RESULT sipxCallStopTone(const SIPX_CALL hCall) ; /** * Play the designated file. The file may be a raw 16 bit signed PCM at * 8000 samples/sec, mono, little endian or a .WAV file. * If a sipxCallDestroy is attempted while an audio file is playing, * sipxCallDestroy will fail with a SIPX_RESULT_BUSY return code. * Call sipxCallAudioPlayFileStop before making the call to * sipxCallDestroy. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. Audio files can only be played in the * context of a call. * @param szFile Filename for the audio file to be played. * @param bRepeat True if the file is supposed to be played repeatedly * @param bLocal True if the audio file is to be rendered locally. * @param bRemote True if the audio file is to be rendered by the remote * endpoint. * @param bMixWithMicrophone True to mix the audio with the microphone * data or false to replace it. This option is only supported * when sipXtapi is bundled with GIPS VoiceEngine. * @param fVolumeScaling Volume down scaling for the audio file. Valid * values are between 0 and 1.0, where 1.0 is the no down-scaling. * This option is only supported when sipXtapi is bundled with GIPS * VoiceEngine. */ SIPXTAPI_API SIPX_RESULT sipxCallAudioPlayFileStart(const SIPX_CALL hCall, const char* szFile, const bool bRepeat, const bool bLocal, const bool bRemote, const bool bMixWithMicrophone = false, const float fVolumeScaling = 1.0) ; /** * Stop playing a file started with sipxCallPlayFileStart * If a sipxCallDestroy is attempted while an audio file is playing, * sipxCallDestroy will fail with a SIPX_RESULT_BUSY return code. * Call sipxCallAudioPlayFileStop before making the call to * sipxCallDestroy. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. Audio files can only be played and stopped * in the context of a call. */ SIPXTAPI_API SIPX_RESULT sipxCallAudioPlayFileStop(const SIPX_CALL hCall) ; /** * Record a call session (including other parties if this is a multi-party * call / conference) to a file. The resulting file will be a PCM WAV file. * Conference join operation on this call will cause the recording to stop. * In case of conference recording, this function should be called for single * conference call only. Conference recording will continue even after the * original call had been dropped/split, as long as there is at least one call * left in the conference. If the original call has been dropped, use handle * of other call in the conference to stop recording. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szFile Filename for the resulting audio file. */ SIPXTAPI_API SIPX_RESULT sipxCallAudioRecordFileStart(const SIPX_CALL hCall, const char* szFile) ; /** * Stop recording a call to file. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. */ SIPXTAPI_API SIPX_RESULT sipxCallAudioRecordFileStop(const SIPX_CALL hCall) ; /** * Record a call session (including other parties if this is a multi-party * call / conference) to a buffer. * Conference join operation on this call will cause the recording to stop. * In case of conference recording, this function should be called for single * conference call only. Conference recording will continue even after the * original call had been dropped/split, as long as there is at least one call * left in the conference. If the original call has been dropped, use handle * of other call in the conference to stop recording. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param pBuffer Buffer to record data to. * @param bufferSize Size of the buffer in bytes. * @param bufferType The audio encoding format for the data as specified by * the SIPX_AUDIO_DATA_FORMAT enumerations. Currently only RAW_PCM_16 * is supported. * @param maxRecordTime Maximum time to record in milliseconds. Recording stops * automatically when this amount of time is recorded. Pass -1 to disable * time limit. * @param maxSilence Maximum silence time before recording is stopped * automatically. Pass -1 to disable stop on silence. */ SIPXTAPI_API SIPX_RESULT sipxCallAudioRecordBufferStart(const SIPX_CALL hCall, const char* pBuffer, const int bufferSize, const int bufferType = RAW_PCM_16, const int maxRecordTime = -1, const int maxSilence = -1) ; /** * Stop recording a call to buffer. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. */ SIPXTAPI_API SIPX_RESULT sipxCallAudioRecordBufferStop(const SIPX_CALL hCall) ; /** * Play the specified audio data. Currently the only data format that * is supported is raw 16 bit signed PCM at 8000 samples/sec, mono, * little endian. * If a sipxCallDestroy is attempted while an audio buffer is playing, * sipxCallDestroy will fail with a SIPX_RESULT_BUSY return code. * Call sipxCallPlayBufferStop before making the call to * sipxCallDestroy. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. Audio can only be played in the context * of a call. * @param szBuffer Pointer to the audio data to be played. * @param bufSize Length, in bytes, of the audio data. * @param bufType The audio encoding format for the data as specified * by the SIPX_AUDIO_DATA_FORMAT enumerations. Currently * only RAW_PCM_16 is supported. * @param bRepeat True if the audio is supposed to be played repeatedly * @param bLocal True if the audio is to be rendered locally. * @param bRemote True if the audio is to be rendered by the remote endpoint. */ SIPXTAPI_API SIPX_RESULT sipxCallPlayBufferStart(const SIPX_CALL hCall, const char* szBuffer, const int bufSize, const int bufType, const bool bRepeat, const bool bLocal, const bool bRemote) ; /** * Stop playing the audio started with sipxCallPlayBufferStart * If a sipxCallDestroy is attempted while an audio buffer is playing, * sipxCallDestroy will fail with a SIPX_RESULT_BUSY return code. * Call sipxCallPlayBufferStop before making the call to * sipxCallDestroy. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. Audio can only be played and stopped * in the context of a call. */ SIPXTAPI_API SIPX_RESULT sipxCallPlayBufferStop(const SIPX_CALL hCall) ; /** * Set the address and port to which the given media stream is to be recieved. * This is generally used when a separate process is to recieve the media stream. * @param hCall - call handle for the RTP stream * @param mediaType - audio or video * @param mediaTypeStreamIndex - connection Id * @param streamReceiveAddress - IP address on which RTP stream is to be received * @param rtpPort - RTP port on which to receive stream * @param rtcpPort - RTCP port on which to recieve stream */ SIPXTAPI_API SIPX_RESULT sipxCallSetMediaPassThrough(const SIPX_CALL hCall, MEDIA_TYPE mediaType, int mediaTypeStreamIndex, const char* streamReceiveAddress, int rtpPort, int rtcpPort); /** * Subscribe for NOTIFY events which may be published by the other end-point * of the call. This API differs from sipxConfigSubscribe in that it allows * you to use the contact address from the remote party as the subscription * target (see the bRemoteContactIsGruu parameter). * * sipXtapi will automatically refresh subscriptions until sipxCallUnsubscribe * is called. Please make sure you call sipxCallUnsubscribe before tearing * down your call. * * @param hCall The call handle of the call associated with the subscription. * @param szEventType A string representing the type of event that can be * published. This string is used to populate the "Event" header in * the SIP SUBSCRIBE request. For example, if checking voicemail * status, your would use "message-summary". * @param szAcceptType A string representing the types of NOTIFY events that * this client will accept. This string is used to populate the * "Accept" header in the SIP SUBSCRIBE request. For example, if * checking voicemail status, you would use * "application/simple-message-summary" * @param phSub Pointer to a subscription handle whose value is set by this * function. This handle allows you to cancel the subscription and * differentiate between NOTIFY events. * @param bRemoteContactIsGruu indicates whether the Contact for the remote * side of the call can be assumed to be a Globally Routable Unique URI * (GRUU). Normally one cannot assume that a contact is a GRUU and the * To or From address for the remote side is assumed to be an Address Of * Record (AOR) that is globally routable. */ SIPXTAPI_API SIPX_RESULT sipxCallSubscribe(const SIPX_CALL hCall, const char* szEventType, const char* szAcceptType, SIPX_SUB* phSub, bool bRemoteContactIsGruu = false); /** * Unsubscribe from previously subscribed NOTIFY events. This method will * send another subscription request with an expires time of 0 (zero) to end * your subscription. * * @param hSub The subscription handle obtained from the call to * sipxCallSubscribe. */ SIPXTAPI_API SIPX_RESULT sipxCallUnsubscribe(const SIPX_SUB hSub) ; /** * Sends an INFO event to the specified call. * * This method will fail with an SIPX_RESULT_INVALID_STATE return code * if an existing INFO message transaction is still outstanding (sipXtapi * has not received a final response to the initial request). * * @param phInfo Pointer to an INFO message handle, whose value is set by * this method. * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szContentType String representation of the INFO content type * @param szContent Pointer to the INFO messasge's content * @param nContentLength Size of the INFO content */ SIPXTAPI_API SIPX_RESULT sipxCallSendInfo(SIPX_INFO* phInfo, const SIPX_CALL hCall, const char* szContentType, const char* szContent, const size_t nContentLength); /** * Blind transfer the specified call to another party. Monitor the * TRANSFER state events for details on the transfer attempt. If the * call is not already on hold, the party will be placed on hold. * * Assuming that all parties are using sipXtapi, all of the calls * are active (not held), and the transfer works, you should expect the * following event sequence: * *

Transferee (party being transfered):

* * The transferee's original call will be placed on remote hold from the * transfer controller and will then put itself on full hold before starting * the transfer. The transfer is implemented as a new call -- this allows * the developer to reclaim the original call if the transfer fails. The * NEWCALL event will include a cause for of CALLSTATE_CAUSE_TRANSFER and * the hAssociatedCall member of the SIPX_CALLSTATE_INFO structure will * include the handle of the original call. * *
 * Original Call: MEDIA_LOCAL_STOP
 * Original Call: MEDIA_REMOTE_STOP
 * Original Call: CALLSTATE_REMOTE_HELD
 * Original Call: CALLSTATE_HELD
 *
 * New Call: CALLSTATE_NEWCALL
 * New Call: CALLSTATE_REMOTE_OFFERING
 * New Call: CALLSTATE_REMOTE_ALERTING
 * New Call: CALLSTATE_CONNECTED
 * New Call: MEDIA_LOCAL_START
 * New Call: MEDIA_REMOTE_START
 * 
* * After the transfer completes, the application developer must destroy * the original call using sipxCallDestroy. If the new call fails for * any reason, the application layer should resume the original call by * taking it off hold. * *

Transfer Controller (this user agent):

* * The transfer controller will automatically take the call out of * focus and place it on hold. Afterwards, the transfer controller * will receive CALLSTATE_TRANSFER_EVENTs indicating the status of * the transfer. * *
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_CAUSE_TRANSFER_INITIATED
 * Source Call: CALLSTATE_BRIDGED
 * Source Call: CALLSTATE_HELD
 * Source Call: MEDIA_CAUSE_HOLD
 * Source Call: MEDIA_CAUSE_HOLD
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_CAUSE_TRANSFER_ACCEPTED
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_CAUSE_TRANSFER_RINGING
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_CAUSE_TRANSFER_SUCCESS
 * Source Call: CALLSTATE_DISCONNECTED
 * 
* * Upon success, the call will automatically be disconnected, however, * the application layer needs to call sipXcallDestroy to free the handle * and call processing resources. * *

Transfer Target (identified by szAddress):

* * The transferee will go through the normal event progression for an incoming * call: * *
 * New Call: CALLSTATE_NEWCALL
 * New Call: CALLSTATE_OFFERING
 * New Call: CALLSTATE_ALERTING
 * New Call: CALLSTATE_CONNECTED
 * 
* * If the transfer target rejects the call or fails to answer, the transfer * will fail. * * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param szAddress SIP url identifing the transfer target (who the call * identified by hCall will be transfered to). * * @see SIPX_CALLSTATE_EVENT * @see SIPX_CALLSTATE_CAUSE */ SIPXTAPI_API SIPX_RESULT sipxCallBlindTransfer(const SIPX_CALL hCall, const char* szAddress) ; /** * Transfer the source call to the target call. This method can be used * to implement consultative transfer (transfer initiator can speak with * the transfer target prior to transferring). If you wish to consult * privately, create a new call to the transfer target. If you wish * consult and allow the source (transferee) to participant in the * conversation, create a conference and then transfer one leg to * another. * * If not already on hold, the transferee (hSourceCall) is placed on * hold as part of the transfer operation. * * The event sequence may differ slightly depending on whether the calls * are part of a conference (attended transfer) or individual calls (semi- * attended transfer). * * Assuming the calls are part of a conference and not on hold, the event * sequences are as follows: * *

Transfer Controller (this user agent):

* *
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_CAUSE_TRANSFER_INITIATED
 * Source Call: CALLSTATE_REMOTE_HELD
 * Source Call: MEDIA_LOCAL_STOP
 * Source Call: MEDIA_REMOTE_STOP
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_CAUSE_TRANSFER_ACCEPTED
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_CAUSE_TRANSFER_SUCCESS
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_DISCONNECTED
 * Source Call: CALLSTATE_TRANSFER_EVENT::CALLSTATE_DESTROYED
 * 
* * The source call will automatically be disconnected if the transfer is * successful. Also, if the source call is part of a conference, the call * will automatically be destroyed. If not part of a conference, the * application must destroy the call using sipxCallDestroy. * *
 * Target Call: CALLSTATE_REMOTE_HELD
 * Target Call: MEDIA_LOCAL_STOP
 * Target Call: MEDIA_REMOTE_STOP
 * Target Call: CALLSTATE_DISCONNECTED
 * Target Call: CALLSTATE_DESTROYED
 * 
* * The target call is remote held as part of the transfer operation. If the * target call is part of a conference, it will automatically be destroyed. * Otherwise, the application layer is responsible for calling * sipxCallDestroy. * *

Transferee (user agent on other side of hSourceCall):

* * The transferee will create a new call to the transfer target and * automatically disconnect the original call upon success. The new call * will be created with a cause of CALLSTATE_CAUSE_TRANSFER in the * SIPX_CALLSTATE_INFO event data. The application layer can look at * the hAssociatedCall member to connect the new call to the original * call. * *
 * Original Call: MEDIA_LOCAL_STOP
 * Original Call: MEDIA_REMOTE_STOP
 * Original Call: CALLSTATE_REMOTE_HELD
 * Original Call: CALLSTATE_HELD
 * Original Call: CALLSTATE_DISCONNECTED
 *
 * New Call: CALLSTATE_NEWCALL::CALLSTATE_CAUSE_TRANSFER
 * New Call: CALLSTATE_REMOTE_OFFERING
 * New Call: CALLSTATE_CONNECTED
 * New Call: MEDIA_LOCAL_START
 * New Call: MEDIA_REMOTE_START
 * 
* * The application is responsible for calling sipxCallDestroy on the original * call after the CALLSTATE_DISCONNECT event. * *

Transfer Target (user agent on other side of hTargetCall):

* * The transfer target will automatically receive and answer the inbound call * from the transferee. After this completes, the original call is * disconnected. * *
 * CALLSTATE_NEWCALL::CALLSTATE_CAUSE_TRANSFERRED
 * CALLSTATE_CONNECTED
 * MEDIA_LOCAL_START
 * MEDIA_REMOTE_START
 * 
* * Please note that no offering event was fired. The target does not have * the option to accept or reject the call. If this call was part of a * conference, the new call is automatically added to the same conference. * * @param hSourceCall Handle to the source call (transferee). * @param hTargetCall Handle to the target call (transfer target). * * @see SIPX_CALLSTATE_EVENT * @see SIPX_CALLSTATE_CAUSE */ SIPXTAPI_API SIPX_RESULT sipxCallTransfer(const SIPX_CALL hSourceCall, const SIPX_CALL hTargetCall) ; /** * Updates the Video window with a new frame buffer. Should be called * when the window receives a PAINT message. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param hWnd Window handle of the video preview window. */ SIPXTAPI_API SIPX_RESULT sipxCallUpdateVideoWindow(const SIPX_CALL hCall, const SIPX_WINDOW_HANDLE hWnd); /** * Resizes the video window. Should be called when the window receives a SIZE message. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param hWnd Window handle of the video window. */ SIPXTAPI_API SIPX_RESULT sipxCallResizeWindow(const SIPX_CALL hCall, const SIPX_WINDOW_HANDLE hWnd); /** * Gets energy levels for a call. The call must be in the connected state * for this request to succeed. * * This API is only supported when sipXtapi is bundled with VoiceEngine from * GIPS. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param iInputEnergyLevel Input/Microphone energy level ranging from 0 to 9. * @param iOutputEnergyLevel Output/Speaker energy level ranging from 0 to 9. * The output energy level is pre-mixed (before mixing any files/tones or * other parties). sipxConferenceGetEnergyLevels provides an API to * obtain post-mixed energy levels. * @param nMaxContributors Max number of contributors/energy levels. * Contributors are derived by looking at the contributing RTP source * IDs from the RTP stream. * @param CCSRCs Array of contributing source ids. This array will be filled * in up to a max of nMaxContributors. See nActualContributors for * the actual number of elements returned. * @param iEnergyLevels Energy level for each contributing source id ranging * from 0 to 9. This array in up to a max of nMaxContributors. See * nActualContributors for the actual number of elements returned. * @param nActualContributors The actual number of contributing source ids and * energy levels returned. */ SIPXTAPI_API SIPX_RESULT sipxCallGetEnergyLevels(const SIPX_CALL hCall, int& iInputEnergyLevel, int& iOutputEnergyLevel, const size_t nMaxContributors, unsigned int CCSRCs[], int iEnergyLevels[], size_t& nActualContributors) ; /** * Gets the sending and receiving Audio RTP SSRC IDs. The SSRC ID is used to * identify the RTP/audio stream. The call must be in the connected state * for this request to succeed. * * This API is only supported when sipXtapi is bundled with VoiceEngine from * GIPS. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param iSendSSRC The RTP SSRC used when sending audio * @param iReceiveSSRC The RTP SSRC used by the remote party to sending audio */ SIPXTAPI_API SIPX_RESULT sipxCallGetAudioRtpSourceIds(const SIPX_CALL hCall, unsigned int& iSendSSRC, unsigned int& iReceiveSSRC) ; /** * Obtain RTCP stats for the specified call. * * This API is only supported when sipXtapi is bundled with VoiceEngine from * GIPS. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * * @param pStats Structure to place call stats, the structure's cbSize * member must be filled out prior to calling this API. For example: * myStats.cbSize = sizeof(SIPX_RTCP_STATS); */ SIPXTAPI_API SIPX_RESULT sipxCallGetAudioRtcpStats(const SIPX_CALL hCall, SIPX_RTCP_STATS* pStats) ; /** * Restrict the set of codecs that are allowed to be used for the given call. * This method does not force signalling to occur. Codecs must be restricted before * the offer or answer SDP is sent from this side. * * @param hCall - call handle for call on which to restrict codec set * @param codecNames - space delimited list of codec names. * Note: codecNames MUST be a subset of the codecs enabled via sipxConfigSetAudioCodecByName * TELEPHONE-EVENT is implicitly included */ SIPXTAPI_API SIPX_RESULT sipxCallLimitCodecs(const SIPX_CALL hCall, const char* codecNames); /** * Limits the codec preferences on a per-call basis. This API will force a * codec renegotiation with the specified call regardless if the codecs * changed. A renegotiation includes sending a new INVITE with an updated SDP * list. Local audio will be stopped and restarted during this process, * however, hold events are not sent to the application. * * NOTE: If a call is on remote hold, it will be taken off remote hold. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param audioBandwidth A bandwidth id to limit audio codecs. Pass in * AUDIO_CODEC_BW_DEFAULT to leave audio codecs unchanged. * @param videoBandwidth A bandwidth id to limit video bitrate and framerate. * (see sipxConfigSetVideoBandwidth for an explanation on how * bandwidth ids affect bitrate and framerate). Pass in AUDIO_CODEC_BW_DEFAULT * to leave these parameters unchanged. * @param szVideoCodecName Codec name that limits the supported video codecs * to this one video codec. * * @see sipxConfigSetVideoBandwidth */ SIPXTAPI_API SIPX_RESULT sipxCallLimitCodecPreferences(const SIPX_CALL hCall, const SIPX_AUDIO_BANDWIDTH_ID audioBandwidth, const SIPX_VIDEO_BANDWIDTH_ID videoBandwidth, const char* szVideoCodecName); /** * Sets the gain of the microphone for a given call. This gain is applied * digitally inside of the media engine. * * @note Right now this is implemented for sipXmediaLib with Topology enabled * only. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param gain Floating point gain to apply. Gain should be >0. Internally, * inside of a media engine, it may be represented as fixed point value. */ SIPXTAPI_API SIPX_RESULT sipxCallSetMicGain(const SIPX_CALL hCall, float gain); /** * Sets the gain for all inputs to the given bridge output, except for * the input of the same index which is set to 0.0f gain. * @param hCall - handle to call using the bridge mixer. * @param bridgeOutputIndex - output index on the bridge whose input * gains are to be set. * @param gain - new gain value to set for inputs. */ SIPXTAPI_API SIPX_RESULT sipxCallSetMixOutputGain(const SIPX_CALL hCall, int bridgeOutputIndex, float gain); //@} /** @name Publishing Methods */ //@{ /** * Creates a publishing context, which performs the processing necessary * to accept SUBSCRIBE requests, and to publish NOTIFY messages to subscribers. * The resource may be specific to a single call, conference or global * to this user agent. The naming of the resource ID determines the scope. * * @param hInst Instance pointer obtained by sipxInitialize. * @param phPub Pointer to a publisher handle - this method modifies the value * to refer to the newly created publishing context. * @param szResourceId The resourceId to the state information being * published. This must match the request URI of the incoming * SUBSCRIBE request (only the user ID, host and port are significant * in matching the request URI). Examples: fred\@10.0.0.1:5555, * sip:conference1\@192.160.0.1, sip:kate\@example.com * @param szEventType A string representing the type of event that can be * published. * @param szContentType String representation of the content type being * published. * @param pContent Pointer to the NOTIFY message's body content. * @param nContentLength Size of the content to be published. * * @return If the resource already has a a publisher created for the given * event type, SIPX_RESULT_INVALID_ARGS is returned. */ SIPXTAPI_API SIPX_RESULT sipxPublisherCreate(const SIPX_INST hInst, SIPX_PUB* phPub, const char* szResourceId, const char* szEventType, const char* szContentType, const char* pContent, const size_t nContentLength); /** * Tears down the publishing context. Any existing subscriptions * are sent a final NOTIFY request. If pFinalContent is not NULL and * nContentLength > 0 the given publish state is given otherwise * the final NOTIFY requests are sent with no body or state. * * @param hPub Handle of the publishing context to destroy * (returned from a call to sipxCreatePublisher) * @param szContentType String representation of the content type being * published * @param pFinalContent Pointer to the NOTIFY message's body content * @param nContentLength Size of the content to be published */ SIPXTAPI_API SIPX_RESULT sipxPublisherDestroy(const SIPX_PUB hPub, const char* szContentType, const char* pFinalContent, const size_t nContentLength); /** * Publishes an updated state to specific event via NOTIFY to its subscribers. * * @param hPub Handle of the publishing context * (returned from a call to sipxCreatePublisher) * @param szContentType String representation of the content type being * published * @param pContent Pointer to the NOTIFY message's body content * @param nContentLength Size of the content to be published */ SIPXTAPI_API SIPX_RESULT sipxPublisherUpdate(const SIPX_PUB hPub, const char* szContentType, const char* pContent, const size_t nContentLength); //@} /** @name Conference Methods */ //@{ /** * Create a conference handle. Conferences are an association of calls * where the audio media is mixed. sipXtapi supports conferences up to * 4 (CONF_MAX_CONNECTIONS) parties in its default configuration. * * @param hInst Instance pointer obtained by sipxInitialize. * @param phConference Pointer to a conference handle. Upon success, * this value is replaced with a valid conference handle. * Success is determined by the SIPX_RESULT result code. */ SIPXTAPI_API SIPX_RESULT sipxConferenceCreate(const SIPX_INST hInst, SIPX_CONF* phConference) ; /** * Join (add) an existing held call into a conference. * * An existing call can be added to a virgin conference without restriction. * Additional calls, must be connected and on remote hold for this operation * to succeed. A remote hold can be accomplished by calling sipxCallHold on * the joining party. The application layer must wait for the * CALLSTATE_HELD event prior to calling join. No events * are fired as part of the operation and the newly joined call is left on * hold. The application layer should call sipxCallUnhold on the new * participant to finalize the join. * * @param hConf Conference handle obtained by calling sipxConferenceCreate. * @param hCall Call handle of the call to join into the conference. */ SIPXTAPI_API SIPX_RESULT sipxConferenceJoin(const SIPX_CONF hConf, const SIPX_CALL hCall) ; /** * Split (remove) a held call from a conference. This method will remove * the specified call from the conference. * * The call must be connected and on remote hold for this operation to * succeed. A remote hold can be accomplished by calling sipxCallHold on * the conference participant or by placing the entire conference on hold * with bridging disabled. The application layer must wait for the * CALLSTATE_HELD event prior to calling split. No events * are fired as part of the operation and the split call is left on hold. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. * @param hCall Call handle of the call that should be removed from the * the conference. */ SIPXTAPI_API SIPX_RESULT sipxConferenceSplit(const SIPX_CONF hConf, const SIPX_CALL hCall) ; /** * Add a new party to an existing conference. A connection is automatically * initiated for the specified address. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. * @param hLine Line Identity for the outbound call. The line identity * helps defines the "From" caller-id. The line identity can't be * SIPX_LIINE_NULL, as it's an outbound call. * @param szAddress SIP URL of the conference participant to add * @param phNewCall Pointer to a call handle to store new call. * @param contactId Id of the desired contact record to use for this call. * The id refers to a Contact Record obtained by a call to * sipxConfigGetLocalContacts. The application can choose a * contact record of type LOCAL, NAT_MAPPED, CONFIG, or RELAY. * The Contact Type allows you to control whether the * user agent and media processing advertises the local address * (e.g. LOCAL contact of 10.1.1.x or * 192.168.x.x), the NAT-derived address to the target party, * or, local contact addresses of other types. * @param pDisplay Pointer to an object describing the display object for * rendering remote video. * @param pSecurity Pointer to an object describing the security attributes * for the call. * @param bTakeFocus Should SIPxua place the newly answered call in focus * (engage local microphone and speaker). In some cases, application * developer may want to answer the call in the background and play * audio while the user finishes up with their active (in focus) call. * @param options Pointer to a SIPX_CALL_OPTIONS structure. * * @see sipxConferenceCreate * @see sipxConfigSetLocationHeader * @see sipxConfigGetLocalContacts * @see sipxConfigSetAudioCodecPreferences */ SIPXTAPI_API SIPX_RESULT sipxConferenceAdd(const SIPX_CONF hConf, const SIPX_LINE hLine, const char* szAddress, SIPX_CALL* phNewCall, SIPX_CONTACT_ID contactId = 0, SIPX_VIDEO_DISPLAY* const pDisplay = NULL, SIPX_SECURITY_ATTRIBUTES* const pSecurity = NULL, bool bTakeFocus = true, SIPX_CALL_OPTIONS* options = NULL); /** * Removes a participant from conference by hanging up on them. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. * @param hCall Call handle identifying which call to remove from the * conference by hanging up. */ SIPXTAPI_API SIPX_RESULT sipxConferenceRemove(const SIPX_CONF hConf, const SIPX_CALL hCall) ; /** * Gets all of the calls participating in a conference. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. * @param calls An array of call handles filled in by the API. * @param iMax The maximum number of call handles to return. * @param nActual The actual number of call handles returned. */ SIPXTAPI_API SIPX_RESULT sipxConferenceGetCalls(const SIPX_CONF hConf, SIPX_CALL calls[], const size_t iMax, size_t& nActual) ; /** * Places a conference on hold. This API can be used to place a * conference on local hold (continue to bridge participants) or full hold * (remaining participants cannot talk to each other). The default is * local hold/bridged. The bBridged flag can be used to change this * behavior (false for full hold). * * Developers may also hold/unhold individual conference participants by * calling sipxCallHold and sipxCallUnhold on individual call handles. The * sipxConferenceGetCalls API can be used to enumerate conference * participants. * * @see sipxCallHold for a description of the expected * events. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. * @param bBridging true for a bridging conference hold, * false for a non-bridging conference hold. */ SIPXTAPI_API SIPX_RESULT sipxConferenceHold(const SIPX_CONF hConf, bool bBridging = true); /** * Removes conference members from a held state. This method will take a call * off either local or remote/full hold. * * @see sipxConferenceHold for details on holding * conferences. * @see sipxCallHold for a description of the expected * events. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. */ SIPXTAPI_API SIPX_RESULT sipxConferenceUnhold(const SIPX_CONF hConf); /** * Play the designated audio file to all conference participants and/or the * local speaker. The file may be a raw 16 bit signed PCM at 8000 * samples/sec, mono, little endian or a .WAV file. * If a sipxConferenceDestroy is attempted while an audio file is playing, * sipxConferenceDestroy will fail with a SIPX_RESULT_BUSY return code. * Call sipxConferencePlayAudioFileStop before making the call to * sipxConferenceDestroy. * * * @param hConf Conference handle obtained by calling sipxConferenceCreate. * @param szFile Filename for the audio file to be played. * @param bRepeat True if the file is supposed to be played repeatedly * @param bLocal True if the audio file is to be rendered locally. * @param bRemote True if the audio file is to be rendered by the remote * endpoint. * @param bMixWithMicrophone True to mix the audio with the microphone * data or false to replace it. This option is only supported * when sipXtapi is bundled with GIPS VoiceEngine. * @param fVolumeScaling Volume down scaling for the audio file. Valid * values are between 0 and 1.0, where 1.0 is the no down-scaling. * This option is only supported when sipXtapi is bundled with GIPS * VoiceEngine. */ SIPXTAPI_API SIPX_RESULT sipxConferencePlayAudioFileStart(const SIPX_CONF hConf, const char* szFile, const bool bRepeat, const bool bLocal, const bool bRemote, const bool bMixWithMicrophone = false, const float fVolumeScaling = 1.0) ; /* * Stop playing a file started with sipxConferencePlayAudioFileStart * If a sipxConferenceDestroy is attempted while an audio file is playing, * sipxConferenceDestroy will fail with a SIPX_RESULT_BUSY return code. * Call sipxConferencePlayAudioFileStop before making the call to * sipxConferenceDestroy. * * @param hConf Conference handle obtained by calling sipxConferenceCreate. */ SIPXTAPI_API SIPX_RESULT sipxConferencePlayAudioFileStop(const SIPX_CONF hConf) ; /** * Destroys a conference. All participants within a conference are * dropped. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. */ SIPXTAPI_API SIPX_RESULT sipxConferenceDestroy(SIPX_CONF hConf) ; /** * Gets energy levels for a conference. The conference must be in the * connected state (not held or bridged) for this request to succeed. * * This API is only supported when sipXtapi is bundled with VoiceEngine from * GIPS. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. * @param iInputEnergyLevel Input/Microphone energy level ranging from 0 to 9. * @param iOutputEnergyLevel Output/Speaker energy level ranging from 0 to 9. * The output energy level is post-mixed (after mixing all files/tones * and other parties. sipxCallGetEnergyLevel provides an API to obtain * pre-mixed energy levels. */ SIPXTAPI_API SIPX_RESULT sipxConferenceGetEnergyLevels(const SIPX_CONF hConf, int& iInputEnergyLevel, int& iOutputEnergyLevel) ; /** * Limits the codec preferences on a conference. This API will force a * codec renegotiation with the specified calls regardless if the codecs * changed. A renegotiation includes sending a new INVITE with an updated SDP * list. Local audio will be stopped and restarted during this process, * however, hold events are not sent to the application. * * NOTE: If any calls are on remote hold, they will be taken off hold. * * @param hConf Handle to a conference. Conference handles are obtained * by invoking sipxConferenceCreate. * @param audioBandwidth A bandwidth id to limit audio codecs. Pass in * AUDIO_CODEC_BW_DEFAULT to leave audio codecs unchanged. * @param videoBandwidth A bandwidth id to limit video bitrate and framerate. * (see sipxConfigSetVideoBandwidth for an explanation on how * bandwidth ids affect bitrate and framerate). Pass in AUDIO_CODEC_BW_DEFAULT * to leave these parameters unchanged. * @param szVideoCodecName Codec name that limits the supported video codecs * to this one video codec. * * @see sipxConfigSetVideoBandwidth */ SIPXTAPI_API SIPX_RESULT sipxConferenceLimitCodecPreferences(const SIPX_CONF hConf, const SIPX_AUDIO_BANDWIDTH_ID audioBandwidth, const SIPX_VIDEO_BANDWIDTH_ID videoBandwidth, const char* szVideoCodecName) ; /** * Create a new media connetion that is indpendent of any existing call legs in the conference. * This media connection is for independent control independent of SIP call control. * RTP streams may be stopped and started manually via the sipXtapi methods: * sipxConferenceRtpSetDestination * sipxConferenceRtpStartSend * sipxConferenceRtpStopSend * * @param[in] hConf - conference handle indicating which media interface in which the new * media connection is to be created. * @param[out] connectionId - handle/id for the media connection created. */ SIPXTAPI_API SIPX_RESULT sipxMediaConnectionCreate(const SIPX_CONF hConf, int& connectionId); /** * Set the destination to which RTP streams are to be sent. * * @param[in] hConf - conference handle indicating which media interface the connection * belongs. * @param[in] connectionId - handle/id for media connection * @param[in] mediaType - media stream type (e.g. VIDEO_MEDIA, AUDIO_MEDIA) * @param[in] mediaTypeStreamIndex - index to which stream for the given type of media * for now limited to 1 stream (i.e. index = 0) * @param[in] streamSendAddress - remote IP address to send RTP to * @param[in] rtpPort - port at remote address to send RTP stream to * @param[in] rtcpPort - port at remote address to send RTCP stream to */ SIPXTAPI_API SIPX_RESULT sipxMediaConnectionRtpSetDestination(const SIPX_CONF hConf, int connectionId, MEDIA_TYPE mediaType, int mediaTypeStreamIndex, const char* streamSendAddress, int rtpPort, int rtcpPort); /** * Start sending the RTP/RTCP stream * @param[in] hConf - conference handle indicating which media interface the connection * belongs. * @param[in] connectionId - handle/id for media connection * @param[in] numTokens - number of codec tokens in codecTokens array * @param[in] codecTokens - array of codec names * @param[in] payloadIds - payload ID to use for corresponding codec in codecTokens array * */ SIPXTAPI_API SIPX_RESULT sipxMediaConnectionRtpStartSend(const SIPX_CONF hConf, int connectionId, int numTokens, const char* codecTokens[], int payloadIds[]); /** * Stop sending RTP/RTCP * @param[in] hConf - conference handle indicating which media interface the connection * belongs. * @param[in] connectionId - handle/id for media connection */ SIPXTAPI_API SIPX_RESULT sipxMediaConnectionRtpStopSend(const SIPX_CONF hConf, int connectionId); //@} /** @name Audio Methods */ //@{ /** * Set the local microphone gain. If the microphone is muted, * resetting the gain will not enable audio -- you must unmute * the microphone. * * @param hInst Instance pointer obtained by sipxInitialize. * @param iLevel The level of the local microphone gain */ SIPXTAPI_API SIPX_RESULT sipxAudioSetGain(const SIPX_INST hInst, const int iLevel) ; /** * Get the current microphone gain. * * @param hInst Instance pointer obtained by sipxInitialize. * @param iLevel The level of the gain of the microphone */ SIPXTAPI_API SIPX_RESULT sipxAudioGetGain(const SIPX_INST hInst, int& iLevel) ; /** * Mute or unmute the microphone. * * @param hInst Instance pointer obtained by sipxInitialize. * @param bMute True if the microphone is to be muted and false if it * is not to be muted */ SIPXTAPI_API SIPX_RESULT sipxAudioMute(const SIPX_INST hInst, const bool bMute) ; /** * Gets the mute state of the microphone. * * @param hInst Instance pointer obtained by sipxInitialize. * @param bMuted True if the microphone has been muted and false if it * is not mute */ SIPXTAPI_API SIPX_RESULT sipxAudioIsMuted(const SIPX_INST hInst, bool &bMuted) ; /** * Enables one of the speaker outputs. * * @param hInst Instance pointer obtained by sipxInitialize. * @param type The type of the speaker either the logical ringer * (used to alert user of in inbound call) or speaker * (in call audio device). */ SIPXTAPI_API SIPX_RESULT sipxAudioEnableSpeaker(const SIPX_INST hInst, const SPEAKER_TYPE type) ; /** * Gets the enabled speaker selection. * * @param hInst Instance pointer obtained by sipxInitialize. * @param type The type of the speaker either the logical ringer * (used to alert user of in inbound call) or speaker * (in call audio device). */ SIPXTAPI_API SIPX_RESULT sipxAudioGetEnabledSpeaker(const SIPX_INST hInst, SPEAKER_TYPE& type) ; /** * Sets the audio level for the designated speaker type. If the speaker type * is enabled, the change it audio will be heard instantly. * * @param hInst Instance pointer obtained by sipxInitialize. * @param type The type of the speaker either the logical ringer * (used to alert user of in inbound call) or speaker * (in call audio device). * @param iLevel The level of the gain of the microphone */ SIPXTAPI_API SIPX_RESULT sipxAudioSetVolume(const SIPX_INST hInst, const SPEAKER_TYPE type, const int iLevel) ; /** * Gets the audio level for the designated speaker type * * @param hInst Instance pointer obtained by sipxInitialize. * @param type The type of the speaker either the logical ringer * (used to alert user of in inbound call) or speaker * (in call audio device). * @param iLevel The level of the gain of the microphone */ SIPXTAPI_API SIPX_RESULT sipxAudioGetVolume(const SIPX_INST hInst, const SPEAKER_TYPE type, int& iLevel) ; /** * Enables or disables Acoustic Echo Cancellation (AEC). By default, sipXtapi * assumes SIPX_AEC_CANCEL_AUTO. Change this parameter will modify the policy * for both existing and new calls. * * Note: This API is only supported when bundled with VoiceEngine from * Global IP Sound or Speex library. * * @param hInst Instance pointer obtained by sipxInitialize. * @param mode AEC mode. * * @see SIPX_AEC_MODE */ SIPXTAPI_API SIPX_RESULT sipxAudioSetAECMode(const SIPX_INST hInst, const SIPX_AEC_MODE mode) ; /** * Get the mode of Acoustic Echo Cancellation (AEC). * * Note: This API is only supported when bundled with VoiceEngine from * Global IP Sound or Speex library. * * @param hInst Instance pointer obtained by sipxInitialize. * @param mode AEC mode. * * @see SIPX_AEC_MODE */ SIPXTAPI_API SIPX_RESULT sipxAudioGetAECMode(const SIPX_INST hInst, SIPX_AEC_MODE& mode) ; /** * Enable/Disable Automatic Gain Control (AGC). By default, AGC is disabled. * * Note: This API is only supported when bundled with VoiceEngine from * Global IP Sound or Speex library. * * @param hInst Instance pointer obtained by sipxInitialize. * @param bEnable true to enable AGC or false to disable */ SIPXTAPI_API SIPX_RESULT sipxAudioSetAGCMode(const SIPX_INST hInst, const bool bEnable) ; /** * Get the enable/disable state of Automatic Gain Control (AGC). * Note: This API is only supported when bundled with VoiceEngine from * Global IP Sound or Speex library. * * @param hInst Instance pointer obtained by sipxInitialize. * @param bEnabled true if AGC is enabled; otherwise false. */ SIPXTAPI_API SIPX_RESULT sipxAudioGetAGCMode(const SIPX_INST hInst, bool& bEnabled) ; /** * Set the noise reduction mode/policy for suppressing background noise. By * default sipXtapi assumes SIPX_NOISE_REDUCTION_LOW. Change this parameter * will modify the policy for both existing and new calls. * * Note: This API is only supported when bundled with VoiceEngine from * Global IP Sound or Speex library. * * @param hInst Instance pointer obtained by sipxInitialize. * @param mode noise reduction mode. * * @see SIPX_NOISE_REDUCTION_MODE */ SIPXTAPI_API SIPX_RESULT sipxAudioSetNoiseReductionMode(const SIPX_INST hInst, const SIPX_NOISE_REDUCTION_MODE mode) ; /** * Get the mode/policy for Noise Reduction (NR). * * Note: This API is only supported when bundled with VoiceEngine from * Global IP Sound or Speex library. * * @param hInst Instance pointer obtained by sipxInitialize. * @param mode noise reduction mode. * * @see SIPX_NOISE_REDUCTION_MODE */ SIPXTAPI_API SIPX_RESULT sipxAudioGetNoiseReductionMode(const SIPX_INST hInst, SIPX_NOISE_REDUCTION_MODE& mode) ; /** * Get the number of input devices available on this system. * * @param hInst Instance pointer obtained by sipxInitialize. * @param numDevices The number of input devices available * on this system. */ SIPXTAPI_API SIPX_RESULT sipxAudioGetNumInputDevices(const SIPX_INST hInst, size_t& numDevices) ; /** * Get the name/identifier for input device at position index * * @param hInst Instance pointer obtained by sipxInitialize. * @param index Zero based index of the input device to be queried. * @param szDevice Reference an character string pointer to receive * the device name. */ SIPXTAPI_API SIPX_RESULT sipxAudioGetInputDevice(const SIPX_INST hInst, const int index, const char*& szDevice) ; /** * Get the number of output devices available on this system * @param hInst Instance pointer obtained by sipxInitialize. * @param numDevices The number of output devices available * on this system. */ SIPXTAPI_API SIPX_RESULT sipxAudioGetNumOutputDevices(const SIPX_INST hInst, size_t& numDevices) ; /** * Get the name/identifier for output device at position index * * @param hInst Instance pointer obtained by sipxInitialize. * @param index Zero based index of the output device to be queried. * @param szDevice Reference an character string pointer to receive * the device name. */ SIPXTAPI_API SIPX_RESULT sipxAudioGetOutputDevice(const SIPX_INST hInst, const int index, const char*& szDevice) ; /** * Set the call input device (in-call microphone). * * @param hInst Instance pointer obtained by sipxInitialize. * @param szDevice Character string pointer to be set to * a string name of the output device. */ SIPXTAPI_API SIPX_RESULT sipxAudioSetCallInputDevice(const SIPX_INST hInst, const char* szDevice) ; /** * Set the call ringer/alerting device. * @param hInst Instance pointer obtained by sipxInitialize. * @param szDevice The call ringer/alerting device. */ SIPXTAPI_API SIPX_RESULT sipxAudioSetRingerOutputDevice(const SIPX_INST hInst, const char* szDevice) ; /** * Set the call output device (in-call speaker). * @param hInst Instance pointer obtained by sipxInitialize. * @param szDevice The call output device. */ SIPXTAPI_API SIPX_RESULT sipxAudioSetCallOutputDevice(const SIPX_INST hInst, const char* szDevice) ; //@} /** @name Line / Identity Methods*/ //@{ /** * Adds a line appearance. A line appearance defines your address of record * and is used both as your "From" caller-id and as the public identity to * which you will receive calls for. Directing calls to a particular user * agent is achieved using registrations. * * @param hInst Instance pointer obtained by sipxInitialize. * @param szLineURL The address of record for the line identity. Can be * prepended with a Display Name. * e.g. - "Zaphod Beeblebrox" * @param phLine Pointer to a line handle. Upon success, a handle to the * newly added line is returned. * @param contactId Id of the desired contact record to use for this line. * The id refers to a Contact Record obtained by a call to * sipxConfigGetLocalContacts. The application can choose a * contact record of type LOCAL, NAT_MAPPED, CONFIG, or RELAY. * The Contact Type allows you to control whether the * user agent and media processing advertises the local address * (e.g. LOCAL contact of 10.1.1.x or * 192.168.x.x), the NAT-derived address to the target party, * or, local contact addresses of other types. * * @see sipxConfigGetLocalContacts */ SIPXTAPI_API SIPX_RESULT sipxLineAdd(const SIPX_INST hInst, const char* szLineURL, SIPX_LINE* phLine, SIPX_CONTACT_ID contactId = 0) ; /** * Adds an alias for a line definition. Line aliases are used to map an * inbound call request to an existing line definition. You should only * need to an a alias if your network infrastructure directs calls to this * user agent using multiple identities. For example, if user agent * registers as "sip:bandreasen\@example.com"; however, calls can also be * directed to you via an exention (e.g. sip:122\@example.com). * * If sipXtapi receives a call with an unknown line, you can still answer * and interact wtih the call; however, the line handle will be SIPX_LINE_NULL * in all event callbacks. Adding an aliases allows you to correlate another * line url with your line definition and receive real line handles with event * callbacks. * * Line aliases are not used for outbound calls. * * @see sipxConfigGetLocalContacts */ SIPXTAPI_API SIPX_RESULT sipxLineAddAlias(const SIPX_LINE hLine, const char* szLineURL) ; /** * Registers a line with the proxy server. Registrations will be re-registered * automatically, before they expire. * * Unless your user agent is designated a static IP address or DNS name and * that routing information is provisioned into a SIP server, you should * register the line by calling this function. * * Please unregister your line before calling sipxLineRemove. * * @param hLine Handle to a line appearance. Line handles are obtained by * creating a line using the sipxLineAdd function or by receiving * a line event notification. * @param bRegister true if Registration is desired, otherwise, an Unregister * is performed. */ SIPXTAPI_API SIPX_RESULT sipxLineRegister(const SIPX_LINE hLine, const bool bRegister); /** * Remove the designated line appearance. If the line was previous registered * using the sipxLineRegister API, please unregister the line and wait for the * unregistered event before calling sipxLineRemove. Otherwise, the line will * be removed without unregistering. * * @param hLine Handle to a line appearance. Line handles are obtained by * creating a line using the sipxLineAdd function or by receiving * a line event notification. */ SIPXTAPI_API SIPX_RESULT sipxLineRemove(SIPX_LINE hLine) ; /** * Adds authentication credentials to the designated line appearance. * Credentials are often required by registration services to verify that the * line is being used by the line appearance/address of record owner. * * @param hLine Handle to a line appearance. Line handles are obtained by * creating a line using the sipxLineAdd function or by receiving * a line event notification. * @param szUserID user id used for the line appearance. * @param szPasswd passwd used for the line appearance. * @param szRealm realm for which the user and passwd are valid. Supply * NULL for automatic realm. */ SIPXTAPI_API SIPX_RESULT sipxLineAddCredential(const SIPX_LINE hLine, const char* szUserID, const char* szPasswd, const char* szRealm) ; /** * Gets the active list of line identities. * * @param hInst Instance pointer obtained by sipxInitialize. * @param lines Pre-allocated array of line handles. * @param max Maximum number of lines to return. * @param actual Actual number of valid lines returned. */ SIPXTAPI_API SIPX_RESULT sipxLineGet(const SIPX_INST hInst, SIPX_LINE lines[], const size_t max, size_t& actual) ; /** * Get the Line URI for the designated line handle * * @param hLine Handle to a line appearance. Line handles are obtained by * creating a line using the sipxLineAdd function or by receiving * a line event notification. * @param szBuffer Buffer to place line URL. A NULL value will return * the amount of storage needed in nActual. * @param nBuffer Size of szBuffer in bytes (not to exceed) * @param nActual Actual number of bytes written */ SIPXTAPI_API SIPX_RESULT sipxLineGetURI(const SIPX_LINE hLine, char* szBuffer, const size_t nBuffer, size_t& nActual) ; /** * Get the contact ID for the designated line handle * * @param hLine Handle to a line appearance. Line handles are obtained by * creating a line using the sipxLineAdd function or by receiving * a line event notification. * @param contactId contact Id specified during line creation */ SIPXTAPI_API SIPX_RESULT sipxLineGetContactId(const SIPX_LINE hLine, SIPX_CONTACT_ID& contactId) ; /** * Find a line definition given a URI. * * @param hInst Instance pointer obtained by sipxInitialize. * @param szURI URI used to search for a line definition * @param hLine line handle if successful */ SIPXTAPI_API SIPX_RESULT sipxLineFindByURI(const SIPX_INST hInst, const char* szURI, SIPX_LINE& hLine) ; //@} /** @name Configuration Methods*/ //@{ /** * The sipxConfigEnableLog method enables logging for the sipXtapi API, * media processing, call processing, SIP stack, and OS abstraction layer. * Logging is disabled by default. The underlying framework makes no attempts * to bound the log file to a fixed size. * * Log Format: * time:event id:facility:priority:host name:task name:task id:process id:log message * * @param logLevel Designates the amount of detail includes in the log. See * SIPX_LOG_LEVEL for more details. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetLogLevel(SIPX_LOG_LEVEL logLevel) ; /** * The sipxConfigSetlogFile method sets the filename of the log file and * directs output to that file * * NOTE: At this time no validation is performed on the specified filename. * Please make sure the directories exist and the appropriate permissions * are available. * * @param szFilename The filename for the log file. Designated a NULL * filename will disable logging, however, threads/resources will not * be deallocated. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetLogFile(const char *szFilename) ; /** * Set a callback function to collect logging information. This function * directs logging output to the specified function. * * @param pCallback is a pointer to a callback function. This callback function * gets passed three strings, first string is the priority level, * second string is the source id of the subsystem that generated * the message, and the third string is the message itself. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetLogCallback(sipxLogCallback pCallback); /** * Enables GIPS tracing in sipXtapi (if bundled with sipXtapi). Log entries * are under the facility "VIDEOENGINE" and "VOICEENGINE" and are Base64 * encoded (to avoid issues with binary data. * * NOTE: Tracing must be enabled prior to setting up a call. * * @param hInst Instance pointer obtained by sipxInitialize. * @param bEnable true to enable GIPS tracing or false to disable. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableGIPSTracing(SIPX_INST hInst, bool bEnable) ; /** * Designate a callback routine as a microphone replacement or supplement. * The callback is invoked with microphone data and the data can be reviewed, * modified, replaced, or discarded. * * This callback proc must *NOT* block and must return data quickly. * Additionally, the method should not call any blocking function (i.e. IO * operations, malloc, new, etc). * * Data must be formatted as mono 16-bit signed PCM, little endian, 8000 * samples per second. The callback is handed 80 samples (10ms) of data at * a time. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetMicAudioHook(fnMicAudioHook hookProc) ; /** * Designate a callback routine for post-mixing audio data (e.g. to speaker * data). The hook may review, modify, replace, or discard data. * * This callback proc must *NOT* block and must return data quickly. * Additionally, the method should not call any blocking function (i.e. IO * operations, malloc, new, etc). * * Data must be formatted as mono 16-bit signed PCM, little endian, 8000 * samples per second. The callback is handed 80 samples (10ms) of data at * a time. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetSpkrAudioHook(fnSpkrAudioHook hookProc) ; /* * Set the period of time between stream (e.g. mic, RTP) energy * level notifications. * @ param */ SIPXTAPI_API SIPX_RESULT sipxConfigSetEnergyLevelNotificationPeriod(const SIPX_INST hInst, int periodMs); /** * Sets the User-Agent name to be used with outgoing SIP messages. * * @param hInst Instance pointer obtained by sipxInitialize. * @param szName The user-agent name. * @param bIncludePlatformName Indicates whether or not to append the * platform description onto the user agent name. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetUserAgentName(const SIPX_INST hInst, const char* szName, const bool bIncludePlatformName = true); /** * Defines the SIP proxy used for outbound requests. * * @param hInst Instance pointer obtained by sipxInitialize. * @param szProxy the new outbound proxy */ SIPXTAPI_API SIPX_RESULT sipxConfigSetOutboundProxy(const SIPX_INST hInst, const char* szProxy) ; /** * Modifies the timeout values used for DNS SRV lookups. In generally, * you shouldn't need to modified these, however, if you find yourself * in a situation where a router/network fails to send responses to * DNS SRV requests these values can be tweaked. Note, failing to send * responses is different then a receiving an no-such-animal response. *

* The default values are initialTimeout = 5 seconds, and 4 retries. The * time waited is doubled after each timeout, so with the default settings, * a single DNS SRV can block for 75 seconds (5 + 10 + 20 + 40). In general, * 4 DNS SRV requests are made for each hostname (e.g. domain.com): *

    *
  • _sip._udp.domain.com
  • *
  • _sip._tcp.domain.com
  • *
  • _sip._udp.domain.com.domain.com
  • *
  • _sip._tcp.domain.com.domain.com
  • *
* * If DNS response are dropped in the network (or your DNS server is down), * the API will block for 3 minutes. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetDnsSrvTimeouts(const int initialTimeoutInSecs, const int retries) ; /** * Specifies the time to wait for a REGISTER response before sending a * LINESTATE_REGISTER_FAILED (or LINESTATE_UNREGISTER_FAILED) message. * If not set, the user-agent will use a 4 second timeout. * * @param hInst Instance pointer obtained by sipxInitialize. * @param seconds The number of seconds to wait for a REGISTER response, before it is considered a failure. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetRegisterResponseWaitSeconds(const SIPX_INST hInst, const int seconds); /** * Specifies the time to wait before trying the next DNS SRV record. The user * agent will attempt to obtain DNS SRV resolutions for the child DNS SRV * records. This setting is the time allowed for attempting a lookup - if the * time expires without a lookup, then next child is attempted. * * @param hInst Instance pointer obtained by sipxInitialize. * @param failoverTimeoutInSecs Number of seconds until the next DNS SRV * record is tried. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetDnsSrvFailoverTimeout(const SIPX_INST hInst, const int failoverTimeoutInSecs); /** * Enable or disable the use of "rport". If rport is included on a via, * responses should be sent back to the originating port -- not what is * advertised as part of via. Additionally, the sip stack will not * receive messages sent to the originating port unless this is enabled. * * @param hInst Instance pointer obtained by sipxInitialize. * @param bEnable Enable or disable the use of rport. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableRport(const SIPX_INST hInst, const bool bEnable) ; /** * Enable or diable the use of IP and port provided in the response via (rport) for * mapping of NAT/public IP address and port in the contact database. By default * rport mapping is enabled. * * @param bEnable - true/false if IP address and port provided via rport should be * used for contact database NAT address mapping. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableRportMapping(const SIPX_INST hInst, const bool bEnable); /** * Specifies the expiration period for registration. After setting this * configuration, all subsequent REGISTER messages will be sent with the new * registration period. * * @param hInst Instance pointer obtained by sipxInitialize. * @param nRegisterExpirationSecs Number of seconds until the expiration of a * REGISTER message */ SIPXTAPI_API SIPX_RESULT sipxConfigSetRegisterExpiration(const SIPX_INST hInst, const int nRegisterExpirationSecs); /** * Specifies the expiration period for subscription. After setting this * configuration, all subsequent SUBSCRIBE messages will be sent with the new * subscribe period. * * @param hInst Instance pointer obtained by sipxInitialize. * @param nSubscribeExpirationSecs Number of seconds until the expiration of a * SUBSCRIBE message */ SIPXTAPI_API SIPX_RESULT sipxConfigSetSubscribeExpiration(const SIPX_INST hInst, const int nSubscribeExpirationSecs); /** * Enables STUN (Simple Traversal of UDP through NAT) support for both * UDP SIP signaling and UDP audio/video (RTP). STUN helps user agents * determine thier external IP address from the inside of NAT/Firewall. * This method should be invoked immediately after calling sipxInitialize * and before creating any lines or calls. Enabling STUN while calls are * setup should not effect the media path of existing calls. The "contact" * address uses for UDP signaling may change on the next request. * * TODO :: STUN conforms to IETF RFC/DRAFT XXXX with the following exceptions: * * @param hInst Instance pointer obtained by sipxInitialize * @param szServer The stun server that should be used for discovery. * @param iServerPort The port of the stun server that should be used for * discovery. * @param iKeepAliveInSecs This setting controls how often to refresh the stun * binding. The most aggressive NAT/Firewall solutions free port * mappings after 30 seconds of non-use. We recommend a value of 28 * seconds to be safe. * */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableStun(const SIPX_INST hInst, const char* szServer, int iServerPort, int iKeepAliveInSecs) ; /** * Disable the use of STUN. See sipxConfigEnableStun for details on STUN. * * @param hInst Instance pointer obtained by sipxInitialize. */ SIPXTAPI_API SIPX_RESULT sipxConfigDisableStun(const SIPX_INST hInst) ; /** * Enable TURN for support for UDP audio/video (RTP). TURN allows VoIP * communications while operating behind a symmetric NAT or firewall (cannot * only receive data from the same IP/port that you have sent to). * * This implementation is based on draft-rosenberg-midcom-turn-04. * * @param hInst Instance pointer obtained by sipxInitialize. * @param szServer The TURN server that should be used for relaying. * @param iServerPort The TURN sever port that should be used for relaying * @param szUsername TURN username for authentication * @param szPassword TURN password for authentication * @param iKeepAliveInSecs This setting controls how often to refresh the TURN * binding. The recommended value is 28 seconds. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableTurn(const SIPX_INST hInst, const char* szServer, const int iServerPort, const char* szUsername, const char* szPassword, const int iKeepAliveInSecs) ; /** * Disable the use of TURN. See sipxConfigEnableTurn for details TURN. * * @param hInst Instance pointer obtained by sipxInitialize. */ SIPXTAPI_API SIPX_RESULT sipxConfigDisableTurn(const SIPX_INST hInst) ; /** * Enables an ICE-like mechanism for determining connectivity of remote * parties dynamically. By default, ICE is disabled. * * The current sipXtapi implementation is a bastardization of * draft-ietf-mmusic-ice-04. In subsequent release, this will * conform to draft-ietf-mmusic-ice-05 or the latest draft. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableIce(const SIPX_INST hInst) ; /** * Disable the use of ICE. See sipxConfigEnableICE for details. * * @param hInst Instance pointer obtained by sipxInitialize. */ SIPXTAPI_API SIPX_RESULT sipxConfigDisableIce(const SIPX_INST hInst) ; /** * Add a signaling keep alive to a remote ip address. * * @param hInst Instance pointer obtained by sipxInitialize * @param contactId Contact ID used for the keep alive. sipXtapi will * send keep alives from the interface identified by the * contactId. Specify a contactId of -1 to send keep alives from * all interfaces. * @param type Designates the method of keep alives. * @param remoteIp Remote IP address used to send keep alives. The caller is * responsible for converting hostnames to IP address. * @param remotePort Remote port used to send keep alives. * @param keepAliveSecs The number of seconds to wait before resending. If * the value is <= 0, only one keep alive will be sent (calling * sipxConfigKeepAliveRemove will fail). * * @see sipxConfigGetLocalContacts */ SIPXTAPI_API SIPX_RESULT sipxConfigKeepAliveAdd(const SIPX_INST hInst, SIPX_CONTACT_ID contactId, SIPX_KEEPALIVE_TYPE type, const char* remoteIp, int remotePort, int keepAliveSecs) ; /** * Remove a signaling keepalive. * * @param hInst Instance pointer obtained by sipxInitialize * @param contactId Contact ID used for the keep alive. sipXtapi will * remove keep alives from the interface identified by the * contactId. Specify a contactId of -1 to remove keep alives from * all interfaces. * @param type Designates the method of keep alives. * @param remoteIp Remote IP address used to send keep alives. The caller is * responsible for converting hostnames to IP address. This value must * match what was specified in sipxConfigKeepAliveAdd. * @param remotePort Remote port used to send keep alives. * * @see sipxConfigGetLocalContacts */ SIPXTAPI_API SIPX_RESULT sipxConfigKeepAliveRemove(const SIPX_INST hInst, SIPX_CONTACT_ID contactId, SIPX_KEEPALIVE_TYPE type, const char* remoteIp, int remotePort) ; /** * Enable/disable sending of RFC 2833 DTMF tones. If disabled the tones * will be sent in-band (if in-band DTMF is enabled). RFC 2833 DTMF * is enabled by default. * * Generally, out-of-band DTMF should always be enabled. In-band DTMF * can be distorted and unrecognized by gateways/IVRs/ACDs when using * compressed codecs such as G729. By nature, many compressed codecs * are lossy and cannot regenerate DTMF signals. If you find that you * need to disable out-of-band DTMF (due to duplicate DTMF signals) on * another device, please consider reconfiguring that other device. * * This function is currently not implemented. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnable Enable or disable out-of-band DTMF tones. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableOutOfBandDTMF(const SIPX_INST hInst, const bool bEnable) ; /** * Enable/disable sending of in-band DTMF tones. In-band DTMF * is disabled by default. * * This function is currently not implemented. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnable Enable or disable in-band DTMF tones. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableInBandDTMF(const SIPX_INST hInst, const bool bEnable) ; /** * Enable or disable sending RTCP reports. By default, RTCP is enabled and * sends reports every ~5 seconds. RTCP is enabled by default. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnable Enable or disable sending of RTCP reports. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableRTCP(const SIPX_INST hInst, const bool bEnable) ; /** * Enables/disables sending of DNS SRV request for all sipXtapi instances. * DNS SRV is enabled by default. * * @param bEnable Enable or disable DNS SRV resolution. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableDnsSrv(const bool bEnable); /** * Determines if sending of out-of-band DTMF tones is enabled or disabled. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnable Out-of-band DTMF tones enabled or disabled. */ SIPXTAPI_API SIPX_RESULT sipxConfigIsOutOfBandDTMFEnabled(const SIPX_INST hInst, bool& bEnable) ; /** * Determines if sending of in-band DTMF tones is enabled or disabled. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnable in-band DTMF tones enabled or disabled. */ SIPXTAPI_API SIPX_RESULT sipxConfigIsInBandDTMFEnabled(const SIPX_INST hInst, bool& bEnable) ; /** * Get the sipXtapi API version string. * * @param szVersion Buffer to store the version string. A zero-terminated * string will be copied into this buffer on success. * @param nBuffer Size of szBuffer in bytes (not to exceed). A size of 48 bytes * should be sufficient in most cases. */ SIPXTAPI_API SIPX_RESULT sipxConfigGetVersion(char* szVersion, const size_t nBuffer) ; /** * Get the local UDP port for SIP signaling. The port is supplied in the * call to sipXinitialize; however, the port may be allocated dynamically. * This method will return SIPX_RESULT_SUCCESS if able to return the port * value. SIPX_RESULT_FAILURE is returned if the protocol is not enabled. * * @param hInst Instance pointer obtained by sipxInitialize * @param pPort Pointer to a port number. This value must not be NULL. * */ SIPXTAPI_API SIPX_RESULT sipxConfigGetLocalSipUdpPort(SIPX_INST hInst, int* pPort) ; /** * Add a contact using the given IP address and port. This can be used for * IP address spoofing in the SIP Contact and SDP/RTP c address. * * @param szSipContactAddress - IP address to use in SIP Contact in initial * REGISTER and INVITE requests as well as the c field in the SDP. * @param iSipContactPort - port to use in the SIP Contact headers. * @param iNewContactId - contactId to use to specify this contact should * be used (see @sipxLineAdd, @sipxCallCreate, @sipxCallConnect). */ SIPXTAPI_API SIPX_RESULT sipxConfigAddContact(const SIPX_INST hInst, const char* szSipContactAddress, const int iSipContactPort, SIPX_CONTACT_ID& iNewContactId); /** * Get the local TCP port for SIP signaling. The port is supplied in the * call to sipXinitialize; however, the port may be allocated dynamically. * This method will return SIPX_RESULT_SUCCESS if able to return the port * value. SIPX_RESULT_FAILURE is returned if the protocol is not enabled. * * @param hInst Instance pointer obtained by sipxInitialize * @param pPort Pointer to a port number. This value must not be NULL. * */ SIPXTAPI_API SIPX_RESULT sipxConfigGetLocalSipTcpPort(SIPX_INST hInst, int* pPort) ; /** * Get the local TLS port for SIP signaling. The port is supplied in the * call to sipXinitialize; however, the port may be allocated dynamically. * This method will return SIPX_RESULT_SUCCESS if able to return the port * value. SIPX_RESULT_FAILURE is returned if the protocol is not enabled. * * @param hInst Instance pointer obtained by sipxInitialize * @param pPort Pointer to a port number. This value must not be NULL. * */ SIPXTAPI_API SIPX_RESULT sipxConfigGetLocalSipTlsPort(SIPX_INST hInst, int* pPort) ; /** * Set the preferred bandwidth requirement for codec selection. Whenever * possible a codec matching that requirement will be selected for a call. * This method will return SIPX_RESULT_SUCCESS if able to set the audio codec * preferences. SIPX_RESULT_FAILURE is returned if the preference is not set. * * @param hInst Instance pointer obtained by sipxInitialize * @param bandWidth Valid bandwidth requirements are AUDIO_CODEC_BW_LOW, * AUDIO_CODEC_BW_NORMAL, and AUDIO_CODEC_BW_HIGH. * */ SIPXTAPI_API SIPX_RESULT sipxConfigSetAudioCodecPreferences(const SIPX_INST hInst, SIPX_AUDIO_BANDWIDTH_ID bandWidth) ; /** * Set the codec preference order by name. The codec name(s) must match one of * the supported codecs otherwise this function will fail. * This method will return SIPX_RESULT_SUCCESS if able to set the audio codec. * SIPX_RESULT_FAILURE is returned if the codec is not set. * * @param hInst Instance pointer obtained by sipxInitialize * @param szCodecName space delimited list of codec names. * Note: TELEPHONE-EVENT is implicitly included * */ SIPXTAPI_API SIPX_RESULT sipxConfigSetAudioCodecByName(const SIPX_INST hInst, const char* szCodecName) ; /** * Get the current codec preference. * * @param hInst Instance pointer obtained by sipxInitialize * @param pBandWidth pointer to an integer that will contain AUDIO_CODEC_BW_LOW, * AUDIO_CODEC_BW_NORMAL, or AUDIO_CODEC_BW_HIGH. AUDIO_CODEC_BW_CUSTOM * will be returned if a specific codec was et using the * sipxConfigSetAudioCodecByName function. */ SIPXTAPI_API SIPX_RESULT sipxConfigGetAudioCodecPreferences(const SIPX_INST hInst, SIPX_AUDIO_BANDWIDTH_ID *pBandWidth); /** * Get the number of audio codecs. * This method will return SIPX_RESULT_SUCCESS if able to set the audio codec * preferences. SIPX_RESULT_FAILURE is returned if the number of codecs can * no be retrieved. * * @param hInst Instance pointer obtained by sipxInitialize * @param pNumCodecs Pointer to the number of codecs. This value must not be NULL. * */ SIPXTAPI_API SIPX_RESULT sipxConfigGetNumAudioCodecs(const SIPX_INST hInst, int* pNumCodecs) ; /** * Get the audio codec at a certain index in the list of codecs. Use this * function in conjunction with sipxConfigGetNumAudioCodecs to enumerate * the list of audio codecs. * This method will return SIPX_RESULT_SUCCESS if able to set the audio codec * preferences. SIPX_RESULT_FAILURE is returned if the audio codec can not * be retrieved. * * @param hInst Instance pointer obtained by sipxInitialize * @param index Index in the list of codecs * @param pCodec SIPX_AUDIO_CODEC structure that holds information * (name, bandwidth requirement) about the codec. * */ SIPXTAPI_API SIPX_RESULT sipxConfigGetAudioCodec(const SIPX_INST hInst, const int index, SIPX_AUDIO_CODEC* pCodec) ; /** * Set the bandwidth parameters for video codecs.Depending on the bandwidth * parameter that is passed in the settings will be set to: * * VIDEO_CODEC_BW_LOW bitrate 5 kbps, framerate 10 fps * VIDEO_CODEC_BW_NORMAL bitrate 70 kbps, framerate is what it was set to * with sipxConfigSetVideoParameters or 30 if not set. * VIDEO_CODEC_BW_HIGH bitrate 400 kbps, framerate is what it was set to * with sipxConfigSetVideoParameters or 30 if not set. * * This method will return SIPX_RESULT_SUCCESS if able to set the video codec * preferences. SIPX_RESULT_FAILURE is returned if the preference is not set. * * @param hInst Instance pointer obtained by sipxInitialize * @param bandWidth Valid bandwidth requirements are VIDEO_CODEC_BW_LOW, * VIDEO_CODEC_BW_NORMAL, and VIDEO_CODEC_BW_HIGH. * * @see sipxConfigSetVideoParameters */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoBandwidth(const SIPX_INST hInst, SIPX_VIDEO_BANDWIDTH_ID bandWidth); /** * Gets the list of video capture devices. * * @param hInst Instance pointer obtained by sipxInitialize * @param arrSzCaptureDevices Array of character arrays to be populated * by this function call. * @param nDeviceStringLength Length of buffer in arrSzCaptureDevice array. * @param nArrayLength Number of strings (of length nDeviceStringLength) in * the arrSzCaptureDevice array. */ SIPXTAPI_API SIPX_RESULT sipxConfigGetVideoCaptureDevices(const SIPX_INST hInst, char **arrSzCaptureDevices, int nDeviceStringLength, int nArrayLength); /** * Gets the current video capture device. * * @param hInst Instance pointer obtained by sipxInitialize * @param szCaptureDevice Character array to be populated by this function * call. * @param nLength Max length of szCaptureDevice buffer. * */ SIPXTAPI_API SIPX_RESULT sipxConfigGetVideoCaptureDevice(const SIPX_INST hInst, char* szCaptureDevice, int nLength); /** * Sets the video capture device. * * @param hInst Instance pointer obtained by sipxInitialize * @param szCaptureDevice Pointer to a character array containing the * name of the desired video capture device. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoCaptureDevice(const SIPX_INST hInst, const char* szCaptureDevice); /** * Set the codec by name. The name must match one of the supported codecs * otherwise this function will fail. * This method will return SIPX_RESULT_SUCCESS if able to set the video codec. * SIPX_RESULT_FAILURE is returned if the codec is not set. * * @param hInst Instance pointer obtained by sipxInitialize * @param szCodecName codec name * */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoCodecByName(const SIPX_INST hInst, const char* szCodecName) ; /** * Reset the codec list if it was modified by sipxConfigSetVideoCodecByName. This * resets the selection to a full codec list. * This method will return SIPX_RESULT_SUCCESS if able to set the audio codec. * SIPX_RESULT_FAILURE is returned if the codec is not set. * * @param hInst Instance pointer obtained by sipxInitialize * */ SIPXTAPI_API SIPX_RESULT sipxConfigResetVideoCodecs(const SIPX_INST hInst); /** * Get the current codec preference. * * @param hInst Instance pointer obtained by sipxInitialize * @param pBandWidth pointer to an integer that will contain AUDIO_CODEC_BW_LOW, * AUDIO_CODEC_BW_NORMAL, or AUDIO_CODEC_BW_HIGH. AUDIO_CODEC_BW_CUSTOM * will be returned if a specific codec was set using the * sipxConfigSetVideoCodecByName function. */ SIPXTAPI_API SIPX_RESULT sipxConfigGetVideoCodecPreferences(const SIPX_INST hInst, SIPX_VIDEO_BANDWIDTH_ID *pBandWidth); /** * Get the number of video codecs. * This method will return SIPX_RESULT_SUCCESS if able to set the audio codec * preferences. SIPX_RESULT_FAILURE is returned if the number of codecs can * no be retrieved. * * @param hInst Instance pointer obtained by sipxInitialize * @param pNumCodecs Pointer to the number of codecs. This value must not be NULL. * */ SIPXTAPI_API SIPX_RESULT sipxConfigGetNumVideoCodecs(const SIPX_INST hInst, int* pNumCodecs) ; /** * Set the supported video format * This method will limit the supported video format to either * VIDEO_FORMAT_CIF (352x288), VIDEO_FORMAT_QCIF (176x144), * VIDEO_FORMAT_SQCIF (128x92), or VIDEO_FORMAT_QVGA (320x240). * The method will return SIPX_RESULT_SUCCESS if it is able to set the video * format, SIPX_RESULT_FAILURE is returned if the video format can not be set. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoFormat(const SIPX_INST hInst, SIPX_VIDEO_FORMAT videoFormat); /** * Get the video codec at a certain index in the list of codecs. Use this * function in conjunction with sipxConfigGetNumVideoCodecs to enumerate * the list of video codecs. * This method will return SIPX_RESULT_SUCCESS if able to set the video codec * preferences. SIPX_RESULT_FAILURE is returned if the video codec can not * be retrieved. * * @param hInst Instance pointer obtained by sipxInitialize * @param index Index in the list of codecs * @param pCodec SIPX_VIDEO_CODEC structure that holds information * (name, bandwidth requirement) about the codec. * */ SIPXTAPI_API SIPX_RESULT sipxConfigGetVideoCodec(const SIPX_INST hInst, const int index, SIPX_VIDEO_CODEC* pCodec) ; /** * Get the local contact address available for outbound/inbound signaling and * audio. The local contact addresses will always include the local IP * addresses. The local contact addresses may also include external NAT- * derived addresses (e.g. STUN). See the definition of SIPX_CONTACT_ADDRESS * for more details on the structure. * * Determining which contact address to use depends on your network topology. * If you have a proxy/edge proxy within the same firewall/NAT space, you can * use the LOCAL UDP, TCP, or TLS contact type for your calls. If your * proxy resides outside of the firewall/NAT space, you should use the * NAT_MAPPED or RELAY contact type (UDP only). Both NAT_MAPPED and RELAY * use your STUN-derived IP address, however RELAY requests TURN for media * paths. * * @param hInst Instance pointer obtained by sipxInitialize * @param addresses A pre-allocated list of SIPX_CONTACT_ADDRESS * structures. This data will be filled in by the API call. * @param nMaxAddresses The maximum number of addresses supplied by the * addresses parameter. * @param nActualAddresses The actual number of addresses populated in * the addresses parameter. */ SIPXTAPI_API SIPX_RESULT sipxConfigGetLocalContacts(const SIPX_INST hInst, SIPX_CONTACT_ADDRESS addresses[], size_t nMaxAddresses, size_t& nActualAddresses) ; /** * Get our local ip/port combination for the designated remote ip/port. This * API will look at all of the stun and/or SIP message results to see if a * NAT binding exists for this particular host. If using a proxy server, * this is generally never needed, however, in peer-to-peer modes this can * sometimes help you get through NATs when using out-of-band registrars / * signaling helpers (not recommended -- use a proxy instead). * * For this API to be useful, you need to add a keepalive to the remote host * prior to calling this API. This may optionally block if a keep-alive request * has been started, but we are waiting for a response. * * @param hInst Instance pointer obtained by sipxInitialize * @param szRemoteIp IP of remote party * @param iRemotePort port or remote party * @param szContactIp Buffer to place local contact IP if successful * @param nContactIpLength Length of szContactIp buffer * @param iContactPort Int to place contact port * @param iTimeoutMs Timeout in MS. Values of 0 (or less) signal not to * block. Any other value is rounded up to multiple of 50ms. For * VoIP, a value of 500ms seems plenty (latency longer than 300ms * will result in a fairly bad audio experience). */ SIPXTAPI_API SIPX_RESULT sipxConfigGetLocalFeedbackAddress(const SIPX_INST hInst, const char* szRemoteIp, const int iRemotePort, char* szContactIp, size_t nContactIpLength, int& iContactPort, int iTimeoutMs) ; /** * Populates an array of IP Addresses in char* form. The array must be preallocated to * contain MAX_IP_ADDRESSES elements. * * WARNING: THIS API IS DEPRECATED AND WILL CHANGE IN FUTURE REVISIONS * * @param arrAddresses Pre-allocated array to be popluated with ip addresses. * @param arrAddressAdapter For each record in arrAddresses, there is a corresponding record, * with the same index, in arrAddressAdpater which represents the * "sipx adapter name" for that address * @param numAddresses Input: Size of the preallocated arrays. * Output: Number of IPs found by the system. */ SIPXTAPI_API SIPX_RESULT sipxConfigGetAllLocalNetworkIps(const char* arrAddresses[], const char* arrAddressAdapter[], int &numAddresses); /** * Set security parameters for an instance of sipXtapi. * @deprecated These should be set using sipxInitialize. * * @param hInst Instance pointer obtained by sipxInitialize * @param szDbLocation The directory in which the certificate database resides. * @param szMyCertNickname The local user's certificate nickname, for database lookup. * @param szDbPassword The password for the certificated database. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetSecurityParameters(const SIPX_INST hInst, const char* szDbLocation, const char* szMyCertNickname, const char* szDbPassword); /** * Enables/Disables use of short field names in sip messages. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnabled True if short names, false if long names */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableSipShortNames(const SIPX_INST hInst, const bool bEnabled); /** * Enables/Disables use of date header in sip messages. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnabled True if date header, false if no date header */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableSipDateHeader(const SIPX_INST hInst, const bool bEnabled); /** * Enables/Disables use of allow header in sip messages. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnabled True if allow header, false if no allow header */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableSipAllowHeader(const SIPX_INST hInst, const bool bEnabled); /** * Sets the Accept Language used in sip messages. e.g. - "EN" * * @param hInst Instance pointer obtained by sipxInitialize * @param szLanguage - Accept Language string */ SIPXTAPI_API SIPX_RESULT sipxConfigSetSipAcceptLanguage(const SIPX_INST hInst, const char* szLanguage); /** * Sets the location header for SIP messages. The location header will be * included in SIP requests and responses. You can disable the location * header on a call-by-call basis in the by changing the bEnableLocationHeader * flag on sipxCallAccept, sipxCallConnect, and sipxConferenceAdd methods. * * @param hInst Instance pointer obtained by sipxInitialize * @param szHeader - Location header * * @see sipxCallAccept * @see sipxCallConnect * @see sipxConferenceAdd */ SIPXTAPI_API SIPX_RESULT sipxConfigSetLocationHeader(const SIPX_INST hInst, const char* szHeader); /** * Set the connection idle timeout. If a media connection is idle for this * threshold, a SILENCE event will be fired to the application layer. * * Applications may decide to tear down the call after receiving this event * under the assumption that the remote party is gone away. Be careful when * using codecs that support silence suppression -- Some implementations * continue to send RTP heartbeats, however, others will not send any data * and may appear to be dead. * * @param hInst Instance pointer obtained by sipxInitialize * @param idleTimeout The time in seconds that a socket is idle before a * MEDIA_REMOTE_SILENT event is fired. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetConnectionIdleTimeout(const SIPX_INST hInst, const int idleTimeout); /** * Call this function to prepare a sipXtapi instance for a * system hibernation. This function is not thread-safe. * * @param hInst Instance pointer obtained by sipxInitialize */ SIPXTAPI_API SIPX_RESULT sipxConfigPrepareToHibernate(const SIPX_INST hInst); /** * Call this function upon returning from a system hibernation. * This function is not thread-safe. * @param hInst Instance pointer obtained by sipxInitialize */ SIPXTAPI_API SIPX_RESULT sipxConfigUnHibernate(const SIPX_INST hInst); /** * Enables RTP streaming over TCP. Enabling this feature * allows the application to use RTP streaming over TCP or UDP. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnable True allows RTP-over-TCP, false disallows it. */ SIPXTAPI_API SIPX_RESULT sipxConfigEnableRtpOverTcp(const SIPX_INST hInst, bool bEnable); /** * Sets the display object for the "video preview". * * @param hInst Instance pointer obtained by sipxInitialize * @param pDisplay Pointer to a video preview display object. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoPreviewDisplay(const SIPX_INST hInst, SIPX_VIDEO_DISPLAY* const pDisplay); /** * Updates the Preview window with a new frame buffer. Should be called * when the window receives a PAINT message. * * @param hInst Instance pointer obtained by sipxInitialize * @param hWnd Window handle of the video preview window. */ SIPXTAPI_API SIPX_RESULT sipxConfigUpdatePreviewWindow(const SIPX_INST hInst, const SIPX_WINDOW_HANDLE hWnd); /** * Sets the video quality. * * @param hInst Instance pointer obtained by sipxInitialize * @param quality Id setting the video quality. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoQuality(const SIPX_INST hInst, const SIPX_VIDEO_QUALITY_ID quality); /** * Sets the bit rate and frame rate parameters for video. * * @param hInst Instance pointer obtained by sipxInitialize * @param bitRate Bit rate parameter in kbps * @param frameRate Frame rate parameter frames per second */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoParameters(const SIPX_INST hInst, const int bitRate, const int frameRate); /** * Sets the video bitrate * * @param hInst Instance pointer obtained by sipxInitialize * @param bitRate Bit rate parameter */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoBitrate(const SIPX_INST hInst, const int bitRate); /** * Sets the video framerate * * @param hInst Instance pointer obtained by sipxInitialize * @param frameRate Frame rate parameter */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoFramerate(const SIPX_INST hInst, const int frameRate); /** * Set the cpu usage * * @param hInst Instance pointer obtained by sipxInitialize * @param cpuUsage CPU usage in percent */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVideoCpuUsage(const SIPX_INST hInst, const int cpuUsage); /** * Subscribe for NOTIFY events which may be published by another end-point or * server. * * sipXtapi will automatically refresh subscriptions until * sipxConfigUnsubscribe is called. Please make sure you call * sipxCallUnsubscribe before tearing down your instance of sipXtapi. * * @param hInst Instance pointer obtained by sipxInitialize * @param hLine Line Identity for the outbound call. The line identity * helps defines the "From" caller-id. * @param szTargetUrl The Url of the publishing end-point. * @param szEventType A string representing the type of event that can be * published. This string is used to populate the "Event" header in * the SIP SUBSCRIBE request. For example, if checking voicemail * status, your would use "message-summary". * @param szAcceptType A string representing the types of NOTIFY events that * this client will accept. This string is used to populate the * "Accept" header in the SIP SUBSCRIBE request. For example, if * checking voicemail status, you would use * "application/simple-message-summary" * @param contactId Id of the desired contact record to use for this call. * The id refers to a Contact Record obtained by a call to * sipxConfigGetLocalContacts. The application can choose a * contact record of type LOCAL, NAT_MAPPED, CONFIG, or RELAY. * The Contact Type allows you to control whether the * user agent and media processing advertises the local address * (e.g. LOCAL contact of 10.1.1.x or * 192.168.x.x), the NAT-derived address to the target party, * or, local contact addresses of other types. * @param phSub Pointer to a subscription handle whose value is set by this * funtion. This handle allows you to cancel the subscription and * differeniate between NOTIFY events. */ SIPXTAPI_API SIPX_RESULT sipxConfigSubscribe(const SIPX_INST hInst, const SIPX_LINE hLine, const char* szTargetUrl, const char* szEventType, const char* szAcceptType, const SIPX_CONTACT_ID contactId, SIPX_SUB* phSub); /** * Unsubscribe from previously subscribed NOTIFY events. This method will * send another subscription request with an expires time of 0 (zero) to end * your subscription. * * @param hSub The subscription handle obtained from the call to * sipxConfigSubscribe. */ SIPXTAPI_API SIPX_RESULT sipxConfigUnsubscribe(const SIPX_SUB hSub); /** * Associates an external transport mechanism for SIP signaling with * the given instance. * * @param hInst An instance handle obtained from sipxInitialize. * @param hTransport Reference to a SIPX_TRANSPORT handle. This function will * assign a value to the referenced handle. * @param bIsReliable If false, indicates that SIPxua should retry external transport * writes in case of response timeouts. If true, SIPxua will not attempt retries * in case of a response timeouts. For connection oriented transport (like TCP), * bIsReliable should be true, for packet oriented transport (like UDP), * bIsReliable should be false. * @param szTransport Transport type string to be used in SIP URIs. * For example, passing in a szTransport of "flibble" will cause the * transport tag to be added to the URI like so: * "sip:mickey\@example.com;transport=flibble" * @param szLocalIP IP address which is the source address for the write. * @param iLocalPort Port value from which the data will be sent. * @param writeProc Function pointer to the callback for writing data * using the transport mechanism. * @param szLocalRoutingId A local routing id pass back to the write proc callback. * @param pUserData User data passed back to the write proc. */ SIPXTAPI_API SIPX_RESULT sipxConfigExternalTransportAdd(SIPX_INST const hInst, SIPX_TRANSPORT& hTransport, const bool bIsReliable, const char* szTransport, const char* szLocalIP, const int iLocalPort, SIPX_TRANSPORT_WRITE_PROC writeProc, const char* szLocalRoutingId, const void* pUserData = NULL) ; /** * Removes an external transport mechanism from the given instance. * Will fail if transport in use. * * @param hTransport Handle to the external transport object. Obtained via * a call to sipxConfigExternalTransportAdd */ SIPXTAPI_API SIPX_RESULT sipxConfigExternalTransportRemove(const SIPX_TRANSPORT hTransport); /** * The external transport mechanism can be configured to route by user or by * destination ip/port. User is the default. * * @param hTransport Handle to the external transport object. Obtained via a * call to sipxConfigExternalTransportAdd * @param bRouteByUser true to route by user (default), false to route by * destination ip/port. */ SIPXTAPI_API SIPX_RESULT sipxConfigExternalTransportRouteByUser(const SIPX_TRANSPORT hTransport, bool bRouteByUser) ; /** * Called by the application when it receives a complete SIP message via * it's external transport mechanism and want to pass it along to sipXtapi. * The application is responsible for * preparing the Data so that it is composed of a single and complete * SIP message. * * @param hTransport Handle to the external transport object. Obtained via * a call to sipxConfigExternalTransportAdd * @param szSourceIP IP address which was the source of the data which was read. * @param iSourcePort Port value from which the data was sent. * @param szLocalIP Local IP address on which the data was received. * @param iLocalPort Local port value on which the data was received. * @param pData Pointer to the data which was received, which should point to * a single and complete SIP message. * @param nData Size of the data which was received. */ SIPXTAPI_API SIPX_RESULT sipxConfigExternalTransportHandleMessage(const SIPX_TRANSPORT hTransport, const char* szSourceIP, const int iSourcePort, const char* szLocalIP, const int iLocalPort, const void* pData, const size_t nData); /** * Sets the SIP target URL for voice quality reports. Voice Quality reports * are sent at the completion of each call and give details on the voice * quality (latency, noise, MOS scores, etc). Presently, this is not * implemented in the open source version. * * This must be enabled prior to creating a call or receiving a new call * indiciation. Likewise, changes will not take effect for existing calls. * * @param hInst An instance handle obtained from sipxInitialize. * @param szServer Target SIP URL for the voice quality reports. A * value of NULL will disable voice quality reports. */ SIPXTAPI_API SIPX_RESULT sipxConfigSetVoiceQualityServer(const SIPX_INST hInst, const char* szServer) ; //@} /** @name Utility Functions */ //@{ /** * Simple utility function to parse the username, host, and port from * a URL. All url, field, and header parameters are ignored. You may also * specify NULL for any parameters (except szUrl) which are not needed. * Lastly, the caller must allocate enough storage space for each url * component -- if in doubt use the length of the supplied szUrl. */ SIPXTAPI_API SIPX_RESULT sipxUtilUrlParse(const char* szUrl, char* szUsername, char* szHostname, int* iPort) ; /** * Simple utility function to parse the display name from a SIP URL. */ SIPXTAPI_API SIPX_RESULT sipxUtilUrlGetDisplayName(const char* szUrl, char* szDisplayName, size_t nDisplayName) ; /** * Simple utility function to update a URL. If the szUrl isn't large enough, * or is NULL, this function will fail, however, the nUrl will contained the * required size in bytes. * * To leave an existing component unchanged, use NULL for strings and -1 for * ports. */ SIPXTAPI_API SIPX_RESULT sipxUtilUrlUpdate(char* szUrl, size_t & nUrl, const char* szNewUsername, const char* szNewHostname, const int iNewPort) ; /** * Get the Nth named url parameter from the designated url. * * @param szUrl The url to parse * @param szParamName Name of the url parameter * @param nParamIndex Index of the url parameter (zero-based). This is used * if you have multiple url parameters with the same name -- otherwise, * you should use 0. * @param szParamValue Buffer to place parameter value * @param nParamValue size of parameter value buffer (szParamValue) */ SIPXTAPI_API SIPX_RESULT sipxUtilUrlGetUrlParam(const char* szUrl, const char* szParamName, size_t nParamIndex, char* szParamValue, size_t nParamValue) ; //@} #endif // _sipXtapi_h_ sipxtapi-3.3.0~test17/sipXcallLib/include/tapi/sipXtapiEvents.h0000644000175000017500000017415012205613256025335 0ustar00danieldaniel00000000000000// // Copyright (C) 2007 Robert J. Andreasen, Jr. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// /** * @file sipXtapiEvents.h * sipXtapi event declarations * * The sipXtapiEvents.h header file defines all of the events fired as part of * sipXtapi. Event categories include call state events, line state events, * SIP info events, SIP subscription events, configuration events, security * events, media events, and keepalive events. * * Each event notification is comprised of a event type and a cause code. * The event type identifies a state transition (e.g. from call connected to * call disconnected. The cause identifies the reason for the change (e.g. * someone hung up). * * @see sipxEventListenerAdd * @see sipxEventListenerRemove * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ #ifndef _SIPXTAPIEVENT_H #define _SIPXTAPIEVENT_H // SYSTEM INCLUDES // APPLICATION INCLUDES #include "sipXtapi.h" // DEFINES // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // FORWARD DECLARATIONS /** * Enum with all of the possible event types. */ typedef enum SIPX_EVENT_CATEGORY { EVENT_CATEGORY_CALLSTATE, /**< CALLSTATE events signify a change in state of a call. States range from the notification of a new call to ringing to connection established to changes in audio state (starting sending, stop sending) to termination of a call. */ EVENT_CATEGORY_LINESTATE, /**< LINESTATE events indicate changes in the status of a line appearance. Lines identify inbound and outbound identities and can be either provisioned (hardcoded) or configured to automatically register with a registrar. Lines also encapsulate the authentication criteria needed for dynamic registrations. */ EVENT_CATEGORY_INFO_STATUS, /**< INFO_STATUS events are sent when the application requests sipXtapi to send an INFO message to another user agent. The status event includes the response for the INFO method. Application developers should look at this event to determine the outcome of the INFO message. */ EVENT_CATEGORY_INFO, /**< INFO events are sent to the application whenever an INFO message is received by the sipXtapi user agent. INFO messages are sent to a specific call. sipXtapi will automatically acknowledges the INFO message at the protocol layer. */ EVENT_CATEGORY_SUB_STATUS, /**< SUB_STATUS events are sent to the application layer for information on the subscription state (e.g. OK, Expired). */ EVENT_CATEGORY_NOTIFY, /**< NOTIFY evens are send to the application layer after a remote publisher has sent data to the application. The application layer can retrieve the data from this event. */ EVENT_CATEGORY_CONFIG, /**< CONFIG events signify changes in configuration. For example, when requesting STUN support, a notification is sent with the STUN outcome (either SUCCESS or FAILURE) */ EVENT_CATEGORY_SECURITY, /**< SECURITY events signify occurences in call security processing. These events are only sent when using S/MIME or TLS. */ EVENT_CATEGORY_MEDIA, /**< MEDIA events signify changes in the audio state for sipXtapi or a particular call. */ EVENT_CATEGORY_KEEPALIVE /**< KEEPALIVE events signal when a keepalive is started/stopped/fails. A feedback event will report back your NAT-mapped IP address in some cases. @see SIPX_KEEPALIVE_TYPE for more information.*/ } SIPX_EVENT_CATEGORY; /** * VALID_SIPX_EVENT_CATEGORY utility macro to validate if an event category * is valid (within expected range). */ #define VALID_SIPX_EVENT_CATEGORY(x) (((x) >= EVENT_CATEGORY_CALLSTATE) && ((x) <= EVENT_CATEGORY_KEEPALIVE)) /** * Signature for event callback/observer. Application developers should * not block this event callback thread -- You should re-post these events * to your own thread context for handling if you require blocking and/or * heavy prorcessing. The sipxDuplicateEvent and sipxFreeDuplicatedEvent * methods are available to copy the event callback data (The data is only * available for the duration of the callback). For example, upon receiving * the callback, copy the data using sipxDuplicateEvent(...), post the * copied data to your event callback, process it, and lastly free the event * data using sipxFreeDuplicatedEvent(...). * * The application developer must look at the SIPX_EVENT_CATEGORY and then * cast the pInfo method to the appropriate structure: * *
 * EVENT_CATEGORY_CALLSTATE:   pCallInfo = (SIPX_CALLSTATE_INFO*) pInfo ;
 * EVENT_CATEGORY_LINESTATE:   pLineInfo = (SIPX_LINESTATE_INFO*) pInfo ;
 * EVENT_CATEGORY_INFO_STATUS: pInfoStatus = (SIPX_INFOSTATUS_INFO*) pInfo ;
 * EVENT_CATEGORY_INFO:        pInfoInfo = (SIPX_INFO_INFO*) pInfo ;
 * EVENT_CATEGORY_SUB_STATUS:  pSubInfo = (SIPX_SUBSTATUS_INFO*) pInfo ;
 * EVENT_CATEGORY_NOTIFY:      pNotifyInfo = (SIPX_NOTIFY_INFO*) pInfo ;
 * EVENT_CATEGORY_CONFIG:      pConfigInfo - (SIPX_CONFIG_INFO*) pInfo ;
 * EVENT_CATEGORY_SECURITY:    pSecInfo = (SIPX_SECURITY_INFO*) pInfo ;
 * EVENT_CATEGORY_MEDIA:       pMediaInfo = (SIPX_MEDIA_INFO*) pInfo ;
 * 
* * Please see the SIPX_EVENT_CATEGORY and structure definitions for details. * * @param category The category of the event (call, line, subscription, notify, etc.). * @param pInfo Pointer to the event info structure. Depending on the event * type, the application layer needs to cast this parameter to the * appropriate structure. * @param pUserData User data provided when listener was added */ typedef bool (SIPX_CALLING_CONVENTION *SIPX_EVENT_CALLBACK_PROC)(SIPX_EVENT_CATEGORY category, void* pInfo, void* pUserData); /** * Major call state events identify significant changes in the state of a * call. * * Below you will find state diagrams that show the typical event transitions * for both outbound and inbound calls. * * @image html callevents_inbound.gif * * Figure 1: Event flows for an inbound call (received call) * * @image html callevents_outbound.gif * * Figure 2: Event flows for an outbound call (placed call) */ typedef enum SIPX_CALLSTATE_EVENT { CALLSTATE_UNKNOWN = 0, /**< An UNKNOWN event is generated when the state for a call is no longer known. This is generally an error condition; see the minor event for specific causes. */ CALLSTATE_NEWCALL = 1000, /**< The NEWCALL event indicates that a new call has been created automatically by the sipXtapi. This event is most frequently generated in response to an inbound call request. */ CALLSTATE_DIALTONE = 2000, /**< The DIALTONE event indicates that a new call has been created for the purpose of placing an outbound call. The application layer should determine if it needs to simulate dial tone for the end user. */ CALLSTATE_REMOTE_OFFERING = 2500, /**< The REMOTE_OFFERING event indicates that a call setup invitation has been sent to the remote party. The invitation may or may not every receive a response. If a response is not received in a timely manor, sipXtapi will move the call into a disconnected state. If calling another sipXtapi user agent, the reciprocal state is OFFER. */ CALLSTATE_REMOTE_ALERTING = 3000, /**< The REMOTE_ALERTING event indicates that a call setup invitation has been accepted and the end user is in the alerting state (ringing). Depending on the SIP configuration, end points, and proxy servers involved, this event should only last for 3 minutes. Afterwards, the state will automatically move to DISCONNECTED. If calling another sipXtapi user agent, the reciprocate state is ALERTING. Pay attention to the cause code for this event. If the cause code is "CALLSTATE_CAUSE_EARLY_MEDIA", the remote the party is sending early media (e.g. gateway is producing ringback or audio feedback). In this case, the user agent should not produce local ringback. */ CALLSTATE_CONNECTED = 4000, /**< The CONNECTED state indicates that call has been setup between the local and remote party. Network audio should be flowing provided and the microphone and speakers should be engaged. */ CALLSTATE_BRIDGED = 5000, /** The BRIDGED state indicates that a call is active, however, the local microphone/speaker are not engaged. If this call is part of a conference, the party will be able to talk with other BRIDGED conference parties. Application developers can still play and record media. */ CALLSTATE_HELD = 6000, /** The HELD state indicates that a call is both locally and remotely held. No network audio is flowing and the local microphone and speaker are not engaged. */ CALLSTATE_REMOTE_HELD = 7000, /** The REMOTE_HELD state indicates that the remote party is on hold. Locally, the microphone and speaker are still engaged, however, no network audio is flowing. */ CALLSTATE_DISCONNECTED = 8000, /**< The DISCONNECTED state indicates that a call was disconnected or failed to connect. A call may move into the DISCONNECTED states from almost every other state. Please review the DISCONNECTED minor events to understand the cause. */ CALLSTATE_OFFERING = 9000, /**< An OFFERING state indicates that a new call invitation has been extended this user agent. Application developers should invoke sipxCallAccept(), sipxCallReject() or sipxCallRedirect() in response. Not responding will result in an implicit call sipXcallReject(). */ CALLSTATE_ALERTING = 10000, /**< An ALERTING state indicates that an inbound call has been accepted and the application layer should alert the end user. The alerting state is limited to 3 minutes in most configurations; afterwards the call will be canceled. Applications will generally play some sort of ringing tone in response to this event. */ CALLSTATE_DESTROYED = 11000, /**< The DESTORYED event indicates the underlying resources have been removed for a call. This is the last event that the application will receive for any call. The call handle is invalid after this event is received. */ CALLSTATE_TRANSFER_EVENT = 12000, /**< The transfer state indicates a state change in a transfer attempt. Please see the CALLSTATE_TRANSFER_EVENT cause codes for details on each state transition */ } SIPX_CALLSTATE_EVENT; /** * Callstate cause events identify the reason for a Callstate event or * provide more detail. */ typedef enum SIPX_CALLSTATE_CAUSE { CALLSTATE_CAUSE_UNKNOWN, /**< Unknown cause */ CALLSTATE_CAUSE_NORMAL, /**< The stage changed due to normal operation */ CALLSTATE_CAUSE_TRANSFERRED, /**< A call is being transferred to this user agent from another user agent.*/ CALLSTATE_CAUSE_TRANSFER, /**< A call on this user agent is being transferred to another user agent. */ CALLSTATE_CAUSE_CONFERENCE, /**< A conference operation caused a stage change */ CALLSTATE_CAUSE_EARLY_MEDIA, /**< The remote party is alerting and providing ringback audio (early media) */ CALLSTATE_CAUSE_REQUEST_NOT_ACCEPTED, /**< The callee rejected a request (e.g. hold) */ CALLSTATE_CAUSE_BAD_ADDRESS, /**< The state changed due to a bad address. This can be caused by a malformed URL or network problems with your DNS server */ CALLSTATE_CAUSE_BUSY, /**< The state changed because the remote party is busy */ CALLSTATE_CAUSE_RESOURCE_LIMIT, /**< Not enough resources are available to complete the desired operation */ CALLSTATE_CAUSE_NETWORK, /**< A network error caused the desired operation to fail */ CALLSTATE_CAUSE_REDIRECTED, /**< The stage changed due to a redirection of a call. */ CALLSTATE_CAUSE_NO_RESPONSE, /**< No response was received from the remote party or network node. */ CALLSTATE_CAUSE_AUTH, /**< Unable to authenticate due to either bad or missing credentials */ CALLSTATE_CAUSE_TRANSFER_INITIATED, /**< A transfer attempt has been initiated. This event is sent when a user agent attempts either a blind or consultative transfer. */ CALLSTATE_CAUSE_TRANSFER_ACCEPTED, /**< A transfer attempt has been accepted by the remote transferee. This event indicates that the transferee supports transfers (REFER method). The event is fired upon a 2xx class response to the SIP REFER request. */ CALLSTATE_CAUSE_TRANSFER_TRYING, /**< The transfer target is attempting the transfer. This event is sent when transfer target (or proxy / B2BUA) receives the call invitation, but before the the tranfer target accepts is. */ CALLSTATE_CAUSE_TRANSFER_RINGING, /**< The transfer target is ringing. This event is generally only sent during blind transfer. Consultative transfer should proceed directly to TRANSFER_SUCCESS or TRANSFER_FAILURE. */ CALLSTATE_CAUSE_TRANSFER_SUCCESS, /**< The transfer was completed successfully. The original call to transfer target will automatically disconnect.*/ CALLSTATE_CAUSE_TRANSFER_FAILURE, /**< The transfer failed. After a transfer fails, the application layer is responsible for recovering original call to the transferee. That call is left on hold. */ CALLSTATE_CAUSE_REMOTE_SMIME_UNSUPPORTED, /**< Fired if the remote party's user-agent does not support S/MIME. */ CALLSTATE_CAUSE_SMIME_FAILURE, /**< Fired if a local S/MIME operation failed. For more information, applications should process the SECURITY event. */ CALLSTATE_CAUSE_SHUTDOWN, /**< The even was fired as part of sipXtapi shutdown. */ CALLSTATE_CAUSE_BAD_REFER, /**< An unusable refer was sent to this user-agent. */ CALLSTATE_CAUSE_NO_KNOWN_INVITE, /**< This user-agent received a request or response, but there is no known matching invite. */ CALLSTATE_CAUSE_BYE_DURING_IDLE, /**< A BYE message was received, however, the call is in in an idle state. */ CALLSTATE_CAUSE_UNKNOWN_STATUS_CODE, /**< A response was received with an unknown status code. */ CALLSTATE_CAUSE_BAD_REDIRECT, /**< Receive a redirect with NO contact or a RANDOM redirect. */ CALLSTATE_CAUSE_TRANSACTION_DOES_NOT_EXIST, /**< No such transaction; Accepting or Rejecting a call that is part of a transfer. */ CALLSTATE_CAUSE_CANCEL, /**< The event was fired in response to a cancel attempt from the remote party */ CALLSTATE_CAUSE_NO_CODECS, /**< An attempt to send INVITE with no codecs in SDP.*/ CALLSTATE_CAUSE_SERVER_ERROR /**< Server or client at far end had major (500 class) error */ } SIPX_CALLSTATE_CAUSE ; /** * Enumeration of possible linestate Events. * * @image html lineevents.gif */ typedef enum SIPX_LINESTATE_EVENT { LINESTATE_UNKNOWN = 0, /**< This is the initial Line event state. */ LINESTATE_REGISTERING = 20000, /**< The REGISTERING event is fired when sipXtapi has successfully sent a REGISTER message, but has not yet received a success response from the registrar server */ LINESTATE_REGISTERED = 21000, /**< The REGISTERED event is fired after sipXtapi has received a response from the registrar server, indicating a successful registration. */ LINESTATE_UNREGISTERING = 22000, /**< The UNREGISTERING event is fired when sipXtapi has successfully sent a REGISTER message with an expires=0 parameter, but has not yet received a success response from the registrar server */ LINESTATE_UNREGISTERED = 23000, /**< The UNREGISTERED event is fired after sipXtapi has received a response from the registrar server, indicating a successful un-registration. */ LINESTATE_REGISTER_FAILED = 24000, /**< The REGISTER_FAILED event is fired to indicate a failure of REGISTRATION. It is fired in the following cases: The client could not connect to the registrar server. The registrar server challenged the client for authentication credentials, and the client failed to supply valid credentials. The registrar server did not generate a success response (status code == 200) within a timeout period. */ LINESTATE_UNREGISTER_FAILED = 25000, /**< The UNREGISTER_FAILED event is fired to indicate a failure of un-REGISTRATION. It is fired in the following cases: The client could not connect to the registrar server. The registrar server challenged the client for authentication credentials, and the client failed to supply valid credentials. The registrar server did not generate a success response (status code == 200) within a timeout period. */ LINESTATE_PROVISIONED = 26000, /**< The PROVISIONED event is fired when a sipXtapi Line is added, and Registration is not requested (i.e. - sipxLineAdd is called with a bRegister parameter of false. */ } SIPX_LINESTATE_EVENT; /** * Enumeration of possible linestate Event causes. */ typedef enum SIPX_LINESTATE_CAUSE { LINESTATE_CAUSE_UNKNOWN = 0, /**< No cause specified. */ LINESTATE_REGISTERING_NORMAL = LINESTATE_REGISTERING + 1, /**< See LINESTATE_REGISTERING event. */ LINESTATE_REGISTERED_NORMAL = LINESTATE_REGISTERED + 1, /**< See LINESTATE_REGISTERED event. */ LINESTATE_UNREGISTERING_NORMAL = LINESTATE_UNREGISTERING + 1, /**< See LINESTATE_UNREGISTERING event. */ LINESTATE_UNREGISTERED_NORMAL = LINESTATE_UNREGISTERED + 1, /**< See LINESTATE_UNREGISTERED event. */ LINESTATE_REGISTER_FAILED_COULD_NOT_CONNECT = LINESTATE_REGISTER_FAILED + 1, /**< Failed to register because of a connectivity problem. */ LINESTATE_REGISTER_FAILED_NOT_AUTHORIZED = LINESTATE_REGISTER_FAILED + 2, /**< Failed to register because of an authorization / authentication failure. */ LINESTATE_REGISTER_FAILED_TIMEOUT = LINESTATE_REGISTER_FAILED + 3, /**< Failed to register because of a timeout. */ LINESTATE_UNREGISTER_FAILED_COULD_NOT_CONNECT = LINESTATE_UNREGISTER_FAILED + 1, /**< Failed to unregister because of a connectivity problem. */ LINESTATE_UNREGISTER_FAILED_NOT_AUTHORIZED = LINESTATE_UNREGISTER_FAILED + 2, /**< Failed to unregister because of of an authorization / authentication failure. */ LINESTATE_UNREGISTER_FAILED_TIMEOUT = LINESTATE_UNREGISTER_FAILED + 3, /**< Failed to register because of a timeout. */ LINESTATE_PROVISIONED_NORMAL = LINESTATE_PROVISIONED + 1 /**< See LINESTATE_PROVISIONED event. */ } SIPX_LINESTATE_CAUSE; /** * Enumeration of possible INFO status events */ enum SIPX_INFOSTATUS_EVENT { INFOSTATUS_UNKNOWN = 0 , /**< This is the initial value for an INFOSTATUS event. */ INFOSTATUS_RESPONSE = 30000, /**< This event is fired if a response is received after an INFO message has been sent */ INFOSTATUS_NETWORK_ERROR = 31000 /**< This event is fired in case a network error was encountered while trying to send an INFO event. */ }; /** * Enumeration of possible configuration events */ enum SIPX_CONFIG_EVENT { CONFIG_UNKNOWN = 0, /**< Unknown configuration event */ CONFIG_STUN_SUCCESS = 40000, /**< A STUN binding has been obtained for signaling purposes. For a SIPX_CONFIG_EVENT type of CONFIG_STUN_SUCCESS, the pData pointer of the info structure will point to a SIPX_CONTACT_ADDRESS structure. */ CONFIG_STUN_FAILURE = 41000, /**< Unable to obtain a STUN binding for signaling purposes. */ } ; /** * Enumeration of possible security events */ typedef enum SIPX_SECURITY_EVENT { SECURITY_UNKNOWN = 0,/**< An UNKNOWN event is generated when the state for a call is no longer known. This is generally an error condition; see the minor event for specific causes. */ SECURITY_ENCRYPT = 1000, /**< The ENCRYPT event indicates that an SMIME encryption has been attempted. See the cause code for the encryption outcome, and the info structure for more information. */ SECURITY_DECRYPT = 2000, /**< The DECRYPT event indicates that an SMIME decryption has been attempted. See the cause code for the encryption outcome, and the info structure for more information. */ SECURITY_TLS = 4000, /**< TLS related security event. */ } SIPX_SECURITY_EVENT; /** * Enumeration of possible security causes */ typedef enum SIPX_SECURITY_CAUSE { SECURITY_CAUSE_UNKNOWN = 0, /**< An UNKNOWN cause code is generated when the state for the security operation is no longer known. This is generally an error condition; see the info structure for details. */ SECURITY_CAUSE_NORMAL, /**< Event was fired as part of the normal encryption / decryption process. */ SECURITY_CAUSE_ENCRYPT_SUCCESS, /**< An S/MIME encryption succeeded. */ SECURITY_CAUSE_ENCRYPT_FAILURE_LIB_INIT, /**< An S/MIME encryption failed because the security library could not start. */ SECURITY_CAUSE_ENCRYPT_FAILURE_BAD_PUBLIC_KEY, /**< An S/MIME encryption failed because of a bad certificate / public key. */ SECURITY_CAUSE_ENCRYPT_FAILURE_INVALID_PARAMETER,/**< An S/MIME encryption failed because of an invalid parameter. */ SECURITY_CAUSE_DECRYPT_SUCCESS, /**< An S/MIME decryption succeeded. */ SECURITY_CAUSE_DECRYPT_FAILURE_DB_INIT, /**< An S/MIME decryption failed due to a failure to initialize the certificate database. */ SECURITY_CAUSE_DECRYPT_FAILURE_BAD_DB_PASSWORD, /**< An S/MIME decryption failed due to an invalid certificate database password. */ SECURITY_CAUSE_DECRYPT_FAILURE_INVALID_PARAMETER,/**< An S/MIME decryption failed due to an invalid parameter. */ SECURITY_CAUSE_DECRYPT_BAD_SIGNATURE, /**< An S/MIME decryption operation aborted due to a bad signature. */ SECURITY_CAUSE_DECRYPT_MISSING_SIGNATURE, /**< An S/MIME decryption operation aborted due to a missing signature. */ SECURITY_CAUSE_DECRYPT_SIGNATURE_REJECTED, /**< An S/MIME decryption operation aborted because the signature was rejected. */ SECURITY_CAUSE_TLS_SERVER_CERTIFICATE, /**< A TLS server certificate is being presented to the application for possible rejection. The application must respond to this message. If the application returns false, the certificate is rejected and the call will not complete. If the application returns true, the certificate is accepted. */ SECURITY_CAUSE_TLS_BAD_PASSWORD, /**< A TLS operation failed due to a bad password. */ SECURITY_CAUSE_TLS_LIBRARY_FAILURE, /**< A TLS operation failed. */ SECURITY_CAUSE_REMOTE_HOST_UNREACHABLE, /**< The remote host is not reachable. */ SECURITY_CAUSE_TLS_CONNECTION_FAILURE, /**< A TLS connection to the remote party failed. */ SECURITY_CAUSE_TLS_HANDSHAKE_FAILURE, /**< A failure occured during the TLS handshake. */ SECURITY_CAUSE_SIGNATURE_NOTIFY, /**< The SIGNATURE_NOTIFY event is fired when the user-agent receives a SIP message with signed SMIME as its content. The signer's certificate will be located in the info structure associated with this event. The application can choose to accept the signature, by returning 'true' in response to this message or can choose to reject the signature by returning 'false' in response to this message. */ SECURITY_CAUSE_TLS_CERTIFICATE_REJECTED /** < The application has rejected the server's TLS certificate. */ } SIPX_SECURITY_CAUSE; /** * Enumeration of possible media events */ typedef enum SIPX_MEDIA_EVENT { MEDIA_UNKNOWN = 0, /**< Unknown or undefined media event, this is generally the sign of an internal error in sipXtapi */ MEDIA_LOCAL_START = 50000, /**< Local media (audio or video) is being sent to the remote party */ MEDIA_LOCAL_STOP, /**< Local media (audio or video) is no longer being sent to the remote party. This may be caused by a local/remote hold operation, call tear down, or error. See the SIPX_MEDIA_CAUSE enumeration for more information. */ MEDIA_REMOTE_START, /**< Remote media (audio or video) is ready to be received. If no audio/video is received for longer then the idle period, a MEDIA_REMOTE_SILENT event will be fired. See sipxConfigSetConnectionIdleTimeout. */ MEDIA_REMOTE_STOP, /**< Remote media (audio or video) has been stopped due to a hold or call tear down.*/ MEDIA_REMOTE_SILENT, /**< Remote media has not been received for some configured period. This generally indicates a network problem and/or a problem with the remote party. See sipxConfigSetConnectionIdleTimeout for more information. */ MEDIA_PLAYFILE_START, /**< A file is being played to local and/or remote parties. This event will be followed by a MEDIA_PLAYFILE_STOP when the file is manually stopped or finished playing. */ MEDIA_PLAYFILE_FINISH, /**< A file has completed playing. You need to call sipxCallAudioPlayFileStop() or sipxConferencePlayAudioFileStop() to prepare for the next file playback. */ MEDIA_PLAYFILE_STOP, /**< A file playback has been stopped.*/ MEDIA_PLAYBUFFER_START, /**< A buffer is being played to local and/or remote parties. This event will be followed by a MEDIA_PLAYBUFFER_STOP when the file is manually stopped or finished playing. */ MEDIA_PLAYBUFFER_FINISH, /**< A buffer has completed playing. You need to call sipxCallPlayBufferStop() to prepare for the next buffer playback. */ MEDIA_PLAYBUFFER_STOP, /**< A buffer playback has been stopped.*/ MEDIA_RECORDFILE_START, /**< Recording to a file has started. This event will be followed by a MEDIA_RECORDFILE_STOP when the recording is manually stopped or or finished after specified amount of time. */ MEDIA_RECORDFILE_STOP, /**< A recording has been manually stopped, automatically finished or aborted because of an error.*/ MEDIA_RECORDBUFFER_START, /**< Recording to a buffer has started. This event will be followed by a MEDIA_RECORDBUFFER_STOP when the recording is manually stopped or or finished after specified amount of time. */ MEDIA_RECORDBUFFER_STOP, /**< A recording has been manually stopped, automatically finished or aborted because of an error.*/ MEDIA_REMOTE_DTMF, /**< A dtmf tone was started/stopped, see the cause codes for exact status */ MEDIA_DEVICE_FAILURE, /**< Fired if the media device is not present or already in use. */ MEDIA_REMOTE_ACTIVE, /**< Media has been received */ MEDIA_MIC_ENERGY_LEVEL, /**< Mic energy level - value in idleTime */ MEDIA_H264_SPS, /**< H.264 SPS parameter set recieved */ MEDIA_H264_PPS /**< H.264 PPS parameter set recieved */ } SIPX_MEDIA_EVENT ; /** * Enumeration of possible KEEPALIVE events (EVENT_CATEGORY_KEEPALIVE) */ typedef enum SIPX_KEEPALIVE_EVENT { KEEPALIVE_START, /**< A keepalive attempt has been started. The developer is responsible for stopping all keepalives. In some cases, keepalives will be automatically stopped -- however do not rely on that.*/ KEEPALIVE_FEEDBACK, /**< The keepalive process has obtained information regarding your NAT mapped address (or local address). Feedback events are sent with the mapped address from a STUN transaction or the rport results from a SIP transaction. */ KEEPALIVE_FAILURE, /**< FAILURE events are only fired when the physical send fails. The application developer should stop the keepalive or can monitor the keepalive until the condition changes (lack of failure or feedback event). */ KEEPALIVE_STOP /**< A keepalive process has been stopped. */ } SIPX_KEEPALIVE_EVENT ; /** * Enumeration of possible KEEPALIVE cause codes (EVENT_CATEGORY_KEEPALIVE) */ typedef enum SIPX_KEEPALIVE_CAUSE { KEEPALIVE_CAUSE_NORMAL } SIPX_KEEPALIVE_CAUSE ; /** * Keepalive event information structure. This information is passed as * part of the sipXtapi callback mechanism. Based on the * SIPX_KEEPALIVE_CATEGORY, the application developer should cast the pInfo * member of your callback to the appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_KEEPALIVE_INFO { size_t nSize ; /**< Size of the structure */ SIPX_KEEPALIVE_EVENT event ; /**< Keepalive event identifier. */ SIPX_KEEPALIVE_CAUSE cause ; /**< Keepalive cause */ SIPX_KEEPALIVE_TYPE type ; /**< Keepalive type */ const char* szRemoteAddress ; /**< Target IP/host where you are sending the keepalives */ int remotePort ; /**< Target port where you are sending the keepalives */ int keepAliveSecs ; /**< How often keepalives are being sent */ const char* szFeedbackAddress; /**< This UA's IP address as seen by the remote side (only valid in FEEDBACK events) */ int feedbackPort ; /**< This UA's port as seen by the remote side (only valid in FEEDBACK events) */ } SIPX_KEEPALIVE_INFO ; /** * Enumeration of possible media event causes. */ typedef enum SIPX_MEDIA_CAUSE { MEDIA_CAUSE_NORMAL, /**< Normal cause; the call was likely torn down.*/ MEDIA_CAUSE_HOLD, /**< Media state changed due to a local or remote hold operation */ MEDIA_CAUSE_UNHOLD, /**< Media state changed due to a local or remote unhold operation */ MEDIA_CAUSE_FAILED, /**< Media state changed due to an error condition. */ MEDIA_CAUSE_DEVICE_UNAVAILABLE, /**< Media state changed due to an error condition, (device was removed, already in use, etc). */ MEDIA_CAUSE_INCOMPATIBLE, /**< Incompatible destination -- We were unable to negotiate a codec */ MEDIA_CAUSE_DTMF_START, /**< A DTMF tone has started */ MEDIA_CAUSE_DTMF_STOP /**< A DTMF tone has stopped */ } SIPX_MEDIA_CAUSE ; /** * Enumeration of possible media event types. Today, MEDIA_TYPE_AUDIO and * MEDIA_TYPE_VIDEO are supported. */ typedef enum SIPX_MEDIA_TYPE { MEDIA_TYPE_AUDIO, /**< Audio media event type */ MEDIA_TYPE_VIDEO, /**< Video media event type */ } SIPX_MEDIA_TYPE ; /** * Media event information structure. This information is passed as part of * the sipXtapi callback mechanism. Based on the SIPX_EVENT_CATEGORY, the * application developer should cast the pInfo member of your callback to the * appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_MEDIA_INFO { size_t nSize ; /**< Size of the structure. */ SIPX_MEDIA_EVENT event ; /**< Media event identifier. See SIPX_MEDIA_EVENT for more information. */ SIPX_MEDIA_CAUSE cause ; /**< Media cause identifier. See SIPX_MEDIA_CAUSE for more information. */ SIPX_MEDIA_TYPE mediaType ; /**< Media type: Either MEDIA_TYPE_AUDIO or MEDIA_TYPE_VIDEO. */ SIPX_CALL hCall ; /**< Associate call (or SIPX_CALL_NULL if not associated with a call). */ SIPX_CODEC_INFO codec ; /**< Negotiated codec; only supplied on MEDIA_LOCAL_START and MEDIA_REMOTE_START events. */ int idleTime; /**< For MEDIA_REMOTE_SILENT events contains idle time (ms). For MEDIA_RECORDFILE_STOP and MEDIA_RECORDBUFFER_STOP events contains number of recorded samples. For other events this value should be ignored. For MEDIA_MIC_ENERGY_LEVEL contains energy level*/ SIPX_TONE_ID toneId; /**< DTMF tone received from remote party; only supplied on MEDIA_REMOTE_DTMF event). Note: Only RFC 2833 DTMF detection is supported (not in-band DTMF or dialtone detection, etc.)*/ } SIPX_MEDIA_INFO ; /** * Callstate event information structure. This information is passed as part of * the sipXtapi callback mechanism. Based on the SIPX_EVENT_CATEGORY, the * application developer should cast the pInfo member of your callback to the * appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_CALLSTATE_INFO { // TODO: Add a bitmask that identified which structure items are valid. For // example, codec and hAssociatedCall are only valid for certain event // sequences. size_t nSize; /**< The size of this structure. */ SIPX_CALL hCall; /**< Call handle associated with the callstate event. */ SIPX_LINE hLine; /**< Line handle associated with the callstate event. */ SIPX_CALLSTATE_EVENT event; /**< Callstate event enum code. Identifies the callstate event. */ SIPX_CALLSTATE_CAUSE cause; /**< Callstate cause enum code. Identifies the cause of the callstate event. */ SIPX_CALL hAssociatedCall ; /**< Call associated with this event. For example, when a new call is created as part of a consultative transfer, this handle contains the handle of the original call. */ } SIPX_CALLSTATE_INFO; /** * Linestate event information structure. This information is passed as part of * the sipXtapi callback mechanism. Based on the SIPX_EVENT_CATEGORY, the * application developer should cast the pInfo member of your callback to the * appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct { size_t nSize ; /**< The size of this structure. */ SIPX_LINE hLine; /**< Line handle associated with the linestate event. */ SIPX_LINESTATE_EVENT event ; /**< Callstate event enum code. Identifies the linestate event. */ SIPX_LINESTATE_CAUSE cause ; /**< Callstate cause enum code. Identifies the cause of the linestate event. */ } SIPX_LINESTATE_INFO ; /** * Major classifications of response statuses for a SIP message. */ typedef enum SIPX_MESSAGE_STATUS { SIPX_MESSAGE_OK, /**< The message was successfully processed (200) */ SIPX_MESSAGE_FAILURE, /**< The server received the message, but could or would not process it. */ SIPX_MESSAGE_SERVER_FAILURE, /**< The server encountered an error while trying to process the message. */ SIPX_MESSAGE_GLOBAL_FAILURE, /**< Fatal error encountered. */ } SIPX_MESSAGE_STATUS ; /** * An INFOSTATUS event informs that application layer of the status * of an outbound INFO requests. This information is passed as part of * the sipXtapi callback mechanism. Based on the SIPX_EVENT_CATEGORY, the * application developer should cast the pInfo member of your callback to the * appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_INFOSTATUS_INFO { size_t nSize ; /**< the size of this structure in bytes */ SIPX_INFO hInfo ; /**< the handle used to make the outbound info request. */ SIPX_MESSAGE_STATUS status ; /**< Emumerated status for this request acknowledgement. */ int responseCode ; /**< Numerical status code for this request acknowledgement. */ const char* szResponseText ; /**< The text of the request acknowledgement. */ SIPX_INFOSTATUS_EVENT event; /**< Event code for this INFO STATUS message */ } SIPX_INFOSTATUS_INFO ; /** * An INFO event signals the application layer that an INFO message * was sent to this user agent. If the INFO message was sent to a * call context (session) hCall will desiginate the call session. * * This information is passed as part of the sipXtapi callback mechanism. * Based on the SIPX_EVENT_CATEGORY, the application developer should cast the * pInfo member of your callback to the appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_INFO_INFO { size_t nSize ; /**< Size of structure */ SIPX_CALL hCall ; /**< Call handle if available */ SIPX_LINE hLine ; /**< Line handle if available */ const char* szFromURL ; /**< the URL of the host that originated the INFO message */ const char* szUserAgent; /**< the User Agent string of the source agent */ const char* szContentType ; /**< string indicating the info content type */ const char* pContent ; /**< pointer to the INFO message content */ size_t nContentLength ; /**< length of the INFO message content */ } SIPX_INFO_INFO ; /** * Enumeration of the possible subscription states visible to the client. */ typedef enum SIPX_SUBSCRIPTION_STATE { SIPX_SUBSCRIPTION_PENDING, /**< THe subscription is being set up, but not yet active. */ SIPX_SUBSCRIPTION_ACTIVE , /**< The subscription is currently active. */ SIPX_SUBSCRIPTION_FAILED , /**< The subscription is not active due to a failure.*/ SIPX_SUBSCRIPTION_EXPIRED , /**< The subscription's lifetime has expired. */ // TBD } SIPX_SUBSCRIPTION_STATE; /** * Enumeration of cause codes for state subscription state changes. */ typedef enum SIPX_SUBSCRIPTION_CAUSE { SUBSCRIPTION_CAUSE_UNKNOWN = -1, /**< No cause specified. */ SUBSCRIPTION_CAUSE_NORMAL /**< Normal cause for state change. */ } SIPX_SUBSCRIPTION_CAUSE; /** * An SUBSTATUS event informs that application layer of the status * of an outbound SUBSCRIPTION requests; * * This information is passed as part of the sipXtapi callback mechanism. * Based on the SIPX_EVENT_CATEGORY, the application developer should cast the * pInfo member of your callback to the appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_SUBSTATUS_INFO { size_t nSize ; /**< The size of this structure in bytes */ SIPX_SUB hSub ; /**< A handle to the subscription to which this state change occurred. */ SIPX_SUBSCRIPTION_STATE state ; /**< Enum state value indicating the current state of the subscription. */ SIPX_SUBSCRIPTION_CAUSE cause; /**< Enum cause for the state change in this event. */ const char* szSubServerUserAgent; /**< The User Agent header field value from the SIP SUBSCRIBE response (may be NULL) */ } SIPX_SUBSTATUS_INFO ; /** * A NOTIFY_INFO event signifies that a NOTIFY message was received for * an active subscription. * * This information is passed as part of the sipXtapi callback mechanism. * Based on the SIPX_EVENT_CATEGORY, the application developer should cast the * pInfo member of your callback to the appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_NOTIFY_INFO { size_t nSize ; /**< The size of this structure in bytes */ SIPX_SUB hSub ; /**< A handle to the subscrption which caused this NOTIFY event to be received. */ const char* szNotiferUserAgent; /**< The User-Agent header field value from the SIP NOTIFY response (may be NULL) */ const char* szContentType ; /**< String indicating the info content type */ const void* pContent ; /**< Pointer to the NOTIFY message content */ size_t nContentLength ; /**< Length of the NOTIFY message content in bytes */ } SIPX_NOTIFY_INFO ; /** * SIPX_CONFIG_INFO events signifies that a change in configuration was * observed. * * NOTE: This structure is subject to change. * * This information is passed as part of the sipXtapi callback mechanism. * Based on the SIPX_EVENT_CATEGORY, the application developer should cast the * pInfo member of your callback to the appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_CONFIG_INFO { size_t nSize ; /**< The size of this structure in bytes */ SIPX_CONFIG_EVENT event ; /**< Event code -- see SIPX_CONFIG_EVENT for details. */ void* pData; /**< Pointer to event data -- SEE SIPX_CONFIG_EVENT for details. */ } SIPX_CONFIG_INFO ; /** * An SIPX_SECURITY_INFO event informs that application layer of the status * of a security operation. * * This information is passed as part of the sipXtapi callback mechanism. * Based on the SIPX_EVENT_CATEGORY, the application developer should cast the * pInfo member of your callback to the appropriate structure. * * @see SIPX_EVENT_CALLBACK_PROC * @see SIPX_EVENT_CATEGORY */ typedef struct SIPX_SECURITY_INFO { size_t nSize ; /**< the size of this structure in bytes */ char* szSRTPkey; /**< the negotiated SRTP key, if any. */ void* pCertificate; /**< pointer to the certificate blob that was used to encrypt and/or sign. */ int nCertificateSize; /**< size of the certificate blob */ SIPX_SECURITY_EVENT event; /**< Event code for this SECURITY_INFO message */ SIPX_SECURITY_CAUSE cause; /**< Cause code for this SECURITY_INFO message*/ char* szSubjAltName; /**< Populated for SECURITY_CAUSE_SIGNATURE_NOTIFY.*/ char* callId; /**< Points to a call-id string associated with the event. Can be NULL. */ SIPX_CALL hCall; /**< A call handle associated with the event. Can be 0, to signify that the event is not associated with a call. */ char* remoteAddress; /**< A remote address associated with the event. Can be NULL. */ } SIPX_SECURITY_INFO ; /* ============================ FUNCTIONS ================================= */ /** * Duplicate the event information for a sipXtapi event. This method is only * needed if you wish to post the event information to another thread context. * Once the event has been handled, you must call sipxFreeDuplicatedEvent on * the copy to avoid memory leaks. * * @param category Category type supplied by the sipXtapi event callback. * @param pEventSource Source of event data supplied by the sipXtapi event * callback. * @param pEventCopy New copy of the event data. This data must be freed * by calling sipxFreeDuplicatedEvent. */ SIPXTAPI_API SIPX_RESULT sipxDuplicateEvent(SIPX_EVENT_CATEGORY category, const void* pEventSource, void** pEventCopy) ; /** * Frees up memory allocated as part of sipxDuplicateEvent. Do not call this * API on pointers received as part of the sipXtapi call back. * * @param category Category type supplied by the sipXtapi event callback. * @param pEventCopy Copy of event data supplied by sipxDuplicateEvent. */ SIPXTAPI_API SIPX_RESULT sipxFreeDuplicatedEvent(SIPX_EVENT_CATEGORY category, void* pEventCopy) ; /** * Add a callback/observer for the purpose of receiving sipXtapi events * * @param hInst Instance pointer obtained by sipxInitialize. * @param pCallbackProc Function to receive sipx events * @param pUserData user data passed along with event data */ SIPXTAPI_API SIPX_RESULT sipxEventListenerAdd(const SIPX_INST hInst, SIPX_EVENT_CALLBACK_PROC pCallbackProc, void *pUserData); /** * Remove a sipXtapi event callback/observer. Supply the same * pCallbackProc and pUserData values as sipxEventListenerAdd. * * @param hInst Instance pointer obtained by sipxInitialize. * @param pCallbackProc Function used to receive sipx events * @param pUserData user data specified as part of sipxListenerAdd */ SIPXTAPI_API SIPX_RESULT sipxEventListenerRemove(const SIPX_INST hInst, SIPX_EVENT_CALLBACK_PROC pCallbackProc, void* pUserData) ; /* ============================ FUNCTIONS ================================= */ /** * Create a printable string version of the designated call state event ids. * This is generally used for debugging. * * @param event sipxtapi event code * @param cause sipxtapi cause event code * @param szBuffer buffer to store event string * @param nBuffer length of string buffer szBuffer */ SIPXTAPI_API char* sipxCallEventToString(SIPX_CALLSTATE_EVENT event, SIPX_CALLSTATE_CAUSE cause, char* szBuffer, size_t nBuffer) ; /** * Create a printable string version of the designated event. * This is generally used for debugging. * * @param category Event category code * @param pEvent Pointer to the Event. * @param szBuffer buffer to store event string * @param nBuffer length of string buffer szBuffer */ SIPXTAPI_API char* sipxEventToString(const SIPX_EVENT_CATEGORY category, const void* pEvent, char* szBuffer, size_t nBuffer); /** * Create a printable string version of the designated line event ids. * This is generally used for debugging. * * @deprecated Use sipxEventToString instead. * @param event major event type id * @param cause event type id * @param szBuffer buffer to store event string * @param nBuffer length of string buffer szBuffer */ SIPXTAPI_API char* sipxLineEventToString(SIPX_LINESTATE_EVENT event, SIPX_LINESTATE_CAUSE cause, char* szBuffer, size_t nBuffer); /** * Create a printable string version of the designated config event. * This is generally used for debugging. * * @param event Configuration event id * @param szBuffer Buffer to store event string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxConfigEventToString(SIPX_CONFIG_EVENT event, char* szBuffer, size_t nBuffer) ; /** * Create a printable string version of the designated subscription status state. * This is generally used for debugging. * * @param state Subscription state id * @param szBuffer Buffer to store event string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxSubStatusStateToString(SIPX_SUBSCRIPTION_STATE state, char* szBuffer, size_t nBuffer) ; /** * Create a printable string version of the designated subscription status cause. * This is generally used for debugging. * * @param cause Subscription cause id * @param szBuffer Buffer to store event string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxSubStatusCauseToString(SIPX_SUBSCRIPTION_CAUSE cause, char* szBuffer, size_t nBuffer) ; /** * Create a printable string version of the designated security event. * This is generally used for debugging. * * @param event Security event id * @param szBuffer Buffer to store event string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxSecurityEventToString(SIPX_SECURITY_EVENT event, char* szBuffer, size_t nBuffer); /** * Create a printable string version of the designated security cause. * This is generally used for debugging. * * @param cause Security cause id * @param szBuffer Buffer to store cause string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxSecurityCauseToString(SIPX_SECURITY_CAUSE cause, char* szBuffer, size_t nBuffer); /** * Create a printable string version of the designated media event. * This is generally used for debugging. * * @param event Media event id * @param szBuffer Buffer to store event string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxMediaEventToString(SIPX_MEDIA_EVENT event, char* szBuffer, size_t nBuffer); /** * Create a printable string version of the designated media cause. * This is generally used for debugging. * * @param cause Media cause id * @param szBuffer Buffer to store cause string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxMediaCauseToString(SIPX_MEDIA_CAUSE cause, char* szBuffer, size_t nBuffer); /** * Create a printable string version of the designated keepalive event. * This is generally used for debugging. * * @param event Keepalive event id * @param szBuffer Buffer to store event string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxKeepaliveEventToString(SIPX_KEEPALIVE_EVENT event, char* szBuffer, size_t nBuffer); /** * Create a printable string version of the designated keepalive cause. * This is generally used for debugging. * * @param cause Keepalive cause id * @param szBuffer Buffer to store cause string * @param nBuffer Length of string buffer szBuffer */ SIPXTAPI_API char* sipxKeepaliveCauseToString(SIPX_KEEPALIVE_CAUSE cause, char* szBuffer, size_t nBuffer); #endif /* ifndef _sipXtapiEvents_h_ */ sipxtapi-3.3.0~test17/sipXcallLib/include/tapi/sipXtapiInternal.h0000644000175000017500000010101412205613256025632 0ustar00danieldaniel00000000000000// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _SIPXTAPIINTERNAL_H /* [ */ #define _SIPXTAPIINTERNAL_H // SYSTEM INCLUDES // APPLICATION INCLUDES #include "tapi/sipXtapi.h" #include "tapi/SipXMessageObserver.h" #ifdef VOICE_ENGINE # include "tapi/GipsDefs.h" #endif #include "net/SipSession.h" #include "net/SipUserAgent.h" #include "net/SipSubscribeClient.h" #include "utl/UtlDefs.h" #include "utl/UtlContainable.h" #include "os/OsRWMutex.h" #include "os/OsReadLock.h" #include "os/OsWriteLock.h" #include "os/OsSysLog.h" #include "os/OsMutex.h" #include "os/OsMsgQ.h" #include "os/OsNatKeepaliveListener.h" // DEFINES /** sipXtapi can be configured to expire after a certain date */ //#define SIPXTAPI_EVAL_EXPIRATION #ifdef SIPXTAPI_EVAL_EXPIRATION # define EVAL_EXPIRE_MONTH 0 // zero based # define EVAL_EXPIRE_DAY 31 # define EVAL_EXPIRE_YEAR 2006 #endif // MACROS // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // FORWARD DECLARATIONS class SipSubscribeServer; class SipSubscribeClient; class CallManager ; class SipUserAgent ; class SipRefreshMgr ; class KeepaliveEventDispatcher; class SipXEventDispatcher; class CpMediaInterface; // STRUCTS // TYPEDEFS typedef struct MIC_SETTING { bool bInitialized ; /**< Is the data valid */ bool bMuted ; /**< Muted state (regain gain) */ int iGain ; /**< Gain setting (GAIN_MIN-GAIN_MAX) */ char device[MAX_VIDEO_DEVICE_LENGTH]; /**< Desired auto device */ } MIC_SETTING ; typedef struct SPEAKER_SETTING { bool bInitialized ; /**< Is the data valid */ int iVol ; /**< Gain setting (VOLUME_MIN-VOLUME_MAX) */ char device[MAX_VIDEO_DEVICE_LENGTH]; /**< Desired auto device */ } SPEAKER_SETTING ; typedef struct AEC_SETTING { bool bInitialized ; /**< Is the data valid */ SIPX_AEC_MODE mode ; /**< Is AEC enabled? */ } AEC_SETTING ; typedef struct AGC_SETTING { bool bInitialized ; /**< Is the data valid */ bool bEnabled; /**< Is AGC enabled? */ } AGC_SETTING ; typedef struct NOISE_REDUCTION_SETTING { bool bInitialized ; /**< Is the data valid */ SIPX_NOISE_REDUCTION_MODE mode ; /**< Is NR enabled? */ } NOISE_REDUCTION_SETTING ; typedef struct AUDIO_CODEC_PREFERENCES { bool bInitialized; /**< Is the data valid */ int numCodecs; /**< Number of codecs */ SIPX_AUDIO_BANDWIDTH_ID codecPref; /**< Numeric Id of codec preference */ SIPX_AUDIO_BANDWIDTH_ID fallBack; /**< Fallback id if codec setting fails */ UtlString* pPreferences; /**< List of preferred codecs */ SdpCodec** sdpCodecArray; /**< Pointer to an array of codecs */ } AUDIO_CODEC_PREFERENCES; typedef struct VIDEO_CODEC_PREFERENCES { bool bInitialized; /**< Is the data valid */ int numCodecs; /**< Number of codecs */ SIPX_VIDEO_BANDWIDTH_ID codecPref; /**< Numeric Id of codec preference */ SIPX_VIDEO_BANDWIDTH_ID fallBack; /**< Fallback id if codec setting fails */ UtlString* pPreferences; /**< List of preferred codecs */ SdpCodec** sdpCodecArray; /**< Pointer to an array of codecs */ } VIDEO_CODEC_PREFERENCES; typedef struct TONE_STATES { bool bInitialized; // bool tonePlaying; } TONE_STATES; typedef struct SIPX_INSTANCE_DATA { SipUserAgent* pSipUserAgent ; SdpCodecList* pCodecFactory ; CallManager* pCallManager ; SipLineMgr* pLineManager ; SipRefreshMgr* pRefreshManager ; SipSubscribeServer* pSubscribeServer; SipSubscribeClient* pSubscribeClient; SipRefreshManager* pSipRefreshManager ; SipDialogMgr* pDialogManager ; MIC_SETTING micSetting ; SPEAKER_SETTING speakerSettings[2] ; AEC_SETTING aecSetting ; AGC_SETTING agcSetting ; NOISE_REDUCTION_SETTING nrSetting ; SPEAKER_TYPE enabledSpeaker ; AUDIO_CODEC_PREFERENCES audioCodecSetting; VIDEO_CODEC_PREFERENCES videoCodecSetting; TONE_STATES toneStates; SipXEventDispatcher* pEventDispatcher; char* inputAudioDevices[MAX_AUDIO_DEVICES] ; char* outputAudioDevices[MAX_AUDIO_DEVICES] ; SipXMessageObserver* pMessageObserver; OsNotification *pStunNotification ; /**< Signals the initial stun success/failure when calling sipXconfigEnableStun */ OsMutex* pLock ; int nCalls ; /**< Counter for inprocess calls */ int nConferences ; /**< Counter for inprocess conferences */ int nLines ; /**< Counter for inprocess lines */ void* pVoiceEngine; /**< Cache VoiceEngine pointer */ char dbLocation[256]; /**< Cache cert db location > */ char myCertNickname[32]; /**< Cache certificate nickname > */ char dbPassword[32]; /**< Cache cert db password > */ bool bShortNames; /**< short names in sip messages >*/ bool bAllowHeader; /**< use allow header in sip messages>*/ bool bDateHeader; /**< use Date header in sip messages>*/ char szAcceptLanguage[16]; /**< accept language to use in sip messages>*/ char szLocationHeader[256]; /**< location header */ bool bRtpOverTcp; /**< allow RTP over TCP */ int nEnergyLevelNotificationPeriodMs; /**< period of time between each stream energy level notification>*/ KeepaliveEventDispatcher* pKeepaliveDispatcher ; } SIPX_INSTANCE_DATA ; typedef enum SIPX_INTERNAL_CALLSTATE { SIPX_INTERNAL_CALLSTATE_UNKNOWN = 0, /** Unknown call state */ SIPX_INTERNAL_CALLSTATE_OUTBOUND_ATTEMPT, /** Early dialog: outbound */ SIPX_INTERNAL_CALLSTATE_INBOUND_ATEMPT, /** Early dialog: inbound */ SIPX_INTERNAL_CALLSTATE_CONNECTED, /** Active call - remote audio */ SIPX_INTERNAL_CALLSTATE_HELD, /** both on hold due to a local hold */ SIPX_INTERNAL_CALLSTATE_REMOTE_HELD, /** Remotely held call */ SIPX_INTERNAL_CALLSTATE_BRIDGED, /** Locally held call, bridging */ SIPX_INTERNAL_CALLSTATE_DISCONNECTED, /** Disconnected or failed */ SIPX_INTERNAL_CALLSTATE_DESTROYING, /** In the process of being destroyed */ } SIPX_INTERNAL_CALLSTATE ; typedef struct SIPX_CALL_DATA { UtlString* callId; UtlString* sessionCallId; UtlString* ghostCallId; UtlString* remoteAddress ; UtlString* lineURI ; UtlString* contactAddress ; SIPX_LINE hLine ; SIPX_INSTANCE_DATA* pInst ; OsRWMutex* pMutex ; SIPX_CONF hConf ; SIPX_SECURITY_ATTRIBUTES security; SIPX_VIDEO_DISPLAY display; UtlBoolean bRemoveInsteadOfDrop ; /** Remove the call instead of dropping it -- this is used as part of consultative transfer when we are the transfer target and need to replace a call leg within the same CpPeerCall. */ SIPX_CALLSTATE_EVENT lastCallstateEvent ; SIPX_CALLSTATE_CAUSE lastCallstateCause ; SIPX_MEDIA_EVENT lastLocalMediaAudioEvent ; SIPX_MEDIA_EVENT lastLocalMediaVideoEvent ; SIPX_MEDIA_EVENT lastRemoteMediaAudioEvent ; SIPX_MEDIA_EVENT lastRemoteMediaVideoEvent ; SIPX_INTERNAL_CALLSTATE state ; UtlBoolean bInFocus ; int connectionId; /** Cache the connection id */ SIPX_TRANSPORT hTransport; bool bHoldAfterConnect; /** Used if we are the transfer target, and the replaced call is HELD or REMOTE_HELD, then this flag is set, and indicates that the call should be placed on hold after the connection is established. */ bool bCallHoldInvoked; /** Set to true if sipxCallHold has been invoked. Set to fales if sipxCallUnhold has been invoked. */ bool bTonePlaying; int nFilesPlaying; } SIPX_CALL_DATA ; typedef enum CONF_HOLD_STATE { CONF_STATE_UNHELD = 0, CONF_STATE_BRIDGING_HOLD, CONF_STATE_NON_BRIDGING_HOLD } CONF_HOLD_STATE; typedef struct { UtlString strCallId ; SIPX_INSTANCE_DATA* pInst ; size_t nCalls ; SIPX_CALL hCalls[CONF_MAX_CONNECTIONS] ; CONF_HOLD_STATE confHoldState; SIPX_TRANSPORT hTransport; int nNumFilesPlaying; OsRWMutex* pMutex ; } SIPX_CONF_DATA ; typedef struct { Url* lineURI ; SIPX_INSTANCE_DATA* pInst ; OsRWMutex* pMutex ; SIPX_CONTACT_TYPE contactType ; UtlSList* pLineAliases ; SIPX_CONTACT_ID contactId ; } SIPX_LINE_DATA ; typedef struct { SIPX_INFO_INFO infoData; SIPX_INSTANCE_DATA* pInst; SipSession* pSession; OsRWMutex* pMutex; } SIPX_INFO_DATA; typedef struct { SIPX_INSTANCE_DATA* pInst; UtlString* pResourceId; UtlString* pEventType; HttpBody* pContent; OsRWMutex* pMutex; } SIPX_PUBLISH_DATA; typedef struct { SIPX_INSTANCE_DATA* pInst; UtlString* pDialogHandle; OsRWMutex* pMutex; } SIPX_SUBSCRIPTION_DATA; #define MAX_TRANSPORT_NAME 32 class SIPX_TRANSPORT_DATA { public: SIPX_TRANSPORT_DATA() { pInst = NULL; bIsReliable = false; iLocalPort = -1; pFnWriteProc = NULL; pMutex = NULL; hTransport = 0; pUserData = NULL; bRouteByUser = true; memset(szLocalIp, 0, sizeof(szLocalIp)); memset(szTransport, 0, sizeof(szTransport)); memset(cRoutingId, 0, sizeof(cRoutingId)) ; } /** Copy constructor. */ SIPX_TRANSPORT_DATA(const SIPX_TRANSPORT_DATA& ref) { copy(ref); } /** Assignment operator. */ SIPX_TRANSPORT_DATA& operator=(const SIPX_TRANSPORT_DATA& ref) { // check for assignment to self if (this == &ref) return *this; return copy(ref); } SIPX_TRANSPORT_DATA& copy(const SIPX_TRANSPORT_DATA& ref) { hTransport = ref.hTransport; pInst = ref.pInst; bIsReliable = ref.bIsReliable; memset(szTransport, 0, sizeof(szTransport)) ; strncpy(szTransport, ref.szTransport, MAX_TRANSPORT_NAME - 1); memset(szLocalIp, 0, sizeof(szLocalIp)) ; strncpy(szLocalIp, ref.szLocalIp, sizeof(szLocalIp)-1); memset(cRoutingId, 0, sizeof(cRoutingId)) ; strncpy(cRoutingId, ref.cRoutingId, sizeof(cRoutingId)-1); iLocalPort = ref.iLocalPort; pFnWriteProc = ref.pFnWriteProc; pUserData = ref.pUserData ; bRouteByUser = ref.bRouteByUser; return *this; } static const bool isCustomTransport(const SIPX_TRANSPORT_DATA* const pTransport) { bool bRet = false; if (pTransport) { if (strlen(pTransport->szTransport) > 0) { bRet = true; } } return bRet; } SIPX_TRANSPORT hTransport; SIPX_INSTANCE_DATA* pInst; bool bIsReliable; char szTransport[MAX_TRANSPORT_NAME]; char szLocalIp[32]; int iLocalPort; SIPX_TRANSPORT_WRITE_PROC pFnWriteProc; OsRWMutex* pMutex; const void* pUserData; char cRoutingId[64] ; bool bRouteByUser; } ; /** * internal sipXtapi structure that binds a * an event callback proc * with an instance pointer and user data */ typedef struct { SIPX_EVENT_CALLBACK_PROC pCallbackProc; void* pUserData; SIPX_INSTANCE_DATA* pInst; } EVENT_LISTENER_DATA; typedef enum SIPX_LOCK_TYPE { SIPX_LOCK_NONE, SIPX_LOCK_READ, SIPX_LOCK_WRITE } SIPX_LOCK_TYPE ; /* ============================ FUNCTION POINTER DEFINITIONS =============== */ typedef void (*sipxCallEventCallbackFn)(const void* pSrc, const char* szCallId, SipSession* pSession, const char* szRemoteAddress, SIPX_CALLSTATE_EVENT event, SIPX_CALLSTATE_CAUSE cause, void* pEventData, const char* assertedIdentity); typedef void (*sipxMediaCallbackFn)(const void* pSrc, const char* szCallId, const char* szRemoteAddress, SIPX_MEDIA_EVENT event, SIPX_MEDIA_CAUSE cause, SIPX_MEDIA_TYPE type, void* pEventData); typedef void (*sipxLineEventCallbackFn)(const void* pSrc, const char* szLineIdentifier, SIPX_LINESTATE_EVENT event, SIPX_LINESTATE_CAUSE cause, const char *bodyBytes); typedef bool (*sipxEventCallbackFn)(const void* pSrc, SIPX_EVENT_CATEGORY category, void* pInfo); /* ============================ FUNCTIONS ================================= */ /** * Disable all listener callbacks -- events will be dropped */ void sipxDisableListeners() ; /** * Enable all listener callbacks (default setting) */ void sipxEnableListeners() ; /** * Destroy all calls and send simulated DESTROY events */ void sipxCallDestroyAll(const SIPX_INST hInst) ; /** * Remove/Destroy all Conferences */ void sipxConferenceDestroyAll(const SIPX_INST hInst) ; /** * Remove/Destroy all Lines */ void sipxLineRemoveAll(const SIPX_INST hInst) ; /** * Remove/Destroy all Publishers */ void sipxPublisherDestroyAll(const SIPX_INST hInst) ; /** * Remove/Destroy all subscriptions */ void sipxSubscribeDestroyAll(const SIPX_INST hInst) ; /** * Fire events to interested listeners (call events only). */ void sipxFireCallEvent(const void* pSrc, const char* szCallId, SipSession* pSession, const char* szRemoteAddress, SIPX_CALLSTATE_EVENT event, SIPX_CALLSTATE_CAUSE cause, void* pEventData=NULL, const char* szRemoteAssertedIdentity = NULL) ; /** * Fires events to interested listener (media events only) */ void sipxFireMediaEvent(const void* pSrc, const char* szCallId, const char* szRemoteAddress, SIPX_MEDIA_EVENT event, SIPX_MEDIA_CAUSE cause, SIPX_MEDIA_TYPE type, void* pEventData = NULL) ; /** * Fires events to interested listener (keepalive events only) */ void sipxFireKeepaliveEvent(const void* pSrc, SIPX_KEEPALIVE_EVENT event, SIPX_KEEPALIVE_CAUSE cause, SIPX_KEEPALIVE_TYPE type, const char* szRemoteAddress, int remotePort, int keepAliveSecs, const char* szMappedAddress, int mappedPort) ; /** * Fires a Line Event to the listeners. */ void sipxFireLineEvent(const void* pSrc, const char* szLineIdentifier, SIPX_LINESTATE_EVENT event, SIPX_LINESTATE_CAUSE cause, const char *bodyBytes = NULL); /** * Bubbles up all non-line and non-call events to the application layer */ bool sipxFireEvent(const void* pSrc, SIPX_EVENT_CATEGORY category, void* pInfo); SIPX_INSTANCE_DATA* findSessionByCallManager(const void* pCallManager) ; SIPX_CALL_DATA* sipxCallLookup(const SIPX_CALL hCall, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); void sipxCallReleaseLock(SIPX_CALL_DATA*, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); void sipxCallObjectFree(const SIPX_CALL hCall, const OsStackTraceLogger& oneBackInStack); SIPX_CALL sipxCallLookupHandle(const UtlString& callID, const void* pSrc); void destroyCallData(SIPX_CALL_DATA* pData); UtlBoolean validCallData(SIPX_CALL_DATA* pData); UtlBoolean sipxCallGetCommonData(SIPX_CALL hCall, SIPX_INSTANCE_DATA** pInst, UtlString* pStrCallId, UtlString* pStrRemoteAddress, UtlString* pLineId, UtlString* pGhostCallId = NULL, UtlString* pContactAddress = NULL) ; SIPX_CONF sipxCallGetConf(SIPX_CALL hCall) ; SIPXTAPI_API UtlBoolean sipxCallGetState(SIPX_CALL hCall, SIPX_CALLSTATE_EVENT& lastEvent, SIPX_CALLSTATE_CAUSE& lastCause, SIPX_INTERNAL_CALLSTATE& state) ; UtlBoolean sipxCallGetMediaState(SIPX_CALL hCall, SIPX_MEDIA_EVENT& lastLocalMediaAudioEvent, SIPX_MEDIA_EVENT& lastLocalMediaVideoEvent, SIPX_MEDIA_EVENT& lastRemoteMediaAudioEvent, SIPX_MEDIA_EVENT& lastRemoteMediaVideoEvent) ; UtlBoolean sipxCallSetMediaState(SIPX_CALL hCall, SIPX_MEDIA_EVENT event, SIPX_MEDIA_TYPE type) ; UtlBoolean sipxCallSetState(SIPX_CALL hCall, SIPX_CALLSTATE_EVENT event, SIPX_CALLSTATE_CAUSE cause) ; SIPX_CONTACT_TYPE sipxCallGetLineContactType(SIPX_CALL hCall) ; SIPX_LINE_DATA* sipxLineLookup(const SIPX_LINE hLine, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); void sipxLineReleaseLock(SIPX_LINE_DATA* pData, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); void sipxLineObjectFree(const SIPX_LINE hLine) ; SIPX_LINE sipxLineLookupHandle(const char* szLineURI, const char* requestUri); SIPX_LINE sipxLineLookupHandleByURI(const char* szURI); UtlBoolean validLineData(const SIPX_LINE_DATA*) ; UtlBoolean sipxAddCallHandleToConf(const SIPX_CALL hCall, const SIPX_CONF hConf) ; UtlBoolean sipxRemoveCallHandleFromConf(const SIPX_CONF hConf, const SIPX_CALL hCall) ; SIPX_CONF_DATA* sipxConfLookup(const SIPX_CONF hConf, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); void sipxConfReleaseLock(SIPX_CONF_DATA* pData, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); void sipxConfFree(const SIPX_CONF hConf) ; UtlBoolean validConfData(const SIPX_CONF_DATA* pData) ; void sipxIncSessionCount(); void sipxDecSessionCount(); int sipxGetSessionCount(); UtlBoolean sipxIsCallInFocus() ; SIPXTAPI_API SIPX_RESULT sipxStructureIntegrityCheck(); const char* sipxContactTypeToString(SIPX_CONTACT_TYPE type) ; const char* sipxTransportTypeToString(SIPX_TRANSPORT_TYPE type) ; /** * Frees the INFO structure allocated by a call to sipxCallSendInfo * * @param pData Pointer to SIPX_INFO_DATA structure */ void sipxInfoFree(SIPX_INFO_DATA* pData); /** * Releases the INFO handle created by a call to sipxCallSendInfo. * Also cals sipxInfoFree. * * @param hInfo Handle to the Info object */ void sipxInfoObjectFree(SIPX_INFO hInfo); /** * Frees the TRANSPORT structure allocated by a call to sipxConfigExternalTransportAdd * * @param pData Pointer to SIPX_TRANSPORT_DATA structure */ void sipxTransportFree(SIPX_TRANSPORT_DATA* pData); /** * Releases the TRANSPORT handle created sipxConfigExternalTransportAdd * Also cals sipxTransportFree. * * @param hInfo Handle to the Transport object */ void sipxTransportObjectFree(SIPX_TRANSPORT hTransport); void sipxGetContactHostPort(SIPX_INSTANCE_DATA* pData, SIPX_CONTACT_TYPE contactType, Url& uri, SIPX_TRANSPORT_TYPE protocol) ; //: Get the external host and port given the contact preference /** * Looks up the SIPX_INFO_DATA structure pointer, given the SIPX_INFO handle. * @param hInfo Info Handle * @param type Lock type to use during lookup. */ SIPX_INFO_DATA* sipxInfoLookup(const SIPX_INFO hInfo, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); /** * Unlocks the mutex associated with the INFO DATA * * @param pData pointer to the SIPX_INFO structure * @param type Type of lock (read or write) */ void sipxInfoReleaseLock(SIPX_INFO_DATA* pData, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); SIPX_PUBLISH_DATA* sipxPublishLookup(const SIPX_PUB hPub, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); void sipxPublishReleaseLock(SIPX_PUBLISH_DATA* pData, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); SIPX_SUBSCRIPTION_DATA* sipxSubscribeLookup(const SIPX_SUB hSub, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); void sipxSubscribeReleaseLock(SIPX_SUBSCRIPTION_DATA* pData, SIPX_LOCK_TYPE type, const OsStackTraceLogger& oneBackInStack); /** * Looks up the SIPX_TRANSPORT_DATA structure pointer, given the SIPX_TRANSPORT handle. * @param hTransport Transport Handle * @param type Lock type to use during lookup. */ SIPX_TRANSPORT_DATA* sipxTransportLookup(const SIPX_TRANSPORT hTransport, SIPX_LOCK_TYPE type); /** * Unlocks the mutex associated with the TRANSPORT DATA * * @param pData pointer to the SIPX_TRANSPORT structure * @param type Type of lock (read or write) */ void sipxTransportReleaseLock(SIPX_TRANSPORT_DATA* pData, SIPX_LOCK_TYPE type); /** * Destroy all external transports for a given instance */ void sipxTransportDestroyAll(const SIPX_INST hInst) ; /** * Adds a log entry to the system log - made necessary to add logging * capability on the API level. * * @param logLevel priority of the log entry * @param format a format string for the following variable argument list */ SIPXTAPI_API void sipxLogEntryAdd(OsSysLogPriority logLevel, const char *format, ...); /** * Utility function for setting allowed methods on a * instance's user-agent. */ SIPXTAPI_API SIPX_RESULT sipxConfigAllowMethod(const SIPX_INST hInst, const char* method, const bool bAllow = true); /** * Get the list of active calls for the specified call manager instance */ SIPXTAPI_API SIPX_RESULT sipxGetActiveCallIds(SIPX_INST hInst, int maxCalls, int& actualCalls, UtlString callIds[]) ; /** * Callback for subscription client state */ void sipxSubscribeClientSubCallback(enum SipSubscribeClient::SubscriptionState newState, const char* earlyDialogHandle, const char* dialogHandle, void* applicationData, int responseCode, const char* responseText, long expiration, const SipMessage* subscribeResponse); /** * Callback for subscription client NOTIFY content */ void sipxSubscribeClientNotifyCallback(const char* earlyDialogHandle, const char* dialogHandle, void* applicationData, const SipMessage* notifyRequest); /** * Look for leaks in internal handles */ SIPXTAPI_API SIPX_RESULT sipxCheckForHandleLeaks() ; /** * Flush handles to remove peaks between test cases -- this *WILL* leak * memory. */ SIPXTAPI_API SIPX_RESULT sipxFlushHandles() ; /** * Translate tone ids to implementation specific codes * * @param toneId sipx-internal tone id * @param xlateId implementation-specific tone id */ SIPXTAPI_API SIPX_RESULT sipxTranslateToneId(const SIPX_TONE_ID toneId, SIPX_TONE_ID& xlateId) ; /** * Gets an CpMediaInterface pointer, associated with the call connection. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. * @param ppInstData pointer to a memory address that is set to the media interface * pointer. */ SIPXTAPI_API SIPX_RESULT sipxCallGetConnectionMediaInterface(const SIPX_CALL hCall, void** ppInstData); /** * Returns the 'local' connection id * * @param hInst Instance pointer obtained by sipxInitialize */ SIPXTAPI_API SIPX_RESULT sipxConfigGetLocalAudioConnectionId(const SIPX_INST hInst, int& connectionId); #ifdef VOICE_ENGINE /** * For Gips VoiceEngine versions of sipXtapi, this method will * return the GipsVoiceEngineLib pointer associated with the * call. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. */ SIPXTAPI_API GipsVoiceEngineLib* sipxCallGetVoiceEnginePtr(const SIPX_CALL hCall); /** * For Gips VoiceEngine versions of sipXtapi, this method will * return the GipsVoiceEngineLib pointer associated with the * factory implementation. * * @param hInst Instance pointer obtained by sipxInitialize */ SIPXTAPI_API GipsVoiceEngineLib* sipxConfigGetVoiceEnginePtr(const SIPX_INST hInst); #ifdef _WIN32 /** * For Gips VoiceEngine versions of sipXtapi, this method will * return a Audio Tuning Wizard pointer associated with the * factory implementation. * * @param hInst Instance pointer obtained by sipxInitialize */ SIPXTAPI_API GIPSAECTuningWizard* sipxConfigGetVoiceEngineAudioWizard(); #endif #ifdef VIDEO /** * For Gips VideoEngine versions of sipXtapi, this method will * return the GipsVideoEngine[Windows|Mac] pointer associated with * the factory implementation. * * @param hInst Instance pointer obtained by sipxInitialize */ SIPXTAPI_API GipsVideoEnginePlatform* sipxConfigGetVideoEnginePtr(const SIPX_INST hInst); #endif VIDEO /** * For Gips VoiceEngine versions of sipXtapi, this method will * creates a Local Audio connection, which can be used to play * media files. * * @param hInst Instance pointer obtained by sipxInitialize */ SIPXTAPI_API SIPX_RESULT sipxCreateLocalAudioConnection(const SIPX_INST hInst); /** * For Gips VoiceEngine versions of sipXtapi, this method will * destroys the Local Audio connection, which was created by a * call to sipxCreateLocalAudioConnection. * * @param hInst Instance pointer obtained by sipxInitialize */ SIPXTAPI_API SIPX_RESULT sipxDestroyLocalAudioConnection(const SIPX_INST hInst); /** * For Gips VoiceEngine versions of sipXtapi, this method will * enable or disable insertion of VoiceEngine trace output into the * sipXtapi log. * * @param hInst Instance pointer obtained by sipxInitialize * @param bEnable Enable or disable VoceEngine trace output */ SIPXTAPI_API SIPX_RESULT sipxEnableAudioLogging(const SIPX_INST hInst, bool bEnable); #else /* not VoiceEngine */ /** * Get pointer to Sipx media interface for call. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. */ SIPXTAPI_API CpMediaInterface* sipxCallGetCpMediaInterface(const SIPX_CALL hCall); /** * Get pointer to Sipx media control message queue for call. * * @param hCall Handle to a call. Call handles are obtained either by * invoking sipxCallCreate or passed to your application through * a listener interface. */ SIPXTAPI_API OsMsgQ* sipxCallGetMediaConrolQueue(const SIPX_CALL hCall); #endif UtlBoolean sipxCallSetRemoveInsteadofDrop(SIPX_CALL hCall) ; UtlBoolean sipxCallIsRemoveInsteadOfDropSet(SIPX_CALL hCall) ; SIPX_RESULT __sipxEventListenerAdd(const SIPX_INST hInst, SIPX_EVENT_CALLBACK_PROC pCallbackProc, void *pUserData) ; SIPX_RESULT __sipxEventListenerRemove(const SIPX_INST hInst, SIPX_EVENT_CALLBACK_PROC pCallbackProc, void* pUserData) ; void sipxUpdateListeners(SIPX_INST hOldInst, SIPX_INST hNewInst) ; /** * Dynamically loads the following NSS runtime libraries, if they can be found: * smime3.dll;nss3.dll;nspr4.dll;plc4.dll * * @returns SIPX_RESULT_SUCCESS if all NSS libraries were loaded. Otherwise, * SIPX_RESULT_MISSING_RUNTIME_FILES is returned. * */ SIPXTAPI_API SIPX_RESULT sipxConfigLoadSecurityRuntime(); /** * Called from sipxConfigExternalTransportAdd, this function creates * LOCAL, STUN, and RELAY contact records for the newly added * transport mechanism. */ void sipxCreateExternalTransportContacts(const SIPX_TRANSPORT_DATA* pData); class SecurityHelper { public: void generateSrtpKey(SIPX_SECURITY_ATTRIBUTES& securityAttrib); void setDbLocation(SIPX_SECURITY_ATTRIBUTES& securityAttrib, const char* dbLocation); void setMyCertNickname(SIPX_SECURITY_ATTRIBUTES& securityAttrib, const char* myCertNickname); void setDbPassword(SIPX_SECURITY_ATTRIBUTES& securityAttrib, const char* dbPassword); }; class KeepaliveEventDispatcher : public OsNatKeepaliveListener { public: KeepaliveEventDispatcher(void* pSrc) : OsNatKeepaliveListener() { m_pSrc = pSrc ; } ; virtual ~KeepaliveEventDispatcher() {} ; virtual void OnKeepaliveStart(const OsNatKeepaliveEvent& event) { sipxFireKeepaliveEvent(m_pSrc, KEEPALIVE_START, KEEPALIVE_CAUSE_NORMAL, (SIPX_KEEPALIVE_TYPE) event.type, event.remoteAddress, event.remotePort, event.keepAliveSecs, event.mappedAddress, event.mappedPort) ; } virtual void OnKeepaliveStop(const OsNatKeepaliveEvent& event) { sipxFireKeepaliveEvent(m_pSrc, KEEPALIVE_STOP, KEEPALIVE_CAUSE_NORMAL, (SIPX_KEEPALIVE_TYPE) event.type, event.remoteAddress, event.remotePort, event.keepAliveSecs, event.mappedAddress, event.mappedPort) ; } virtual void OnKeepaliveFeedback(const OsNatKeepaliveEvent& event) { sipxFireKeepaliveEvent(m_pSrc, KEEPALIVE_FEEDBACK, KEEPALIVE_CAUSE_NORMAL, (SIPX_KEEPALIVE_TYPE) event.type, event.remoteAddress, event.remotePort, event.keepAliveSecs, event.mappedAddress, event.mappedPort) ; } virtual void OnKeepaliveFailure(const OsNatKeepaliveEvent& event) { sipxFireKeepaliveEvent(m_pSrc, KEEPALIVE_FAILURE, KEEPALIVE_CAUSE_NORMAL, (SIPX_KEEPALIVE_TYPE) event.type, event.remoteAddress, event.remotePort, event.keepAliveSecs, event.mappedAddress, event.mappedPort) ; } protected: void* m_pSrc ; } ; #endif /* ] _SIPXTAPIINTERNAL_H */ sipxtapi-3.3.0~test17/sipXcallLib/include/test/0000755000175000017500000000000012321445035022205 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXcallLib/include/test/mp/0000755000175000017500000000000012321445035022621 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXcallLib/include/test/mp/MpTestConfig.h0000644000175000017500000000412212205613256025336 0ustar00danieldaniel00000000000000// // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// #ifndef _MpTestConfig_h_ #define _MpTestConfig_h_ #include "mp/MpMediaTask.h" #include "ps/PsPhoneTask.h" #include "net/SipUserAgent.h" #include "cp/CallManager.h" class MpCallFlowGraph; // Base URL to find data sources for this test program. This software expects // to find the followings files: // // http:///dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = sipXcallLib/include DIST_COMMON = $(nobase_pkginclude_HEADERS) $(noinst_HEADERS) \ $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/general.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/sipXlib.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(pkgincludedir)" HEADERS = $(nobase_pkginclude_HEADERS) $(noinst_HEADERS) ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMRNB_INCLUDE = @AMRNB_INCLUDE@ AMRNB_LIB_ROOT = @AMRNB_LIB_ROOT@ AMRWB_INCLUDE = @AMRWB_INCLUDE@ AMRWB_LIB_ROOT = @AMRWB_LIB_ROOT@ AMRWB_TARGET = @AMRWB_TARGET@ AMR_TARGET = @AMR_TARGET@ AMTAR = @AMTAR@ ANT = @ANT@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CARBON_LIBS = @CARBON_LIBS@ CA_LIBS = @CA_LIBS@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPUNIT_CFLAGS = @CPPUNIT_CFLAGS@ CPPUNIT_CONFIG = @CPPUNIT_CONFIG@ CPPUNIT_LIBS = @CPPUNIT_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPS_PCRE_CFLAGS = @DEPS_PCRE_CFLAGS@ DEPS_PCRE_LIBS = @DEPS_PCRE_LIBS@ DLLTOOL = @DLLTOOL@ DOT = @DOT@ DOXYGEN = @DOXYGEN@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DYNEXT = @DYNEXT@ EAGC_LDFLAGS = @EAGC_LDFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EJBE_LDFLAGS = @EJBE_LDFLAGS@ EPLC_LDFLAGS = @EPLC_LDFLAGS@ EVAD_LDFLAGS = @EVAD_LDFLAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ G722_TARGET = @G722_TARGET@ G726_TARGET = @G726_TARGET@ GIPSINC = @GIPSINC@ GIPS_CE_OBJS = @GIPS_CE_OBJS@ GIPS_CPPFLAGS = @GIPS_CPPFLAGS@ GIPS_NEQ_OBJS = @GIPS_NEQ_OBJS@ GIPS_VE_OBJS = @GIPS_VE_OBJS@ GREP = @GREP@ GSM_CFLAGS = @GSM_CFLAGS@ GSM_CXXFLAGS = @GSM_CXXFLAGS@ GSM_LDFLAGS = @GSM_LDFLAGS@ GSM_LIBS = @GSM_LIBS@ GSM_TARGET = @GSM_TARGET@ ILBC_INCLUDE = @ILBC_INCLUDE@ ILBC_LIB_ROOT = @ILBC_LIB_ROOT@ ILBC_LIB_TARGET = @ILBC_LIB_TARGET@ ILBC_TARGET = @ILBC_TARGET@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTERFACE_FLAGS = @INTERFACE_FLAGS@ JAVA = @JAVA@ JAVAC_DEBUG = @JAVAC_DEBUG@ JAVAC_OPTIMIZED = @JAVAC_OPTIMIZED@ JAVA_HOME = @JAVA_HOME@ L16_TARGET = @L16_TARGET@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NAMED_PROGRAM = @NAMED_PROGRAM@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPUS_CFLAGS = @OPUS_CFLAGS@ OPUS_LIBS = @OPUS_LIBS@ OPUS_TARGET = @OPUS_TARGET@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PCMAPCMU_TARGET = @PCMAPCMU_TARGET@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ RTL_CXXFLAGS = @RTL_CXXFLAGS@ RTL_LDFLAGS = @RTL_LDFLAGS@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SIPXMEDIA_CE_LIBS = @SIPXMEDIA_CE_LIBS@ SIPXMEDIA_VE_LIBS = @SIPXMEDIA_VE_LIBS@ SIPXMEDIA_VE_STATIC_LIBS = @SIPXMEDIA_VE_STATIC_LIBS@ SIPXPBXUSER = @SIPXPBXUSER@ SIPXPHONECONF = @SIPXPHONECONF@ SIPXPHONEDATA = @SIPXPHONEDATA@ SIPXPHONELIB = @SIPXPHONELIB@ SIPX_BACKUPDIR = @SIPX_BACKUPDIR@ SIPX_BINDIR = @SIPX_BINDIR@ SIPX_CONFDIR = @SIPX_CONFDIR@ SIPX_CONFIGPHONEDIR = @SIPX_CONFIGPHONEDIR@ SIPX_DATADIR = @SIPX_DATADIR@ SIPX_DBDIR = @SIPX_DBDIR@ SIPX_DOCDIR = @SIPX_DOCDIR@ SIPX_INCDIR = @SIPX_INCDIR@ SIPX_LIBDIR = @SIPX_LIBDIR@ SIPX_LOGDIR = @SIPX_LOGDIR@ SIPX_PARKMUSICDIR = @SIPX_PARKMUSICDIR@ SIPX_RUNDIR = @SIPX_RUNDIR@ SIPX_SCHEMADIR = @SIPX_SCHEMADIR@ SIPX_TMPDIR = @SIPX_TMPDIR@ SIPX_UNIT_TARGET = @SIPX_UNIT_TARGET@ SIPX_VXMLDATADIR = @SIPX_VXMLDATADIR@ SPANDSP_CFLAGS = @SPANDSP_CFLAGS@ SPANDSP_CXXFLAGS = @SPANDSP_CXXFLAGS@ SPANDSP_LDFLAGS = @SPANDSP_LDFLAGS@ SPANDSP_LIBS = @SPANDSP_LIBS@ SPEEXDSP_CFLAGS = @SPEEXDSP_CFLAGS@ SPEEXDSP_LIBS = @SPEEXDSP_LIBS@ SPEEXDSP_STATIC_LIB = @SPEEXDSP_STATIC_LIB@ SPEEX_CFLAGS = @SPEEX_CFLAGS@ SPEEX_LIBS = @SPEEX_LIBS@ SPEEX_ROOT = @SPEEX_ROOT@ SPEEX_STATIC_LIB = @SPEEX_STATIC_LIB@ SPEEX_TARGET = @SPEEX_TARGET@ SS_LDFLAGS = @SS_LDFLAGS@ STATIC_CODEC_LIBS = @STATIC_CODEC_LIBS@ STRIP = @STRIP@ TONES_TARGET = @TONES_TARGET@ VERSION = @VERSION@ VIDEO_DEFINE = @VIDEO_DEFINE@ WXWIDGETS_CFLAGS = @WXWIDGETS_CFLAGS@ WXWIDGETS_CONFIG = @WXWIDGETS_CONFIG@ WXWIDGETS_CXXFLAGS = @WXWIDGETS_CXXFLAGS@ WXWIDGETS_LIBS = @WXWIDGETS_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ codeclibdir = @codeclibdir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ enable_dot = @enable_dot@ enable_html_docs = @enable_html_docs@ enable_latex_docs = @enable_latex_docs@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ jar = @jar@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ sipx_abs_srcdir = @sipx_abs_srcdir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ wwwdir = @wwwdir@ # preserve header timestamps to preserve incremental builds across # projects nobase_pkgincludeHEADERS_INSTALL = $(INSTALL) -D -p -c -m 644 nobase_pkginclude_HEADERS = \ cp/CallManager.h \ cp/CSeqManager.h \ cp/Connection.h \ cp/CpCall.h \ cp/CpCallManager.h \ cp/CpGatewayManager.h \ cp/CpGhostConnection.h \ cp/CpIntMessage.h \ cp/CpMultiStringMessage.h \ cp/CpPeerCall.h \ cp/CpStringMessage.h \ cp/SipConnection.h \ ps/PsButtonId.h \ ps/PsButtonInfo.h \ ps/PsButtonTask.h \ ps/PsHookswDev.h \ ps/PsHookswTask.h \ ps/PsKeybdDev.h \ ps/PsLampDev.h \ ps/PsLampId.h \ ps/PsLampInfo.h \ ps/PsLampTask.h \ ps/PsMsg.h \ ps/PsPhoneTask.h \ ps/PsTaoButton.h \ ps/PsTaoComponent.h \ ps/PsTaoComponentGroup.h \ ps/PsTaoDisplay.h \ ps/PsTaoHookswitch.h \ ps/PsTaoLamp.h \ ps/PsTaoMicrophone.h \ ps/PsTaoRinger.h \ ps/PsTaoSpeaker.h \ ps/linux/PsHookswDevLinux.h \ ps/linux/PsKeybdDevLinux.h \ ps/linux/PsLampDevLinux.h \ ps/wnt/PsHookswDevWnt.h \ ps/wnt/PsKeybdDevWnt.h \ ps/wnt/PsLampDevWnt.h \ ptapi/PtAddessCapabilities.h \ ptapi/PtAddress.h \ ptapi/PtAddressEvent.h \ ptapi/PtAddressForwarding.h \ ptapi/PtAddressListener.h \ ptapi/PtAudioCodec.h \ ptapi/PtCall.h \ ptapi/PtCallCapabilities.h \ ptapi/PtCallEvent.h \ ptapi/PtCallListener.h \ ptapi/PtComponent.h \ ptapi/PtComponentGroup.h \ ptapi/PtComponentGroupCapabilities.h \ ptapi/PtComponentIntChangeEvent.h \ ptapi/PtComponentStringChangeEvent.h \ ptapi/PtConfigDb.h \ ptapi/PtConnection.h \ ptapi/PtConnectionCapabilities.h \ ptapi/PtConnectionEvent.h \ ptapi/PtConnectionListener.h \ ptapi/PtDefs.h \ ptapi/PtEvent.h \ ptapi/PtEventListener.h \ ptapi/PtEventMask.h \ ptapi/PtGatewayInterface.h \ ptapi/PtMediaCapabilities.h \ ptapi/PtMetaEvent.h \ ptapi/PtMultiCallEvent.h \ ptapi/PtMultiCallMetaEvent.h \ ptapi/PtPhoneButton.h \ ptapi/PtPhoneDisplay.h \ ptapi/PtPhoneExtSpeaker.h \ ptapi/PtPhoneGraphicDisplay.h \ ptapi/PtPhoneHookswitch.h \ ptapi/PtPhoneLamp.h \ ptapi/PtPhoneMicrophone.h \ ptapi/PtPhoneRinger.h \ ptapi/PtPhoneSpeaker.h \ ptapi/PtPhoneTerminal.h \ ptapi/PtPhoneTextDisplay.h \ ptapi/PtProvider.h \ ptapi/PtProviderCapabilities.h \ ptapi/PtProviderEvent.h \ ptapi/PtProviderListener.h \ ptapi/PtSessionDesc.h \ ptapi/PtSingleCallMetaEvent.h \ ptapi/PtTerminal.h \ ptapi/PtTerminalCapabilities.h \ ptapi/PtTerminalComponentEvent.h \ ptapi/PtTerminalComponentListener.h \ ptapi/PtTerminalConnection.h \ ptapi/PtTerminalConnectionCapabilities.h \ ptapi/PtTerminalConnectionEvent.h \ ptapi/PtTerminalConnectionListener.h \ ptapi/PtTerminalEvent.h \ ptapi/PtTerminalListener.h \ tao/TaoAdaptor.h \ tao/TaoAddressAdaptor.h \ tao/TaoCallAdaptor.h \ tao/TaoClientTask.h \ tao/TaoConnectionAdaptor.h \ tao/TaoDefs.h \ tao/TaoEvent.h \ tao/TaoEventDispatcher.h \ tao/TaoEventListener.h \ tao/TaoListenerClient.h \ tao/TaoListenerEventMessage.h \ tao/TaoListenerManager.h \ tao/TaoListeningTask.h \ tao/TaoMessage.h \ tao/TaoObject.h \ tao/TaoObjectMap.h \ tao/TaoPhoneComponentAdaptor.h \ tao/TaoProviderAdaptor.h \ tao/TaoProviderListener.h \ tao/TaoReference.h \ tao/TaoServerTask.h \ tao/TaoString.h \ tao/TaoTerminalAdaptor.h \ tao/TaoTerminalConnectionAdaptor.h \ tao/TaoTerminalConnectionListener.h \ tao/TaoTransportAgent.h \ tao/TaoTransportTask.h \ tapi/SipXHandleMap.h \ tapi/SipXMessageObserver.h \ tapi/SipXEventDispatcher.h \ tapi/sipXtapi.h \ tapi/sipXtapiEvents.h \ tapi/sipXtapiInternal.h noinst_HEADERS = \ test/mp/MpTestConfig.h \ test/mp/MyPlayerListenerHistoryKeeper.h \ test/mp/MyPlayerListenerPoller.h \ test/mp/MyStreamQueueHistoryKeeper.h all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu sipXcallLib/include/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu sipXcallLib/include/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-nobase_pkgincludeHEADERS: $(nobase_pkginclude_HEADERS) @$(NORMAL_INSTALL) @list='$(nobase_pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(pkgincludedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(pkgincludedir)" || exit 1; \ fi; \ $(am__nobase_list) | while read dir files; do \ xfiles=; for file in $$files; do \ if test -f "$$file"; then xfiles="$$xfiles $$file"; \ else xfiles="$$xfiles $(srcdir)/$$file"; fi; done; \ test -z "$$xfiles" || { \ test "x$$dir" = x. || { \ echo " $(MKDIR_P) '$(DESTDIR)$(pkgincludedir)/$$dir'"; \ $(MKDIR_P) "$(DESTDIR)$(pkgincludedir)/$$dir"; }; \ echo " $(INSTALL_HEADER) $$xfiles '$(DESTDIR)$(pkgincludedir)/$$dir'"; \ $(INSTALL_HEADER) $$xfiles "$(DESTDIR)$(pkgincludedir)/$$dir" || exit $$?; }; \ done uninstall-nobase_pkgincludeHEADERS: @$(NORMAL_UNINSTALL) @list='$(nobase_pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \ $(am__nobase_strip_setup); files=`$(am__nobase_strip)`; \ dir='$(DESTDIR)$(pkgincludedir)'; $(am__uninstall_files_from_dir) ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(HEADERS) installdirs: for dir in "$(DESTDIR)$(pkgincludedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-nobase_pkgincludeHEADERS install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-nobase_pkgincludeHEADERS .MAKE: install-am install-strip .PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ clean-libtool ctags distclean distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-nobase_pkgincludeHEADERS \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags uninstall uninstall-am uninstall-nobase_pkgincludeHEADERS # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: sipxtapi-3.3.0~test17/sipXcallLib/doc/0000755000175000017500000000000012321445035020350 5ustar00danieldaniel00000000000000sipxtapi-3.3.0~test17/sipXcallLib/doc/Makefile.am0000644000175000017500000000156212205613305022406 0ustar00danieldaniel00000000000000include $(top_srcdir)/config/sipXcommon.am.inc EXTRA_DIST = \ Doxyfile.in \ header.html \ footer.html all: doc PROJECT = sipXcallLib doc: $(PROJECT) $(PROJECT): Doxyfile rm -rf $(PROJECT) @DOXYGEN@ Doxyfile: $(srcdir)/Doxyfile.in $(LocalizeSipXconfig) \ -e 's,@enable_html_docs\@,@enable_html_docs@,g' \ -e 's,@enable_latex_docs\@,@enable_latex_docs@,g' \ -e 's,@enable_dot\@,@enable_dot@,g' \ -e 's,@srcdir\@,$(srcdir),g' \ -e 's,@top_srcdir\@,$(top_srcdir),g' \ $(srcdir)/Doxyfile.in > Doxyfile install: install-doc .PHONY: install-doc install-doc: $(PROJECT) rm -rf $(DESTDIR)@docdir@/$(PROJECT) @INSTALL@ -d $(DESTDIR)@docdir@/$(PROJECT) find $(PROJECT) -type f -print \ | xargs --replace=% @INSTALL@ -m u=rw,go=r % $(DESTDIR)@docdir@/% clean-local: clean-doc .PHONY: clean-doc clean-doc: rm -rf $(PROJECT) Doxyfile DISTCLEANFILES = Doxyfile sipxtapi-3.3.0~test17/sipXcallLib/doc/Makefile.in0000644000175000017500000004152312321444775022434 0ustar00danieldaniel00000000000000# Makefile.in generated by automake 1.11.6 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # -*-makefile-*- VPATH = @srcdir@ am__make_dryrun = \ { \ am__dry=no; \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ *) \ for am__flg in $$MAKEFLAGS; do \ case $$am__flg in \ *=*|--*) ;; \ *n*) am__dry=yes; break;; \ esac; \ done;; \ esac; \ test $$am__dry = yes; \ } pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ $(top_srcdir)/config/sipXcommon.am.inc subdir = sipXcallLib/doc ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/general.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/sipXlib.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMRNB_INCLUDE = @AMRNB_INCLUDE@ AMRNB_LIB_ROOT = @AMRNB_LIB_ROOT@ AMRWB_INCLUDE = @AMRWB_INCLUDE@ AMRWB_LIB_ROOT = @AMRWB_LIB_ROOT@ AMRWB_TARGET = @AMRWB_TARGET@ AMR_TARGET = @AMR_TARGET@ AMTAR = @AMTAR@ ANT = @ANT@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CARBON_LIBS = @CARBON_LIBS@ CA_LIBS = @CA_LIBS@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPUNIT_CFLAGS = @CPPUNIT_CFLAGS@ CPPUNIT_CONFIG = @CPPUNIT_CONFIG@ CPPUNIT_LIBS = @CPPUNIT_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DEPS_PCRE_CFLAGS = @DEPS_PCRE_CFLAGS@ DEPS_PCRE_LIBS = @DEPS_PCRE_LIBS@ DLLTOOL = @DLLTOOL@ DOT = @DOT@ DOXYGEN = @DOXYGEN@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ DYNEXT = @DYNEXT@ EAGC_LDFLAGS = @EAGC_LDFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EJBE_LDFLAGS = @EJBE_LDFLAGS@ EPLC_LDFLAGS = @EPLC_LDFLAGS@ EVAD_LDFLAGS = @EVAD_LDFLAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ G722_TARGET = @G722_TARGET@ G726_TARGET = @G726_TARGET@ GIPSINC = @GIPSINC@ GIPS_CE_OBJS = @GIPS_CE_OBJS@ GIPS_CPPFLAGS = @GIPS_CPPFLAGS@ GIPS_NEQ_OBJS = @GIPS_NEQ_OBJS@ GIPS_VE_OBJS = @GIPS_VE_OBJS@ GREP = @GREP@ GSM_CFLAGS = @GSM_CFLAGS@ GSM_CXXFLAGS = @GSM_CXXFLAGS@ GSM_LDFLAGS = @GSM_LDFLAGS@ GSM_LIBS = @GSM_LIBS@ GSM_TARGET = @GSM_TARGET@ ILBC_INCLUDE = @ILBC_INCLUDE@ ILBC_LIB_ROOT = @ILBC_LIB_ROOT@ ILBC_LIB_TARGET = @ILBC_LIB_TARGET@ ILBC_TARGET = @ILBC_TARGET@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTERFACE_FLAGS = @INTERFACE_FLAGS@ JAVA = @JAVA@ JAVAC_DEBUG = @JAVAC_DEBUG@ JAVAC_OPTIMIZED = @JAVAC_OPTIMIZED@ JAVA_HOME = @JAVA_HOME@ L16_TARGET = @L16_TARGET@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NAMED_PROGRAM = @NAMED_PROGRAM@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPUS_CFLAGS = @OPUS_CFLAGS@ OPUS_LIBS = @OPUS_LIBS@ OPUS_TARGET = @OPUS_TARGET@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PCMAPCMU_TARGET = @PCMAPCMU_TARGET@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ RANLIB = @RANLIB@ RTL_CXXFLAGS = @RTL_CXXFLAGS@ RTL_LDFLAGS = @RTL_LDFLAGS@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SIPXMEDIA_CE_LIBS = @SIPXMEDIA_CE_LIBS@ SIPXMEDIA_VE_LIBS = @SIPXMEDIA_VE_LIBS@ SIPXMEDIA_VE_STATIC_LIBS = @SIPXMEDIA_VE_STATIC_LIBS@ SIPXPBXUSER = @SIPXPBXUSER@ SIPXPHONECONF = @SIPXPHONECONF@ SIPXPHONEDATA = @SIPXPHONEDATA@ SIPXPHONELIB = @SIPXPHONELIB@ SIPX_BACKUPDIR = @SIPX_BACKUPDIR@ SIPX_BINDIR = @SIPX_BINDIR@ SIPX_CONFDIR = @SIPX_CONFDIR@ SIPX_CONFIGPHONEDIR = @SIPX_CONFIGPHONEDIR@ SIPX_DATADIR = @SIPX_DATADIR@ SIPX_DBDIR = @SIPX_DBDIR@ SIPX_DOCDIR = @SIPX_DOCDIR@ SIPX_INCDIR = @SIPX_INCDIR@ SIPX_LIBDIR = @SIPX_LIBDIR@ SIPX_LOGDIR = @SIPX_LOGDIR@ SIPX_PARKMUSICDIR = @SIPX_PARKMUSICDIR@ SIPX_RUNDIR = @SIPX_RUNDIR@ SIPX_SCHEMADIR = @SIPX_SCHEMADIR@ SIPX_TMPDIR = @SIPX_TMPDIR@ SIPX_UNIT_TARGET = @SIPX_UNIT_TARGET@ SIPX_VXMLDATADIR = @SIPX_VXMLDATADIR@ SPANDSP_CFLAGS = @SPANDSP_CFLAGS@ SPANDSP_CXXFLAGS = @SPANDSP_CXXFLAGS@ SPANDSP_LDFLAGS = @SPANDSP_LDFLAGS@ SPANDSP_LIBS = @SPANDSP_LIBS@ SPEEXDSP_CFLAGS = @SPEEXDSP_CFLAGS@ SPEEXDSP_LIBS = @SPEEXDSP_LIBS@ SPEEXDSP_STATIC_LIB = @SPEEXDSP_STATIC_LIB@ SPEEX_CFLAGS = @SPEEX_CFLAGS@ SPEEX_LIBS = @SPEEX_LIBS@ SPEEX_ROOT = @SPEEX_ROOT@ SPEEX_STATIC_LIB = @SPEEX_STATIC_LIB@ SPEEX_TARGET = @SPEEX_TARGET@ SS_LDFLAGS = @SS_LDFLAGS@ STATIC_CODEC_LIBS = @STATIC_CODEC_LIBS@ STRIP = @STRIP@ TONES_TARGET = @TONES_TARGET@ VERSION = @VERSION@ VIDEO_DEFINE = @VIDEO_DEFINE@ WXWIDGETS_CFLAGS = @WXWIDGETS_CFLAGS@ WXWIDGETS_CONFIG = @WXWIDGETS_CONFIG@ WXWIDGETS_CXXFLAGS = @WXWIDGETS_CXXFLAGS@ WXWIDGETS_LIBS = @WXWIDGETS_LIBS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ codeclibdir = @codeclibdir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ enable_dot = @enable_dot@ enable_html_docs = @enable_html_docs@ enable_latex_docs = @enable_latex_docs@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ jar = @jar@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ sipx_abs_srcdir = @sipx_abs_srcdir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ wwwdir = @wwwdir@ ConfigureArgs = $(shell sed \ -e '/^ *\$$ .*\/configure/!d' \ -e 's/^ *\$$ .*\/configure *//' \ $(top_builddir)/config.log \ ) LocalizeSipXconfig = sed \ -e 's,@PACKAGE\@,@PACKAGE@,g' \ -e 's,@VERSION\@,@VERSION@,g' \ -e 's,@abs_builddir\@,@abs_builddir@,g' \ -e 's,@abs_srcdir\@,@abs_srcdir@,g' \ -e 's,@abs_top_srcdir\@,@abs_top_srcdir@,g' \ -e 's,@sipx_abs_srcdir\@,@sipx_abs_srcdir@,g' \ -e 's!@CONFIGURE_OPTIONS@!$(ConfigureArgs)!g' \ -e 's,@bindir\@,$(bindir),g' \ -e 's,@datadir\@,$(datadir),g' \ -e 's,@htmldir\@,@htmldir@,g' \ -e 's,@INSTALL\@,@INSTALL@,g' \ -e 's,@install_sh\@,@install_sh@,g' \ -e 's,@libdir\@,$(libdir),g' \ -e 's,@localstatedir\@,$(localstatedir),g' \ -e 's,@pkgdatadir\@,@pkgdatadir@,g' \ -e 's,@prefix\@,$(prefix),g' \ -e 's,@profiledir\@,@profiledir@,g' \ -e 's,@wwwdir\@,@wwwdir@,g' \ -e 's,@host\@,@host@,g' \ -e 's,@PERL\@,@PERL@,g' \ -e 's,@APACHE2_HTTPD\@,@APACHE2_HTTPD@,g' \ -e 's,@APACHE2_MOD\@,@APACHE2_MOD@,g' \ -e 's,@CLOVER_HOME\@,@CLOVER_HOME@,g' \ -e 's,@JAVAC_DEBUG\@,@JAVAC_DEBUG@,g' \ -e 's,@JAVAC_OPTIMIZED\@,@JAVAC_OPTIMIZED@,g' \ -e 's,@JAVA\@,@JAVA@,g' \ -e 's,@JAVA_HOME\@,@JAVA_HOME@,g' \ -e 's,@JBOSS_HOME\@,@JBOSS_HOME@,g' \ -e 's,@JBOSS_SERVER_CONF\@,@JBOSS_SERVER_CONF@,g' \ -e 's,@SIPFOUNDRY_ORG\@,@SIPFOUNDRY_ORG@,g' \ -e 's,@SIPXCONFIG_LIBDIR\@,@SIPXCONFIG_LIBDIR@,g' \ -e 's,@SIPXPBXUSER\@,@SIPXPBXUSER@,g' \ -e 's,@SIPX_BINDIR\@,@SIPX_BINDIR@,g' \ -e 's,@SIPX_CONFDIR\@,@SIPX_CONFDIR@,g' \ -e 's,@SIPX_CONFIGPHONEDIR\@,@SIPX_CONFIGPHONEDIR@,g' \ -e 's,@SIPX_BACKUPDIR\@,@SIPX_BACKUPDIR@,g' \ -e 's,@SIPX_DATADIR\@,@SIPX_DATADIR@,g' \ -e 's,@SIPX_DBDIR\@,@SIPX_DBDIR@,g' \ -e 's,@SIPX_DOCDIR\@,@SIPX_DOCDIR@,g' \ -e 's,@SIPX_LOGDIR\@,@SIPX_LOGDIR@,g' \ -e 's,@SIPX_RUNDIR\@,@SIPX_RUNDIR@,g' \ -e 's,@SIPX_TMPDIR\@,@SIPX_TMPDIR@,g' \ -e 's,@SIPX_INCDIR\@,@SIPX_INCDIR@,g' \ -e 's,@SIPX_LIBDIR\@,@SIPX_LIBDIR@,g' \ -e 's,@SIPX_SCHEMADIR\@,@SIPX_SCHEMADIR@,g' \ -e 's,@SIPX_VXMLDATADIR\@,@SIPX_VXMLDATADIR@,g' \ -e 's,@SIPX_PARKMUSICDIR\@,@SIPX_PARKMUSICDIR@,g' \ -e 's,@SPRING_HOME\@,@SPRING_HOME@,g' \ -e 's,@XPRESSA_BUILD_NUMBER\@,@XPRESSA_BUILD_NUMBER@,g' \ -e 's,@XPRESSA_BUILD_COMMENT\@,@XPRESSA_BUILD_COMMENT@,g' \ -e 's,@SIPXPHONELIB\@,@SIPXPHONELIB@,g' \ -e 's,@SIPXPHONEDATA\@,@SIPXPHONEDATA@,g' \ -e 's,@SIPXPHONECONF\@,@SIPXPHONECONF@,g' \ -e 's,@NAMED_PROGRAM\@,@NAMED_PROGRAM@,g' EXTRA_DIST = \ Doxyfile.in \ header.html \ footer.html PROJECT = sipXcallLib DISTCLEANFILES = Doxyfile all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(top_srcdir)/config/sipXcommon.am.inc $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu sipXcallLib/doc/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu sipXcallLib/doc/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_srcdir)/config/sipXcommon.am.inc: $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile installdirs: install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) -test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libtool clean-local mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ clean-local distclean distclean-generic distclean-libtool \ distdir dvi dvi-am html html-am info info-am install \ install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ uninstall uninstall-am all: doc doc: $(PROJECT) $(PROJECT): Doxyfile rm -rf $(PROJECT) @DOXYGEN@ Doxyfile: $(srcdir)/Doxyfile.in $(LocalizeSipXconfig) \ -e 's,@enable_html_docs\@,@enable_html_docs@,g' \ -e 's,@enable_latex_docs\@,@enable_latex_docs@,g' \ -e 's,@enable_dot\@,@enable_dot@,g' \ -e 's,@srcdir\@,$(srcdir),g' \ -e 's,@top_srcdir\@,$(top_srcdir),g' \ $(srcdir)/Doxyfile.in > Doxyfile install: install-doc .PHONY: install-doc install-doc: $(PROJECT) rm -rf $(DESTDIR)@docdir@/$(PROJECT) @INSTALL@ -d $(DESTDIR)@docdir@/$(PROJECT) find $(PROJECT) -type f -print \ | xargs --replace=% @INSTALL@ -m u=rw,go=r % $(DESTDIR)@docdir@/% clean-local: clean-doc .PHONY: clean-doc clean-doc: rm -rf $(PROJECT) Doxyfile # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: sipxtapi-3.3.0~test17/sipXcallLib/doc/Doxyfile.in0000644000175000017500000005437312205613305022475 0ustar00danieldaniel00000000000000# Doxyfile 1.1.4 # This file describes the settings to be used by doxygen for a project # # All text after a hash (#) is considered a comment and will be ignored # The format is: # TAG = value [value, ...] # Values that contain spaces should be placed between quotes (" ") #--------------------------------------------------------------------------- # General configuration options #--------------------------------------------------------------------------- # The PROJECT_NAME tag is a single word (or a sequence of words surrounded # by quotes) that should identify the project. PROJECT_NAME = sipXcallLib # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = "Version @VERSION@" # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = . # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Dutch, French, Italian, Czech, Swedish, German, Finnish, Japanese, # Spanish and Russian OUTPUT_LANGUAGE = English # The DISABLE_INDEX tag can be used to turn on/off the condensed index at # top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. DISABLE_INDEX = NO # If the EXTRACT_ALL tag is set to YES all classes and functions will be # included in the documentation, even if no documentation was available. EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = YES # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members inside documented classes or files. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSESS tag is set to YES, Doxygen will hide all # undocumented classes. HIDE_UNDOC_CLASSES = NO # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = NO # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. STRIP_FROM_PATH = @sipx_abs_srcdir@ # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a class diagram (in Html and LaTeX) for classes with base or # super classes. Setting the tag to NO turns the diagrams off. CLASS_DIAGRAMS = YES # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the CASE_SENSE_NAMES tag is set to NO (the default) then Doxygen # will only generate file names in lower case letters. If set to # YES upper case letters are also allowed. This is useful if you have # classes or files whose names only differ in case and if your file system # supports case sensitive file names. CASE_SENSE_NAMES = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the JAVADOC_AUTOBRIEF tag is set to YES (the default) then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the Javadoc-style will # behave just like the Qt-style comments. JAVADOC_AUTOBRIEF = YES # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # reimplements. INHERIT_DOCS = YES # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 8 # The ENABLE_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = YES # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. WARN_FORMAT = "$file:$line: $text" #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = @top_srcdir@/include @top_srcdir@/src # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. FILE_PATTERNS = *.cpp *.h # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. EXCLUDE = @top_srcdir@/src/test # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. EXCLUDE_PATTERNS = config-*.h # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = ../examples # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = *.cpp *.h # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. INPUT_FILTER = #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = YES # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = @enable_html_docs@ # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = sipXcallLib # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. HTML_HEADER = @srcdir@/header.html # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = @srcdir@/footer.html # The HTML_STYLESHEET tag can be used to specify a user defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet HTML_STYLESHEET = # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. HTML_ALIGN_MEMBERS = YES # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compressed HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = @enable_latex_docs@ # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, a4wide, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = NO # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # For now this is experimental and is disabled by default. The RTF output # is optimised for Word 97 and may not look too pretty with other readers # or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using a WORD or other. # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. MACRO_EXPANSION = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # in the INCLUDE_PATH (see below) will be search if a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = @top_srcdir@/meta/doc # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. PREDEFINED = # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED tag. EXPAND_ONLY_PREDEF = YES #--------------------------------------------------------------------------- # Configuration::addtions related to external references #--------------------------------------------------------------------------- # The TAGFILES tag can be used to specify one or more tagfiles. TAGFILES = \ @SIPX_DOCDIR@/sipxportlib/sipxportlib.tag=@SIPX_DOCDIR@/sipxportlib/ \ @SIPX_DOCDIR@/sipxsdplib/sipxsdplib.tag=@SIPX_DOCDIR@/sipxsdplib/ \ @SIPX_DOCDIR@/sipxtacklib/sipxtacklib.tag=@SIPX_DOCDIR@/sipxtacklib/ \ @SIPX_DOCDIR@/sipxmedialib/sipxmedialib.tag=@SIPX_DOCDIR@/sipxmedialib/ @SIPX_DOCDIR@/sipxmediaadapterlib/sipxmediaadapterlib.tag=@SIPX_DOCDIR@/sipxmediaadapterlib/ # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = sipXcallLib/sipXcallLib.tag # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = @enable_dot@ # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # the CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the ENABLE_PREPROCESSING, INCLUDE_GRAPH, and HAVE_DOT tags are set to # YES then doxygen will generate a graph for each documented file showing # the direct and indirect include dependencies of the file with other # documented files. INCLUDE_GRAPH = YES # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # This tag can be used to specify the path where the dot tool can be found. # If left blank, it is assumed the dot tool can be found on the path. DOT_PATH = #--------------------------------------------------------------------------- # Configuration::addtions related to the search engine #--------------------------------------------------------------------------- # The SEARCHENGINE tag specifies whether or not a search engine should be # used. If set to NO the values of all tags below this one will be ignored. SEARCHENGINE = NO # Got these recommendations from Rich S. MULTILINE_CPP_IS_BRIEF = YES DETAILS_AT_TOP = YES HIDE_SCOPE_NAMES = YES SHOW_USED_FILES = NO sipxtapi-3.3.0~test17/sipXcallLib/doc/header.html0000644000175000017500000000041312205613256022467 0ustar00danieldaniel00000000000000 sipXcallLib - Call processing library

sipXcallLib home page


sipxtapi-3.3.0~test17/sipXcallLib/doc/footer.html0000644000175000017500000000003312205613256022533 0ustar00danieldaniel00000000000000