code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
#include "../unix/sockaddr.c"
001-log4cxx
trunk/src/apr/network_io/os2/sockaddr.c
C
asf20
30
#include "../unix/inet_ntop.c"
001-log4cxx
trunk/src/apr/network_io/os2/inet_ntop.c
C
asf20
31
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_networkio.h" #include "apr_network_io.h" #include "apr_portable.h" #include "apr_general.h" #include "apr_lib.h" static int os2_socket_init(int, int ,int); int (*apr_os2_socket)(int, int, int) = os2_socket_init; int (*apr_os2_select)(int *, int, int, int, long) = NULL; int (*apr_os2_sock_errno)() = NULL; int (*apr_os2_accept)(int, struct sockaddr *, int *) = NULL; int (*apr_os2_bind)(int, struct sockaddr *, int) = NULL; int (*apr_os2_connect)(int, struct sockaddr *, int) = NULL; int (*apr_os2_getpeername)(int, struct sockaddr *, int *) = NULL; int (*apr_os2_getsockname)(int, struct sockaddr *, int *) = NULL; int (*apr_os2_getsockopt)(int, int, int, char *, int *) = NULL; int (*apr_os2_ioctl)(int, int, caddr_t, int) = NULL; int (*apr_os2_listen)(int, int) = NULL; int (*apr_os2_recv)(int, char *, int, int) = NULL; int (*apr_os2_send)(int, const char *, int, int) = NULL; int (*apr_os2_setsockopt)(int, int, int, char *, int) = NULL; int (*apr_os2_shutdown)(int, int) = NULL; int (*apr_os2_soclose)(int) = NULL; int (*apr_os2_writev)(int, struct iovec *, int) = NULL; int (*apr_os2_sendto)(int, const char *, int, int, const struct sockaddr *, int); int (*apr_os2_recvfrom)(int, char *, int, int, struct sockaddr *, int *); static HMODULE hSO32DLL; static int os2_fn_link() { DosEnterCritSec(); /* Stop two threads doing this at the same time */ if (apr_os2_socket == os2_socket_init) { ULONG rc; char errorstr[200]; rc = DosLoadModule(errorstr, sizeof(errorstr), "SO32DLL", &hSO32DLL); if (rc) return APR_OS2_STATUS(rc); rc = DosQueryProcAddr(hSO32DLL, 0, "SOCKET", &apr_os2_socket); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "SELECT", &apr_os2_select); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "SOCK_ERRNO", &apr_os2_sock_errno); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "ACCEPT", &apr_os2_accept); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "BIND", &apr_os2_bind); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "CONNECT", &apr_os2_connect); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "GETPEERNAME", &apr_os2_getpeername); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "GETSOCKNAME", &apr_os2_getsockname); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "GETSOCKOPT", &apr_os2_getsockopt); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "IOCTL", &apr_os2_ioctl); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "LISTEN", &apr_os2_listen); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "RECV", &apr_os2_recv); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "SEND", &apr_os2_send); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "SETSOCKOPT", &apr_os2_setsockopt); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "SHUTDOWN", &apr_os2_shutdown); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "SOCLOSE", &apr_os2_soclose); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "WRITEV", &apr_os2_writev); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "SENDTO", &apr_os2_sendto); if (!rc) rc = DosQueryProcAddr(hSO32DLL, 0, "RECVFROM", &apr_os2_recvfrom); if (rc) return APR_OS2_STATUS(rc); } DosExitCritSec(); return APR_SUCCESS; } static int os2_socket_init(int domain, int type, int protocol) { int rc = os2_fn_link(); if (rc == APR_SUCCESS) return apr_os2_socket(domain, type, protocol); return rc; }
001-log4cxx
trunk/src/apr/network_io/os2/os2calls.c
C
asf20
4,503
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_networkio.h" #include "apr_errno.h" #include "apr_general.h" #include "apr_network_io.h" #include "apr_support.h" #include "apr_lib.h" #include <sys/time.h> APR_DECLARE(apr_status_t) apr_socket_sendto(apr_socket_t *sock, apr_sockaddr_t *where, apr_int32_t flags, const char *buf, apr_size_t *len) { apr_ssize_t rv; int serrno; do { rv = sendto(sock->socketdes, buf, (*len), flags, (struct sockaddr*)&where->sa, where->salen); } while (rv == -1 && (serrno = sock_errno()) == EINTR); if (rv == -1 && serrno == SOCEWOULDBLOCK && sock->timeout != 0) { apr_status_t arv = apr_wait_for_io_or_timeout(NULL, sock, 0); if (arv != APR_SUCCESS) { *len = 0; return arv; } else { do { rv = sendto(sock->socketdes, buf, *len, flags, (const struct sockaddr*)&where->sa, where->salen); } while (rv == -1 && (serrno = sock_errno()) == SOCEINTR); } } if (rv == -1) { *len = 0; return APR_FROM_OS_ERROR(serrno); } *len = rv; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_recvfrom(apr_sockaddr_t *from, apr_socket_t *sock, apr_int32_t flags, char *buf, apr_size_t *len) { apr_ssize_t rv; int serrno; do { rv = recvfrom(sock->socketdes, buf, (*len), flags, (struct sockaddr*)&from->sa, &from->salen); } while (rv == -1 && (serrno = sock_errno()) == EINTR); if (rv == -1 && serrno == SOCEWOULDBLOCK && sock->timeout != 0) { apr_status_t arv = apr_wait_for_io_or_timeout(NULL, sock, 1); if (arv != APR_SUCCESS) { *len = 0; return arv; } else { do { rv = recvfrom(sock->socketdes, buf, *len, flags, (struct sockaddr*)&from->sa, &from->salen); } while (rv == -1 && (serrno = sock_errno()) == EINTR); } } if (rv == -1) { (*len) = 0; return APR_FROM_OS_ERROR(serrno); } (*len) = rv; if (rv == 0 && sock->type == SOCK_STREAM) return APR_EOF; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/network_io/os2/sendrecv_udp.c
C
asf20
3,342
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_networkio.h" #include "apr_errno.h" #include "apr_general.h" #include "apr_network_io.h" #include "apr_lib.h" #include <sys/time.h> APR_DECLARE(apr_status_t) apr_socket_send(apr_socket_t *sock, const char *buf, apr_size_t *len) { apr_ssize_t rv; int fds, err = 0; if (*len > 65536) { *len = 65536; } do { if (!sock->nonblock || err == SOCEWOULDBLOCK) { fds = sock->socketdes; rv = select(&fds, 0, 1, 0, sock->timeout >= 0 ? sock->timeout/1000 : -1); if (rv != 1) { *len = 0; err = sock_errno(); if (rv == 0) return APR_TIMEUP; if (err == SOCEINTR) continue; return APR_OS2_STATUS(err); } } rv = send(sock->socketdes, buf, (*len), 0); err = rv < 0 ? sock_errno() : 0; } while (err == SOCEINTR || err == SOCEWOULDBLOCK); if (err) { *len = 0; return APR_OS2_STATUS(err); } (*len) = rv; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_recv(apr_socket_t *sock, char *buf, apr_size_t *len) { apr_ssize_t rv; int fds, err = 0; do { if (!sock->nonblock || (err == SOCEWOULDBLOCK && sock->timeout != 0)) { fds = sock->socketdes; rv = select(&fds, 1, 0, 0, sock->timeout >= 0 ? sock->timeout/1000 : -1); if (rv != 1) { *len = 0; err = sock_errno(); if (rv == 0) return APR_TIMEUP; if (err == SOCEINTR) continue; return APR_OS2_STATUS(err); } } rv = recv(sock->socketdes, buf, (*len), 0); err = rv < 0 ? sock_errno() : 0; } while (err == SOCEINTR || (err == SOCEWOULDBLOCK && sock->timeout != 0)); if (err) { *len = 0; return APR_OS2_STATUS(err); } (*len) = rv; return rv == 0 ? APR_EOF : APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_sendv(apr_socket_t *sock, const struct iovec *vec, apr_int32_t nvec, apr_size_t *len) { apr_status_t rv; struct iovec *tmpvec; int fds, err = 0; int nv_tosend, total = 0; /* Make sure writev() only gets fed 64k at a time */ for ( nv_tosend = 0; nv_tosend < nvec && total + vec[nv_tosend].iov_len < 65536; nv_tosend++ ) { total += vec[nv_tosend].iov_len; } tmpvec = alloca(sizeof(struct iovec) * nv_tosend); memcpy(tmpvec, vec, sizeof(struct iovec) * nv_tosend); do { if (!sock->nonblock || err == SOCEWOULDBLOCK) { fds = sock->socketdes; rv = select(&fds, 0, 1, 0, sock->timeout >= 0 ? sock->timeout/1000 : -1); if (rv != 1) { *len = 0; err = sock_errno(); if (rv == 0) return APR_TIMEUP; if (err == SOCEINTR) continue; return APR_OS2_STATUS(err); } } rv = writev(sock->socketdes, tmpvec, nv_tosend); err = rv < 0 ? sock_errno() : 0; } while (err == SOCEINTR || err == SOCEWOULDBLOCK); if (err) { *len = 0; return APR_OS2_STATUS(err); } *len = rv; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/network_io/os2/sendrecv.c
C
asf20
4,332
#!/bin/sh # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # APR script designed to allow easy command line access to APR configuration # parameters. APR_MAJOR_VERSION="@APR_MAJOR_VERSION@" APR_DOTTED_VERSION="@APR_DOTTED_VERSION@" prefix="@prefix@" exec_prefix="@exec_prefix@" bindir="@bindir@" libdir="@libdir@" datadir="@datadir@" installbuilddir="@installbuilddir@" includedir="@includedir@" CC="@CC@" CPP="@CPP@" SHELL="@SHELL@" CPPFLAGS="@EXTRA_CPPFLAGS@" CFLAGS="@EXTRA_CFLAGS@" LDFLAGS="@EXTRA_LDFLAGS@" LIBS="@EXTRA_LIBS@" EXTRA_INCLUDES="@EXTRA_INCLUDES@" SHLIBPATH_VAR="@shlibpath_var@" APR_SOURCE_DIR="@apr_srcdir@" APR_BUILD_DIR="@apr_builddir@" APR_SO_EXT="@so_ext@" APR_LIB_TARGET="@export_lib_target@" APR_LIBNAME="@APR_LIBNAME@" # NOTE: the following line is modified during 'make install': alter with care! location=@APR_CONFIG_LOCATION@ show_usage() { cat << EOF Usage: apr-$APR_MAJOR_VERSION-config [OPTION] Known values for OPTION are: --prefix[=DIR] change prefix to DIR --bindir print location where binaries are installed --includedir print location where headers are installed --cc print C compiler name --cpp print C preprocessor name and any required options --cflags print C compiler flags --cppflags print C preprocessor flags --includes print include information --ldflags print linker flags --libs print additional libraries to link against --srcdir print APR source directory --installbuilddir print APR build helper directory --link-ld print link switch(es) for linking to APR --link-libtool print the libtool inputs for linking to APR --shlib-path-var print the name of the shared library path env var --apr-la-file print the path to the .la file, if available --apr-so-ext print the extensions of shared objects on this platform --apr-lib-target print the libtool target information --apr-libtool print the path to APR's libtool --version print the APR's version as a dotted triple --help print this help When linking with libtool, an application should do something like: APR_LIBS="\`apr-$APR_MAJOR_VERSION-config --link-libtool --libs\`" or when linking directly: APR_LIBS="\`apr-$APR_MAJOR_VERSION-config --link-ld --libs\`" An application should use the results of --cflags, --cppflags, --includes, and --ldflags in their build process. EOF } if test $# -eq 0; then show_usage exit 1 fi if test "$location" = "installed"; then LA_FILE="$libdir/lib${APR_LIBNAME}.la" else LA_FILE="$APR_BUILD_DIR/lib${APR_LIBNAME}.la" fi flags="" while test $# -gt 0; do # Normalize the prefix. case "$1" in -*=*) optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` ;; *) optarg= ;; esac case "$1" in # It is possible for the user to override our prefix. --prefix=*) prefix=$optarg ;; --prefix) echo $prefix exit 0 ;; --bindir) echo $bindir exit 0 ;; --includedir) if test "$location" = "installed"; then flags="$includedir" elif test "$location" = "source"; then flags="$APR_SOURCE_DIR/include" else # this is for VPATH builds flags="$APR_BUILD_DIR/include $APR_SOURCE_DIR/include" fi echo $flags exit 0 ;; --cc) echo $CC exit 0 ;; --cpp) echo $CPP exit 0 ;; --cflags) flags="$flags $CFLAGS" ;; --cppflags) flags="$flags $CPPFLAGS" ;; --libs) flags="$flags $LIBS" ;; --ldflags) flags="$flags $LDFLAGS" ;; --includes) if test "$location" = "installed"; then flags="$flags -I$includedir $EXTRA_INCLUDES" elif test "$location" = "source"; then flags="$flags -I$APR_SOURCE_DIR/include $EXTRA_INCLUDES" else # this is for VPATH builds flags="$flags -I$APR_BUILD_DIR/include -I$APR_SOURCE_DIR/include $EXTRA_INCLUDES" fi ;; --srcdir) echo $APR_SOURCE_DIR exit 0 ;; --installbuilddir) if test "$location" = "installed"; then echo "${installbuilddir}" elif test "$location" = "source"; then echo "$APR_SOURCE_DIR/build" else # this is for VPATH builds echo "$APR_BUILD_DIR/build" fi exit 0 ;; --version) echo $APR_DOTTED_VERSION exit 0 ;; --link-ld) if test "$location" = "installed"; then ### avoid using -L if libdir is a "standard" location like /usr/lib flags="$flags -L$libdir -l${APR_LIBNAME}" else ### this surely can't work since the library is in .libs? flags="$flags -L$APR_BUILD_DIR -l${APR_LIBNAME}" fi ;; --link-libtool) # If the LA_FILE exists where we think it should be, use it. If we're # installed and the LA_FILE does not exist, assume to use -L/-l # (the LA_FILE may not have been installed). If we're building ourselves, # we'll assume that at some point the .la file be created. if test -f "$LA_FILE"; then flags="$flags $LA_FILE" elif test "$location" = "installed"; then ### avoid using -L if libdir is a "standard" location like /usr/lib # Since the user is specifying they are linking with libtool, we # *know* that -R will be recognized by libtool. flags="$flags -L$libdir -R$libdir -l${APR_LIBNAME}" else flags="$flags $LA_FILE" fi ;; --shlib-path-var) echo "$SHLIBPATH_VAR" exit 0 ;; --apr-la-file) if test -f "$LA_FILE"; then flags="$flags $LA_FILE" fi ;; --apr-so-ext) echo "$APR_SO_EXT" exit 0 ;; --apr-lib-target) echo "$APR_LIB_TARGET" exit 0 ;; --apr-libtool) if test "$location" = "installed"; then echo "${installbuilddir}/libtool" else echo "$APR_BUILD_DIR/libtool" fi exit 0 ;; --help) show_usage exit 0 ;; *) show_usage exit 1 ;; esac # Next please. shift done if test -n "$flags"; then echo "$flags" fi exit 0
001-log4cxx
trunk/src/apr/apr-config.in
Shell
asf20
6,879
#!/bin/sh # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # buildconf: Build the support scripts needed to compile from a # checked-out version of the source code. # Verify that the builder has the right config tools installed # build/buildcheck.sh || exit 1 libtoolize=`build/PrintPath glibtoolize libtoolize15 libtoolize14 libtoolize` if [ "x$libtoolize" = "x" ]; then echo "libtoolize not found in path" exit 1 fi # Create the libtool helper files # # Note: we copy (rather than link) them to simplify distribution. # Note: APR supplies its own config.guess and config.sub -- we do not # rely on libtool's versions # echo "Copying libtool helper files ..." # Remove any libtool files so one can switch between libtool 1.3 # and libtool 1.4 by simply rerunning the buildconf script. (cd build ; rm -f ltconfig ltmain.sh libtool.m4) $libtoolize --copy --automake if [ -f libtool.m4 ]; then ltfile=`pwd`/libtool.m4 else ltfindcmd="`sed -n \"/=[^\\\`]/p;/libtool_m4=/{s/.*=/echo /p;q;}\" \ < $libtoolize`" ltfile=${LIBTOOL_M4-`eval "$ltfindcmd"`} # Expecting the code above to be very portable, but just in case... if [ -z "$ltfile" -o ! -f "$ltfile" ]; then ltpath=`dirname $libtoolize` ltfile=`cd $ltpath/../share/aclocal ; pwd`/libtool.m4 fi fi if [ ! -f $ltfile ]; then echo "$ltfile not found" exit 1 fi echo "buildconf: Using libtool.m4 at ${ltfile}." cat $ltfile | sed -e 's/LIBTOOL=\(.*\)top_build/LIBTOOL=\1apr_build/' > build/libtool.m4 # libtool.m4 from 1.6 requires ltsugar.m4 if [ -f ltsugar.m4 ]; then rm -f build/ltsugar.m4 mv ltsugar.m4 build/ltsugar.m4 fi # Clean up any leftovers rm -f aclocal.m4 libtool.m4 # # Generate the autoconf header and ./configure # echo "Creating include/arch/unix/apr_private.h.in ..." ${AUTOHEADER:-autoheader} echo "Creating configure ..." ### do some work to toss config.cache? ${AUTOCONF:-autoconf} # Remove autoconf 2.5x's cache directory rm -rf autom4te*.cache echo "Generating 'make' outputs ..." build/gen-build.py make # Create RPM Spec file if [ -f `which cut` ]; then echo rebuilding rpm spec file ( REVISION=`build/get-version.sh all include/apr_version.h APR` VERSION=`echo $REVISION | cut -d- -s -f1` RELEASE=`echo $REVISION | cut -d- -s -f2` if [ "x$VERSION" = "x" ]; then VERSION=$REVISION RELEASE=1 fi cat ./build/rpm/apr.spec.in | \ sed -e "s/APR_VERSION/$VERSION/" \ -e "s/APR_RELEASE/$RELEASE/" \ > apr.spec ) fi exit 0
001-log4cxx
trunk/src/apr/.svn/text-base/buildconf.svn-base
Shell
asf20
3,281
#!/bin/sh # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # APR script designed to allow easy command line access to APR configuration # parameters. APR_MAJOR_VERSION="@APR_MAJOR_VERSION@" APR_DOTTED_VERSION="@APR_DOTTED_VERSION@" prefix="@prefix@" exec_prefix="@exec_prefix@" bindir="@bindir@" libdir="@libdir@" datadir="@datadir@" installbuilddir="@installbuilddir@" includedir="@includedir@" CC="@CC@" CPP="@CPP@" SHELL="@SHELL@" CPPFLAGS="@EXTRA_CPPFLAGS@" CFLAGS="@EXTRA_CFLAGS@" LDFLAGS="@EXTRA_LDFLAGS@" LIBS="@EXTRA_LIBS@" EXTRA_INCLUDES="@EXTRA_INCLUDES@" SHLIBPATH_VAR="@shlibpath_var@" APR_SOURCE_DIR="@apr_srcdir@" APR_BUILD_DIR="@apr_builddir@" APR_SO_EXT="@so_ext@" APR_LIB_TARGET="@export_lib_target@" APR_LIBNAME="@APR_LIBNAME@" # NOTE: the following line is modified during 'make install': alter with care! location=@APR_CONFIG_LOCATION@ show_usage() { cat << EOF Usage: apr-$APR_MAJOR_VERSION-config [OPTION] Known values for OPTION are: --prefix[=DIR] change prefix to DIR --bindir print location where binaries are installed --includedir print location where headers are installed --cc print C compiler name --cpp print C preprocessor name and any required options --cflags print C compiler flags --cppflags print C preprocessor flags --includes print include information --ldflags print linker flags --libs print additional libraries to link against --srcdir print APR source directory --installbuilddir print APR build helper directory --link-ld print link switch(es) for linking to APR --link-libtool print the libtool inputs for linking to APR --shlib-path-var print the name of the shared library path env var --apr-la-file print the path to the .la file, if available --apr-so-ext print the extensions of shared objects on this platform --apr-lib-target print the libtool target information --apr-libtool print the path to APR's libtool --version print the APR's version as a dotted triple --help print this help When linking with libtool, an application should do something like: APR_LIBS="\`apr-$APR_MAJOR_VERSION-config --link-libtool --libs\`" or when linking directly: APR_LIBS="\`apr-$APR_MAJOR_VERSION-config --link-ld --libs\`" An application should use the results of --cflags, --cppflags, --includes, and --ldflags in their build process. EOF } if test $# -eq 0; then show_usage exit 1 fi if test "$location" = "installed"; then LA_FILE="$libdir/lib${APR_LIBNAME}.la" else LA_FILE="$APR_BUILD_DIR/lib${APR_LIBNAME}.la" fi flags="" while test $# -gt 0; do # Normalize the prefix. case "$1" in -*=*) optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` ;; *) optarg= ;; esac case "$1" in # It is possible for the user to override our prefix. --prefix=*) prefix=$optarg ;; --prefix) echo $prefix exit 0 ;; --bindir) echo $bindir exit 0 ;; --includedir) if test "$location" = "installed"; then flags="$includedir" elif test "$location" = "source"; then flags="$APR_SOURCE_DIR/include" else # this is for VPATH builds flags="$APR_BUILD_DIR/include $APR_SOURCE_DIR/include" fi echo $flags exit 0 ;; --cc) echo $CC exit 0 ;; --cpp) echo $CPP exit 0 ;; --cflags) flags="$flags $CFLAGS" ;; --cppflags) flags="$flags $CPPFLAGS" ;; --libs) flags="$flags $LIBS" ;; --ldflags) flags="$flags $LDFLAGS" ;; --includes) if test "$location" = "installed"; then flags="$flags -I$includedir $EXTRA_INCLUDES" elif test "$location" = "source"; then flags="$flags -I$APR_SOURCE_DIR/include $EXTRA_INCLUDES" else # this is for VPATH builds flags="$flags -I$APR_BUILD_DIR/include -I$APR_SOURCE_DIR/include $EXTRA_INCLUDES" fi ;; --srcdir) echo $APR_SOURCE_DIR exit 0 ;; --installbuilddir) if test "$location" = "installed"; then echo "${installbuilddir}" elif test "$location" = "source"; then echo "$APR_SOURCE_DIR/build" else # this is for VPATH builds echo "$APR_BUILD_DIR/build" fi exit 0 ;; --version) echo $APR_DOTTED_VERSION exit 0 ;; --link-ld) if test "$location" = "installed"; then ### avoid using -L if libdir is a "standard" location like /usr/lib flags="$flags -L$libdir -l${APR_LIBNAME}" else ### this surely can't work since the library is in .libs? flags="$flags -L$APR_BUILD_DIR -l${APR_LIBNAME}" fi ;; --link-libtool) # If the LA_FILE exists where we think it should be, use it. If we're # installed and the LA_FILE does not exist, assume to use -L/-l # (the LA_FILE may not have been installed). If we're building ourselves, # we'll assume that at some point the .la file be created. if test -f "$LA_FILE"; then flags="$flags $LA_FILE" elif test "$location" = "installed"; then ### avoid using -L if libdir is a "standard" location like /usr/lib # Since the user is specifying they are linking with libtool, we # *know* that -R will be recognized by libtool. flags="$flags -L$libdir -R$libdir -l${APR_LIBNAME}" else flags="$flags $LA_FILE" fi ;; --shlib-path-var) echo "$SHLIBPATH_VAR" exit 0 ;; --apr-la-file) if test -f "$LA_FILE"; then flags="$flags $LA_FILE" fi ;; --apr-so-ext) echo "$APR_SO_EXT" exit 0 ;; --apr-lib-target) echo "$APR_LIB_TARGET" exit 0 ;; --apr-libtool) if test "$location" = "installed"; then echo "${installbuilddir}/libtool" else echo "$APR_BUILD_DIR/libtool" fi exit 0 ;; --help) show_usage exit 0 ;; *) show_usage exit 1 ;; esac # Next please. shift done if test -n "$flags"; then echo "$flags" fi exit 0
001-log4cxx
trunk/src/apr/.svn/text-base/apr-config.in.svn-base
Shell
asf20
6,879
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "win32/apr_arch_file_io.h" #include "apr_file_io.h" #include <errno.h> #include <string.h> static apr_status_t setptr(apr_file_t *thefile, apr_off_t pos ) { apr_size_t newbufpos; apr_status_t rv; DWORD rc; if (thefile->direction == 1) { /* XXX: flush here is not mutex protected */ rv = apr_file_flush(thefile); if (rv != APR_SUCCESS) return rv; thefile->bufpos = thefile->dataRead = 0; thefile->direction = 0; } /* We may be truncating to size here. * XXX: testing an 'unsigned' as >= 0 below indicates a bug */ newbufpos = (apr_size_t)(pos - (thefile->filePtr - thefile->dataRead)); if (newbufpos >= 0 && newbufpos <= thefile->dataRead) { thefile->bufpos = (apr_size_t)newbufpos; rv = APR_SUCCESS; } else { DWORD offlo = (DWORD)pos; DWORD offhi = (DWORD)(pos >> 32); rc = SetFilePointer(thefile->filehand, offlo, &offhi, FILE_BEGIN); if (rc == (DWORD)-1) /* A legal value, perhaps? MSDN implies prior SetLastError isn't * needed, googling for SetLastError SetFilePointer seems * to confirm this. INVALID_SET_FILE_POINTER is too recently * added for us to rely on it as a constant. */ rv = apr_get_os_error(); else rv = APR_SUCCESS; if (rv == APR_SUCCESS) { rv = APR_SUCCESS; thefile->eof_hit = 0; thefile->bufpos = thefile->dataRead = 0; thefile->filePtr = pos; } } return rv; } APR_DECLARE(apr_status_t) apr_file_seek(apr_file_t *thefile, apr_seek_where_t where, apr_off_t *offset) { apr_finfo_t finfo; apr_status_t rc = APR_SUCCESS; thefile->eof_hit = 0; if (thefile->buffered) { switch (where) { case APR_SET: rc = setptr(thefile, *offset); break; case APR_CUR: rc = setptr(thefile, thefile->filePtr - thefile->dataRead + thefile->bufpos + *offset); break; case APR_END: rc = apr_file_info_get(&finfo, APR_FINFO_SIZE, thefile); if (rc == APR_SUCCESS) rc = setptr(thefile, finfo.size + *offset); break; default: return APR_EINVAL; } *offset = thefile->filePtr - thefile->dataRead + thefile->bufpos; return rc; } /* A file opened with APR_XTHREAD has been opened for overlapped i/o. * APR must explicitly track the file pointer in this case. */ else if (thefile->pOverlapped || thefile->flags & APR_XTHREAD) { switch(where) { case APR_SET: thefile->filePtr = *offset; break; case APR_CUR: thefile->filePtr += *offset; break; case APR_END: rc = apr_file_info_get(&finfo, APR_FINFO_SIZE, thefile); if (rc == APR_SUCCESS && finfo.size + *offset >= 0) thefile->filePtr = finfo.size + *offset; break; default: return APR_EINVAL; } *offset = thefile->filePtr; return rc; } else { DWORD howmove; DWORD offlo = (DWORD)*offset; DWORD offhi = (DWORD)(*offset >> 32); switch(where) { case APR_SET: howmove = FILE_BEGIN; break; case APR_CUR: howmove = FILE_CURRENT; break; case APR_END: howmove = FILE_END; break; default: return APR_EINVAL; } offlo = SetFilePointer(thefile->filehand, (LONG)offlo, (LONG*)&offhi, howmove); if (offlo == 0xFFFFFFFF) rc = apr_get_os_error(); else rc = APR_SUCCESS; /* Since we can land at 0xffffffff we will measure our APR_SUCCESS */ if (rc == APR_SUCCESS) *offset = ((apr_off_t)offhi << 32) | offlo; return rc; } } APR_DECLARE(apr_status_t) apr_file_trunc(apr_file_t *thefile, apr_off_t offset) { apr_status_t rv; DWORD offlo = (DWORD)offset; DWORD offhi = (DWORD)(offset >> 32); DWORD rc; rc = SetFilePointer(thefile->filehand, offlo, &offhi, FILE_BEGIN); if (rc == 0xFFFFFFFF) if ((rv = apr_get_os_error()) != APR_SUCCESS) return rv; if (!SetEndOfFile(thefile->filehand)) return apr_get_os_error(); if (thefile->buffered) { return setptr(thefile, offset); } return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/win32/seek.c
C
asf20
5,605
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "win32/apr_arch_file_io.h" #include "apr_file_io.h" #include "apr_general.h" #include "apr_strings.h" #include <string.h> #include "apr_arch_inherit.h" APR_DECLARE(apr_status_t) apr_file_dup(apr_file_t **new_file, apr_file_t *old_file, apr_pool_t *p) { #ifdef _WIN32_WCE return APR_ENOTIMPL; #else HANDLE hproc = GetCurrentProcess(); HANDLE newhand = NULL; if (!DuplicateHandle(hproc, old_file->filehand, hproc, &newhand, 0, FALSE, DUPLICATE_SAME_ACCESS)) { return apr_get_os_error(); } (*new_file) = (apr_file_t *) apr_pcalloc(p, sizeof(apr_file_t)); (*new_file)->filehand = newhand; (*new_file)->flags = old_file->flags & ~APR_INHERIT; (*new_file)->pool = p; (*new_file)->fname = apr_pstrdup(p, old_file->fname); (*new_file)->append = old_file->append; (*new_file)->buffered = FALSE; (*new_file)->ungetchar = old_file->ungetchar; #if APR_HAS_THREADS if (old_file->mutex) { apr_thread_mutex_create(&((*new_file)->mutex), APR_THREAD_MUTEX_DEFAULT, p); } #endif apr_pool_cleanup_register((*new_file)->pool, (void *)(*new_file), file_cleanup, apr_pool_cleanup_null); /* Create a pollset with room for one descriptor. */ /* ### check return codes */ (void) apr_pollset_create(&(*new_file)->pollset, 1, p, 0); return APR_SUCCESS; #endif /* !defined(_WIN32_WCE) */ } #define stdin_handle 0x01 #define stdout_handle 0x02 #define stderr_handle 0x04 APR_DECLARE(apr_status_t) apr_file_dup2(apr_file_t *new_file, apr_file_t *old_file, apr_pool_t *p) { #ifdef _WIN32_WCE return APR_ENOTIMPL; #else DWORD stdhandle = 0; HANDLE hproc = GetCurrentProcess(); HANDLE newhand = NULL; apr_int32_t newflags; /* dup2 is not supported literaly with native Windows handles. * We can, however, emulate dup2 for the standard i/o handles, * and close and replace other handles with duped handles. * The os_handle will change, however. */ if (new_file->filehand == GetStdHandle(STD_ERROR_HANDLE)) { stdhandle |= stderr_handle; } if (new_file->filehand == GetStdHandle(STD_OUTPUT_HANDLE)) { stdhandle |= stdout_handle; } if (new_file->filehand == GetStdHandle(STD_INPUT_HANDLE)) { stdhandle |= stdin_handle; } if (stdhandle) { if (!DuplicateHandle(hproc, old_file->filehand, hproc, &newhand, 0, TRUE, DUPLICATE_SAME_ACCESS)) { return apr_get_os_error(); } if (((stdhandle & stderr_handle) && !SetStdHandle(STD_ERROR_HANDLE, newhand)) || ((stdhandle & stdout_handle) && !SetStdHandle(STD_OUTPUT_HANDLE, newhand)) || ((stdhandle & stdin_handle) && !SetStdHandle(STD_INPUT_HANDLE, newhand))) { return apr_get_os_error(); } newflags = old_file->flags | APR_INHERIT; } else { if (!DuplicateHandle(hproc, old_file->filehand, hproc, &newhand, 0, FALSE, DUPLICATE_SAME_ACCESS)) { return apr_get_os_error(); } newflags = old_file->flags & ~APR_INHERIT; } if (new_file->filehand && (new_file->filehand != INVALID_HANDLE_VALUE)) { CloseHandle(new_file->filehand); } new_file->flags = newflags; new_file->filehand = newhand; new_file->fname = apr_pstrdup(new_file->pool, old_file->fname); new_file->append = old_file->append; new_file->buffered = FALSE; new_file->ungetchar = old_file->ungetchar; #if APR_HAS_THREADS if (old_file->mutex) { apr_thread_mutex_create(&(new_file->mutex), APR_THREAD_MUTEX_DEFAULT, p); } #endif return APR_SUCCESS; #endif /* !defined(_WIN32_WCE) */ } APR_DECLARE(apr_status_t) apr_file_setaside(apr_file_t **new_file, apr_file_t *old_file, apr_pool_t *p) { *new_file = (apr_file_t *)apr_palloc(p, sizeof(apr_file_t)); memcpy(*new_file, old_file, sizeof(apr_file_t)); (*new_file)->pool = p; if (old_file->buffered) { (*new_file)->buffer = apr_palloc(p, APR_FILE_BUFSIZE); if (old_file->direction == 1) { memcpy((*new_file)->buffer, old_file->buffer, old_file->bufpos); } else { memcpy((*new_file)->buffer, old_file->buffer, old_file->dataRead); } } if (old_file->mutex) { apr_thread_mutex_create(&((*new_file)->mutex), APR_THREAD_MUTEX_DEFAULT, p); apr_thread_mutex_destroy(old_file->mutex); } if (old_file->fname) { (*new_file)->fname = apr_pstrdup(p, old_file->fname); } if (!(old_file->flags & APR_FILE_NOCLEANUP)) { apr_pool_cleanup_register(p, (void *)(*new_file), file_cleanup, file_cleanup); } old_file->filehand = INVALID_HANDLE_VALUE; apr_pool_cleanup_kill(old_file->pool, (void *)old_file, file_cleanup); /* Create a pollset with room for one descriptor. */ /* ### check return codes */ (void) apr_pollset_create(&(*new_file)->pollset, 1, p, 0); return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/win32/filedup.c
C
asf20
6,299
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include <aclapi.h> #include "apr_private.h" #include "apr_arch_file_io.h" #include "apr_file_io.h" #include "apr_general.h" #include "apr_strings.h" #include "apr_errno.h" #include "apr_time.h" #include <sys/stat.h> #include "apr_arch_atime.h" #include "apr_arch_misc.h" /* We have to assure that the file name contains no '*'s, or other * wildcards when using FindFirstFile to recover the true file name. */ static apr_status_t test_safe_name(const char *name) { /* Only accept ':' in the second position of the filename, * as the drive letter delimiter: */ if (apr_isalpha(*name) && (name[1] == ':')) { name += 2; } while (*name) { if (!IS_FNCHAR(*name) && (*name != '\\') && (*name != '/')) { if (*name == '?' || *name == '*') return APR_EPATHWILD; else return APR_EBADPATH; } ++name; } return APR_SUCCESS; } static apr_status_t free_localheap(void *heap) { LocalFree(heap); return APR_SUCCESS; } static apr_gid_t worldid = NULL; static void free_world(void) { if (worldid) { FreeSid(worldid); worldid = NULL; } } /* Left bit shifts from World scope to given scope */ typedef enum prot_scope_e { prot_scope_world = 0, prot_scope_group = 4, prot_scope_user = 8 } prot_scope_e; static apr_fileperms_t convert_prot(ACCESS_MASK acc, prot_scope_e scope) { /* These choices are based on the single filesystem bit that controls * the given behavior. They are -not- recommended for any set protection * function, such a function should -set- use GENERIC_READ/WRITE/EXECUTE */ apr_fileperms_t prot = 0; if (acc & FILE_EXECUTE) prot |= APR_WEXECUTE; if (acc & FILE_WRITE_DATA) prot |= APR_WWRITE; if (acc & FILE_READ_DATA) prot |= APR_WREAD; return (prot << scope); } static void resolve_prot(apr_finfo_t *finfo, apr_int32_t wanted, PACL dacl) { TRUSTEE_W ident = {NULL, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_SID}; ACCESS_MASK acc; /* * This function is only invoked for WinNT, * there is no reason for os_level testing here. */ if ((wanted & APR_FINFO_WPROT) && !worldid) { SID_IDENTIFIER_AUTHORITY SIDAuth = SECURITY_WORLD_SID_AUTHORITY; if (AllocateAndInitializeSid(&SIDAuth, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &worldid)) atexit(free_world); else worldid = NULL; } if ((wanted & APR_FINFO_UPROT) && (finfo->valid & APR_FINFO_USER)) { ident.TrusteeType = TRUSTEE_IS_USER; ident.ptstrName = finfo->user; /* GetEffectiveRightsFromAcl isn't supported under Win9x, * which shouldn't come as a surprize. Since we are passing * TRUSTEE_IS_SID, always skip the A->W layer. */ if (GetEffectiveRightsFromAclW(dacl, &ident, &acc) == ERROR_SUCCESS) { finfo->protection |= convert_prot(acc, prot_scope_user); finfo->valid |= APR_FINFO_UPROT; } } /* Windows NT: did not return group rights. * Windows 2000 returns group rights information. * Since WinNT kernels don't follow the unix model of * group associations, this all all pretty mute. */ if ((wanted & APR_FINFO_GPROT) && (finfo->valid & APR_FINFO_GROUP)) { ident.TrusteeType = TRUSTEE_IS_GROUP; ident.ptstrName = finfo->group; if (GetEffectiveRightsFromAclW(dacl, &ident, &acc) == ERROR_SUCCESS) { finfo->protection |= convert_prot(acc, prot_scope_group); finfo->valid |= APR_FINFO_GPROT; } } if ((wanted & APR_FINFO_WPROT) && (worldid)) { ident.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; ident.ptstrName = worldid; if (GetEffectiveRightsFromAclW(dacl, &ident, &acc) == ERROR_SUCCESS) { finfo->protection |= convert_prot(acc, prot_scope_world); finfo->valid |= APR_FINFO_WPROT; } } } static apr_status_t resolve_ident(apr_finfo_t *finfo, const char *fname, apr_int32_t wanted, apr_pool_t *pool) { apr_file_t *thefile = NULL; apr_status_t rv; /* * NT5 (W2K) only supports symlinks in the same manner as mount points. * This code should eventually take that into account, for now treat * every reparse point as a symlink... * * We must open the file with READ_CONTROL if we plan to retrieve the * user, group or permissions. */ if ((rv = apr_file_open(&thefile, fname, APR_OPENINFO | ((wanted & APR_FINFO_LINK) ? APR_OPENLINK : 0) | ((wanted & (APR_FINFO_PROT | APR_FINFO_OWNER)) ? APR_READCONTROL : 0), APR_OS_DEFAULT, pool)) == APR_SUCCESS) { rv = apr_file_info_get(finfo, wanted, thefile); finfo->filehand = NULL; apr_file_close(thefile); } else if (APR_STATUS_IS_EACCES(rv) && (wanted & (APR_FINFO_PROT | APR_FINFO_OWNER))) { /* We have a backup plan. Perhaps we couldn't grab READ_CONTROL? * proceed without asking for that permission... */ if ((rv = apr_file_open(&thefile, fname, APR_OPENINFO | ((wanted & APR_FINFO_LINK) ? APR_OPENLINK : 0), APR_OS_DEFAULT, pool)) == APR_SUCCESS) { rv = apr_file_info_get(finfo, wanted & ~(APR_FINFO_PROT | APR_FINFO_OWNER), thefile); finfo->filehand = NULL; apr_file_close(thefile); } } if (rv != APR_SUCCESS && rv != APR_INCOMPLETE) return (rv); /* We picked up this case above and had opened the link's properties */ if (wanted & APR_FINFO_LINK) finfo->valid |= APR_FINFO_LINK; return rv; } static void guess_protection_bits(apr_finfo_t *finfo) { /* Read, write execute for owner. In the Win9x environment, any * readable file is executable (well, not entirely 100% true, but * still looking for some cheap logic that would help us here.) * The same holds on NT if a file doesn't have a DACL (e.g., on FAT) */ if (finfo->protection & APR_FREADONLY) { finfo->protection |= APR_WREAD | APR_WEXECUTE; } else { finfo->protection |= APR_WREAD | APR_WEXECUTE | APR_WWRITE; } finfo->protection |= (finfo->protection << prot_scope_group) | (finfo->protection << prot_scope_user); finfo->valid |= APR_FINFO_UPROT | APR_FINFO_GPROT | APR_FINFO_WPROT; } apr_status_t more_finfo(apr_finfo_t *finfo, const void *ufile, apr_int32_t wanted, int whatfile) { PSID user = NULL, grp = NULL; PACL dacl = NULL; apr_status_t rv; if (apr_os_level < APR_WIN_NT) guess_protection_bits(finfo); else if (wanted & (APR_FINFO_PROT | APR_FINFO_OWNER)) { /* On NT this request is incredibly expensive, but accurate. * Since the WinNT-only functions below are protected by the * (apr_os_level < APR_WIN_NT) case above, we need no extra * tests, but remember GetNamedSecurityInfo & GetSecurityInfo * are not supported on 9x. */ SECURITY_INFORMATION sinf = 0; PSECURITY_DESCRIPTOR pdesc = NULL; if (wanted & (APR_FINFO_USER | APR_FINFO_UPROT)) sinf |= OWNER_SECURITY_INFORMATION; if (wanted & (APR_FINFO_GROUP | APR_FINFO_GPROT)) sinf |= GROUP_SECURITY_INFORMATION; if (wanted & APR_FINFO_PROT) sinf |= DACL_SECURITY_INFORMATION; if (whatfile == MORE_OF_WFSPEC) { apr_wchar_t *wfile = (apr_wchar_t*) ufile; int fix = 0; if (wcsncmp(wfile, L"\\\\?\\", 4) == 0) { fix = 4; if (wcsncmp(wfile + fix, L"UNC\\", 4) == 0) wfile[6] = L'\\', fix = 6; } rv = GetNamedSecurityInfoW(wfile + fix, SE_FILE_OBJECT, sinf, ((wanted & (APR_FINFO_USER | APR_FINFO_UPROT)) ? &user : NULL), ((wanted & (APR_FINFO_GROUP | APR_FINFO_GPROT)) ? &grp : NULL), ((wanted & APR_FINFO_PROT) ? &dacl : NULL), NULL, &pdesc); if (fix == 6) wfile[6] = L'C'; } else if (whatfile == MORE_OF_FSPEC) rv = GetNamedSecurityInfoA((char*)ufile, SE_FILE_OBJECT, sinf, ((wanted & (APR_FINFO_USER | APR_FINFO_UPROT)) ? &user : NULL), ((wanted & (APR_FINFO_GROUP | APR_FINFO_GPROT)) ? &grp : NULL), ((wanted & APR_FINFO_PROT) ? &dacl : NULL), NULL, &pdesc); else if (whatfile == MORE_OF_HANDLE) rv = GetSecurityInfo((HANDLE)ufile, SE_FILE_OBJECT, sinf, ((wanted & (APR_FINFO_USER | APR_FINFO_UPROT)) ? &user : NULL), ((wanted & (APR_FINFO_GROUP | APR_FINFO_GPROT)) ? &grp : NULL), ((wanted & APR_FINFO_PROT) ? &dacl : NULL), NULL, &pdesc); else return APR_INCOMPLETE; if (rv == ERROR_SUCCESS) apr_pool_cleanup_register(finfo->pool, pdesc, free_localheap, apr_pool_cleanup_null); else user = grp = dacl = NULL; if (user) { finfo->user = user; finfo->valid |= APR_FINFO_USER; } if (grp) { finfo->group = grp; finfo->valid |= APR_FINFO_GROUP; } if (dacl) { /* Retrieved the discresionary access list */ resolve_prot(finfo, wanted, dacl); } else if (wanted & APR_FINFO_PROT) guess_protection_bits(finfo); } return ((wanted & ~finfo->valid) ? APR_INCOMPLETE : APR_SUCCESS); } /* This generic fillin depends upon byhandle to be passed as 0 when * a WIN32_FILE_ATTRIBUTE_DATA or either WIN32_FIND_DATA [A or W] is * passed for wininfo. When the BY_HANDLE_FILE_INFORMATION structure * is passed for wininfo, byhandle is passed as 1 to offset the one * dword discrepancy in offset of the High/Low size structure members. * * The generic fillin returns 1 if the caller should further inquire * if this is a CHR filetype. If it's reasonably certain it can't be, * then the function returns 0. */ int fillin_fileinfo(apr_finfo_t *finfo, WIN32_FILE_ATTRIBUTE_DATA *wininfo, int byhandle, apr_int32_t wanted) { DWORD *sizes = &wininfo->nFileSizeHigh + byhandle; int warn = 0; memset(finfo, '\0', sizeof(*finfo)); FileTimeToAprTime(&finfo->atime, &wininfo->ftLastAccessTime); FileTimeToAprTime(&finfo->ctime, &wininfo->ftCreationTime); FileTimeToAprTime(&finfo->mtime, &wininfo->ftLastWriteTime); #if APR_HAS_LARGE_FILES finfo->size = (apr_off_t)sizes[1] | ((apr_off_t)sizes[0] << 32); #else finfo->size = (apr_off_t)sizes[1]; if (finfo->size < 0 || sizes[0]) finfo->size = 0x7fffffff; #endif if (wanted & APR_FINFO_LINK && wininfo->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { finfo->filetype = APR_LNK; } else if (wininfo->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { finfo->filetype = APR_DIR; } else if (wininfo->dwFileAttributes & FILE_ATTRIBUTE_DEVICE) { /* Warning: This test only succeeds on Win9x, on NT these files * (con, aux, nul, lpt#, com# etc) escape early detection! */ finfo->filetype = APR_CHR; } else { /* Warning: Short of opening the handle to the file, the 'FileType' * appears to be unknowable (in any trustworthy or consistent sense) * on WinNT/2K as far as PIPE, CHR, etc are concerned. */ if (!wininfo->ftLastWriteTime.dwLowDateTime && !wininfo->ftLastWriteTime.dwHighDateTime && !finfo->size) warn = 1; finfo->filetype = APR_REG; } /* The following flags are [for this moment] private to Win32. * That's the only excuse for not toggling valid bits to reflect them. */ if (wininfo->dwFileAttributes & FILE_ATTRIBUTE_READONLY) finfo->protection = APR_FREADONLY; finfo->valid = APR_FINFO_ATIME | APR_FINFO_CTIME | APR_FINFO_MTIME | APR_FINFO_SIZE | APR_FINFO_TYPE; /* == APR_FINFO_MIN */ /* Only byhandle optionally tests link targets, so tell that caller * what it wants to hear, otherwise the byattributes is never * reporting anything but the link. */ if (!byhandle || (wanted & APR_FINFO_LINK)) finfo->valid |= APR_FINFO_LINK; return warn; } APR_DECLARE(apr_status_t) apr_file_info_get(apr_finfo_t *finfo, apr_int32_t wanted, apr_file_t *thefile) { BY_HANDLE_FILE_INFORMATION FileInfo; if (thefile->buffered) { /* XXX: flush here is not mutex protected */ apr_status_t rv = apr_file_flush(thefile); if (rv != APR_SUCCESS) return rv; } if (!GetFileInformationByHandle(thefile->filehand, &FileInfo)) { return apr_get_os_error(); } fillin_fileinfo(finfo, (WIN32_FILE_ATTRIBUTE_DATA *) &FileInfo, 1, wanted); if (finfo->filetype == APR_REG) { /* Go the extra mile to be -certain- that we have a real, regular * file, since the attribute bits aren't a certain thing. Even * though fillin should have hinted if we *must* do this, we * don't need to take chances while the handle is already open. */ DWORD FileType; if (FileType = GetFileType(thefile->filehand)) { if (FileType == FILE_TYPE_CHAR) { finfo->filetype = APR_CHR; } else if (FileType == FILE_TYPE_PIPE) { finfo->filetype = APR_PIPE; } /* Otherwise leave the original conclusion alone */ } } finfo->pool = thefile->pool; /* ### The finfo lifetime may exceed the lifetime of thefile->pool * but finfo's aren't managed in pools, so where on earth would * we pstrdup the fname into??? */ finfo->fname = thefile->fname; /* Extra goodies known only by GetFileInformationByHandle() */ finfo->inode = (apr_ino_t)FileInfo.nFileIndexLow | ((apr_ino_t)FileInfo.nFileIndexHigh << 32); finfo->device = FileInfo.dwVolumeSerialNumber; finfo->nlink = FileInfo.nNumberOfLinks; finfo->valid |= APR_FINFO_IDENT | APR_FINFO_NLINK; /* If we still want something more (besides the name) go get it! */ if ((wanted &= ~finfo->valid) & ~APR_FINFO_NAME) { return more_finfo(finfo, thefile->filehand, wanted, MORE_OF_HANDLE); } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_perms_set(const char *fname, apr_fileperms_t perms) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_stat(apr_finfo_t *finfo, const char *fname, apr_int32_t wanted, apr_pool_t *pool) { /* XXX: is constant - needs testing - which requires a lighter-weight root test fn */ int isroot = 0; apr_status_t ident_rv = 0; apr_status_t rv; #if APR_HAS_UNICODE_FS apr_wchar_t wfname[APR_PATH_MAX]; #endif char *filename = NULL; /* These all share a common subset of this structure */ union { WIN32_FIND_DATAW w; WIN32_FIND_DATAA n; WIN32_FILE_ATTRIBUTE_DATA i; } FileInfo; /* Catch fname length == MAX_PATH since GetFileAttributesEx fails * with PATH_NOT_FOUND. We would rather indicate length error than * 'not found' */ if (strlen(fname) >= APR_PATH_MAX) { return APR_ENAMETOOLONG; } #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { if ((wanted & (APR_FINFO_IDENT | APR_FINFO_NLINK)) || (~wanted & APR_FINFO_LINK)) { /* FindFirstFile and GetFileAttributesEx can't figure the inode, * device or number of links, so we need to resolve with an open * file handle. If the user has asked for these fields, fall over * to the get file info by handle method. If we fail, or the user * also asks for the file name, continue by our usual means. * * We also must use this method for a 'true' stat, that resolves * a symlink (NTFS Junction) target. This is because all fileinfo * on a Junction always returns the junction, opening the target * is the only way to resolve the target's attributes. */ if ((ident_rv = resolve_ident(finfo, fname, wanted, pool)) == APR_SUCCESS) return ident_rv; else if (ident_rv == APR_INCOMPLETE) wanted &= ~finfo->valid; } if (rv = utf8_to_unicode_path(wfname, sizeof(wfname) / sizeof(apr_wchar_t), fname)) return rv; if (!(wanted & APR_FINFO_NAME)) { if (!GetFileAttributesExW(wfname, GetFileExInfoStandard, &FileInfo.i)) return apr_get_os_error(); } else { /* Guard against bogus wildcards and retrieve by name * since we want the true name, and set aside a long * enough string to handle the longest file name. */ char tmpname[APR_FILE_MAX * 3 + 1]; HANDLE hFind; if ((rv = test_safe_name(fname)) != APR_SUCCESS) { return rv; } hFind = FindFirstFileW(wfname, &FileInfo.w); if (hFind == INVALID_HANDLE_VALUE) return apr_get_os_error(); FindClose(hFind); if (unicode_to_utf8_path(tmpname, sizeof(tmpname), FileInfo.w.cFileName)) { return APR_ENAMETOOLONG; } filename = apr_pstrdup(pool, tmpname); } } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { char *root = NULL; const char *test = fname; rv = apr_filepath_root(&root, &test, APR_FILEPATH_NATIVE, pool); isroot = (root && *root && !(*test)); if ((apr_os_level >= APR_WIN_98) && (!(wanted & APR_FINFO_NAME) || isroot)) { /* cannot use FindFile on a Win98 root, it returns \* * GetFileAttributesExA is not available on Win95 */ if (!GetFileAttributesExA(fname, GetFileExInfoStandard, &FileInfo.i)) { return apr_get_os_error(); } } else if (isroot) { /* This is Win95 and we are trying to stat a root. Lie. */ if (GetDriveType(fname) != DRIVE_UNKNOWN) { finfo->pool = pool; finfo->filetype = 0; finfo->mtime = apr_time_now(); finfo->protection |= APR_WREAD | APR_WEXECUTE | APR_WWRITE; finfo->protection |= (finfo->protection << prot_scope_group) | (finfo->protection << prot_scope_user); finfo->valid |= APR_FINFO_TYPE | APR_FINFO_PROT | APR_FINFO_MTIME | (wanted & APR_FINFO_LINK); return (wanted &= ~finfo->valid) ? APR_INCOMPLETE : APR_SUCCESS; } else return APR_FROM_OS_ERROR(ERROR_PATH_NOT_FOUND); } else { /* Guard against bogus wildcards and retrieve by name * since we want the true name, or are stuck in Win95, * or are looking for the root of a Win98 drive. */ HANDLE hFind; if ((rv = test_safe_name(fname)) != APR_SUCCESS) { return rv; } hFind = FindFirstFileA(fname, &FileInfo.n); if (hFind == INVALID_HANDLE_VALUE) { return apr_get_os_error(); } FindClose(hFind); filename = apr_pstrdup(pool, FileInfo.n.cFileName); } } #endif if (ident_rv != APR_INCOMPLETE) { if (fillin_fileinfo(finfo, (WIN32_FILE_ATTRIBUTE_DATA *) &FileInfo, 0, wanted)) { /* Go the extra mile to assure we have a file. WinNT/2000 seems * to reliably translate char devices to the path '\\.\device' * so go ask for the full path. */ if (apr_os_level >= APR_WIN_NT) { #if APR_HAS_UNICODE_FS apr_wchar_t tmpname[APR_FILE_MAX]; apr_wchar_t *tmpoff = NULL; if (GetFullPathNameW(wfname, sizeof(tmpname) / sizeof(apr_wchar_t), tmpname, &tmpoff)) { if (!wcsncmp(tmpname, L"\\\\.\\", 4)) { #else /* Same initial logic as above, but * only for WinNT/non-UTF-8 builds of APR: */ char tmpname[APR_FILE_MAX]; char *tmpoff; if (GetFullPathName(fname, sizeof(tmpname), tmpname, &tmpoff)) { if (!strncmp(tmpname, "\\\\.\\", 4)) { #endif if (tmpoff == tmpname + 4) { finfo->filetype = APR_CHR; } /* For WHATEVER reason, CHR devices such as \\.\con * or \\.\lpt1 *may*not* update tmpoff; in fact the * resulting tmpoff is set to NULL. Guard against * either case. * * This code is identical for wide and narrow chars... */ else if (!tmpoff) { tmpoff = tmpname + 4; while (*tmpoff) { if (*tmpoff == '\\' || *tmpoff == '/') { break; } ++tmpoff; } if (!*tmpoff) { finfo->filetype = APR_CHR; } } } } else { finfo->valid &= ~APR_FINFO_TYPE; } } else { finfo->valid &= ~APR_FINFO_TYPE; } } finfo->pool = pool; } if (filename && !isroot) { finfo->name = filename; finfo->valid |= APR_FINFO_NAME; } if (wanted &= ~finfo->valid) { /* Caller wants more than APR_FINFO_MIN | APR_FINFO_NAME */ #if APR_HAS_UNICODE_FS if (apr_os_level >= APR_WIN_NT) return more_finfo(finfo, wfname, wanted, MORE_OF_WFSPEC); #endif return more_finfo(finfo, fname, wanted, MORE_OF_FSPEC); } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_attrs_set(const char *fname, apr_fileattrs_t attributes, apr_fileattrs_t attr_mask, apr_pool_t *pool) { DWORD flags; apr_status_t rv; #if APR_HAS_UNICODE_FS apr_wchar_t wfname[APR_PATH_MAX]; #endif /* Don't do anything if we can't handle the requested attributes */ if (!(attr_mask & (APR_FILE_ATTR_READONLY | APR_FILE_ATTR_HIDDEN))) return APR_SUCCESS; #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { if (rv = utf8_to_unicode_path(wfname, sizeof(wfname) / sizeof(wfname[0]), fname)) return rv; flags = GetFileAttributesW(wfname); } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { flags = GetFileAttributesA(fname); } #endif if (flags == 0xFFFFFFFF) return apr_get_os_error(); if (attr_mask & APR_FILE_ATTR_READONLY) { if (attributes & APR_FILE_ATTR_READONLY) flags |= FILE_ATTRIBUTE_READONLY; else flags &= ~FILE_ATTRIBUTE_READONLY; } if (attr_mask & APR_FILE_ATTR_HIDDEN) { if (attributes & APR_FILE_ATTR_HIDDEN) flags |= FILE_ATTRIBUTE_HIDDEN; else flags &= ~FILE_ATTRIBUTE_HIDDEN; } #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { rv = SetFileAttributesW(wfname, flags); } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { rv = SetFileAttributesA(fname, flags); } #endif if (rv == 0) return apr_get_os_error(); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_mtime_set(const char *fname, apr_time_t mtime, apr_pool_t *pool) { apr_file_t *thefile; apr_status_t rv; rv = apr_file_open(&thefile, fname, APR_READ | APR_WRITEATTRS, APR_OS_DEFAULT, pool); if (!rv) { FILETIME file_ctime; FILETIME file_atime; FILETIME file_mtime; if (!GetFileTime(thefile->filehand, &file_ctime, &file_atime, &file_mtime)) rv = apr_get_os_error(); else { AprTimeToFileTime(&file_mtime, mtime); if (!SetFileTime(thefile->filehand, &file_ctime, &file_atime, &file_mtime)) rv = apr_get_os_error(); } apr_file_close(thefile); } return rv; }
001-log4cxx
trunk/src/apr/file_io/win32/filestat.c
C
asf20
27,423
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_private.h" #include "apr_arch_file_io.h" #include "apr_file_io.h" #include "apr_general.h" #include "apr_strings.h" #include "apr_portable.h" #include "apr_thread_mutex.h" #if APR_HAVE_ERRNO_H #include <errno.h> #endif #include <winbase.h> #include <string.h> #if APR_HAVE_SYS_STAT_H #include <sys/stat.h> #endif #include "apr_arch_misc.h" #include "apr_arch_inherit.h" #if APR_HAS_UNICODE_FS apr_status_t utf8_to_unicode_path(apr_wchar_t* retstr, apr_size_t retlen, const char* srcstr) { /* TODO: The computations could preconvert the string to determine * the true size of the retstr, but that's a memory over speed * tradeoff that isn't appropriate this early in development. * * Allocate the maximum string length based on leading 4 * characters of \\?\ (allowing nearly unlimited path lengths) * plus the trailing null, then transform /'s into \\'s since * the \\?\ form doesn't allow '/' path seperators. * * Note that the \\?\ form only works for local drive paths, and * \\?\UNC\ is needed UNC paths. */ apr_size_t srcremains = strlen(srcstr) + 1; apr_wchar_t *t = retstr; apr_status_t rv; /* This is correct, we don't twist the filename if it is will * definately be shorter than MAX_PATH. It merits some * performance testing to see if this has any effect, but there * seem to be applications that get confused by the resulting * Unicode \\?\ style file names, especially if they use argv[0] * or call the Win32 API functions such as GetModuleName, etc. * Not every application is prepared to handle such names. * * Note that a utf-8 name can never result in more wide chars * than the original number of utf-8 narrow chars. */ if (srcremains > MAX_PATH) { if (srcstr[1] == ':' && (srcstr[2] == '/' || srcstr[2] == '\\')) { wcscpy (retstr, L"\\\\?\\"); retlen -= 4; t += 4; } else if ((srcstr[0] == '/' || srcstr[0] == '\\') && (srcstr[1] == '/' || srcstr[1] == '\\') && (srcstr[2] != '?')) { /* Skip the slashes */ srcstr += 2; srcremains -= 2; wcscpy (retstr, L"\\\\?\\UNC\\"); retlen -= 8; t += 8; } } if (rv = apr_conv_utf8_to_ucs2(srcstr, &srcremains, t, &retlen)) { return (rv == APR_INCOMPLETE) ? APR_EINVAL : rv; } if (srcremains) { return APR_ENAMETOOLONG; } for (; *t; ++t) if (*t == L'/') *t = L'\\'; return APR_SUCCESS; } apr_status_t unicode_to_utf8_path(char* retstr, apr_size_t retlen, const apr_wchar_t* srcstr) { /* Skip the leading 4 characters if the path begins \\?\, or substitute * // for the \\?\UNC\ path prefix, allocating the maximum string * length based on the remaining string, plus the trailing null. * then transform \\'s back into /'s since the \\?\ form never * allows '/' path seperators, and APR always uses '/'s. */ apr_size_t srcremains = wcslen(srcstr) + 1; apr_status_t rv; char *t = retstr; if (srcstr[0] == L'\\' && srcstr[1] == L'\\' && srcstr[2] == L'?' && srcstr[3] == L'\\') { if (srcstr[4] == L'U' && srcstr[5] == L'N' && srcstr[6] == L'C' && srcstr[7] == L'\\') { srcremains -= 8; srcstr += 8; retstr[0] = '\\'; retstr[1] = '\\'; retlen -= 2; t += 2; } else { srcremains -= 4; srcstr += 4; } } if (rv = apr_conv_ucs2_to_utf8(srcstr, &srcremains, t, &retlen)) { return rv; } if (srcremains) { return APR_ENAMETOOLONG; } return APR_SUCCESS; } #endif void *res_name_from_filename(const char *file, int global, apr_pool_t *pool) { #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { apr_wchar_t *wpre, *wfile, *ch; apr_size_t n = strlen(file) + 1; apr_size_t r, d; apr_status_t rv; if (apr_os_level >= APR_WIN_2000) { if (global) wpre = L"Global\\"; else wpre = L"Local\\"; } else wpre = L""; r = wcslen(wpre); if (n > 256 - r) { file += n - 256 - r; n = 256; /* skip utf8 continuation bytes */ while ((*file & 0xC0) == 0x80) { ++file; --n; } } wfile = apr_palloc(pool, (r + n) * sizeof(apr_wchar_t)); wcscpy(wfile, wpre); d = n; if (rv = apr_conv_utf8_to_ucs2(file, &n, wfile + r, &d)) { return NULL; } for (ch = wfile + r; *ch; ++ch) { if (*ch == ':' || *ch == '/' || *ch == '\\') *ch = '_'; } return wfile; } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { char *nfile, *ch; apr_size_t n = strlen(file) + 1; #if !APR_HAS_UNICODE_FS apr_status_t rv; apr_size_t r, d; char *pre; if (apr_os_level >= APR_WIN_2000) { if (global) pre = "Global\\"; else pre = "Local\\"; } else pre = ""; r = strlen(pre); if (n > 256 - r) { file += n - 256 - r; n = 256; } nfile = apr_palloc(pool, (r + n) * sizeof(apr_wchar_t)); memcpy(nfile, pre, r); memcpy(nfile + r, file, n); #else const apr_size_t r = 0; if (n > 256) { file += n - 256; n = 256; } nfile = apr_pmemdup(pool, file, n); #endif for (ch = nfile + r; *ch; ++ch) { if (*ch == ':' || *ch == '/' || *ch == '\\') *ch = '_'; } return nfile; } #endif } apr_status_t file_cleanup(void *thefile) { apr_file_t *file = thefile; apr_status_t flush_rv = APR_SUCCESS; if (file->filehand != INVALID_HANDLE_VALUE) { /* In order to avoid later segfaults with handle 'reuse', * we must protect against the case that a dup2'ed handle * is being closed, and invalidate the corresponding StdHandle */ if (file->filehand == GetStdHandle(STD_ERROR_HANDLE)) { SetStdHandle(STD_ERROR_HANDLE, INVALID_HANDLE_VALUE); } if (file->filehand == GetStdHandle(STD_OUTPUT_HANDLE)) { SetStdHandle(STD_OUTPUT_HANDLE, INVALID_HANDLE_VALUE); } if (file->filehand == GetStdHandle(STD_INPUT_HANDLE)) { SetStdHandle(STD_INPUT_HANDLE, INVALID_HANDLE_VALUE); } if (file->buffered) { /* XXX: flush here is not mutex protected */ flush_rv = apr_file_flush((apr_file_t *)thefile); } CloseHandle(file->filehand); file->filehand = INVALID_HANDLE_VALUE; } if (file->pOverlapped && file->pOverlapped->hEvent) { CloseHandle(file->pOverlapped->hEvent); file->pOverlapped = NULL; } return flush_rv; } APR_DECLARE(apr_status_t) apr_file_open(apr_file_t **new, const char *fname, apr_int32_t flag, apr_fileperms_t perm, apr_pool_t *pool) { HANDLE handle = INVALID_HANDLE_VALUE; DWORD oflags = 0; DWORD createflags = 0; DWORD attributes = 0; DWORD sharemode = FILE_SHARE_READ | FILE_SHARE_WRITE; apr_status_t rv; if (flag & APR_READ) { oflags |= GENERIC_READ; } if (flag & APR_WRITE) { oflags |= GENERIC_WRITE; } if (flag & APR_WRITEATTRS) { oflags |= FILE_WRITE_ATTRIBUTES; } if (apr_os_level >= APR_WIN_NT) sharemode |= FILE_SHARE_DELETE; if (flag & APR_CREATE) { if (flag & APR_EXCL) { /* only create new if file does not already exist */ createflags = CREATE_NEW; } else if (flag & APR_TRUNCATE) { /* truncate existing file or create new */ createflags = CREATE_ALWAYS; } else { /* open existing but create if necessary */ createflags = OPEN_ALWAYS; } } else if (flag & APR_TRUNCATE) { /* only truncate if file already exists */ createflags = TRUNCATE_EXISTING; } else { /* only open if file already exists */ createflags = OPEN_EXISTING; } if ((flag & APR_EXCL) && !(flag & APR_CREATE)) { return APR_EACCES; } if (flag & APR_DELONCLOSE) { attributes |= FILE_FLAG_DELETE_ON_CLOSE; } if (flag & APR_OPENLINK) { attributes |= FILE_FLAG_OPEN_REPARSE_POINT; } /* Without READ or WRITE, we fail unless apr called apr_file_open * internally with the private APR_OPENINFO flag. * * With the APR_OPENINFO flag on NT, use the option flag * FILE_FLAG_BACKUP_SEMANTICS to allow us to open directories. * See the static resolve_ident() fn in file_io/win32/filestat.c */ if (!(flag & (APR_READ | APR_WRITE))) { if (flag & APR_OPENINFO) { if (apr_os_level >= APR_WIN_NT) { attributes |= FILE_FLAG_BACKUP_SEMANTICS; } } else { return APR_EACCES; } if (flag & APR_READCONTROL) oflags |= READ_CONTROL; } if (flag & APR_XTHREAD) { /* This win32 specific feature is required * to allow multiple threads to work with the file. */ attributes |= FILE_FLAG_OVERLAPPED; } #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { apr_wchar_t wfname[APR_PATH_MAX]; if (flag & APR_SENDFILE_ENABLED) { /* This feature is required to enable sendfile operations * against the file on Win32. Also implies APR_XTHREAD. */ flag |= APR_XTHREAD; attributes |= FILE_FLAG_SEQUENTIAL_SCAN | FILE_FLAG_OVERLAPPED; } if (rv = utf8_to_unicode_path(wfname, sizeof(wfname) / sizeof(apr_wchar_t), fname)) return rv; handle = CreateFileW(wfname, oflags, sharemode, NULL, createflags, attributes, 0); } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { handle = CreateFileA(fname, oflags, sharemode, NULL, createflags, attributes, 0); if (flag & APR_SENDFILE_ENABLED) { /* This feature is not supported on this platform. */ flag &= ~APR_SENDFILE_ENABLED; } } #endif if (handle == INVALID_HANDLE_VALUE) { return apr_get_os_error(); } (*new) = (apr_file_t *)apr_pcalloc(pool, sizeof(apr_file_t)); (*new)->pool = pool; (*new)->filehand = handle; (*new)->fname = apr_pstrdup(pool, fname); (*new)->flags = flag; (*new)->timeout = -1; (*new)->ungetchar = -1; if (flag & APR_APPEND) { (*new)->append = 1; SetFilePointer((*new)->filehand, 0, NULL, FILE_END); } if (flag & APR_BUFFERED) { (*new)->buffered = 1; (*new)->buffer = apr_palloc(pool, APR_FILE_BUFSIZE); } /* Need the mutex to handled buffered and O_APPEND style file i/o */ if ((*new)->buffered || (*new)->append) { rv = apr_thread_mutex_create(&(*new)->mutex, APR_THREAD_MUTEX_DEFAULT, pool); if (rv) { if (file_cleanup(*new) == APR_SUCCESS) { apr_pool_cleanup_kill(pool, *new, file_cleanup); } return rv; } } /* Create a pollset with room for one descriptor. */ /* ### check return codes */ (void) apr_pollset_create(&(*new)->pollset, 1, pool, 0); if (!(flag & APR_FILE_NOCLEANUP)) { apr_pool_cleanup_register((*new)->pool, (void *)(*new), file_cleanup, apr_pool_cleanup_null); } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_close(apr_file_t *file) { apr_status_t stat; if ((stat = file_cleanup(file)) == APR_SUCCESS) { apr_pool_cleanup_kill(file->pool, file, file_cleanup); if (file->mutex) { apr_thread_mutex_destroy(file->mutex); } return APR_SUCCESS; } return stat; } APR_DECLARE(apr_status_t) apr_file_remove(const char *path, apr_pool_t *pool) { #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { apr_wchar_t wpath[APR_PATH_MAX]; apr_status_t rv; if (rv = utf8_to_unicode_path(wpath, sizeof(wpath) / sizeof(apr_wchar_t), path)) { return rv; } if (DeleteFileW(wpath)) return APR_SUCCESS; } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI if (DeleteFile(path)) return APR_SUCCESS; #endif return apr_get_os_error(); } APR_DECLARE(apr_status_t) apr_file_rename(const char *frompath, const char *topath, apr_pool_t *pool) { IF_WIN_OS_IS_UNICODE { #if APR_HAS_UNICODE_FS apr_wchar_t wfrompath[APR_PATH_MAX], wtopath[APR_PATH_MAX]; apr_status_t rv; if (rv = utf8_to_unicode_path(wfrompath, sizeof(wfrompath) / sizeof(apr_wchar_t), frompath)) { return rv; } if (rv = utf8_to_unicode_path(wtopath, sizeof(wtopath) / sizeof(apr_wchar_t), topath)) { return rv; } #ifndef _WIN32_WCE if (MoveFileExW(wfrompath, wtopath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED)) #else if (MoveFileW(wfrompath, wtopath)) #endif return APR_SUCCESS; #else if (MoveFileEx(frompath, topath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED)) return APR_SUCCESS; #endif } #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { /* Windows 95 and 98 do not support MoveFileEx, so we'll use * the old MoveFile function. However, MoveFile requires that * the new file not already exist...so we have to delete that * file if it does. Perhaps we should back up the to-be-deleted * file in case something happens? */ HANDLE handle = INVALID_HANDLE_VALUE; if ((handle = CreateFile(topath, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE ) { CloseHandle(handle); if (!DeleteFile(topath)) return apr_get_os_error(); } if (MoveFile(frompath, topath)) return APR_SUCCESS; } #endif return apr_get_os_error(); } APR_DECLARE(apr_status_t) apr_os_file_get(apr_os_file_t *thefile, apr_file_t *file) { *thefile = file->filehand; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_file_put(apr_file_t **file, apr_os_file_t *thefile, apr_int32_t flags, apr_pool_t *pool) { (*file) = apr_pcalloc(pool, sizeof(apr_file_t)); (*file)->pool = pool; (*file)->filehand = *thefile; (*file)->ungetchar = -1; /* no char avail */ (*file)->timeout = -1; (*file)->flags = flags; if (flags & APR_APPEND) { (*file)->append = 1; } if (flags & APR_BUFFERED) { (*file)->buffered = 1; (*file)->buffer = apr_palloc(pool, APR_FILE_BUFSIZE); } if ((*file)->append || (*file)->buffered) { apr_status_t rv; rv = apr_thread_mutex_create(&(*file)->mutex, APR_THREAD_MUTEX_DEFAULT, pool); if (rv) { if (file_cleanup(*file) == APR_SUCCESS) { apr_pool_cleanup_kill(pool, *file, file_cleanup); } return rv; } } /* Create a pollset with room for one descriptor. */ /* ### check return codes */ (void) apr_pollset_create(&(*file)->pollset, 1, pool, 0); /* XXX... we pcalloc above so all others are zeroed. * Should we be testing if thefile is a handle to * a PIPE and set up the mechanics appropriately? * * (*file)->pipe; */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_eof(apr_file_t *fptr) { if (fptr->eof_hit == 1) { return APR_EOF; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_open_stderr(apr_file_t **thefile, apr_pool_t *pool) { #ifdef _WIN32_WCE return APR_ENOTIMPL; #else apr_os_file_t file_handle; apr_set_os_error(APR_SUCCESS); file_handle = GetStdHandle(STD_ERROR_HANDLE); if (!file_handle || (file_handle == INVALID_HANDLE_VALUE)) { apr_status_t rv = apr_get_os_error(); if (rv == APR_SUCCESS) { return APR_EINVAL; } return rv; } return apr_os_file_put(thefile, &file_handle, 0, pool); #endif } APR_DECLARE(apr_status_t) apr_file_open_stdout(apr_file_t **thefile, apr_pool_t *pool) { #ifdef _WIN32_WCE return APR_ENOTIMPL; #else apr_os_file_t file_handle; apr_set_os_error(APR_SUCCESS); file_handle = GetStdHandle(STD_OUTPUT_HANDLE); if (!file_handle || (file_handle == INVALID_HANDLE_VALUE)) { apr_status_t rv = apr_get_os_error(); if (rv == APR_SUCCESS) { return APR_EINVAL; } return rv; } return apr_os_file_put(thefile, &file_handle, 0, pool); #endif } APR_DECLARE(apr_status_t) apr_file_open_stdin(apr_file_t **thefile, apr_pool_t *pool) { #ifdef _WIN32_WCE return APR_ENOTIMPL; #else apr_os_file_t file_handle; apr_set_os_error(APR_SUCCESS); file_handle = GetStdHandle(STD_INPUT_HANDLE); if (!file_handle || (file_handle == INVALID_HANDLE_VALUE)) { apr_status_t rv = apr_get_os_error(); if (rv == APR_SUCCESS) { return APR_EINVAL; } return rv; } return apr_os_file_put(thefile, &file_handle, 0, pool); #endif } APR_POOL_IMPLEMENT_ACCESSOR(file); APR_IMPLEMENT_INHERIT_SET(file, flags, pool, file_cleanup) APR_IMPLEMENT_INHERIT_UNSET(file, flags, pool, file_cleanup)
001-log4cxx
trunk/src/apr/file_io/win32/open.c
C
asf20
19,438
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "win32/apr_arch_file_io.h" #include "apr_file_io.h" #include "apr_general.h" #include "apr_strings.h" #if APR_HAVE_ERRNO_H #include <errno.h> #endif #include <string.h> #include <stdio.h> #if APR_HAVE_SYS_TYPES_H #include <sys/types.h> #endif #if APR_HAVE_SYS_STAT_H #include <sys/stat.h> #endif #include "apr_arch_misc.h" APR_DECLARE(apr_status_t) apr_file_pipe_timeout_set(apr_file_t *thepipe, apr_interval_time_t timeout) { /* Always OK to unset timeouts */ if (timeout == -1) { thepipe->timeout = timeout; return APR_SUCCESS; } if (!thepipe->pipe) { return APR_ENOTIMPL; } if (timeout && !(thepipe->pOverlapped)) { /* Cannot be nonzero if a pipe was opened blocking */ return APR_EINVAL; } thepipe->timeout = timeout; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_pipe_timeout_get(apr_file_t *thepipe, apr_interval_time_t *timeout) { /* Always OK to get the timeout (even if it's unset ... -1) */ *timeout = thepipe->timeout; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_pipe_create(apr_file_t **in, apr_file_t **out, apr_pool_t *p) { /* Unix creates full blocking pipes. */ return apr_create_nt_pipe(in, out, APR_FULL_BLOCK, p); } /* apr_create_nt_pipe() * An internal (for now) APR function used by apr_proc_create() * when setting up pipes to communicate with the child process. * apr_create_nt_pipe() allows setting the blocking mode of each end of * the pipe when the pipe is created (rather than after the pipe is created). * A pipe handle must be opened in full async i/o mode in order to * emulate Unix non-blocking pipes with timeouts. * * In general, we don't want to enable child side pipe handles for async i/o. * This prevents us from enabling both ends of the pipe for async i/o in * apr_file_pipe_create. * * Why not use NamedPipes on NT which support setting pipe state to * non-blocking? On NT, even though you can set a pipe non-blocking, * there is no clean way to set event driven non-zero timeouts (e.g select(), * WaitForSinglelObject, et. al. will not detect pipe i/o). On NT, you * have to poll the pipe to detect i/o on a non-blocking pipe. */ apr_status_t apr_create_nt_pipe(apr_file_t **in, apr_file_t **out, apr_int32_t blocking_mode, apr_pool_t *p) { #ifdef _WIN32_WCE return APR_ENOTIMPL; #else SECURITY_ATTRIBUTES sa; static unsigned long id = 0; DWORD dwPipeMode; DWORD dwOpenMode; char name[50]; sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; (*in) = (apr_file_t *)apr_pcalloc(p, sizeof(apr_file_t)); (*in)->pool = p; (*in)->fname = NULL; (*in)->pipe = 1; (*in)->timeout = -1; (*in)->ungetchar = -1; (*in)->eof_hit = 0; (*in)->filePtr = 0; (*in)->bufpos = 0; (*in)->dataRead = 0; (*in)->direction = 0; (*in)->pOverlapped = NULL; (void) apr_pollset_create(&(*in)->pollset, 1, p, 0); (*out) = (apr_file_t *)apr_pcalloc(p, sizeof(apr_file_t)); (*out)->pool = p; (*out)->fname = NULL; (*out)->pipe = 1; (*out)->timeout = -1; (*out)->ungetchar = -1; (*out)->eof_hit = 0; (*out)->filePtr = 0; (*out)->bufpos = 0; (*out)->dataRead = 0; (*out)->direction = 0; (*out)->pOverlapped = NULL; (void) apr_pollset_create(&(*out)->pollset, 1, p, 0); if (apr_os_level >= APR_WIN_NT) { /* Create the read end of the pipe */ dwOpenMode = PIPE_ACCESS_INBOUND; if (blocking_mode == APR_WRITE_BLOCK /* READ_NONBLOCK */ || blocking_mode == APR_FULL_NONBLOCK) { dwOpenMode |= FILE_FLAG_OVERLAPPED; (*in)->pOverlapped = (OVERLAPPED*) apr_pcalloc(p, sizeof(OVERLAPPED)); (*in)->pOverlapped->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); } dwPipeMode = 0; sprintf(name, "\\\\.\\pipe\\apr-pipe-%u.%lu", getpid(), id++); (*in)->filehand = CreateNamedPipe(name, dwOpenMode, dwPipeMode, 1, //nMaxInstances, 0, //nOutBufferSize, 65536, //nInBufferSize, 1, //nDefaultTimeOut, &sa); /* Create the write end of the pipe */ dwOpenMode = FILE_ATTRIBUTE_NORMAL; if (blocking_mode == APR_READ_BLOCK /* WRITE_NONBLOCK */ || blocking_mode == APR_FULL_NONBLOCK) { dwOpenMode |= FILE_FLAG_OVERLAPPED; (*out)->pOverlapped = (OVERLAPPED*) apr_pcalloc(p, sizeof(OVERLAPPED)); (*out)->pOverlapped->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); } (*out)->filehand = CreateFile(name, GENERIC_WRITE, // access mode 0, // share mode &sa, // Security attributes OPEN_EXISTING, // dwCreationDisposition dwOpenMode, // Pipe attributes NULL); // handle to template file } else { /* Pipes on Win9* are blocking. Live with it. */ if (!CreatePipe(&(*in)->filehand, &(*out)->filehand, &sa, 65536)) { return apr_get_os_error(); } } apr_pool_cleanup_register((*in)->pool, (void *)(*in), file_cleanup, apr_pool_cleanup_null); apr_pool_cleanup_register((*out)->pool, (void *)(*out), file_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; #endif /* _WIN32_WCE */ } APR_DECLARE(apr_status_t) apr_file_namedpipe_create(const char *filename, apr_fileperms_t perm, apr_pool_t *pool) { /* Not yet implemented, interface not suitable. * Win32 requires the named pipe to be *opened* at the time it's * created, and to do so, blocking or non blocking must be elected. */ return APR_ENOTIMPL; } /* XXX: Problem; we need to choose between blocking and nonblocking based * on how *thefile was opened, and we don't have that information :-/ * Hack; assume a blocking socket, since the most common use for the fn * would be to handle stdio-style or blocking pipes. Win32 doesn't have * select() blocking for pipes anyways :( */ APR_DECLARE(apr_status_t) apr_os_pipe_put_ex(apr_file_t **file, apr_os_file_t *thefile, int register_cleanup, apr_pool_t *pool) { (*file) = apr_pcalloc(pool, sizeof(apr_file_t)); (*file)->pool = pool; (*file)->pipe = 1; (*file)->timeout = -1; (*file)->ungetchar = -1; (*file)->filehand = *thefile; (void) apr_pollset_create(&(*file)->pollset, 1, pool, 0); if (register_cleanup) { apr_pool_cleanup_register(pool, *file, file_cleanup, apr_pool_cleanup_null); } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_pipe_put(apr_file_t **file, apr_os_file_t *thefile, apr_pool_t *pool) { return apr_os_pipe_put_ex(file, thefile, 0, pool); }
001-log4cxx
trunk/src/apr/file_io/win32/pipe.c
C
asf20
8,561
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_arch_file_io.h" #include "apr_file_io.h" #include "apr_strings.h" #include "apr_portable.h" #include "apr_arch_atime.h" #if APR_HAVE_ERRNO_H #include <errno.h> #endif #if APR_HAVE_STRING_H #include <string.h> #endif #if APR_HAVE_DIRENT_H #include <dirent.h> #endif #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif static apr_status_t dir_cleanup(void *thedir) { apr_dir_t *dir = thedir; if (dir->dirhand != INVALID_HANDLE_VALUE && !FindClose(dir->dirhand)) { return apr_get_os_error(); } dir->dirhand = INVALID_HANDLE_VALUE; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_dir_open(apr_dir_t **new, const char *dirname, apr_pool_t *pool) { apr_status_t rv; apr_size_t len = strlen(dirname); (*new) = apr_pcalloc(pool, sizeof(apr_dir_t)); /* Leave room here to add and pop the '*' wildcard for FindFirstFile * and double-null terminate so we have one character to change. */ (*new)->dirname = apr_palloc(pool, len + 3); memcpy((*new)->dirname, dirname, len); if (len && (*new)->dirname[len - 1] != '/') { (*new)->dirname[len++] = '/'; } (*new)->dirname[len++] = '\0'; (*new)->dirname[len] = '\0'; #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { /* Create a buffer for the longest file name we will ever see */ (*new)->w.entry = apr_pcalloc(pool, sizeof(WIN32_FIND_DATAW)); (*new)->name = apr_pcalloc(pool, APR_FILE_MAX * 3 + 1); } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { /* Note that we won't open a directory that is greater than MAX_PATH, * including the trailing /* wildcard suffix. If a * won't fit, then * neither will any other file name within the directory. * The length not including the trailing '*' is stored as rootlen, to * skip over all paths which are too long. */ if (len >= APR_PATH_MAX) { (*new) = NULL; return APR_ENAMETOOLONG; } (*new)->n.entry = apr_pcalloc(pool, sizeof(WIN32_FIND_DATAW)); } #endif (*new)->rootlen = len - 1; (*new)->pool = pool; (*new)->dirhand = INVALID_HANDLE_VALUE; apr_pool_cleanup_register((*new)->pool, (void *)(*new), dir_cleanup, apr_pool_cleanup_null); rv = apr_dir_read(NULL, 0, *new); if (rv != APR_SUCCESS) { dir_cleanup(*new); *new = NULL; } return rv; } APR_DECLARE(apr_status_t) apr_dir_close(apr_dir_t *dir) { apr_pool_cleanup_kill(dir->pool, dir, dir_cleanup); return dir_cleanup(dir); } APR_DECLARE(apr_status_t) apr_dir_read(apr_finfo_t *finfo, apr_int32_t wanted, apr_dir_t *thedir) { apr_status_t rv; char *fname; /* The while loops below allow us to skip all invalid file names, so that * we aren't reporting any files where their absolute paths are too long. */ #if APR_HAS_UNICODE_FS apr_wchar_t wdirname[APR_PATH_MAX]; apr_wchar_t *eos = NULL; IF_WIN_OS_IS_UNICODE { /* This code path is always be invoked by apr_dir_open or * apr_dir_rewind, so return without filling out the finfo. */ if (thedir->dirhand == INVALID_HANDLE_VALUE) { apr_status_t rv; if (rv = utf8_to_unicode_path(wdirname, sizeof(wdirname) / sizeof(apr_wchar_t), thedir->dirname)) { return rv; } eos = wcschr(wdirname, '\0'); eos[0] = '*'; eos[1] = '\0'; thedir->dirhand = FindFirstFileW(wdirname, thedir->w.entry); eos[0] = '\0'; if (thedir->dirhand == INVALID_HANDLE_VALUE) { return apr_get_os_error(); } thedir->bof = 1; return APR_SUCCESS; } else if (thedir->bof) { /* Noop - we already called FindFirstFileW from * either apr_dir_open or apr_dir_rewind ... use * that first record. */ thedir->bof = 0; } else if (!FindNextFileW(thedir->dirhand, thedir->w.entry)) { return apr_get_os_error(); } while (thedir->rootlen && thedir->rootlen + wcslen(thedir->w.entry->cFileName) >= APR_PATH_MAX) { if (!FindNextFileW(thedir->dirhand, thedir->w.entry)) { return apr_get_os_error(); } } if (rv = unicode_to_utf8_path(thedir->name, APR_FILE_MAX * 3 + 1, thedir->w.entry->cFileName)) return rv; fname = thedir->name; } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { /* This code path is always be invoked by apr_dir_open or * apr_dir_rewind, so return without filling out the finfo. */ if (thedir->dirhand == INVALID_HANDLE_VALUE) { /* '/' terminated, so add the '*' and pop it when we finish */ char *eop = strchr(thedir->dirname, '\0'); eop[0] = '*'; eop[1] = '\0'; thedir->dirhand = FindFirstFileA(thedir->dirname, thedir->n.entry); eop[0] = '\0'; if (thedir->dirhand == INVALID_HANDLE_VALUE) { return apr_get_os_error(); } thedir->bof = 1; return APR_SUCCESS; } else if (thedir->bof) { /* Noop - we already called FindFirstFileW from * either apr_dir_open or apr_dir_rewind ... use * that first record. */ thedir->bof = 0; } else if (!FindNextFile(thedir->dirhand, thedir->n.entry)) { return apr_get_os_error(); } while (thedir->rootlen && thedir->rootlen + strlen(thedir->n.entry->cFileName) >= MAX_PATH) { if (!FindNextFileW(thedir->dirhand, thedir->w.entry)) { return apr_get_os_error(); } } fname = thedir->n.entry->cFileName; } #endif fillin_fileinfo(finfo, (WIN32_FILE_ATTRIBUTE_DATA *) thedir->w.entry, 0, wanted); finfo->pool = thedir->pool; finfo->valid |= APR_FINFO_NAME; finfo->name = fname; if (wanted &= ~finfo->valid) { /* Go back and get more_info if we can't answer the whole inquiry */ #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { /* Almost all our work is done. Tack on the wide file name * to the end of the wdirname (already / delimited) */ if (!eos) eos = wcschr(wdirname, '\0'); wcscpy(eos, thedir->w.entry->cFileName); rv = more_finfo(finfo, wdirname, wanted, MORE_OF_WFSPEC); eos[0] = '\0'; return rv; } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { #if APR_HAS_UNICODE_FS /* Don't waste stack space on a second buffer, the one we set * aside for the wide directory name is twice what we need. */ char *fspec = (char*)wdirname; #else char fspec[APR_PATH_MAX]; #endif apr_size_t dirlen = strlen(thedir->dirname); if (dirlen >= sizeof(fspec)) dirlen = sizeof(fspec) - 1; apr_cpystrn(fspec, thedir->dirname, sizeof(fspec)); apr_cpystrn(fspec + dirlen, fname, sizeof(fspec) - dirlen); return more_finfo(finfo, fspec, wanted, MORE_OF_FSPEC); } #endif } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_dir_rewind(apr_dir_t *dir) { apr_status_t rv; /* this will mark the handle as invalid and we'll open it * again if apr_dir_read() is subsequently called */ rv = dir_cleanup(dir); if (rv == APR_SUCCESS) rv = apr_dir_read(NULL, 0, dir); return rv; } APR_DECLARE(apr_status_t) apr_dir_make(const char *path, apr_fileperms_t perm, apr_pool_t *pool) { #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { apr_wchar_t wpath[APR_PATH_MAX]; apr_status_t rv; if (rv = utf8_to_unicode_path(wpath, sizeof(wpath) / sizeof(apr_wchar_t), path)) { return rv; } if (!CreateDirectoryW(wpath, NULL)) { return apr_get_os_error(); } } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI if (!CreateDirectory(path, NULL)) { return apr_get_os_error(); } #endif return APR_SUCCESS; } static apr_status_t dir_make_parent(char *path, apr_fileperms_t perm, apr_pool_t *pool) { apr_status_t rv; char *ch = strrchr(path, '\\'); if (!ch) { return APR_ENOENT; } *ch = '\0'; rv = apr_dir_make (path, perm, pool); /* Try to make straight off */ if (APR_STATUS_IS_ENOENT(rv)) { /* Missing an intermediate dir */ rv = dir_make_parent(path, perm, pool); if (rv == APR_SUCCESS) { rv = apr_dir_make (path, perm, pool); /* And complete the path */ } } *ch = '\\'; /* Always replace the slash before returning */ return rv; } APR_DECLARE(apr_status_t) apr_dir_make_recursive(const char *path, apr_fileperms_t perm, apr_pool_t *pool) { apr_status_t rv = 0; rv = apr_dir_make (path, perm, pool); /* Try to make PATH right out */ if (APR_STATUS_IS_EEXIST(rv)) /* It's OK if PATH exists */ return APR_SUCCESS; if (APR_STATUS_IS_ENOENT(rv)) { /* Missing an intermediate dir */ char *dir; rv = apr_filepath_merge(&dir, "", path, APR_FILEPATH_NATIVE, pool); if (rv == APR_SUCCESS) rv = dir_make_parent(dir, perm, pool); /* Make intermediate dirs */ if (rv == APR_SUCCESS) rv = apr_dir_make (dir, perm, pool); /* And complete the path */ } return rv; } APR_DECLARE(apr_status_t) apr_dir_remove(const char *path, apr_pool_t *pool) { #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { apr_wchar_t wpath[APR_PATH_MAX]; apr_status_t rv; if (rv = utf8_to_unicode_path(wpath, sizeof(wpath) / sizeof(apr_wchar_t), path)) { return rv; } if (!RemoveDirectoryW(wpath)) { return apr_get_os_error(); } } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI if (!RemoveDirectory(path)) { return apr_get_os_error(); } #endif return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_dir_get(apr_os_dir_t **thedir, apr_dir_t *dir) { if (dir == NULL) { return APR_ENODIR; } *thedir = dir->dirhand; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_dir_put(apr_dir_t **dir, apr_os_dir_t *thedir, apr_pool_t *pool) { return APR_ENOTIMPL; }
001-log4cxx
trunk/src/apr/file_io/win32/dir.c
C
asf20
12,265
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "win32/apr_arch_file_io.h" #include "apr_file_io.h" #include "apr_general.h" #include "apr_strings.h" #include "apr_lib.h" #include "apr_errno.h" #include <malloc.h> #include "apr_arch_atime.h" #include "apr_arch_misc.h" /* * read_with_timeout() * Uses async i/o to emulate unix non-blocking i/o with timeouts. */ static apr_status_t read_with_timeout(apr_file_t *file, void *buf, apr_size_t len_in, apr_size_t *nbytes) { apr_status_t rv; DWORD len = (DWORD)len_in; DWORD bytesread = 0; /* Handle the zero timeout non-blocking case */ if (file->timeout == 0) { /* Peek at the pipe. If there is no data available, return APR_EAGAIN. * If data is available, go ahead and read it. */ if (file->pipe) { DWORD bytes; if (!PeekNamedPipe(file->filehand, NULL, 0, NULL, &bytes, NULL)) { rv = apr_get_os_error(); if (rv == APR_FROM_OS_ERROR(ERROR_BROKEN_PIPE)) { rv = APR_EOF; } *nbytes = 0; return rv; } else { if (bytes == 0) { *nbytes = 0; return APR_EAGAIN; } if (len > bytes) { len = bytes; } } } else { /* ToDo: Handle zero timeout non-blocking file i/o * This is not needed until an APR application needs to * timeout file i/o (which means setting file i/o non-blocking) */ } } if (file->pOverlapped && !file->pipe) { file->pOverlapped->Offset = (DWORD)file->filePtr; file->pOverlapped->OffsetHigh = (DWORD)(file->filePtr >> 32); } rv = ReadFile(file->filehand, buf, len, &bytesread, file->pOverlapped); *nbytes = bytesread; if (!rv) { rv = apr_get_os_error(); if (rv == APR_FROM_OS_ERROR(ERROR_IO_PENDING)) { /* Wait for the pending i/o */ if (file->timeout > 0) { /* timeout in milliseconds... */ rv = WaitForSingleObject(file->pOverlapped->hEvent, (DWORD)(file->timeout/1000)); } else if (file->timeout == -1) { rv = WaitForSingleObject(file->pOverlapped->hEvent, INFINITE); } switch (rv) { case WAIT_OBJECT_0: GetOverlappedResult(file->filehand, file->pOverlapped, &bytesread, TRUE); *nbytes = bytesread; rv = APR_SUCCESS; break; case WAIT_TIMEOUT: rv = APR_TIMEUP; break; case WAIT_FAILED: rv = apr_get_os_error(); break; default: break; } if (rv != APR_SUCCESS) { if (apr_os_level >= APR_WIN_98) { CancelIo(file->filehand); } } } else if (rv == APR_FROM_OS_ERROR(ERROR_BROKEN_PIPE)) { /* Assume ERROR_BROKEN_PIPE signals an EOF reading from a pipe */ rv = APR_EOF; } } else { /* OK and 0 bytes read ==> end of file */ if (*nbytes == 0) rv = APR_EOF; else rv = APR_SUCCESS; } if (rv == APR_SUCCESS && file->pOverlapped && !file->pipe) { file->filePtr += *nbytes; } return rv; } APR_DECLARE(apr_status_t) apr_file_read(apr_file_t *thefile, void *buf, apr_size_t *len) { apr_status_t rv; DWORD bytes_read = 0; if (*len <= 0) { *len = 0; return APR_SUCCESS; } /* If the file is open for xthread support, allocate and * initialize the overlapped and io completion event (hEvent). * Threads should NOT share an apr_file_t or its hEvent. */ if ((thefile->flags & APR_XTHREAD) && !thefile->pOverlapped ) { thefile->pOverlapped = (OVERLAPPED*) apr_pcalloc(thefile->pool, sizeof(OVERLAPPED)); thefile->pOverlapped->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if (!thefile->pOverlapped->hEvent) { rv = apr_get_os_error(); return rv; } } /* Handle the ungetchar if there is one */ if (thefile->ungetchar != -1) { bytes_read = 1; *(char *)buf = (char)thefile->ungetchar; buf = (char *)buf + 1; (*len)--; thefile->ungetchar = -1; if (*len == 0) { *len = bytes_read; return APR_SUCCESS; } } if (thefile->buffered) { char *pos = (char *)buf; apr_size_t blocksize; apr_size_t size = *len; apr_thread_mutex_lock(thefile->mutex); if (thefile->direction == 1) { rv = apr_file_flush(thefile); if (rv != APR_SUCCESS) { apr_thread_mutex_unlock(thefile->mutex); return rv; } thefile->bufpos = 0; thefile->direction = 0; thefile->dataRead = 0; } rv = 0; while (rv == 0 && size > 0) { if (thefile->bufpos >= thefile->dataRead) { apr_size_t read; rv = read_with_timeout(thefile, thefile->buffer, APR_FILE_BUFSIZE, &read); if (read == 0) { if (rv == APR_EOF) thefile->eof_hit = TRUE; break; } else { thefile->dataRead = read; thefile->filePtr += thefile->dataRead; thefile->bufpos = 0; } } blocksize = size > thefile->dataRead - thefile->bufpos ? thefile->dataRead - thefile->bufpos : size; memcpy(pos, thefile->buffer + thefile->bufpos, blocksize); thefile->bufpos += blocksize; pos += blocksize; size -= blocksize; } *len = pos - (char *)buf; if (*len) { rv = APR_SUCCESS; } apr_thread_mutex_unlock(thefile->mutex); } else { /* Unbuffered i/o */ apr_size_t nbytes; rv = read_with_timeout(thefile, buf, *len, &nbytes); if (rv == APR_EOF) thefile->eof_hit = TRUE; *len = nbytes; } return rv; } APR_DECLARE(apr_status_t) apr_file_write(apr_file_t *thefile, const void *buf, apr_size_t *nbytes) { apr_status_t rv; DWORD bwrote; /* If the file is open for xthread support, allocate and * initialize the overlapped and io completion event (hEvent). * Threads should NOT share an apr_file_t or its hEvent. */ if ((thefile->flags & APR_XTHREAD) && !thefile->pOverlapped ) { thefile->pOverlapped = (OVERLAPPED*) apr_pcalloc(thefile->pool, sizeof(OVERLAPPED)); thefile->pOverlapped->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if (!thefile->pOverlapped->hEvent) { rv = apr_get_os_error(); return rv; } } if (thefile->buffered) { char *pos = (char *)buf; apr_size_t blocksize; apr_size_t size = *nbytes; apr_thread_mutex_lock(thefile->mutex); if (thefile->direction == 0) { // Position file pointer for writing at the offset we are logically reading from apr_off_t offset = thefile->filePtr - thefile->dataRead + thefile->bufpos; DWORD offlo = (DWORD)offset; DWORD offhi = (DWORD)(offset >> 32); if (offset != thefile->filePtr) SetFilePointer(thefile->filehand, offlo, &offhi, FILE_BEGIN); thefile->bufpos = thefile->dataRead = 0; thefile->direction = 1; } rv = 0; while (rv == 0 && size > 0) { if (thefile->bufpos == APR_FILE_BUFSIZE) // write buffer is full rv = apr_file_flush(thefile); blocksize = size > APR_FILE_BUFSIZE - thefile->bufpos ? APR_FILE_BUFSIZE - thefile->bufpos : size; memcpy(thefile->buffer + thefile->bufpos, pos, blocksize); thefile->bufpos += blocksize; pos += blocksize; size -= blocksize; } apr_thread_mutex_unlock(thefile->mutex); return rv; } else { if (!thefile->pipe) { apr_off_t offset = 0; apr_status_t rc; if (thefile->append) { /* apr_file_lock will mutex the file across processes. * The call to apr_thread_mutex_lock is added to avoid * a race condition between LockFile and WriteFile * that occasionally leads to deadlocked threads. */ apr_thread_mutex_lock(thefile->mutex); rc = apr_file_lock(thefile, APR_FLOCK_EXCLUSIVE); if (rc != APR_SUCCESS) { apr_thread_mutex_unlock(thefile->mutex); return rc; } rc = apr_file_seek(thefile, APR_END, &offset); if (rc != APR_SUCCESS) { apr_thread_mutex_unlock(thefile->mutex); return rc; } } if (thefile->pOverlapped) { thefile->pOverlapped->Offset = (DWORD)thefile->filePtr; thefile->pOverlapped->OffsetHigh = (DWORD)(thefile->filePtr >> 32); } rv = WriteFile(thefile->filehand, buf, (DWORD)*nbytes, &bwrote, thefile->pOverlapped); if (thefile->append) { apr_file_unlock(thefile); apr_thread_mutex_unlock(thefile->mutex); } } else { rv = WriteFile(thefile->filehand, buf, (DWORD)*nbytes, &bwrote, thefile->pOverlapped); } if (rv) { *nbytes = bwrote; rv = APR_SUCCESS; } else { (*nbytes) = 0; rv = apr_get_os_error(); if (rv == APR_FROM_OS_ERROR(ERROR_IO_PENDING)) { DWORD timeout_ms; if (thefile->timeout == 0) { timeout_ms = 0; } else if (thefile->timeout < 0) { timeout_ms = INFINITE; } else { timeout_ms = (DWORD)(thefile->timeout / 1000); } rv = WaitForSingleObject(thefile->pOverlapped->hEvent, timeout_ms); switch (rv) { case WAIT_OBJECT_0: GetOverlappedResult(thefile->filehand, thefile->pOverlapped, &bwrote, TRUE); *nbytes = bwrote; rv = APR_SUCCESS; break; case WAIT_TIMEOUT: rv = APR_TIMEUP; break; case WAIT_FAILED: rv = apr_get_os_error(); break; default: break; } if (rv != APR_SUCCESS) { if (apr_os_level >= APR_WIN_98) CancelIo(thefile->filehand); } } } if (rv == APR_SUCCESS && thefile->pOverlapped && !thefile->pipe) { thefile->filePtr += *nbytes; } } return rv; } /* ToDo: Write for it anyway and test the oslevel! * Too bad WriteFileGather() is not supported on 95&98 (or NT prior to SP2) */ APR_DECLARE(apr_status_t) apr_file_writev(apr_file_t *thefile, const struct iovec *vec, apr_size_t nvec, apr_size_t *nbytes) { apr_status_t rv = APR_SUCCESS; apr_size_t i; apr_size_t bwrote = 0; char *buf; *nbytes = 0; for (i = 0; i < nvec; i++) { buf = vec[i].iov_base; bwrote = vec[i].iov_len; rv = apr_file_write(thefile, buf, &bwrote); *nbytes += bwrote; if (rv != APR_SUCCESS) { break; } } return rv; } APR_DECLARE(apr_status_t) apr_file_putc(char ch, apr_file_t *thefile) { apr_size_t len = 1; return apr_file_write(thefile, &ch, &len); } APR_DECLARE(apr_status_t) apr_file_ungetc(char ch, apr_file_t *thefile) { thefile->ungetchar = (unsigned char) ch; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_getc(char *ch, apr_file_t *thefile) { apr_status_t rc; apr_size_t bread; bread = 1; rc = apr_file_read(thefile, ch, &bread); if (rc) { return rc; } if (bread == 0) { thefile->eof_hit = TRUE; return APR_EOF; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_puts(const char *str, apr_file_t *thefile) { apr_size_t len = strlen(str); return apr_file_write(thefile, str, &len); } APR_DECLARE(apr_status_t) apr_file_gets(char *str, int len, apr_file_t *thefile) { apr_size_t readlen; apr_status_t rv = APR_SUCCESS; int i; for (i = 0; i < len-1; i++) { readlen = 1; rv = apr_file_read(thefile, str+i, &readlen); if (rv != APR_SUCCESS && rv != APR_EOF) return rv; if (readlen == 0) { /* If we have bytes, defer APR_EOF to the next call */ if (i > 0) rv = APR_SUCCESS; break; } if (str[i] == '\n') { i++; /* don't clobber this char below */ break; } } str[i] = 0; return rv; } APR_DECLARE(apr_status_t) apr_file_flush(apr_file_t *thefile) { if (thefile->buffered) { DWORD numbytes, written = 0; apr_status_t rc = 0; char *buffer; apr_size_t bytesleft; if (thefile->direction == 1 && thefile->bufpos) { buffer = thefile->buffer; bytesleft = thefile->bufpos; do { if (bytesleft > APR_DWORD_MAX) { numbytes = APR_DWORD_MAX; } else { numbytes = (DWORD)bytesleft; } if (!WriteFile(thefile->filehand, buffer, numbytes, &written, NULL)) { rc = apr_get_os_error(); thefile->filePtr += written; break; } thefile->filePtr += written; bytesleft -= written; buffer += written; } while (bytesleft > 0); if (rc == 0) thefile->bufpos = 0; } return rc; } /* There isn't anything to do if we aren't buffering the output * so just return success. */ return APR_SUCCESS; } struct apr_file_printf_data { apr_vformatter_buff_t vbuff; apr_file_t *fptr; char *buf; }; static int file_printf_flush(apr_vformatter_buff_t *buff) { struct apr_file_printf_data *data = (struct apr_file_printf_data *)buff; if (apr_file_write_full(data->fptr, data->buf, data->vbuff.curpos - data->buf, NULL)) { return -1; } data->vbuff.curpos = data->buf; return 0; } APR_DECLARE_NONSTD(int) apr_file_printf(apr_file_t *fptr, const char *format, ...) { struct apr_file_printf_data data; va_list ap; int count; data.buf = malloc(HUGE_STRING_LEN); if (data.buf == NULL) { return 0; } data.vbuff.curpos = data.buf; data.vbuff.endpos = data.buf + HUGE_STRING_LEN; data.fptr = fptr; va_start(ap, format); count = apr_vformatter(file_printf_flush, (apr_vformatter_buff_t *)&data, format, ap); /* apr_vformatter does not call flush for the last bits */ if (count >= 0) file_printf_flush((apr_vformatter_buff_t *)&data); va_end(ap); free(data.buf); return count; }
001-log4cxx
trunk/src/apr/file_io/win32/readwrite.c
C
asf20
17,298
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" APR_DECLARE(apr_status_t) apr_file_lock(apr_file_t *thefile, int type) { #ifdef _WIN32_WCE /* The File locking is unsuported on WCE */ return APR_ENOTIMPL; #else const DWORD len = 0xffffffff; DWORD flags; flags = ((type & APR_FLOCK_NONBLOCK) ? LOCKFILE_FAIL_IMMEDIATELY : 0) + (((type & APR_FLOCK_TYPEMASK) == APR_FLOCK_SHARED) ? 0 : LOCKFILE_EXCLUSIVE_LOCK); if (apr_os_level >= APR_WIN_NT) { /* Syntax is correct, len is passed for LengthLow and LengthHigh*/ OVERLAPPED offset; memset (&offset, 0, sizeof(offset)); if (!LockFileEx(thefile->filehand, flags, 0, len, len, &offset)) return apr_get_os_error(); } else { /* On Win9x, LockFile() never blocks. Hack in a crufty poll. * * Note that this hack exposes threads to being unserviced forever, * in the situation that the given lock has low availability. * When implemented in the kernel, LockFile will typically use * FIFO or round robin distribution to ensure all threads get * one crack at the lock; but in this case we can't emulate that. * * However Win9x are barely maintainable anyways, if the user does * choose to build to them, this is the best we can do. */ while (!LockFile(thefile->filehand, 0, 0, len, 0)) { DWORD err = GetLastError(); if ((err == ERROR_LOCK_VIOLATION) && !(type & APR_FLOCK_NONBLOCK)) { Sleep(500); /* pause for a half second */ continue; /* ... and then poll again */ } return APR_FROM_OS_ERROR(err); } } return APR_SUCCESS; #endif /* !defined(_WIN32_WCE) */ } APR_DECLARE(apr_status_t) apr_file_unlock(apr_file_t *thefile) { #ifdef _WIN32_WCE return APR_ENOTIMPL; #else DWORD len = 0xffffffff; if (apr_os_level >= APR_WIN_NT) { /* Syntax is correct, len is passed for LengthLow and LengthHigh*/ OVERLAPPED offset; memset (&offset, 0, sizeof(offset)); if (!UnlockFileEx(thefile->filehand, 0, len, len, &offset)) return apr_get_os_error(); } else { if (!UnlockFile(thefile->filehand, 0, 0, len, 0)) return apr_get_os_error(); } return APR_SUCCESS; #endif /* !defined(_WIN32_WCE) */ }
001-log4cxx
trunk/src/apr/file_io/win32/flock.c
C
asf20
3,243
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_private.h" #include "apr_arch_file_io.h" #include "apr_strings.h" #include "apr_lib.h" #include <string.h> #include <ctype.h> #ifdef NETWARE #include <unistd.h> #include <fsio.h> #endif /* WinNT accepts several odd forms of a 'root' path. Under Unicode * calls (ApiFunctionW) the //?/C:/foo or //?/UNC/mach/share/foo forms * are accepted. Ansi and Unicode functions both accept the //./C:/foo * form under WinNT/2K. Since these forms are handled in the utf-8 to * unicode translation phase, we don't want the user confused by them, so * we will accept them but always return the canonical C:/ or //mach/share/ * * OS2 appears immune from the nonsense :) */ APR_DECLARE(apr_status_t) apr_filepath_root(const char **rootpath, const char **inpath, apr_int32_t flags, apr_pool_t *p) { const char *testpath = *inpath; char *newpath; #ifdef NETWARE char seperator[2] = { 0, 0}; char server[APR_PATH_MAX+1]; char volume[APR_PATH_MAX+1]; char file[APR_PATH_MAX+1]; char *volsep = NULL; int elements; if (inpath && *inpath) volsep = strchr (*inpath, ':'); else return APR_EBADPATH; if (strlen(*inpath) > APR_PATH_MAX) { return APR_EBADPATH; } seperator[0] = (flags & APR_FILEPATH_NATIVE) ? '\\' : '/'; /* Allocate and initialize each of the segment buffers */ server[0] = volume[0] = file[0] = '\0'; /* If we don't have a volume separator then don't bother deconstructing the path since we won't use the deconstructed information anyway. */ if (volsep) { /* Split the inpath into its separate parts. */ deconstruct(testpath, server, volume, NULL, file, NULL, &elements, PATH_UNDEF); /* If we got a volume part then continue splitting out the root. Otherwise we either have an incomplete or relative path */ if (volume && strlen(volume) > 0) { newpath = apr_pcalloc(p, strlen(server)+strlen(volume)+5); construct(newpath, server, volume, NULL, NULL, NULL, PATH_NETWARE); /* NetWare doesn't add the root slash so we need to add it manually. */ strcat(newpath, seperator); *rootpath = newpath; /* Skip the inpath pointer down to the first non-root character */ newpath = volsep; do { ++newpath; } while (*newpath && ((*newpath == '/') || (*newpath == '\\'))); *inpath = newpath; /* Need to handle APR_FILEPATH_TRUENAME checking here. */ return APR_SUCCESS; } else return APR_EBADPATH; } else if ((**inpath == '/') || (**inpath == '\\')) { /* if we have a root path without a volume then just split in same manner as unix although this path will be incomplete. */ *rootpath = apr_pstrdup(p, seperator); do { ++(*inpath); } while ((**inpath == '/') || (**inpath == '\\')); } else return APR_ERELATIVE; return APR_EINCOMPLETE; #else /* ndef(NETWARE) */ char seperator[2]; const char *delim1; const char *delim2; seperator[0] = (flags & APR_FILEPATH_NATIVE) ? '\\' : '/'; seperator[1] = 0; if (testpath[0] == '/' || testpath[0] == '\\') { if (testpath[1] == '/' || testpath[1] == '\\') { #ifdef WIN32 /* //server/share isn't the only // delimited syntax */ if ((testpath[2] == '?' || testpath[2] == '.') && (testpath[3] == '/' || testpath[3] == '\\')) { if (IS_FNCHAR(testpath[4]) && testpath[5] == ':') { apr_status_t rv; testpath += 4; /* given '//?/C: or //./C: let us try this * all over again from the drive designator */ rv = apr_filepath_root(rootpath, &testpath, flags, p); if (!rv || rv == APR_EINCOMPLETE) *inpath = testpath; return rv; } else if (strncasecmp(testpath + 4, "UNC", 3) == 0 && (testpath[7] == '/' || testpath[7] == '\\') && (testpath[2] == '?')) { /* given '//?/UNC/machine/share, a little magic * at the end makes this all work out by using * 'C/machine' as the starting point and replacing * the UNC delimiters with \'s, including the 'C' */ testpath += 6; } else /* This must not be a path to a file, but rather * a volume or device. Die for now. */ return APR_EBADPATH; } #endif /* WIN32 (non - //server/share syntax) */ /* Evaluate path of '//[machine/[share[/]]]' */ delim1 = testpath + 2; do { /* Protect against //X/ where X is illegal */ if (*delim1 && !IS_FNCHAR(*(delim1++))) return APR_EBADPATH; } while (*delim1 && *delim1 != '/' && *delim1 != '\\'); if (*delim1) { apr_status_t rv; delim2 = delim1 + 1; while (*delim2 && *delim2 != '/' && *delim2 != '\\') { /* Protect against //machine/X/ where X is illegal */ if (!IS_FNCHAR(*(delim2++))) return APR_EBADPATH; } /* Copy the '//machine/[share[/]]' path, always providing * an extra byte for the trailing slash. */ newpath = apr_pstrmemdup(p, testpath, delim2 - testpath + 1); if (delim2 == delim1 + 1) { /* We found simply \\machine\, so give up already */ *rootpath = newpath; *inpath = delim2; return APR_EINCOMPLETE; } if (flags & APR_FILEPATH_TRUENAME) { /* Validate the \\Machine\Share\ designation, * Win32 will argue about slashed in UNC paths, * so use backslashes till we finish testing, * and add the trailing backslash [required]. * apr_pstrmemdup above guarentees us the new * trailing null character. */ newpath[0] = '\\'; newpath[1] = '\\'; newpath[delim1 - testpath] = '\\'; newpath[delim2 - testpath] = '\\'; rv = filepath_root_test(newpath, p); if (rv) return rv; rv = filepath_root_case(&newpath, newpath, p); if (rv) return rv; newpath[0] = seperator[0]; newpath[1] = seperator[0]; newpath[delim1 - testpath] = seperator[0]; newpath[delim2 - testpath] = (*delim2 ? seperator[0] : '\0'); } else { /* Give back the caller's own choice of delimiters */ newpath[0] = testpath[0]; newpath[1] = testpath[1]; newpath[delim1 - testpath] = *delim1; newpath[delim2 - testpath] = *delim2; } /* If this root included the trailing / or \ designation * then lop off multiple trailing slashes and give back * appropriate delimiters. */ if (*delim2) { *inpath = delim2 + 1; while (**inpath == '/' || **inpath == '\\') ++*inpath; } else { *inpath = delim2; } *rootpath = newpath; return APR_SUCCESS; } /* Have path of '\\[machine]', if the machine is given, * append same trailing slash as the leading slash */ delim1 = strchr(testpath, '\0'); if (delim1 > testpath + 2) { newpath = apr_pstrndup(p, testpath, delim1 - testpath + 1); if (flags & APR_FILEPATH_TRUENAME) newpath[delim1 - testpath] = seperator[0]; else newpath[delim1 - testpath] = newpath[0]; newpath[delim1 - testpath + 1] = '\0'; } else { newpath = apr_pstrndup(p, testpath, delim1 - testpath); } if (flags & APR_FILEPATH_TRUENAME) { newpath[0] = seperator[0]; newpath[1] = seperator[0]; } *rootpath = newpath; *inpath = delim1; return APR_EINCOMPLETE; } /* Left with a path of '/', what drive are we asking about? */ *inpath = testpath + 1; newpath = apr_palloc(p, 2); if (flags & APR_FILEPATH_TRUENAME) newpath[0] = seperator[0]; else newpath[0] = testpath[0]; newpath[1] = '\0'; *rootpath = newpath; return APR_EINCOMPLETE; } /* Evaluate path of 'd:[/]' */ if (IS_FNCHAR(*testpath) && testpath[1] == ':') { apr_status_t rv; /* Validate that D:\ drive exists, test must be rooted * Note that posix/win32 insists a drive letter is upper case, * so who are we to argue with a 'feature'. * It is a safe fold, since only A-Z is legal, and has no * side effects of legal mis-mapped non-us-ascii codes. */ newpath = apr_palloc(p, 4); newpath[0] = testpath[0]; newpath[1] = testpath[1]; newpath[2] = seperator[0]; newpath[3] = '\0'; if (flags & APR_FILEPATH_TRUENAME) { newpath[0] = apr_toupper(newpath[0]); rv = filepath_root_test(newpath, p); if (rv) return rv; } /* Just give back the root the user handed to us. */ if (testpath[2] != '/' && testpath[2] != '\\') { newpath[2] = '\0'; *rootpath = newpath; *inpath = testpath + 2; return APR_EINCOMPLETE; } /* strip off remaining slashes that designate the root, * give the caller back their original choice of slash * unless this is TRUENAME'ed */ *inpath = testpath + 3; while (**inpath == '/' || **inpath == '\\') ++*inpath; if (!(flags & APR_FILEPATH_TRUENAME)) newpath[2] = testpath[2]; *rootpath = newpath; return APR_SUCCESS; } /* Nothing interesting */ return APR_ERELATIVE; #endif /* ndef(NETWARE) */ } APR_DECLARE(apr_status_t) apr_filepath_merge(char **newpath, const char *basepath, const char *addpath, apr_int32_t flags, apr_pool_t *p) { char path[APR_PATH_MAX]; /* isn't null term */ const char *baseroot = NULL; const char *addroot; apr_size_t rootlen; /* the length of the root portion of path, d:/ is 3 */ apr_size_t baselen; /* the length of basepath (excluding baseroot) */ apr_size_t keptlen; /* the length of the retained basepath (incl root) */ apr_size_t pathlen; /* the length of the result path */ apr_size_t segend; /* the end of the current segment */ apr_size_t seglen; /* the length of the segment (excl trailing chars) */ apr_status_t basetype = 0; /* from parsing the basepath's baseroot */ apr_status_t addtype; /* from parsing the addpath's addroot */ apr_status_t rv; #ifndef NETWARE int fixunc = 0; /* flag to complete an incomplete UNC basepath */ #endif /* Treat null as an empty path, otherwise split addroot from the addpath */ if (!addpath) { addpath = addroot = ""; addtype = APR_ERELATIVE; } else { /* This call _should_ test the path */ addtype = apr_filepath_root(&addroot, &addpath, APR_FILEPATH_TRUENAME | (flags & APR_FILEPATH_NATIVE), p); if (addtype == APR_SUCCESS) { addtype = APR_EABSOLUTE; } else if (addtype == APR_ERELATIVE) { addroot = ""; } else if (addtype != APR_EINCOMPLETE) { /* apr_filepath_root was incomprehensible so fail already */ return addtype; } } /* If addpath is (even partially) rooted, then basepath is * unused. Ths violates any APR_FILEPATH_SECUREROOTTEST * and APR_FILEPATH_NOTABSOLUTE flags specified. */ if (addtype == APR_EABSOLUTE || addtype == APR_EINCOMPLETE) { if (flags & APR_FILEPATH_SECUREROOTTEST) return APR_EABOVEROOT; if (flags & APR_FILEPATH_NOTABSOLUTE) return addtype; } /* Optimized tests before we query the current working path */ if (!basepath) { /* If APR_FILEPATH_NOTABOVEROOT wasn't specified, * we won't test the root again, it's ignored. * Waste no CPU retrieving the working path. */ if (addtype == APR_EABSOLUTE && !(flags & APR_FILEPATH_NOTABOVEROOT)) { basepath = baseroot = ""; basetype = APR_ERELATIVE; } /* If APR_FILEPATH_NOTABSOLUTE is specified, the caller * requires an absolutely relative result, So do not retrieve * the working path. */ if (addtype == APR_ERELATIVE && (flags & APR_FILEPATH_NOTABSOLUTE)) { basepath = baseroot = ""; basetype = APR_ERELATIVE; } } if (!basepath) { /* Start with the current working path. This is bass akwards, * but required since the compiler (at least vc) doesn't like * passing the address of a char const* for a char** arg. * We must grab the current path of the designated drive * if addroot is given in drive-relative form (e.g. d:foo) */ char *getpath; #ifndef NETWARE if (addtype == APR_EINCOMPLETE && addroot[1] == ':') rv = filepath_drive_get(&getpath, addroot[0], flags, p); else #endif rv = apr_filepath_get(&getpath, flags, p); if (rv != APR_SUCCESS) return rv; basepath = getpath; } if (!baseroot) { /* This call should _not_ test the path */ basetype = apr_filepath_root(&baseroot, &basepath, (flags & APR_FILEPATH_NATIVE), p); if (basetype == APR_SUCCESS) { basetype = APR_EABSOLUTE; } else if (basetype == APR_ERELATIVE) { baseroot = ""; } else if (basetype != APR_EINCOMPLETE) { /* apr_filepath_root was incomprehensible so fail already */ return basetype; } } baselen = strlen(basepath); /* If APR_FILEPATH_NOTABSOLUTE is specified, the caller * requires an absolutely relative result. If the given * basepath is not relative then fail. */ if ((flags & APR_FILEPATH_NOTABSOLUTE) && basetype != APR_ERELATIVE) return basetype; /* The Win32 nightmare on unc street... start combining for * many possible root combinations. */ if (addtype == APR_EABSOLUTE) { /* Ignore the given root path, and start with the addroot */ if ((flags & APR_FILEPATH_NOTABOVEROOT) && strncmp(baseroot, addroot, strlen(baseroot))) return APR_EABOVEROOT; keptlen = 0; rootlen = pathlen = strlen(addroot); memcpy(path, addroot, pathlen); } else if (addtype == APR_EINCOMPLETE) { /* There are several types of incomplete paths, * incomplete UNC paths (//foo/ or //), * drives without rooted paths (d: as in d:foo), * and simple roots (/ as in /foo). * Deal with these in significantly different manners... */ #ifndef NETWARE if ((addroot[0] == '/' || addroot[0] == '\\') && (addroot[1] == '/' || addroot[1] == '\\')) { /* Ignore the given root path if the incomplete addpath is UNC, * (note that the final result will be incomplete). */ if (flags & APR_FILEPATH_NOTRELATIVE) return addtype; if ((flags & APR_FILEPATH_NOTABOVEROOT) && strncmp(baseroot, addroot, strlen(baseroot))) return APR_EABOVEROOT; fixunc = 1; keptlen = 0; rootlen = pathlen = strlen(addroot); memcpy(path, addroot, pathlen); } else #endif if ((addroot[0] == '/' || addroot[0] == '\\') && !addroot[1]) { /* Bring together the drive or UNC root from the baseroot * if the addpath is a simple root and basepath is rooted, * otherwise disregard the basepath entirely. */ if (basetype != APR_EABSOLUTE && (flags & APR_FILEPATH_NOTRELATIVE)) return basetype; if (basetype != APR_ERELATIVE) { #ifndef NETWARE if (basetype == APR_INCOMPLETE && (baseroot[0] == '/' || baseroot[0] == '\\') && (baseroot[1] == '/' || baseroot[1] == '\\')) fixunc = 1; #endif keptlen = rootlen = pathlen = strlen(baseroot); memcpy(path, baseroot, pathlen); } else { if (flags & APR_FILEPATH_NOTABOVEROOT) return APR_EABOVEROOT; keptlen = 0; rootlen = pathlen = strlen(addroot); memcpy(path, addroot, pathlen); } } #ifdef NETWARE else if (filepath_has_drive(addroot, DRIVE_ONLY, p)) { /* If the addroot is a drive (without a volume root) * use the basepath _if_ it matches this drive letter! * Otherwise we must discard the basepath. */ if (!filepath_compare_drive(addroot, baseroot, p) && filepath_has_drive(baseroot, 0, p)) { #else else if (addroot[0] && addroot[1] == ':' && !addroot[2]) { /* If the addroot is a drive (without a volume root) * use the basepath _if_ it matches this drive letter! * Otherwise we must discard the basepath. */ if (addroot[0] == baseroot[0] && baseroot[1] == ':') { #endif /* Base the result path on the basepath */ if (basetype != APR_EABSOLUTE && (flags & APR_FILEPATH_NOTRELATIVE)) return basetype; rootlen = strlen(baseroot); keptlen = pathlen = rootlen + baselen; if (keptlen >= sizeof(path)) return APR_ENAMETOOLONG; memcpy(path, baseroot, rootlen); memcpy(path + rootlen, basepath, baselen); } else { if (flags & APR_FILEPATH_NOTRELATIVE) return addtype; if (flags & APR_FILEPATH_NOTABOVEROOT) return APR_EABOVEROOT; keptlen = 0; rootlen = pathlen = strlen(addroot); memcpy(path, addroot, pathlen); } } else { /* Now this is unexpected, we aren't aware of any other * incomplete path forms! Fail now. */ return APR_EBADPATH; } } else { /* addtype == APR_ERELATIVE */ /* If both paths are relative, fail early */ if (basetype != APR_EABSOLUTE && (flags & APR_FILEPATH_NOTRELATIVE)) return basetype; #ifndef NETWARE /* An incomplete UNC path must be completed */ if (basetype == APR_INCOMPLETE && (baseroot[0] == '/' || baseroot[0] == '\\') && (baseroot[1] == '/' || baseroot[1] == '\\')) fixunc = 1; #endif /* Base the result path on the basepath */ rootlen = strlen(baseroot); keptlen = pathlen = rootlen + baselen; if (keptlen >= sizeof(path)) return APR_ENAMETOOLONG; memcpy(path, baseroot, rootlen); memcpy(path + rootlen, basepath, baselen); } /* '/' terminate the given root path unless it's already terminated * or is an incomplete drive root. Correct the trailing slash unless * we have an incomplete UNC path still to fix. */ if (pathlen && path[pathlen - 1] != ':') { if (path[pathlen - 1] != '/' && path[pathlen - 1] != '\\') { if (pathlen + 1 >= sizeof(path)) return APR_ENAMETOOLONG; path[pathlen++] = ((flags & APR_FILEPATH_NATIVE) ? '\\' : '/'); } /* XXX: wrong, but gotta figure out what I intended; * else if (!fixunc) * path[pathlen++] = ((flags & APR_FILEPATH_NATIVE) ? '\\' : '/'); */ } while (*addpath) { /* Parse each segment, find the closing '/' */ seglen = 0; while (addpath[seglen] && addpath[seglen] != '/' && addpath[seglen] != '\\') ++seglen; /* Truncate all trailing spaces and all but the first two dots */ segend = seglen; while (seglen && (addpath[seglen - 1] == ' ' || addpath[seglen - 1] == '.')) { if (seglen > 2 || addpath[seglen - 1] != '.' || addpath[0] != '.') --seglen; else break; } if (seglen == 0 || (seglen == 1 && addpath[0] == '.')) { /* NOTE: win32 _hates_ '/ /' and '/. /' (yes, with spaces in there) * so eliminate all preconceptions that it is valid. */ if (seglen < segend) return APR_EBADPATH; #ifndef NETWARE /* This isn't legal unless the unc path is completed */ if (fixunc) return APR_EBADPATH; #endif /* Otherwise, this is a noop segment (/ or ./) so ignore it */ } else if (seglen == 2 && addpath[0] == '.' && addpath[1] == '.') { /* NOTE: win32 _hates_ '/.. /' (yes, with a space in there) * and '/..../', some functions treat it as ".", and some * fail! Eliminate all preconceptions that they are valid. */ if (seglen < segend && (seglen != 3 || addpath[2] != '.')) return APR_EBADPATH; #ifndef NETWARE /* This isn't legal unless the unc path is completed */ if (fixunc) return APR_EBADPATH; #endif /* backpath (../) when an absolute path is given */ if (rootlen && (pathlen <= rootlen)) { /* Attempt to move above root. Always die if the * APR_FILEPATH_SECUREROOTTEST flag is specified. */ if (flags & APR_FILEPATH_SECUREROOTTEST) return APR_EABOVEROOT; /* Otherwise this is simply a noop, above root is root. */ } else if (pathlen == 0 || (pathlen >= 3 && (pathlen == 3 || path[pathlen - 4] == ':' || path[pathlen - 4] == '/' || path[pathlen - 4] == '\\') && path[pathlen - 3] == '.' && path[pathlen - 2] == '.' && (path[pathlen - 1] == '/' || path[pathlen - 1] == '\\'))) { /* Verified path is empty, exactly "..[/\]", or ends * in "[:/\]..[/\]" - these patterns we will not back * over since they aren't 'prior segements'. * * If APR_FILEPATH_SECUREROOTTEST.was given, die now. */ if (flags & APR_FILEPATH_SECUREROOTTEST) return APR_EABOVEROOT; /* Otherwise append another backpath. */ if (pathlen + 3 >= sizeof(path)) return APR_ENAMETOOLONG; path[pathlen++] = '.'; path[pathlen++] = '.'; if (addpath[segend]) { path[pathlen++] = ((flags & APR_FILEPATH_NATIVE) ? '\\' : ((flags & APR_FILEPATH_TRUENAME) ? '/' : addpath[segend])); } /* The 'root' part of this path now includes the ../ path, * because that backpath will not be parsed by the truename * code below. */ keptlen = pathlen; } else { /* otherwise crop the prior segment */ do { --pathlen; } while (pathlen && path[pathlen - 1] != '/' && path[pathlen - 1] != '\\'); /* Now test if we are above where we started and back up * the keptlen offset to reflect the added/altered path. */ if (pathlen < keptlen) { if (flags & APR_FILEPATH_SECUREROOTTEST) return APR_EABOVEROOT; keptlen = pathlen; } } } else /* not empty or dots */ { #ifndef NETWARE if (fixunc) { const char *testpath = path; const char *testroot; apr_status_t testtype; apr_size_t i = (addpath[segend] != '\0'); /* This isn't legal unless the unc path is complete! */ if (seglen < segend) return APR_EBADPATH; if (pathlen + seglen + 1 >= sizeof(path)) return APR_ENAMETOOLONG; memcpy(path + pathlen, addpath, seglen + i); /* Always add the trailing slash to a UNC segment */ path[pathlen + seglen] = ((flags & APR_FILEPATH_NATIVE) ? '\\' : '/'); pathlen += seglen + 1; /* Recanonicalize the UNC root with the new UNC segment, * and if we succeed, reset this test and the rootlen, * and replace our path with the canonical UNC root path */ path[pathlen] = '\0'; /* This call _should_ test the path */ testtype = apr_filepath_root(&testroot, &testpath, APR_FILEPATH_TRUENAME | (flags & APR_FILEPATH_NATIVE), p); if (testtype == APR_SUCCESS) { rootlen = pathlen = (testpath - path); memcpy(path, testroot, pathlen); fixunc = 0; } else if (testtype != APR_EINCOMPLETE) { /* apr_filepath_root was very unexpected so fail already */ return testtype; } } else #endif { /* An actual segment, append it to the destination path */ apr_size_t i = (addpath[segend] != '\0'); if (pathlen + seglen + i >= sizeof(path)) return APR_ENAMETOOLONG; memcpy(path + pathlen, addpath, seglen + i); if (i) path[pathlen + seglen] = ((flags & APR_FILEPATH_NATIVE) ? '\\' : '/'); pathlen += seglen + i; } } /* Skip over trailing slash to the next segment */ if (addpath[segend]) ++segend; addpath += segend; } /* keptlen will be the baselen unless the addpath contained * backpath elements. If so, and APR_FILEPATH_NOTABOVEROOT * is specified (APR_FILEPATH_SECUREROOTTEST was caught above), * compare the string beyond the root to assure the result path * is still within given basepath. Note that the root path * segment is thoroughly tested prior to path parsing. */ if ((flags & APR_FILEPATH_NOTABOVEROOT) && baselen) { if (memcmp(basepath, path + rootlen, baselen) != 0) return APR_EABOVEROOT; /* Ahem... if we have a basepath without a trailing slash, * we better be sure that /foo wasn't replaced with /foobar! */ if (basepath[baselen - 1] != '/' && basepath[baselen - 1] != '\\' && path[rootlen + baselen] && path[rootlen + baselen] != '/' && path[rootlen + baselen] != '\\') return APR_EABOVEROOT; } if (addpath && (flags & APR_FILEPATH_TRUENAME)) { /* We can always skip the root, it's already true-named. */ if (rootlen > keptlen) keptlen = rootlen; if ((path[keptlen] == '/') || (path[keptlen] == '\\')) { /* By rights, keptlen may grown longer than pathlen. * we wont' use it again (in that case) so we don't care. */ ++keptlen; } /* Go through all the new segments */ while (keptlen < pathlen) { apr_finfo_t finfo; char saveslash = 0; seglen = 0; /* find any slash and set it aside for a minute. */ for (seglen = 0; keptlen + seglen < pathlen; ++seglen) { if ((path[keptlen + seglen] == '/') || (path[keptlen + seglen] == '\\')) { saveslash = path[keptlen + seglen]; break; } } /* Null term for stat! */ path[keptlen + seglen] = '\0'; if ((rv = apr_stat(&finfo, path, APR_FINFO_LINK | APR_FINFO_TYPE | APR_FINFO_NAME, p)) == APR_SUCCESS) { apr_size_t namelen = strlen(finfo.name); #if defined(OS2) /* only has case folding, never aliases that change the length */ if (memcmp(finfo.name, path + keptlen, seglen) != 0) { memcpy(path + keptlen, finfo.name, namelen); } #else /* WIN32 || NETWARE; here there be aliases that gire and gimble and change length */ if ((namelen != seglen) || (memcmp(finfo.name, path + keptlen, seglen) != 0)) { if (namelen <= seglen) { memcpy(path + keptlen, finfo.name, namelen); if ((namelen < seglen) && saveslash) { memmove(path + keptlen + namelen + 1, path + keptlen + seglen + 1, pathlen - keptlen - seglen); pathlen += namelen - seglen; seglen = namelen; } } else { /* namelen > seglen */ if (pathlen + namelen - seglen >= sizeof(path)) return APR_ENAMETOOLONG; if (saveslash) { memmove(path + keptlen + namelen + 1, path + keptlen + seglen + 1, pathlen - keptlen - seglen); } memcpy(path + keptlen, finfo.name, namelen); pathlen += namelen - seglen; seglen = namelen; } } #endif /* !OS2 (Whatever that alias was we're over it) */ /* That's it, the rest is path info. * I don't know how we aught to handle this. Should * we define a new error to indicate 'more info'? * Should we split out the rest of the path? */ if ((finfo.filetype != APR_DIR) && (finfo.filetype != APR_LNK) && saveslash) rv = APR_ENOTDIR; #ifdef XXX_FIGURE_THIS_OUT { /* the example inserts a null between the end of * the filename and the next segment, and increments * the path length so we would return both segments. */ if (saveslash) { keptlen += seglen; path[keptlen] = saveslash; if (pathlen + 1 >= sizeof(path)) return APR_ENAMETOOLONG; memmove(path + keptlen + 1, path + keptlen, pathlen - keptlen); path[keptlen] = '\0'; ++pathlen; break; } } #endif } /* put back the '/' */ if (saveslash) { path[keptlen + seglen] = saveslash; ++seglen; } keptlen += seglen; if (rv != APR_SUCCESS) { if (APR_STATUS_IS_ENOENT(rv)) break; if (APR_STATUS_IS_EPATHWILD(rv)) /* This path included wildcards. The path elements * that did not contain wildcards are canonicalized, * so we will return the path, although later elements * don't necessarily exist, and aren't canonical. */ break; else if (APR_STATUS_IS_ENOTDIR(rv)) /* This is a little more serious, we just added a name * onto a filename (think http's PATH_INFO) * If the caller is foolish enough to do this, we expect * the've already canonicalized the root) that they knew * what they are doing :( */ break; else return rv; } } } *newpath = apr_pmemdup(p, path, pathlen + 1); (*newpath)[pathlen] = '\0'; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_filepath_list_split(apr_array_header_t **pathelts, const char *liststr, apr_pool_t *p) { return apr_filepath_list_split_impl(pathelts, liststr, ';', p); } APR_DECLARE(apr_status_t) apr_filepath_list_merge(char **liststr, apr_array_header_t *pathelts, apr_pool_t *p) { return apr_filepath_list_merge_impl(liststr, pathelts, ';', p); } APR_DECLARE(apr_status_t) apr_filepath_encoding(int *style, apr_pool_t *p) { #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { *style = APR_FILEPATH_ENCODING_UTF8; return APR_SUCCESS; } #endif *style = APR_FILEPATH_ENCODING_LOCALE; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/win32/filepath.c
C
asf20
37,643
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_arch_file_io.h" #include "apr_strings.h" /* Win32 Exceptions: * * Note that trailing spaces and trailing periods are never recorded * in the file system, except by a very obscure bug where any file * that is created with a trailing space or period, followed by the * ':' stream designator on an NTFS volume can never be accessed again. * In other words, don't ever accept them when designating a stream! * * An interesting side effect is that two or three periods are both * treated as the parent directory, although the fourth and on are * not [strongly suggest all trailing periods are trimmed off, or * down to two if there are no other characters.] * * Leading spaces and periods are accepted, however. * The * ? < > codes all have wildcard side effects * The " / \ : are exclusively component separator tokens * The system doesn't accept | for any (known) purpose * Oddly, \x7f _is_ acceptable ;) */ /* apr_c_is_fnchar[] maps Win32's file name and shell escape symbols * * element & 1 == valid file name character [excluding delimiters] * element & 2 == character should be shell (caret) escaped from cmd.exe * * this must be in-sync with Apache httpd's gen_test_char.c for cgi escaping. */ const char apr_c_is_fnchar[256] = {/* Reject all ctrl codes... Escape \n and \r (ascii 10 and 13) */ 0,0,0,0,0,0,0,0,0,0,2,0,0,2,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */ 1,1,2,1,3,3,3,3,3,3,2,1,1,1,1,0, 1,1,1,1,1,1,1,1,1,1,0,3,2,1,2,2, /* @ 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 [ \ ] ^ _ */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,3,2,3,3,1, /* ` 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 { | } ~ */ 3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,3,2,3,3,1, /* High bit codes are accepted (subject to utf-8->Unicode xlation) */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }; apr_status_t filepath_root_test(char *path, apr_pool_t *p) { apr_status_t rv; #if APR_HAS_UNICODE_FS if (apr_os_level >= APR_WIN_NT) { apr_wchar_t wpath[APR_PATH_MAX]; if (rv = utf8_to_unicode_path(wpath, sizeof(wpath) / sizeof(apr_wchar_t), path)) return rv; rv = GetDriveTypeW(wpath); } else #endif rv = GetDriveType(path); if (rv == DRIVE_UNKNOWN || rv == DRIVE_NO_ROOT_DIR) return APR_EBADPATH; return APR_SUCCESS; } apr_status_t filepath_drive_get(char **rootpath, char drive, apr_int32_t flags, apr_pool_t *p) { char path[APR_PATH_MAX]; #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { apr_wchar_t *ignored; apr_wchar_t wdrive[8]; apr_wchar_t wpath[APR_PATH_MAX]; apr_status_t rv; /* ???: This needs review, apparently "\\?\d:." returns "\\?\d:" * as if that is useful for anything. */ wcscpy(wdrive, L"D:."); wdrive[0] = (apr_wchar_t)(unsigned char)drive; if (!GetFullPathNameW(wdrive, sizeof(wpath) / sizeof(apr_wchar_t), wpath, &ignored)) return apr_get_os_error(); if ((rv = unicode_to_utf8_path(path, sizeof(path), wpath))) return rv; } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { char *ignored; char drivestr[4]; drivestr[0] = drive; drivestr[1] = ':'; drivestr[2] = '.';; drivestr[3] = '\0'; if (!GetFullPathName(drivestr, sizeof(path), path, &ignored)) return apr_get_os_error(); } #endif if (!(flags & APR_FILEPATH_NATIVE)) { for (*rootpath = path; **rootpath; ++*rootpath) { if (**rootpath == '\\') **rootpath = '/'; } } *rootpath = apr_pstrdup(p, path); return APR_SUCCESS; } apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p) { #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { apr_wchar_t *ignored; apr_wchar_t wpath[APR_PATH_MAX]; apr_status_t rv; apr_wchar_t wroot[APR_PATH_MAX]; /* ???: This needs review, apparently "\\?\d:." returns "\\?\d:" * as if that is useful for anything. */ if (rv = utf8_to_unicode_path(wroot, sizeof(wroot) / sizeof(apr_wchar_t), root)) return rv; if (!GetFullPathNameW(wroot, sizeof(wpath) / sizeof(apr_wchar_t), wpath, &ignored)) return apr_get_os_error(); /* Borrow wroot as a char buffer (twice as big as necessary) */ if ((rv = unicode_to_utf8_path((char*)wroot, sizeof(wroot), wpath))) return rv; *rootpath = apr_pstrdup(p, (char*)wroot); } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { char path[APR_PATH_MAX]; char *ignored; if (!GetFullPathName(root, sizeof(path), path, &ignored)) return apr_get_os_error(); *rootpath = apr_pstrdup(p, path); } #endif return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_filepath_get(char **rootpath, apr_int32_t flags, apr_pool_t *p) { char path[APR_PATH_MAX]; #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { apr_wchar_t wpath[APR_PATH_MAX]; apr_status_t rv; if (!GetCurrentDirectoryW(sizeof(wpath) / sizeof(apr_wchar_t), wpath)) return apr_get_os_error(); if ((rv = unicode_to_utf8_path(path, sizeof(path), wpath))) return rv; } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { if (!GetCurrentDirectory(sizeof(path), path)) return apr_get_os_error(); } #endif if (!(flags & APR_FILEPATH_NATIVE)) { for (*rootpath = path; **rootpath; ++*rootpath) { if (**rootpath == '\\') **rootpath = '/'; } } *rootpath = apr_pstrdup(p, path); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_filepath_set(const char *rootpath, apr_pool_t *p) { #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { apr_wchar_t wpath[APR_PATH_MAX]; apr_status_t rv; if (rv = utf8_to_unicode_path(wpath, sizeof(wpath) / sizeof(apr_wchar_t), rootpath)) return rv; if (!SetCurrentDirectoryW(wpath)) return apr_get_os_error(); } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { if (!SetCurrentDirectory(rootpath)) return apr_get_os_error(); } #endif return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/win32/filesys.c
C
asf20
7,765
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" static apr_status_t setptr(apr_file_t *thefile, apr_off_t pos ) { apr_off_t newbufpos; apr_status_t rv; if (thefile->direction == 1) { rv = apr_file_flush(thefile); if (rv) { return rv; } thefile->bufpos = thefile->direction = thefile->dataRead = 0; } newbufpos = pos - (thefile->filePtr - thefile->dataRead); if (newbufpos >= 0 && newbufpos <= thefile->dataRead) { thefile->bufpos = newbufpos; rv = APR_SUCCESS; } else { if (lseek(thefile->filedes, pos, SEEK_SET) != -1) { thefile->bufpos = thefile->dataRead = 0; thefile->filePtr = pos; rv = APR_SUCCESS; } else { rv = errno; } } return rv; } APR_DECLARE(apr_status_t) apr_file_seek(apr_file_t *thefile, apr_seek_where_t where, apr_off_t *offset) { apr_off_t rv; thefile->eof_hit = 0; if (thefile->buffered) { int rc = EINVAL; apr_finfo_t finfo; switch (where) { case APR_SET: rc = setptr(thefile, *offset); break; case APR_CUR: rc = setptr(thefile, thefile->filePtr - thefile->dataRead + thefile->bufpos + *offset); break; case APR_END: rc = apr_file_info_get(&finfo, APR_FINFO_SIZE, thefile); if (rc == APR_SUCCESS) rc = setptr(thefile, finfo.size + *offset); break; } *offset = thefile->filePtr - thefile->dataRead + thefile->bufpos; return rc; } else { rv = lseek(thefile->filedes, *offset, where); if (rv == -1) { *offset = -1; return errno; } else { *offset = rv; return APR_SUCCESS; } } } apr_status_t apr_file_trunc(apr_file_t *fp, apr_off_t offset) { if (ftruncate(fp->filedes, offset) == -1) { return errno; } return setptr(fp, offset); }
001-log4cxx
trunk/src/apr/file_io/unix/seek.c
C
asf20
2,829
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" #include "apr_file_io.h" static apr_status_t apr_file_transfer_contents(const char *from_path, const char *to_path, apr_int32_t flags, apr_fileperms_t to_perms, apr_pool_t *pool) { apr_file_t *s, *d; apr_status_t status; apr_finfo_t finfo; apr_fileperms_t perms; /* Open source file. */ status = apr_file_open(&s, from_path, APR_READ, APR_OS_DEFAULT, pool); if (status) return status; /* Maybe get its permissions. */ if (to_perms == APR_FILE_SOURCE_PERMS) { status = apr_file_info_get(&finfo, APR_FINFO_PROT, s); if (status != APR_SUCCESS && status != APR_INCOMPLETE) { apr_file_close(s); /* toss any error */ return status; } perms = finfo.protection; } else perms = to_perms; /* Open dest file. */ status = apr_file_open(&d, to_path, flags, perms, pool); if (status) { apr_file_close(s); /* toss any error */ return status; } /* Copy bytes till the cows come home. */ while (1) { char buf[BUFSIZ]; apr_size_t bytes_this_time = sizeof(buf); apr_status_t read_err; apr_status_t write_err; /* Read 'em. */ read_err = apr_file_read(s, buf, &bytes_this_time); if (read_err && !APR_STATUS_IS_EOF(read_err)) { apr_file_close(s); /* toss any error */ apr_file_close(d); /* toss any error */ return read_err; } /* Write 'em. */ write_err = apr_file_write_full(d, buf, bytes_this_time, NULL); if (write_err) { apr_file_close(s); /* toss any error */ apr_file_close(d); /* toss any error */ return write_err; } if (read_err && APR_STATUS_IS_EOF(read_err)) { status = apr_file_close(s); if (status) { apr_file_close(d); /* toss any error */ return status; } /* return the results of this close: an error, or success */ return apr_file_close(d); } } /* NOTREACHED */ } APR_DECLARE(apr_status_t) apr_file_copy(const char *from_path, const char *to_path, apr_fileperms_t perms, apr_pool_t *pool) { return apr_file_transfer_contents(from_path, to_path, (APR_WRITE | APR_CREATE | APR_TRUNCATE), perms, pool); } APR_DECLARE(apr_status_t) apr_file_append(const char *from_path, const char *to_path, apr_fileperms_t perms, apr_pool_t *pool) { return apr_file_transfer_contents(from_path, to_path, (APR_WRITE | APR_CREATE | APR_APPEND), perms, pool); }
001-log4cxx
trunk/src/apr/file_io/unix/copy.c
C
asf20
4,093
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" #include "apr_strings.h" #include "apr_portable.h" #include "apr_thread_mutex.h" #include "apr_arch_inherit.h" static apr_status_t file_dup(apr_file_t **new_file, apr_file_t *old_file, apr_pool_t *p, int which_dup) { int rv; if (which_dup == 2) { if ((*new_file) == NULL) { /* We can't dup2 unless we have a valid new_file */ return APR_EINVAL; } rv = dup2(old_file->filedes, (*new_file)->filedes); } else { rv = dup(old_file->filedes); } if (rv == -1) return errno; if (which_dup == 1) { (*new_file) = (apr_file_t *)apr_pcalloc(p, sizeof(apr_file_t)); (*new_file)->pool = p; (*new_file)->filedes = rv; } (*new_file)->fname = apr_pstrdup(p, old_file->fname); (*new_file)->buffered = old_file->buffered; /* If the existing socket in a dup2 is already buffered, we * have an existing and valid (hopefully) mutex, so we don't * want to create it again as we could leak! */ #if APR_HAS_THREADS if ((*new_file)->buffered && !(*new_file)->thlock && old_file->thlock) { apr_thread_mutex_create(&((*new_file)->thlock), APR_THREAD_MUTEX_DEFAULT, p); } #endif /* As above, only create the buffer if we haven't already * got one. */ if ((*new_file)->buffered && !(*new_file)->buffer) { (*new_file)->buffer = apr_palloc(p, APR_FILE_BUFSIZE); } /* this is the way dup() works */ (*new_file)->blocking = old_file->blocking; /* make sure unget behavior is consistent */ (*new_file)->ungetchar = old_file->ungetchar; /* apr_file_dup2() retains the original cleanup, reflecting * the existing inherit and nocleanup flags. This means, * that apr_file_dup2() cannot be called against an apr_file_t * already closed with apr_file_close, because the expected * cleanup was already killed. */ if (which_dup == 2) { return APR_SUCCESS; } /* apr_file_dup() retains all old_file flags with the exceptions * of APR_INHERIT and APR_FILE_NOCLEANUP. * The user must call apr_file_inherit_set() on the dupped * apr_file_t when desired. */ (*new_file)->flags = old_file->flags & ~(APR_INHERIT | APR_FILE_NOCLEANUP); apr_pool_cleanup_register((*new_file)->pool, (void *)(*new_file), apr_unix_file_cleanup, apr_unix_file_cleanup); #ifndef WAITIO_USES_POLL /* Start out with no pollset. apr_wait_for_io_or_timeout() will * initialize the pollset if needed. */ (*new_file)->pollset = NULL; #endif return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_dup(apr_file_t **new_file, apr_file_t *old_file, apr_pool_t *p) { return file_dup(new_file, old_file, p, 1); } APR_DECLARE(apr_status_t) apr_file_dup2(apr_file_t *new_file, apr_file_t *old_file, apr_pool_t *p) { return file_dup(&new_file, old_file, p, 2); } APR_DECLARE(apr_status_t) apr_file_setaside(apr_file_t **new_file, apr_file_t *old_file, apr_pool_t *p) { *new_file = (apr_file_t *)apr_palloc(p, sizeof(apr_file_t)); memcpy(*new_file, old_file, sizeof(apr_file_t)); (*new_file)->pool = p; if (old_file->buffered) { (*new_file)->buffer = apr_palloc(p, APR_FILE_BUFSIZE); if (old_file->direction == 1) { memcpy((*new_file)->buffer, old_file->buffer, old_file->bufpos); } else { memcpy((*new_file)->buffer, old_file->buffer, old_file->dataRead); } #if APR_HAS_THREADS if (old_file->thlock) { apr_thread_mutex_create(&((*new_file)->thlock), APR_THREAD_MUTEX_DEFAULT, p); apr_thread_mutex_destroy(old_file->thlock); } #endif /* APR_HAS_THREADS */ } if (old_file->fname) { (*new_file)->fname = apr_pstrdup(p, old_file->fname); } if (!(old_file->flags & APR_FILE_NOCLEANUP)) { apr_pool_cleanup_register(p, (void *)(*new_file), apr_unix_file_cleanup, ((*new_file)->flags & APR_INHERIT) ? apr_pool_cleanup_null : apr_unix_file_cleanup); } old_file->filedes = -1; apr_pool_cleanup_kill(old_file->pool, (void *)old_file, apr_unix_file_cleanup); #ifndef WAITIO_USES_POLL (*new_file)->pollset = NULL; #endif return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/unix/filedup.c
C
asf20
5,634
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" #include "apr_file_io.h" #include "apr_general.h" #include "apr_strings.h" #include "apr_errno.h" #ifdef HAVE_UTIME #include <utime.h> #endif static apr_filetype_e filetype_from_mode(mode_t mode) { apr_filetype_e type; switch (mode & S_IFMT) { case S_IFREG: type = APR_REG; break; case S_IFDIR: type = APR_DIR; break; case S_IFLNK: type = APR_LNK; break; case S_IFCHR: type = APR_CHR; break; case S_IFBLK: type = APR_BLK; break; #if defined(S_IFFIFO) case S_IFFIFO: type = APR_PIPE; break; #endif #if !defined(BEOS) && defined(S_IFSOCK) case S_IFSOCK: type = APR_SOCK; break; #endif default: /* Work around missing S_IFxxx values above * for Linux et al. */ #if !defined(S_IFFIFO) && defined(S_ISFIFO) if (S_ISFIFO(mode)) { type = APR_PIPE; } else #endif #if !defined(BEOS) && !defined(S_IFSOCK) && defined(S_ISSOCK) if (S_ISSOCK(mode)) { type = APR_SOCK; } else #endif type = APR_UNKFILE; } return type; } static void fill_out_finfo(apr_finfo_t *finfo, struct_stat *info, apr_int32_t wanted) { finfo->valid = APR_FINFO_MIN | APR_FINFO_IDENT | APR_FINFO_NLINK | APR_FINFO_OWNER | APR_FINFO_PROT; finfo->protection = apr_unix_mode2perms(info->st_mode); finfo->filetype = filetype_from_mode(info->st_mode); finfo->user = info->st_uid; finfo->group = info->st_gid; finfo->size = info->st_size; finfo->inode = info->st_ino; finfo->device = info->st_dev; finfo->nlink = info->st_nlink; apr_time_ansi_put(&finfo->atime, info->st_atime); apr_time_ansi_put(&finfo->mtime, info->st_mtime); apr_time_ansi_put(&finfo->ctime, info->st_ctime); /* ### needs to be revisited * if (wanted & APR_FINFO_CSIZE) { * finfo->csize = info->st_blocks * 512; * finfo->valid |= APR_FINFO_CSIZE; * } */ } APR_DECLARE(apr_status_t) apr_file_info_get(apr_finfo_t *finfo, apr_int32_t wanted, apr_file_t *thefile) { struct_stat info; if (thefile->buffered) { apr_status_t rv = apr_file_flush(thefile); if (rv != APR_SUCCESS) return rv; } if (fstat(thefile->filedes, &info) == 0) { finfo->pool = thefile->pool; finfo->fname = thefile->fname; fill_out_finfo(finfo, &info, wanted); return (wanted & ~finfo->valid) ? APR_INCOMPLETE : APR_SUCCESS; } else { return errno; } } APR_DECLARE(apr_status_t) apr_file_perms_set(const char *fname, apr_fileperms_t perms) { mode_t mode = apr_unix_perms2mode(perms); if (chmod(fname, mode) == -1) return errno; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_attrs_set(const char *fname, apr_fileattrs_t attributes, apr_fileattrs_t attr_mask, apr_pool_t *pool) { apr_status_t status; apr_finfo_t finfo; /* Don't do anything if we can't handle the requested attributes */ if (!(attr_mask & (APR_FILE_ATTR_READONLY | APR_FILE_ATTR_EXECUTABLE))) return APR_SUCCESS; status = apr_stat(&finfo, fname, APR_FINFO_PROT, pool); if (status) return status; /* ### TODO: should added bits be umask'd? */ if (attr_mask & APR_FILE_ATTR_READONLY) { if (attributes & APR_FILE_ATTR_READONLY) { finfo.protection &= ~APR_UWRITE; finfo.protection &= ~APR_GWRITE; finfo.protection &= ~APR_WWRITE; } else { /* ### umask this! */ finfo.protection |= APR_UWRITE; finfo.protection |= APR_GWRITE; finfo.protection |= APR_WWRITE; } } if (attr_mask & APR_FILE_ATTR_EXECUTABLE) { if (attributes & APR_FILE_ATTR_EXECUTABLE) { /* ### umask this! */ finfo.protection |= APR_UEXECUTE; finfo.protection |= APR_GEXECUTE; finfo.protection |= APR_WEXECUTE; } else { finfo.protection &= ~APR_UEXECUTE; finfo.protection &= ~APR_GEXECUTE; finfo.protection &= ~APR_WEXECUTE; } } return apr_file_perms_set(fname, finfo.protection); } APR_DECLARE(apr_status_t) apr_file_mtime_set(const char *fname, apr_time_t mtime, apr_pool_t *pool) { apr_status_t status; apr_finfo_t finfo; status = apr_stat(&finfo, fname, APR_FINFO_ATIME, pool); if (status) { return status; } #ifdef HAVE_UTIMES { struct timeval tvp[2]; tvp[0].tv_sec = apr_time_sec(finfo.atime); tvp[0].tv_usec = apr_time_usec(finfo.atime); tvp[1].tv_sec = apr_time_sec(mtime); tvp[1].tv_usec = apr_time_usec(mtime); if (utimes(fname, tvp) == -1) { return errno; } } #elif defined(HAVE_UTIME) { struct utimbuf buf; buf.actime = (time_t) (finfo.atime / APR_USEC_PER_SEC); buf.modtime = (time_t) (mtime / APR_USEC_PER_SEC); if (utime(fname, &buf) == -1) { return errno; } } #else return APR_ENOTIMPL; #endif return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_stat(apr_finfo_t *finfo, const char *fname, apr_int32_t wanted, apr_pool_t *pool) { struct_stat info; int srv; if (wanted & APR_FINFO_LINK) srv = lstat(fname, &info); else srv = stat(fname, &info); if (srv == 0) { finfo->pool = pool; finfo->fname = fname; fill_out_finfo(finfo, &info, wanted); if (wanted & APR_FINFO_LINK) wanted &= ~APR_FINFO_LINK; return (wanted & ~finfo->valid) ? APR_INCOMPLETE : APR_SUCCESS; } else { #if !defined(ENOENT) || !defined(ENOTDIR) #error ENOENT || ENOTDIR not defined; please see the #error comments at this line in the source for a workaround. /* * If ENOENT || ENOTDIR is not defined in one of the your OS's * include files, APR cannot report a good reason why the stat() * of the file failed; there are cases where it can fail even though * the file exists. This opens holes in Apache, for example, because * it becomes possible for someone to get a directory listing of a * directory even though there is an index (eg. index.html) file in * it. If you do not have a problem with this, delete the above * #error lines and start the compile again. If you need to do this, * please submit a bug report to http://www.apache.org/bug_report.html * letting us know that you needed to do this. Please be sure to * include the operating system you are using. */ /* WARNING: All errors will be handled as not found */ #if !defined(ENOENT) return APR_ENOENT; #else /* WARNING: All errors but not found will be handled as not directory */ if (errno != ENOENT) return APR_ENOENT; else return errno; #endif #else /* All was defined well, report the usual: */ return errno; #endif } }
001-log4cxx
trunk/src/apr/file_io/unix/filestat.c
C
asf20
8,438
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_strings.h" #include "apr_arch_file_io.h" /* A file to put ALL of the accessor functions for apr_file_t types. */ APR_DECLARE(apr_status_t) apr_file_name_get(const char **fname, apr_file_t *thefile) { *fname = thefile->fname; return APR_SUCCESS; } APR_DECLARE(apr_int32_t) apr_file_flags_get(apr_file_t *f) { return f->flags; } #if !defined(OS2) && !defined(WIN32) mode_t apr_unix_perms2mode(apr_fileperms_t perms) { mode_t mode = 0; if (perms & APR_USETID) mode |= S_ISUID; if (perms & APR_UREAD) mode |= S_IRUSR; if (perms & APR_UWRITE) mode |= S_IWUSR; if (perms & APR_UEXECUTE) mode |= S_IXUSR; if (perms & APR_GSETID) mode |= S_ISGID; if (perms & APR_GREAD) mode |= S_IRGRP; if (perms & APR_GWRITE) mode |= S_IWGRP; if (perms & APR_GEXECUTE) mode |= S_IXGRP; #ifdef S_ISVTX if (perms & APR_WSTICKY) mode |= S_ISVTX; #endif if (perms & APR_WREAD) mode |= S_IROTH; if (perms & APR_WWRITE) mode |= S_IWOTH; if (perms & APR_WEXECUTE) mode |= S_IXOTH; return mode; } apr_fileperms_t apr_unix_mode2perms(mode_t mode) { apr_fileperms_t perms = 0; if (mode & S_ISUID) perms |= APR_USETID; if (mode & S_IRUSR) perms |= APR_UREAD; if (mode & S_IWUSR) perms |= APR_UWRITE; if (mode & S_IXUSR) perms |= APR_UEXECUTE; if (mode & S_ISGID) perms |= APR_GSETID; if (mode & S_IRGRP) perms |= APR_GREAD; if (mode & S_IWGRP) perms |= APR_GWRITE; if (mode & S_IXGRP) perms |= APR_GEXECUTE; #ifdef S_ISVTX if (mode & S_ISVTX) perms |= APR_WSTICKY; #endif if (mode & S_IROTH) perms |= APR_WREAD; if (mode & S_IWOTH) perms |= APR_WWRITE; if (mode & S_IXOTH) perms |= APR_WEXECUTE; return perms; } #endif APR_DECLARE(apr_status_t) apr_file_data_get(void **data, const char *key, apr_file_t *file) { return apr_pool_userdata_get(data, key, file->pool); } APR_DECLARE(apr_status_t) apr_file_data_set(apr_file_t *file, void *data, const char *key, apr_status_t (*cleanup)(void *)) { return apr_pool_userdata_set(data, key, cleanup, file->pool); }
001-log4cxx
trunk/src/apr/file_io/unix/fileacc.c
C
asf20
3,257
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" #include "apr_strings.h" #include "apr_portable.h" #include "apr_thread_mutex.h" #include "apr_arch_inherit.h" #ifdef NETWARE #include "nks/dirio.h" #include "apr_hash.h" #include "fsio.h" #endif apr_status_t apr_unix_file_cleanup(void *thefile) { apr_file_t *file = thefile; apr_status_t flush_rv = APR_SUCCESS, rv = APR_SUCCESS; if (file->buffered) { flush_rv = apr_file_flush(file); } if (close(file->filedes) == 0) { file->filedes = -1; if (file->flags & APR_DELONCLOSE) { unlink(file->fname); } #if APR_HAS_THREADS if (file->thlock) { rv = apr_thread_mutex_destroy(file->thlock); } #endif } else { /* Are there any error conditions other than EINTR or EBADF? */ rv = errno; } #ifndef WAITIO_USES_POLL if (file->pollset != NULL) { int pollset_rv = apr_pollset_destroy(file->pollset); /* If the file close failed, return its error value, * not apr_pollset_destroy()'s. */ if (rv == APR_SUCCESS) { rv = pollset_rv; } } #endif /* !WAITIO_USES_POLL */ return rv != APR_SUCCESS ? rv : flush_rv; } APR_DECLARE(apr_status_t) apr_file_open(apr_file_t **new, const char *fname, apr_int32_t flag, apr_fileperms_t perm, apr_pool_t *pool) { apr_os_file_t fd; int oflags = 0; #if APR_HAS_THREADS apr_thread_mutex_t *thlock; apr_status_t rv; #endif if ((flag & APR_READ) && (flag & APR_WRITE)) { oflags = O_RDWR; } else if (flag & APR_READ) { oflags = O_RDONLY; } else if (flag & APR_WRITE) { oflags = O_WRONLY; } else { return APR_EACCES; } if (flag & APR_CREATE) { oflags |= O_CREAT; if (flag & APR_EXCL) { oflags |= O_EXCL; } } if ((flag & APR_EXCL) && !(flag & APR_CREATE)) { return APR_EACCES; } if (flag & APR_APPEND) { oflags |= O_APPEND; } if (flag & APR_TRUNCATE) { oflags |= O_TRUNC; } #ifdef O_BINARY if (flag & APR_BINARY) { oflags |= O_BINARY; } #endif #if APR_HAS_LARGE_FILES && defined(_LARGEFILE64_SOURCE) oflags |= O_LARGEFILE; #elif defined(O_LARGEFILE) if (flag & APR_LARGEFILE) { oflags |= O_LARGEFILE; } #endif #if APR_HAS_THREADS if ((flag & APR_BUFFERED) && (flag & APR_XTHREAD)) { rv = apr_thread_mutex_create(&thlock, APR_THREAD_MUTEX_DEFAULT, pool); if (rv) { return rv; } } #endif if (perm == APR_OS_DEFAULT) { fd = open(fname, oflags, 0666); } else { fd = open(fname, oflags, apr_unix_perms2mode(perm)); } if (fd < 0) { return errno; } (*new) = (apr_file_t *)apr_pcalloc(pool, sizeof(apr_file_t)); (*new)->pool = pool; (*new)->flags = flag; (*new)->filedes = fd; (*new)->fname = apr_pstrdup(pool, fname); (*new)->blocking = BLK_ON; (*new)->buffered = (flag & APR_BUFFERED) > 0; if ((*new)->buffered) { (*new)->buffer = apr_palloc(pool, APR_FILE_BUFSIZE); #if APR_HAS_THREADS if ((*new)->flags & APR_XTHREAD) { (*new)->thlock = thlock; } #endif } else { (*new)->buffer = NULL; } (*new)->is_pipe = 0; (*new)->timeout = -1; (*new)->ungetchar = -1; (*new)->eof_hit = 0; (*new)->filePtr = 0; (*new)->bufpos = 0; (*new)->dataRead = 0; (*new)->direction = 0; #ifndef WAITIO_USES_POLL /* Start out with no pollset. apr_wait_for_io_or_timeout() will * initialize the pollset if needed. */ (*new)->pollset = NULL; #endif if (!(flag & APR_FILE_NOCLEANUP)) { apr_pool_cleanup_register((*new)->pool, (void *)(*new), apr_unix_file_cleanup, apr_unix_file_cleanup); } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_close(apr_file_t *file) { return apr_pool_cleanup_run(file->pool, file, apr_unix_file_cleanup); } APR_DECLARE(apr_status_t) apr_file_remove(const char *path, apr_pool_t *pool) { if (unlink(path) == 0) { return APR_SUCCESS; } else { return errno; } } APR_DECLARE(apr_status_t) apr_file_rename(const char *from_path, const char *to_path, apr_pool_t *p) { if (rename(from_path, to_path) != 0) { return errno; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_file_get(apr_os_file_t *thefile, apr_file_t *file) { *thefile = file->filedes; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_file_put(apr_file_t **file, apr_os_file_t *thefile, apr_int32_t flags, apr_pool_t *pool) { int *dafile = thefile; (*file) = apr_pcalloc(pool, sizeof(apr_file_t)); (*file)->pool = pool; (*file)->eof_hit = 0; (*file)->blocking = BLK_UNKNOWN; /* in case it is a pipe */ (*file)->timeout = -1; (*file)->ungetchar = -1; /* no char avail */ (*file)->filedes = *dafile; (*file)->flags = flags | APR_FILE_NOCLEANUP; (*file)->buffered = (flags & APR_BUFFERED) > 0; #ifndef WAITIO_USES_POLL /* Start out with no pollset. apr_wait_for_io_or_timeout() will * initialize the pollset if needed. */ (*file)->pollset = NULL; #endif if ((*file)->buffered) { (*file)->buffer = apr_palloc(pool, APR_FILE_BUFSIZE); #if APR_HAS_THREADS if ((*file)->flags & APR_XTHREAD) { apr_status_t rv; rv = apr_thread_mutex_create(&((*file)->thlock), APR_THREAD_MUTEX_DEFAULT, pool); if (rv) { return rv; } } #endif } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_eof(apr_file_t *fptr) { if (fptr->eof_hit == 1) { return APR_EOF; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_open_stderr(apr_file_t **thefile, apr_pool_t *pool) { int fd = STDERR_FILENO; return apr_os_file_put(thefile, &fd, 0, pool); } APR_DECLARE(apr_status_t) apr_file_open_stdout(apr_file_t **thefile, apr_pool_t *pool) { int fd = STDOUT_FILENO; return apr_os_file_put(thefile, &fd, 0, pool); } APR_DECLARE(apr_status_t) apr_file_open_stdin(apr_file_t **thefile, apr_pool_t *pool) { int fd = STDIN_FILENO; return apr_os_file_put(thefile, &fd, 0, pool); } APR_IMPLEMENT_INHERIT_SET(file, flags, pool, apr_unix_file_cleanup) APR_IMPLEMENT_INHERIT_UNSET(file, flags, pool, apr_unix_file_cleanup) APR_POOL_IMPLEMENT_ACCESSOR(file)
001-log4cxx
trunk/src/apr/file_io/unix/open.c
C
asf20
7,982
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" #include "apr_strings.h" #include "apr_portable.h" #include "apr_arch_inherit.h" /* Figure out how to get pipe block/nonblock on BeOS... * Basically, BONE7 changed things again so that ioctl didn't work, * but now fcntl does, hence we need to do this extra checking. * The joys of beta programs. :-) */ #if BEOS #if !BONE7 # define BEOS_BLOCKING 1 #else # define BEOS_BLOCKING 0 #endif #endif static apr_status_t pipeblock(apr_file_t *thepipe) { #if !BEOS_BLOCKING int fd_flags; fd_flags = fcntl(thepipe->filedes, F_GETFL, 0); # if defined(O_NONBLOCK) fd_flags &= ~O_NONBLOCK; # elif defined(O_NDELAY) fd_flags &= ~O_NDELAY; # elif defined(O_FNDELAY) fd_flags &= ~O_FNDELAY; # else /* XXXX: this breaks things, but an alternative isn't obvious...*/ return APR_ENOTIMPL; # endif if (fcntl(thepipe->filedes, F_SETFL, fd_flags) == -1) { return errno; } #else /* BEOS_BLOCKING */ # if BEOS_BONE /* This only works on BONE 0-6 */ int on = 0; if (ioctl(thepipe->filedes, FIONBIO, &on, sizeof(on)) < 0) { return errno; } # else /* "classic" BeOS doesn't support this at all */ return APR_ENOTIMPL; # endif #endif /* !BEOS_BLOCKING */ thepipe->blocking = BLK_ON; return APR_SUCCESS; } static apr_status_t pipenonblock(apr_file_t *thepipe) { #if !BEOS_BLOCKING int fd_flags = fcntl(thepipe->filedes, F_GETFL, 0); # if defined(O_NONBLOCK) fd_flags |= O_NONBLOCK; # elif defined(O_NDELAY) fd_flags |= O_NDELAY; # elif defined(O_FNDELAY) fd_flags |= O_FNDELAY; # else /* XXXX: this breaks things, but an alternative isn't obvious...*/ return APR_ENOTIMPL; # endif if (fcntl(thepipe->filedes, F_SETFL, fd_flags) == -1) { return errno; } #else /* BEOS_BLOCKING */ # if BEOS_BONE /* This only works on BONE 0-6 */ int on = 1; if (ioctl(thepipe->filedes, FIONBIO, &on, sizeof(on)) < 0) { return errno; } # else /* "classic" BeOS doesn't support this at all */ return APR_ENOTIMPL; # endif #endif /* !BEOS_BLOCKING */ thepipe->blocking = BLK_OFF; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_pipe_timeout_set(apr_file_t *thepipe, apr_interval_time_t timeout) { if (thepipe->is_pipe == 1) { thepipe->timeout = timeout; if (timeout >= 0) { if (thepipe->blocking != BLK_OFF) { /* blocking or unknown state */ return pipenonblock(thepipe); } } else { if (thepipe->blocking != BLK_ON) { /* non-blocking or unknown state */ return pipeblock(thepipe); } } return APR_SUCCESS; } return APR_EINVAL; } APR_DECLARE(apr_status_t) apr_file_pipe_timeout_get(apr_file_t *thepipe, apr_interval_time_t *timeout) { if (thepipe->is_pipe == 1) { *timeout = thepipe->timeout; return APR_SUCCESS; } return APR_EINVAL; } APR_DECLARE(apr_status_t) apr_os_pipe_put_ex(apr_file_t **file, apr_os_file_t *thefile, int register_cleanup, apr_pool_t *pool) { int *dafile = thefile; (*file) = apr_pcalloc(pool, sizeof(apr_file_t)); (*file)->pool = pool; (*file)->eof_hit = 0; (*file)->is_pipe = 1; (*file)->blocking = BLK_UNKNOWN; /* app needs to make a timeout call */ (*file)->timeout = -1; (*file)->ungetchar = -1; /* no char avail */ (*file)->filedes = *dafile; if (!register_cleanup) { (*file)->flags = APR_FILE_NOCLEANUP; } (*file)->buffered = 0; #if APR_HAS_THREADS (*file)->thlock = NULL; #endif if (register_cleanup) { apr_pool_cleanup_register((*file)->pool, (void *)(*file), apr_unix_file_cleanup, apr_pool_cleanup_null); } #ifndef WAITIO_USES_POLL /* Start out with no pollset. apr_wait_for_io_or_timeout() will * initialize the pollset if needed. */ (*file)->pollset = NULL; #endif return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_pipe_put(apr_file_t **file, apr_os_file_t *thefile, apr_pool_t *pool) { return apr_os_pipe_put_ex(file, thefile, 0, pool); } APR_DECLARE(apr_status_t) apr_file_pipe_create(apr_file_t **in, apr_file_t **out, apr_pool_t *pool) { int filedes[2]; if (pipe(filedes) == -1) { return errno; } (*in) = (apr_file_t *)apr_pcalloc(pool, sizeof(apr_file_t)); (*in)->pool = pool; (*in)->filedes = filedes[0]; (*in)->is_pipe = 1; (*in)->fname = NULL; (*in)->buffered = 0; (*in)->blocking = BLK_ON; (*in)->timeout = -1; (*in)->ungetchar = -1; (*in)->flags = APR_INHERIT; #if APR_HAS_THREADS (*in)->thlock = NULL; #endif #ifndef WAITIO_USES_POLL (*in)->pollset = NULL; #endif (*out) = (apr_file_t *)apr_pcalloc(pool, sizeof(apr_file_t)); (*out)->pool = pool; (*out)->filedes = filedes[1]; (*out)->is_pipe = 1; (*out)->fname = NULL; (*out)->buffered = 0; (*out)->blocking = BLK_ON; (*out)->flags = APR_INHERIT; (*out)->timeout = -1; #if APR_HAS_THREADS (*out)->thlock = NULL; #endif #ifndef WAITIO_USES_POLL (*out)->pollset = NULL; #endif apr_pool_cleanup_register((*in)->pool, (void *)(*in), apr_unix_file_cleanup, apr_pool_cleanup_null); apr_pool_cleanup_register((*out)->pool, (void *)(*out), apr_unix_file_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_namedpipe_create(const char *filename, apr_fileperms_t perm, apr_pool_t *pool) { mode_t mode = apr_unix_perms2mode(perm); if (mkfifo(filename, mode) == -1) { return errno; } return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/unix/pipe.c
C
asf20
6,903
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (c) 1987, 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. */ #include "apr_private.h" #include "apr_file_io.h" /* prototype of apr_mkstemp() */ #include "apr_strings.h" /* prototype of apr_mkstemp() */ #include "apr_arch_file_io.h" /* prototype of apr_mkstemp() */ #include "apr_portable.h" /* for apr_os_file_put() */ #ifndef HAVE_MKSTEMP #if defined(SVR4) || defined(WIN32) || defined(NETWARE) #ifdef SVR4 #if HAVE_INTTYPES_H #include <inttypes.h> #endif #endif #define arc4random() rand() #define seedrandom(a) srand(a) #else #if APR_HAVE_STDINT_H #include <stdint.h> #endif #define arc4random() random() #define seedrandom(a) srandom(a) #endif #if APR_HAVE_SYS_TYPES_H #include <sys/types.h> #endif #if APR_HAVE_SYS_STAT_H #include <sys/stat.h> #endif #if APR_HAVE_FCNTL_H #include <fcntl.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #ifdef HAVE_TIME_H #include <time.h> #endif static const unsigned char padchar[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static apr_uint32_t randseed=0; static int gettemp(char *path, apr_file_t **doopen, apr_int32_t flags, apr_pool_t *p) { register char *start, *trv, *suffp; char *pad; apr_finfo_t sbuf; apr_status_t rv; apr_uint32_t randnum; if (randseed==0) { randseed = (int)apr_time_now(); seedrandom(randseed); } for (trv = path; *trv; ++trv) ; suffp = trv; --trv; if (trv < path) { return APR_EINVAL; } /* Fill space with random characters */ while (*trv == 'X') { randnum = arc4random() % (sizeof(padchar) - 1); *trv-- = padchar[randnum]; } start = trv + 1; /* * check the target directory. */ for (;; --trv) { if (trv <= path) break; if (*trv == '/') { *trv = '\0'; rv = apr_stat(&sbuf, path, APR_FINFO_TYPE, p); *trv = '/'; if (rv != APR_SUCCESS) return rv; if (sbuf.filetype != APR_DIR) { return APR_ENOTDIR; } break; } } for (;;) { if ((rv = apr_file_open(doopen, path, flags, APR_UREAD | APR_UWRITE, p)) == APR_SUCCESS) return APR_SUCCESS; if (!APR_STATUS_IS_EEXIST(rv)) return rv; /* If we have a collision, cycle through the space of filenames */ for (trv = start;;) { if (*trv == '\0' || trv == suffp) return APR_EINVAL; /* XXX: is this the correct return code? */ pad = strchr((char *)padchar, *trv); if (pad == NULL || !*++pad) { *trv++ = padchar[0]; } else { *trv++ = *pad; break; } } } /*NOTREACHED*/ } #else #if APR_HAVE_STDLIB_H #include <stdlib.h> /* for mkstemp() - Single Unix */ #endif #if APR_HAVE_UNISTD_H #include <unistd.h> /* for mkstemp() - FreeBSD */ #endif #endif /* !defined(HAVE_MKSTEMP) */ APR_DECLARE(apr_status_t) apr_file_mktemp(apr_file_t **fp, char *template, apr_int32_t flags, apr_pool_t *p) { #ifdef HAVE_MKSTEMP int fd; #endif flags = (!flags) ? APR_CREATE | APR_READ | APR_WRITE | APR_EXCL | APR_DELONCLOSE : flags; #ifndef HAVE_MKSTEMP return gettemp(template, fp, flags, p); #else #ifdef HAVE_MKSTEMP64 fd = mkstemp64(template); #else fd = mkstemp(template); #endif if (fd == -1) { return errno; } /* XXX: We must reset several flags values as passed-in, since * mkstemp didn't subscribe to our preference flags. * * We either have to unset the flags, or fix up the fd and other * xthread and inherit bits appropriately. Since gettemp() above * calls apr_file_open, our flags are respected in that code path. */ apr_os_file_put(fp, &fd, flags, p); (*fp)->fname = apr_pstrdup(p, template); apr_pool_cleanup_register((*fp)->pool, (void *)(*fp), apr_unix_file_cleanup, apr_unix_file_cleanup); #endif return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/unix/mktemp.c
C
asf20
6,747
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" #include "apr_strings.h" #include "apr_portable.h" #if APR_HAVE_SYS_SYSLIMITS_H #include <sys/syslimits.h> #endif #if APR_HAVE_LIMITS_H #include <limits.h> #endif static apr_status_t dir_cleanup(void *thedir) { apr_dir_t *dir = thedir; if (closedir(dir->dirstruct) == 0) { return APR_SUCCESS; } else { return errno; } } #define PATH_SEPARATOR '/' /* Remove trailing separators that don't affect the meaning of PATH. */ static const char *path_canonicalize (const char *path, apr_pool_t *pool) { /* At some point this could eliminate redundant components. For * now, it just makes sure there is no trailing slash. */ apr_size_t len = strlen (path); apr_size_t orig_len = len; while ((len > 0) && (path[len - 1] == PATH_SEPARATOR)) len--; if (len != orig_len) return apr_pstrndup (pool, path, len); else return path; } /* Remove one component off the end of PATH. */ static char *path_remove_last_component (const char *path, apr_pool_t *pool) { const char *newpath = path_canonicalize (path, pool); int i; for (i = (strlen(newpath) - 1); i >= 0; i--) { if (path[i] == PATH_SEPARATOR) break; } return apr_pstrndup (pool, path, (i < 0) ? 0 : i); } apr_status_t apr_dir_open(apr_dir_t **new, const char *dirname, apr_pool_t *pool) { /* On some platforms (e.g., Linux+GNU libc), d_name[] in struct * dirent is declared with enough storage for the name. On other * platforms (e.g., Solaris 8 for Intel), d_name is declared as a * one-byte array. Note: gcc evaluates this at compile time. */ apr_size_t dirent_size = (sizeof((*new)->entry->d_name) > 1 ? sizeof(struct dirent) : sizeof (struct dirent) + 255); DIR *dir = opendir(dirname); if (!dir) { return errno; } (*new) = (apr_dir_t *)apr_palloc(pool, sizeof(apr_dir_t)); (*new)->pool = pool; (*new)->dirname = apr_pstrdup(pool, dirname); (*new)->dirstruct = dir; (*new)->entry = apr_pcalloc(pool, dirent_size); apr_pool_cleanup_register((*new)->pool, *new, dir_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } apr_status_t apr_dir_close(apr_dir_t *thedir) { return apr_pool_cleanup_run(thedir->pool, thedir, dir_cleanup); } #ifdef DIRENT_TYPE static apr_filetype_e filetype_from_dirent_type(int type) { switch (type) { case DT_REG: return APR_REG; case DT_DIR: return APR_DIR; case DT_LNK: return APR_LNK; case DT_CHR: return APR_CHR; case DT_BLK: return APR_BLK; #if defined(DT_FIFO) case DT_FIFO: return APR_PIPE; #endif #if !defined(BEOS) && defined(DT_SOCK) case DT_SOCK: return APR_SOCK; #endif default: return APR_UNKFILE; } } #endif apr_status_t apr_dir_read(apr_finfo_t *finfo, apr_int32_t wanted, apr_dir_t *thedir) { apr_status_t ret = 0; #ifdef DIRENT_TYPE apr_filetype_e type; #endif #if APR_HAS_THREADS && defined(_POSIX_THREAD_SAFE_FUNCTIONS) \ && !defined(READDIR_IS_THREAD_SAFE) struct dirent *retent; ret = readdir_r(thedir->dirstruct, thedir->entry, &retent); /* Avoid the Linux problem where at end-of-directory thedir->entry * is set to NULL, but ret = APR_SUCCESS. */ if(!ret && thedir->entry != retent) ret = APR_ENOENT; /* Solaris is a bit strange, if there are no more entries in the * directory, it returns EINVAL. Since this is against POSIX, we * hack around the problem here. EINVAL is possible from other * readdir implementations, but only if the result buffer is too small. * since we control the size of that buffer, we should never have * that problem. */ if (ret == EINVAL) { ret = ENOENT; } #else /* We're about to call a non-thread-safe readdir() that may possibly set `errno', and the logic below actually cares about errno after the call. Therefore we need to clear errno first. */ errno = 0; thedir->entry = readdir(thedir->dirstruct); if (thedir->entry == NULL) { /* If NULL was returned, this can NEVER be a success. Can it?! */ if (errno == APR_SUCCESS) { ret = APR_ENOENT; } else ret = errno; } #endif /* No valid bit flag to test here - do we want one? */ finfo->fname = NULL; if (ret) { finfo->valid = 0; return ret; } #ifdef DIRENT_TYPE type = filetype_from_dirent_type(thedir->entry->DIRENT_TYPE); if (type != APR_UNKFILE) { wanted &= ~APR_FINFO_TYPE; } #endif #ifdef DIRENT_INODE if (thedir->entry->DIRENT_INODE && thedir->entry->DIRENT_INODE != -1) { wanted &= ~APR_FINFO_INODE; } #endif wanted &= ~APR_FINFO_NAME; if (wanted) { char fspec[APR_PATH_MAX]; int off; apr_cpystrn(fspec, thedir->dirname, sizeof(fspec)); off = strlen(fspec); if ((fspec[off - 1] != '/') && (off + 1 < sizeof(fspec))) fspec[off++] = '/'; apr_cpystrn(fspec + off, thedir->entry->d_name, sizeof(fspec) - off); ret = apr_stat(finfo, fspec, APR_FINFO_LINK | wanted, thedir->pool); /* We passed a stack name that will disappear */ finfo->fname = NULL; } if (wanted && (ret == APR_SUCCESS || ret == APR_INCOMPLETE)) { wanted &= ~finfo->valid; } else { /* We don't bail because we fail to stat, when we are only -required- * to readdir... but the result will be APR_INCOMPLETE */ finfo->pool = thedir->pool; finfo->valid = 0; #ifdef DIRENT_TYPE if (type != APR_UNKFILE) { finfo->filetype = type; finfo->valid |= APR_FINFO_TYPE; } #endif #ifdef DIRENT_INODE if (thedir->entry->DIRENT_INODE && thedir->entry->DIRENT_INODE != -1) { finfo->inode = thedir->entry->DIRENT_INODE; finfo->valid |= APR_FINFO_INODE; } #endif } finfo->name = apr_pstrdup(thedir->pool, thedir->entry->d_name); finfo->valid |= APR_FINFO_NAME; if (wanted) return APR_INCOMPLETE; return APR_SUCCESS; } apr_status_t apr_dir_rewind(apr_dir_t *thedir) { rewinddir(thedir->dirstruct); return APR_SUCCESS; } apr_status_t apr_dir_make(const char *path, apr_fileperms_t perm, apr_pool_t *pool) { mode_t mode = apr_unix_perms2mode(perm); if (mkdir(path, mode) == 0) { return APR_SUCCESS; } else { return errno; } } apr_status_t apr_dir_make_recursive(const char *path, apr_fileperms_t perm, apr_pool_t *pool) { apr_status_t apr_err = 0; apr_err = apr_dir_make (path, perm, pool); /* Try to make PATH right out */ if (apr_err == EEXIST) /* It's OK if PATH exists */ return APR_SUCCESS; if (apr_err == ENOENT) { /* Missing an intermediate dir */ char *dir; dir = path_remove_last_component(path, pool); /* If there is no path left, give up. */ if (dir[0] == '\0') { return apr_err; } apr_err = apr_dir_make_recursive(dir, perm, pool); if (!apr_err) apr_err = apr_dir_make (path, perm, pool); } return apr_err; } apr_status_t apr_dir_remove(const char *path, apr_pool_t *pool) { if (rmdir(path) == 0) { return APR_SUCCESS; } else { return errno; } } apr_status_t apr_os_dir_get(apr_os_dir_t **thedir, apr_dir_t *dir) { if (dir == NULL) { return APR_ENODIR; } *thedir = dir->dirstruct; return APR_SUCCESS; } apr_status_t apr_os_dir_put(apr_dir_t **dir, apr_os_dir_t *thedir, apr_pool_t *pool) { if ((*dir) == NULL) { (*dir) = (apr_dir_t *)apr_pcalloc(pool, sizeof(apr_dir_t)); (*dir)->pool = pool; } (*dir)->dirstruct = thedir; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/unix/dir.c
C
asf20
8,999
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" #include "apr_strings.h" #include "apr_thread_mutex.h" #include "apr_support.h" /* The only case where we don't use wait_for_io_or_timeout is on * pre-BONE BeOS, so this check should be sufficient and simpler */ #if !BEOS_R5 #define USE_WAIT_FOR_IO #endif APR_DECLARE(apr_status_t) apr_file_read(apr_file_t *thefile, void *buf, apr_size_t *nbytes) { apr_ssize_t rv; apr_size_t bytes_read; if (*nbytes <= 0) { *nbytes = 0; return APR_SUCCESS; } if (thefile->buffered) { char *pos = (char *)buf; apr_uint64_t blocksize; apr_uint64_t size = *nbytes; #if APR_HAS_THREADS if (thefile->thlock) { apr_thread_mutex_lock(thefile->thlock); } #endif if (thefile->direction == 1) { rv = apr_file_flush(thefile); if (rv) { #if APR_HAS_THREADS if (thefile->thlock) { apr_thread_mutex_unlock(thefile->thlock); } #endif return rv; } thefile->bufpos = 0; thefile->direction = 0; thefile->dataRead = 0; } rv = 0; if (thefile->ungetchar != -1) { *pos = (char)thefile->ungetchar; ++pos; --size; thefile->ungetchar = -1; } while (rv == 0 && size > 0) { if (thefile->bufpos >= thefile->dataRead) { int bytesread = read(thefile->filedes, thefile->buffer, APR_FILE_BUFSIZE); if (bytesread == 0) { thefile->eof_hit = TRUE; rv = APR_EOF; break; } else if (bytesread == -1) { rv = errno; break; } thefile->dataRead = bytesread; thefile->filePtr += thefile->dataRead; thefile->bufpos = 0; } blocksize = size > thefile->dataRead - thefile->bufpos ? thefile->dataRead - thefile->bufpos : size; memcpy(pos, thefile->buffer + thefile->bufpos, blocksize); thefile->bufpos += blocksize; pos += blocksize; size -= blocksize; } *nbytes = pos - (char *)buf; if (*nbytes) { rv = 0; } #if APR_HAS_THREADS if (thefile->thlock) { apr_thread_mutex_unlock(thefile->thlock); } #endif return rv; } else { bytes_read = 0; if (thefile->ungetchar != -1) { bytes_read = 1; *(char *)buf = (char)thefile->ungetchar; buf = (char *)buf + 1; (*nbytes)--; thefile->ungetchar = -1; if (*nbytes == 0) { *nbytes = bytes_read; return APR_SUCCESS; } } do { rv = read(thefile->filedes, buf, *nbytes); } while (rv == -1 && errno == EINTR); #ifdef USE_WAIT_FOR_IO if (rv == -1 && (errno == EAGAIN || errno == EWOULDBLOCK) && thefile->timeout != 0) { apr_status_t arv = apr_wait_for_io_or_timeout(thefile, NULL, 1); if (arv != APR_SUCCESS) { *nbytes = bytes_read; return arv; } else { do { rv = read(thefile->filedes, buf, *nbytes); } while (rv == -1 && errno == EINTR); } } #endif *nbytes = bytes_read; if (rv == 0) { thefile->eof_hit = TRUE; return APR_EOF; } if (rv > 0) { *nbytes += rv; return APR_SUCCESS; } return errno; } } APR_DECLARE(apr_status_t) apr_file_write(apr_file_t *thefile, const void *buf, apr_size_t *nbytes) { apr_size_t rv; if (thefile->buffered) { char *pos = (char *)buf; int blocksize; int size = *nbytes; #if APR_HAS_THREADS if (thefile->thlock) { apr_thread_mutex_lock(thefile->thlock); } #endif if ( thefile->direction == 0 ) { /* Position file pointer for writing at the offset we are * logically reading from */ apr_int64_t offset = thefile->filePtr - thefile->dataRead + thefile->bufpos; if (offset != thefile->filePtr) lseek(thefile->filedes, offset, SEEK_SET); thefile->bufpos = thefile->dataRead = 0; thefile->direction = 1; } rv = 0; while (rv == 0 && size > 0) { if (thefile->bufpos == APR_FILE_BUFSIZE) /* write buffer is full*/ rv = apr_file_flush(thefile); blocksize = size > APR_FILE_BUFSIZE - thefile->bufpos ? APR_FILE_BUFSIZE - thefile->bufpos : size; memcpy(thefile->buffer + thefile->bufpos, pos, blocksize); thefile->bufpos += blocksize; pos += blocksize; size -= blocksize; } #if APR_HAS_THREADS if (thefile->thlock) { apr_thread_mutex_unlock(thefile->thlock); } #endif return rv; } else { do { rv = write(thefile->filedes, buf, *nbytes); } while (rv == (apr_size_t)-1 && errno == EINTR); #ifdef USE_WAIT_FOR_IO if (rv == (apr_size_t)-1 && (errno == EAGAIN || errno == EWOULDBLOCK) && thefile->timeout != 0) { apr_status_t arv = apr_wait_for_io_or_timeout(thefile, NULL, 0); if (arv != APR_SUCCESS) { *nbytes = 0; return arv; } else { do { do { rv = write(thefile->filedes, buf, *nbytes); } while (rv == (apr_size_t)-1 && errno == EINTR); if (rv == (apr_size_t)-1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { *nbytes /= 2; /* yes, we'll loop if kernel lied * and we can't even write 1 byte */ } else { break; } } while (1); } } #endif if (rv == (apr_size_t)-1) { (*nbytes) = 0; return errno; } *nbytes = rv; return APR_SUCCESS; } } APR_DECLARE(apr_status_t) apr_file_writev(apr_file_t *thefile, const struct iovec *vec, apr_size_t nvec, apr_size_t *nbytes) { #ifdef HAVE_WRITEV int bytes; if ((bytes = writev(thefile->filedes, vec, nvec)) < 0) { *nbytes = 0; return errno; } else { *nbytes = bytes; return APR_SUCCESS; } #else /** * The problem with trying to output the entire iovec is that we cannot * maintain the behavoir that a real writev would have. If we iterate * over the iovec one at a time, we loose the atomic properties of * writev(). The other option is to combine the entire iovec into one * buffer that we could then send in one call to write(). This is not * reasonable since we do not know how much data an iovec could contain. * * The only reasonable option, that maintains the semantics of a real * writev(), is to only write the first iovec. Callers of file_writev() * must deal with partial writes as they normally would. If you want to * ensure an entire iovec is written, use apr_file_writev_full(). */ *nbytes = vec[0].iov_len; return apr_file_write(thefile, vec[0].iov_base, nbytes); #endif } APR_DECLARE(apr_status_t) apr_file_putc(char ch, apr_file_t *thefile) { apr_size_t nbytes = 1; return apr_file_write(thefile, &ch, &nbytes); } APR_DECLARE(apr_status_t) apr_file_ungetc(char ch, apr_file_t *thefile) { thefile->ungetchar = (unsigned char)ch; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_getc(char *ch, apr_file_t *thefile) { apr_size_t nbytes = 1; return apr_file_read(thefile, ch, &nbytes); } APR_DECLARE(apr_status_t) apr_file_puts(const char *str, apr_file_t *thefile) { return apr_file_write_full(thefile, str, strlen(str), NULL); } APR_DECLARE(apr_status_t) apr_file_flush(apr_file_t *thefile) { if (thefile->buffered) { apr_int64_t written = 0; if (thefile->direction == 1 && thefile->bufpos) { do { written = write(thefile->filedes, thefile->buffer, thefile->bufpos); } while (written == (apr_int64_t)-1 && errno == EINTR); if (written == (apr_int64_t)-1) { return errno; } thefile->filePtr += written; thefile->bufpos = 0; } } /* There isn't anything to do if we aren't buffering the output * so just return success. */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_gets(char *str, int len, apr_file_t *thefile) { apr_status_t rv = APR_SUCCESS; /* get rid of gcc warning */ apr_size_t nbytes; const char *str_start = str; char *final = str + len - 1; if (len <= 1) { /* sort of like fgets(), which returns NULL and stores no bytes */ return APR_SUCCESS; } /* If we have an underlying buffer, we can be *much* more efficient * and skip over the apr_file_read calls. */ if (thefile->buffered) { #if APR_HAS_THREADS if (thefile->thlock) { apr_thread_mutex_lock(thefile->thlock); } #endif if (thefile->direction == 1) { rv = apr_file_flush(thefile); if (rv) { #if APR_HAS_THREADS if (thefile->thlock) { apr_thread_mutex_unlock(thefile->thlock); } #endif return rv; } thefile->direction = 0; thefile->bufpos = 0; thefile->dataRead = 0; } while (str < final) { /* leave room for trailing '\0' */ /* Force ungetc leftover to call apr_file_read. */ if (thefile->bufpos < thefile->dataRead && thefile->ungetchar == -1) { *str = thefile->buffer[thefile->bufpos++]; } else { nbytes = 1; rv = apr_file_read(thefile, str, &nbytes); if (rv != APR_SUCCESS) { break; } } if (*str == '\n') { ++str; break; } ++str; } #if APR_HAS_THREADS if (thefile->thlock) { apr_thread_mutex_unlock(thefile->thlock); } #endif } else { while (str < final) { /* leave room for trailing '\0' */ nbytes = 1; rv = apr_file_read(thefile, str, &nbytes); if (rv != APR_SUCCESS) { break; } if (*str == '\n') { ++str; break; } ++str; } } /* We must store a terminating '\0' if we've stored any chars. We can * get away with storing it if we hit an error first. */ *str = '\0'; if (str > str_start) { /* we stored chars; don't report EOF or any other errors; * the app will find out about that on the next call */ return APR_SUCCESS; } return rv; } struct apr_file_printf_data { apr_vformatter_buff_t vbuff; apr_file_t *fptr; char *buf; }; static int file_printf_flush(apr_vformatter_buff_t *buff) { struct apr_file_printf_data *data = (struct apr_file_printf_data *)buff; if (apr_file_write_full(data->fptr, data->buf, data->vbuff.curpos - data->buf, NULL)) { return -1; } data->vbuff.curpos = data->buf; return 0; } APR_DECLARE_NONSTD(int) apr_file_printf(apr_file_t *fptr, const char *format, ...) { struct apr_file_printf_data data; va_list ap; int count; /* don't really need a HUGE_STRING_LEN anymore */ data.buf = malloc(HUGE_STRING_LEN); if (data.buf == NULL) { return -1; } data.vbuff.curpos = data.buf; data.vbuff.endpos = data.buf + HUGE_STRING_LEN; data.fptr = fptr; va_start(ap, format); count = apr_vformatter(file_printf_flush, (apr_vformatter_buff_t *)&data, format, ap); /* apr_vformatter does not call flush for the last bits */ if (count >= 0) file_printf_flush((apr_vformatter_buff_t *)&data); va_end(ap); free(data.buf); return count; }
001-log4cxx
trunk/src/apr/file_io/unix/readwrite.c
C
asf20
13,696
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define APR_WANT_STRFUNC #define APR_WANT_MEMFUNC #include "apr_want.h" #include "apr_errno.h" #include "apr_pools.h" #include "apr_strings.h" #include "apr_tables.h" #include "apr_private.h" apr_status_t apr_filepath_list_split_impl(apr_array_header_t **pathelts, const char *liststr, char separator, apr_pool_t *p) { char *path, *part, *ptr; char separator_string[2] = { '\0', '\0' }; apr_array_header_t *elts; int nelts; separator_string[0] = separator; /* Count the number of path elements. We know there'll be at least one even if path is an empty string. */ path = apr_pstrdup(p, liststr); for (nelts = 0, ptr = path; ptr != NULL; ++nelts) { ptr = strchr(ptr, separator); if (ptr) ++ptr; } /* Split the path into the array. */ elts = apr_array_make(p, nelts, sizeof(char*)); while ((part = apr_strtok(path, separator_string, &ptr)) != NULL) { if (*part == '\0') /* Ignore empty path components. */ continue; *(char**)apr_array_push(elts) = part; path = NULL; /* For the next call to apr_strtok */ } *pathelts = elts; return APR_SUCCESS; } apr_status_t apr_filepath_list_merge_impl(char **liststr, apr_array_header_t *pathelts, char separator, apr_pool_t *p) { apr_size_t path_size = 0; char *path; int i; /* This test isn't 100% certain, but it'll catch at least some invalid uses... */ if (pathelts->elt_size != sizeof(char*)) return APR_EINVAL; /* Calculate the size of the merged path */ for (i = 0; i < pathelts->nelts; ++i) path_size += strlen(((char**)pathelts->elts)[i]); if (path_size == 0) { *liststr = NULL; return APR_SUCCESS; } if (i > 0) /* Add space for the separators */ path_size += (i - 1); /* Merge the path components */ path = *liststr = apr_palloc(p, path_size + 1); for (i = 0; i < pathelts->nelts; ++i) { /* ### Hmmmm. Calling strlen twice on the same string. Yuck. But is is better than reallocation in apr_pstrcat? */ const char *part = ((char**)pathelts->elts)[i]; apr_size_t part_size = strlen(part); if (part_size == 0) /* Ignore empty path components. */ continue; if (i > 0) *path++ = separator; memcpy(path, part, part_size); path += part_size; } *path = '\0'; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/unix/filepath_util.c
C
asf20
3,578
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_private.h" #include "apr_file_io.h" #include "apr_strings.h" #include "apr_env.h" /* Try to open a temporary file in the temporary dir, write to it, and then close it. */ static int test_tempdir(const char *temp_dir, apr_pool_t *p) { apr_file_t *dummy_file; char *path = apr_pstrcat(p, temp_dir, "/apr-tmp.XXXXXX", NULL); if (apr_file_mktemp(&dummy_file, path, 0, p) == APR_SUCCESS) { if (apr_file_putc('!', dummy_file) == APR_SUCCESS) { if (apr_file_close(dummy_file) == APR_SUCCESS) { return 1; } } } return 0; } APR_DECLARE(apr_status_t) apr_temp_dir_get(const char **temp_dir, apr_pool_t *p) { apr_status_t apr_err; const char *try_dirs[] = { "/tmp", "/usr/tmp", "/var/tmp" }; const char *try_envs[] = { "TMP", "TEMP", "TMPDIR" }; const char *dir; char *cwd; int i; /* Our goal is to find a temporary directory suitable for writing into. We'll only pay the price once if we're successful -- we cache our successful find. Here's the order in which we'll try various paths: $TMP $TEMP $TMPDIR "C:\TEMP" (windows only) "SYS:\TMP" (netware only) "/tmp" "/var/tmp" "/usr/tmp" P_tmpdir (POSIX define) `pwd` NOTE: This algorithm is basically the same one used by Python 2.2's tempfile.py module. */ /* Try the environment first. */ for (i = 0; i < (sizeof(try_envs) / sizeof(const char *)); i++) { char *value; apr_err = apr_env_get(&value, try_envs[i], p); if ((apr_err == APR_SUCCESS) && value) { apr_size_t len = strlen(value); if (len && (len < APR_PATH_MAX) && test_tempdir(value, p)) { dir = value; goto end; } } } #ifdef WIN32 /* Next, on Win32, try the C:\TEMP directory. */ if (test_tempdir("C:\\TEMP", p)) { dir = "C:\\TEMP"; goto end; } #endif #ifdef NETWARE /* Next, on NetWare, try the SYS:/TMP directory. */ if (test_tempdir("SYS:/TMP", p)) { dir = "SYS:/TMP"; goto end; } #endif /* Next, try a set of hard-coded paths. */ for (i = 0; i < (sizeof(try_dirs) / sizeof(const char *)); i++) { if (test_tempdir(try_dirs[i], p)) { dir = try_dirs[i]; goto end; } } #ifdef P_tmpdir /* * If we have it, use the POSIX definition of where * the tmpdir should be */ if (test_tempdir(P_tmpdir, p)) { dir = P_tmpdir; goto end; } #endif /* Finally, try the current working directory. */ if (APR_SUCCESS == apr_filepath_get(&cwd, APR_FILEPATH_NATIVE, p)) { if (test_tempdir(cwd, p)) { dir = cwd; goto end; } } /* We didn't find a suitable temp dir anywhere */ return APR_EGENERAL; end: *temp_dir = apr_pstrdup(p, dir); return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/unix/tempdir.c
C
asf20
3,897
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" #if APR_HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef HAVE_SYS_FILE_H #include <sys/file.h> #endif APR_DECLARE(apr_status_t) apr_file_lock(apr_file_t *thefile, int type) { int rc; #if defined(HAVE_FCNTL_H) { struct flock l = { 0 }; int fc; l.l_whence = SEEK_SET; /* lock from current point */ l.l_start = 0; /* begin lock at this offset */ l.l_len = 0; /* lock to end of file */ if ((type & APR_FLOCK_TYPEMASK) == APR_FLOCK_SHARED) l.l_type = F_RDLCK; else l.l_type = F_WRLCK; fc = (type & APR_FLOCK_NONBLOCK) ? F_SETLK : F_SETLKW; /* keep trying if fcntl() gets interrupted (by a signal) */ while ((rc = fcntl(thefile->filedes, fc, &l)) < 0 && errno == EINTR) continue; if (rc == -1) { /* on some Unix boxes (e.g., Tru64), we get EACCES instead * of EAGAIN; we don't want APR_STATUS_IS_EAGAIN() matching EACCES * since that breaks other things, so fix up the retcode here */ if (errno == EACCES) { return EAGAIN; } return errno; } } #elif defined(HAVE_SYS_FILE_H) { int ltype; if ((type & APR_FLOCK_TYPEMASK) == APR_FLOCK_SHARED) ltype = LOCK_SH; else ltype = LOCK_EX; if ((type & APR_FLOCK_NONBLOCK) != 0) ltype |= LOCK_NB; /* keep trying if flock() gets interrupted (by a signal) */ while ((rc = flock(thefile->filedes, ltype)) < 0 && errno == EINTR) continue; if (rc == -1) return errno; } #else #error No file locking mechanism is available. #endif return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_unlock(apr_file_t *thefile) { int rc; #if defined(HAVE_FCNTL_H) { struct flock l = { 0 }; l.l_whence = SEEK_SET; /* lock from current point */ l.l_start = 0; /* begin lock at this offset */ l.l_len = 0; /* lock to end of file */ l.l_type = F_UNLCK; /* keep trying if fcntl() gets interrupted (by a signal) */ while ((rc = fcntl(thefile->filedes, F_SETLKW, &l)) < 0 && errno == EINTR) continue; if (rc == -1) return errno; } #elif defined(HAVE_SYS_FILE_H) { /* keep trying if flock() gets interrupted (by a signal) */ while ((rc = flock(thefile->filedes, LOCK_UN)) < 0 && errno == EINTR) continue; if (rc == -1) return errno; } #else #error No file locking mechanism is available. #endif return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/unix/flock.c
C
asf20
3,560
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_file_io.h" APR_DECLARE(apr_status_t) apr_file_read_full(apr_file_t *thefile, void *buf, apr_size_t nbytes, apr_size_t *bytes_read) { apr_status_t status; apr_size_t total_read = 0; do { apr_size_t amt = nbytes; status = apr_file_read(thefile, buf, &amt); buf = (char *)buf + amt; nbytes -= amt; total_read += amt; } while (status == APR_SUCCESS && nbytes > 0); if (bytes_read != NULL) *bytes_read = total_read; return status; } APR_DECLARE(apr_status_t) apr_file_write_full(apr_file_t *thefile, const void *buf, apr_size_t nbytes, apr_size_t *bytes_written) { apr_status_t status; apr_size_t total_written = 0; do { apr_size_t amt = nbytes; status = apr_file_write(thefile, buf, &amt); buf = (char *)buf + amt; nbytes -= amt; total_written += amt; } while (status == APR_SUCCESS && nbytes > 0); if (bytes_written != NULL) *bytes_written = total_written; return status; } APR_DECLARE(apr_status_t) apr_file_writev_full(apr_file_t *thefile, const struct iovec *vec, apr_size_t nvec, apr_size_t *bytes_written) { apr_status_t rv = APR_SUCCESS; apr_size_t i; apr_size_t amt = 0; apr_size_t total = 0; for (i = 0; i < nvec && rv == APR_SUCCESS; i++) { rv = apr_file_write_full(thefile, vec[i].iov_base, vec[i].iov_len, &amt); total += amt; } if (bytes_written != NULL) *bytes_written = total; return rv; }
001-log4cxx
trunk/src/apr/file_io/unix/fullrw.c
C
asf20
2,691
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_private.h" #include "apr_arch_file_io.h" #include "apr_file_io.h" #include "apr_strings.h" #define APR_WANT_STRFUNC #include "apr_want.h" #if APR_HAVE_UNISTD_H #include <unistd.h> #endif /* Win32 malpropism that can go away once everyone believes this * code is golden, and I'm not testing it anymore :-) */ #if APR_HAVE_DIRENT_H #include <dirent.h> #endif /* Any OS that requires/refuses trailing slashes should be dealt with here. */ APR_DECLARE(apr_status_t) apr_filepath_get(char **defpath, apr_int32_t flags, apr_pool_t *p) { char path[APR_PATH_MAX]; if (!getcwd(path, sizeof(path))) { if (errno == ERANGE) return APR_ENAMETOOLONG; else return errno; } *defpath = apr_pstrdup(p, path); return APR_SUCCESS; } /* Any OS that requires/refuses trailing slashes should be dealt with here */ APR_DECLARE(apr_status_t) apr_filepath_set(const char *path, apr_pool_t *p) { if (chdir(path) != 0) return errno; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_filepath_root(const char **rootpath, const char **inpath, apr_int32_t flags, apr_pool_t *p) { if (**inpath == '/') { *rootpath = apr_pstrdup(p, "/"); do { ++(*inpath); } while (**inpath == '/'); return APR_SUCCESS; } return APR_ERELATIVE; } APR_DECLARE(apr_status_t) apr_filepath_merge(char **newpath, const char *rootpath, const char *addpath, apr_int32_t flags, apr_pool_t *p) { char *path; apr_size_t rootlen; /* is the length of the src rootpath */ apr_size_t maxlen; /* maximum total path length */ apr_size_t keptlen; /* is the length of the retained rootpath */ apr_size_t pathlen; /* is the length of the result path */ apr_size_t seglen; /* is the end of the current segment */ apr_status_t rv; /* Treat null as an empty path. */ if (!addpath) addpath = ""; if (addpath[0] == '/') { /* If addpath is rooted, then rootpath is unused. * Ths violates any APR_FILEPATH_SECUREROOTTEST and * APR_FILEPATH_NOTABSOLUTE flags specified. */ if (flags & APR_FILEPATH_SECUREROOTTEST) return APR_EABOVEROOT; if (flags & APR_FILEPATH_NOTABSOLUTE) return APR_EABSOLUTE; /* If APR_FILEPATH_NOTABOVEROOT wasn't specified, * we won't test the root again, it's ignored. * Waste no CPU retrieving the working path. */ if (!rootpath && !(flags & APR_FILEPATH_NOTABOVEROOT)) rootpath = ""; } else { /* If APR_FILEPATH_NOTABSOLUTE is specified, the caller * requires a relative result. If the rootpath is * ommitted, we do not retrieve the working path, * if rootpath was supplied as absolute then fail. */ if (flags & APR_FILEPATH_NOTABSOLUTE) { if (!rootpath) rootpath = ""; else if (rootpath[0] == '/') return APR_EABSOLUTE; } } if (!rootpath) { /* Start with the current working path. This is bass akwards, * but required since the compiler (at least vc) doesn't like * passing the address of a char const* for a char** arg. */ char *getpath; rv = apr_filepath_get(&getpath, flags, p); rootpath = getpath; if (rv != APR_SUCCESS) return errno; /* XXX: Any kernel subject to goofy, uncanonical results * must run the rootpath against the user's given flags. * Simplest would be a recursive call to apr_filepath_merge * with an empty (not null) rootpath and addpath of the cwd. */ } rootlen = strlen(rootpath); maxlen = rootlen + strlen(addpath) + 4; /* 4 for slashes at start, after * root, and at end, plus trailing * null */ if (maxlen > APR_PATH_MAX) { return APR_ENAMETOOLONG; } path = (char *)apr_palloc(p, maxlen); if (addpath[0] == '/') { /* Ignore the given root path, strip off leading * '/'s to a single leading '/' from the addpath, * and leave addpath at the first non-'/' character. */ keptlen = 0; while (addpath[0] == '/') ++addpath; path[0] = '/'; pathlen = 1; } else { /* If both paths are relative, fail early */ if (rootpath[0] != '/' && (flags & APR_FILEPATH_NOTRELATIVE)) return APR_ERELATIVE; /* Base the result path on the rootpath */ keptlen = rootlen; memcpy(path, rootpath, rootlen); /* Always '/' terminate the given root path */ if (keptlen && path[keptlen - 1] != '/') { path[keptlen++] = '/'; } pathlen = keptlen; } while (*addpath) { /* Parse each segment, find the closing '/' */ const char *next = addpath; while (*next && (*next != '/')) { ++next; } seglen = next - addpath; if (seglen == 0 || (seglen == 1 && addpath[0] == '.')) { /* noop segment (/ or ./) so skip it */ } else if (seglen == 2 && addpath[0] == '.' && addpath[1] == '.') { /* backpath (../) */ if (pathlen == 1 && path[0] == '/') { /* Attempt to move above root. Always die if the * APR_FILEPATH_SECUREROOTTEST flag is specified. */ if (flags & APR_FILEPATH_SECUREROOTTEST) { return APR_EABOVEROOT; } /* Otherwise this is simply a noop, above root is root. * Flag that rootpath was entirely replaced. */ keptlen = 0; } else if (pathlen == 0 || (pathlen == 3 && !memcmp(path + pathlen - 3, "../", 3)) || (pathlen > 3 && !memcmp(path + pathlen - 4, "/../", 4))) { /* Path is already backpathed or empty, if the * APR_FILEPATH_SECUREROOTTEST.was given die now. */ if (flags & APR_FILEPATH_SECUREROOTTEST) { return APR_EABOVEROOT; } /* Otherwise append another backpath, including * trailing slash if present. */ memcpy(path + pathlen, "../", *next ? 3 : 2); pathlen += *next ? 3 : 2; } else { /* otherwise crop the prior segment */ do { --pathlen; } while (pathlen && path[pathlen - 1] != '/'); } /* Now test if we are above where we started and back up * the keptlen offset to reflect the added/altered path. */ if (pathlen < keptlen) { if (flags & APR_FILEPATH_SECUREROOTTEST) { return APR_EABOVEROOT; } keptlen = pathlen; } } else { /* An actual segment, append it to the destination path */ if (*next) { seglen++; } memcpy(path + pathlen, addpath, seglen); pathlen += seglen; } /* Skip over trailing slash to the next segment */ if (*next) { ++next; } addpath = next; } path[pathlen] = '\0'; /* keptlen will be the rootlen unless the addpath contained * backpath elements. If so, and APR_FILEPATH_NOTABOVEROOT * is specified (APR_FILEPATH_SECUREROOTTEST was caught above), * compare the original root to assure the result path is * still within given root path. */ if ((flags & APR_FILEPATH_NOTABOVEROOT) && keptlen < rootlen) { if (strncmp(rootpath, path, rootlen)) { return APR_EABOVEROOT; } if (rootpath[rootlen - 1] != '/' && path[rootlen] && path[rootlen] != '/') { return APR_EABOVEROOT; } } *newpath = path; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_filepath_list_split(apr_array_header_t **pathelts, const char *liststr, apr_pool_t *p) { return apr_filepath_list_split_impl(pathelts, liststr, ':', p); } APR_DECLARE(apr_status_t) apr_filepath_list_merge(char **liststr, apr_array_header_t *pathelts, apr_pool_t *p) { return apr_filepath_list_merge_impl(liststr, pathelts, ':', p); } APR_DECLARE(apr_status_t) apr_filepath_encoding(int *style, apr_pool_t *p) { *style = APR_FILEPATH_ENCODING_LOCALE; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/unix/filepath.c
C
asf20
10,285
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" #include "fsio.h" #include "nks/dirio.h" #include "apr_file_io.h" #include "apr_general.h" #include "apr_strings.h" #include "apr_errno.h" #include "apr_hash.h" #include "apr_thread_rwlock.h" #ifdef HAVE_UTIME_H #include <utime.h> #endif #define APR_HAS_PSA static apr_filetype_e filetype_from_mode(mode_t mode) { apr_filetype_e type = APR_NOFILE; if (S_ISREG(mode)) type = APR_REG; else if (S_ISDIR(mode)) type = APR_DIR; else if (S_ISCHR(mode)) type = APR_CHR; else if (S_ISBLK(mode)) type = APR_BLK; else if (S_ISFIFO(mode)) type = APR_PIPE; else if (S_ISLNK(mode)) type = APR_LNK; else if (S_ISSOCK(mode)) type = APR_SOCK; else type = APR_UNKFILE; return type; } static void fill_out_finfo(apr_finfo_t *finfo, struct stat *info, apr_int32_t wanted) { finfo->valid = APR_FINFO_MIN | APR_FINFO_IDENT | APR_FINFO_NLINK | APR_FINFO_OWNER | APR_FINFO_PROT; finfo->protection = apr_unix_mode2perms(info->st_mode); finfo->filetype = filetype_from_mode(info->st_mode); finfo->user = info->st_uid; finfo->group = info->st_gid; finfo->size = info->st_size; finfo->inode = info->st_ino; finfo->device = info->st_dev; finfo->nlink = info->st_nlink; apr_time_ansi_put(&finfo->atime, info->st_atime.tv_sec); apr_time_ansi_put(&finfo->mtime, info->st_mtime.tv_sec); apr_time_ansi_put(&finfo->ctime, info->st_ctime.tv_sec); /* ### needs to be revisited * if (wanted & APR_FINFO_CSIZE) { * finfo->csize = info->st_blocks * 512; * finfo->valid |= APR_FINFO_CSIZE; * } */ } APR_DECLARE(apr_status_t) apr_file_info_get(apr_finfo_t *finfo, apr_int32_t wanted, apr_file_t *thefile) { struct stat info; if (thefile->buffered) { apr_status_t rv = apr_file_flush(thefile); if (rv != APR_SUCCESS) return rv; } if (fstat(thefile->filedes, &info) == 0) { finfo->pool = thefile->pool; finfo->fname = thefile->fname; fill_out_finfo(finfo, &info, wanted); return (wanted & ~finfo->valid) ? APR_INCOMPLETE : APR_SUCCESS; } else { return errno; } } APR_DECLARE(apr_status_t) apr_file_perms_set(const char *fname, apr_fileperms_t perms) { mode_t mode = apr_unix_perms2mode(perms); if (chmod(fname, mode) == -1) return errno; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_attrs_set(const char *fname, apr_fileattrs_t attributes, apr_fileattrs_t attr_mask, apr_pool_t *pool) { apr_status_t status; apr_finfo_t finfo; /* Don't do anything if we can't handle the requested attributes */ if (!(attr_mask & (APR_FILE_ATTR_READONLY | APR_FILE_ATTR_EXECUTABLE))) return APR_SUCCESS; status = apr_stat(&finfo, fname, APR_FINFO_PROT, pool); if (status) return status; /* ### TODO: should added bits be umask'd? */ if (attr_mask & APR_FILE_ATTR_READONLY) { if (attributes & APR_FILE_ATTR_READONLY) { finfo.protection &= ~APR_UWRITE; finfo.protection &= ~APR_GWRITE; finfo.protection &= ~APR_WWRITE; } else { /* ### umask this! */ finfo.protection |= APR_UWRITE; finfo.protection |= APR_GWRITE; finfo.protection |= APR_WWRITE; } } if (attr_mask & APR_FILE_ATTR_EXECUTABLE) { if (attributes & APR_FILE_ATTR_EXECUTABLE) { /* ### umask this! */ finfo.protection |= APR_UEXECUTE; finfo.protection |= APR_GEXECUTE; finfo.protection |= APR_WEXECUTE; } else { finfo.protection &= ~APR_UEXECUTE; finfo.protection &= ~APR_GEXECUTE; finfo.protection &= ~APR_WEXECUTE; } } return apr_file_perms_set(fname, finfo.protection); } #ifndef APR_HAS_PSA static apr_status_t stat_cache_cleanup(void *data) { apr_pool_t *p = (apr_pool_t *)getGlobalPool(); apr_hash_index_t *hi; apr_hash_t *statCache = (apr_hash_t*)data; char *key; apr_ssize_t keylen; NXPathCtx_t pathctx; for (hi = apr_hash_first(p, statCache); hi; hi = apr_hash_next(hi)) { apr_hash_this(hi, (const void**)&key, &keylen, (void**)&pathctx); if (pathctx) { NXFreePathContext(pathctx); } } return APR_SUCCESS; } int cstat (NXPathCtx_t ctx, char *path, struct stat *buf, unsigned long requestmap, apr_pool_t *p) { apr_pool_t *gPool = (apr_pool_t *)getGlobalPool(); apr_hash_t *statCache = NULL; apr_thread_rwlock_t *rwlock = NULL; NXPathCtx_t pathctx = 0; char *ptr = NULL, *tr; int len = 0, x; char *ppath; char *pinfo; if (ctx == 1) { /* If there isn't a global pool then just stat the file and return */ if (!gPool) { char poolname[50]; if (apr_pool_create(&gPool, NULL) != APR_SUCCESS) { return getstat(ctx, path, buf, requestmap); } setGlobalPool(gPool); apr_pool_tag(gPool, apr_pstrdup(gPool, "cstat_mem_pool")); statCache = apr_hash_make(gPool); apr_pool_userdata_set ((void*)statCache, "STAT_CACHE", stat_cache_cleanup, gPool); apr_thread_rwlock_create(&rwlock, gPool); apr_pool_userdata_set ((void*)rwlock, "STAT_CACHE_LOCK", apr_pool_cleanup_null, gPool); } else { apr_pool_userdata_get((void**)&statCache, "STAT_CACHE", gPool); apr_pool_userdata_get((void**)&rwlock, "STAT_CACHE_LOCK", gPool); } if (!gPool || !statCache || !rwlock) { return getstat(ctx, path, buf, requestmap); } for (x = 0,tr = path;*tr != '\0';tr++,x++) { if (*tr == '\\' || *tr == '/') { ptr = tr; len = x; } if (*tr == ':') { ptr = "\\"; len = x; } } if (ptr) { ppath = apr_pstrndup (p, path, len); strlwr(ppath); if (ptr[1] != '\0') { ptr++; } /* If the path ended in a trailing slash then our result path will be a single slash. To avoid stat'ing the root with a slash, we need to make sure we stat the current directory with a dot */ if (((*ptr == '/') || (*ptr == '\\')) && (*(ptr+1) == '\0')) { pinfo = apr_pstrdup (p, "."); } else { pinfo = apr_pstrdup (p, ptr); } } /* If we have a statCache then try to pull the information from the cache. Otherwise just stat the file and return.*/ if (statCache) { apr_thread_rwlock_rdlock(rwlock); pathctx = (NXPathCtx_t) apr_hash_get(statCache, ppath, APR_HASH_KEY_STRING); apr_thread_rwlock_unlock(rwlock); if (pathctx) { return getstat(pathctx, pinfo, buf, requestmap); } else { int err; err = NXCreatePathContext(0, ppath, 0, NULL, &pathctx); if (!err) { apr_thread_rwlock_wrlock(rwlock); apr_hash_set(statCache, apr_pstrdup(gPool,ppath) , APR_HASH_KEY_STRING, (void*)pathctx); apr_thread_rwlock_unlock(rwlock); return getstat(pathctx, pinfo, buf, requestmap); } } } } return getstat(ctx, path, buf, requestmap); } #endif APR_DECLARE(apr_status_t) apr_stat(apr_finfo_t *finfo, const char *fname, apr_int32_t wanted, apr_pool_t *pool) { struct stat info; int srv; NXPathCtx_t pathCtx = 0; getcwdpath(NULL, &pathCtx, CTX_ACTUAL_CWD); #ifdef APR_HAS_PSA srv = getstat(pathCtx, (char*)fname, &info, ST_STAT_BITS|ST_NAME_BIT); #else srv = cstat(pathCtx, (char*)fname, &info, ST_STAT_BITS|ST_NAME_BIT, pool); #endif errno = srv; if (srv == 0) { finfo->pool = pool; finfo->fname = fname; fill_out_finfo(finfo, &info, wanted); if (wanted & APR_FINFO_LINK) wanted &= ~APR_FINFO_LINK; if (wanted & APR_FINFO_NAME) { finfo->name = apr_pstrdup(pool, info.st_name); finfo->valid |= APR_FINFO_NAME; } return (wanted & ~finfo->valid) ? APR_INCOMPLETE : APR_SUCCESS; } else { #if !defined(ENOENT) || !defined(ENOTDIR) #error ENOENT || ENOTDIR not defined; please see the #error comments at this line in the source for a workaround. /* * If ENOENT || ENOTDIR is not defined in one of the your OS's * include files, APR cannot report a good reason why the stat() * of the file failed; there are cases where it can fail even though * the file exists. This opens holes in Apache, for example, because * it becomes possible for someone to get a directory listing of a * directory even though there is an index (eg. index.html) file in * it. If you do not have a problem with this, delete the above * #error lines and start the compile again. If you need to do this, * please submit a bug report to http://www.apache.org/bug_report.html * letting us know that you needed to do this. Please be sure to * include the operating system you are using. */ /* WARNING: All errors will be handled as not found */ #if !defined(ENOENT) return APR_ENOENT; #else /* WARNING: All errors but not found will be handled as not directory */ if (errno != ENOENT) return APR_ENOENT; else return errno; #endif #else /* All was defined well, report the usual: */ return errno; #endif } } APR_DECLARE(apr_status_t) apr_file_mtime_set(const char *fname, apr_time_t mtime, apr_pool_t *pool) { apr_status_t status; apr_finfo_t finfo; status = apr_stat(&finfo, fname, APR_FINFO_ATIME, pool); if (status) { return status; } #ifdef HAVE_UTIMES { struct timeval tvp[2]; tvp[0].tv_sec = apr_time_sec(finfo.atime); tvp[0].tv_usec = apr_time_usec(finfo.atime); tvp[1].tv_sec = apr_time_sec(mtime); tvp[1].tv_usec = apr_time_usec(mtime); if (utimes(fname, tvp) == -1) { return errno; } } #elif defined(HAVE_UTIME) { struct utimbuf buf; buf.actime = (time_t) (finfo.atime / APR_USEC_PER_SEC); buf.modtime = (time_t) (mtime / APR_USEC_PER_SEC); if (utime(fname, &buf) == -1) { return errno; } } #else return APR_ENOTIMPL; #endif return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/netware/filestat.c
C
asf20
12,257
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <nks/fsio.h> #include <nks/errno.h> #include "apr_arch_file_io.h" #include "apr_strings.h" #include "apr_portable.h" #include "apr_arch_inherit.h" static apr_status_t pipeblock(apr_file_t *thepipe) { #ifdef USE_FLAGS int err; unsigned long flags; if (fcntl(thepipe->filedes, F_GETFL, &flags) != -1) { flags &= ~FNDELAY; fcntl(thepipe->filedes, F_SETFL, flags); } #else errno = 0; fcntl(thepipe->filedes, F_SETFL, 0); #endif if (errno) return errno; thepipe->blocking = BLK_ON; return APR_SUCCESS; } static apr_status_t pipenonblock(apr_file_t *thepipe) { #ifdef USE_FLAGS int err; unsigned long flags; errno = 0; if (fcntl(thepipe->filedes, F_GETFL, &flags) != -1) { flags |= FNDELAY; fcntl(thepipe->filedes, F_SETFL, flags); } #else errno = 0; fcntl(thepipe->filedes, F_SETFL, FNDELAY); #endif if (errno) return errno; thepipe->blocking = BLK_OFF; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_pipe_timeout_set(apr_file_t *thepipe, apr_interval_time_t timeout) { if (thepipe->is_pipe == 1) { thepipe->timeout = timeout; if (timeout >= 0) { if (thepipe->blocking != BLK_OFF) { /* blocking or unknown state */ return pipenonblock(thepipe); } } else { if (thepipe->blocking != BLK_ON) { /* non-blocking or unknown state */ return pipeblock(thepipe); } } return APR_SUCCESS; } return APR_EINVAL; } APR_DECLARE(apr_status_t) apr_file_pipe_timeout_get(apr_file_t *thepipe, apr_interval_time_t *timeout) { if (thepipe->is_pipe == 1) { *timeout = thepipe->timeout; return APR_SUCCESS; } return APR_EINVAL; } APR_DECLARE(apr_status_t) apr_os_pipe_put_ex(apr_file_t **file, apr_os_file_t *thefile, int register_cleanup, apr_pool_t *pool) { int *dafile = thefile; (*file) = apr_pcalloc(pool, sizeof(apr_file_t)); (*file)->pool = pool; (*file)->eof_hit = 0; (*file)->is_pipe = 1; (*file)->blocking = BLK_UNKNOWN; /* app needs to make a timeout call */ (*file)->timeout = -1; (*file)->ungetchar = -1; /* no char avail */ (*file)->filedes = *dafile; if (!register_cleanup) { (*file)->flags = APR_FILE_NOCLEANUP; } (*file)->buffered = 0; #if APR_HAS_THREADS (*file)->thlock = NULL; #endif if (register_cleanup) { apr_pool_cleanup_register((*file)->pool, (void *)(*file), apr_unix_file_cleanup, apr_pool_cleanup_null); } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_pipe_put(apr_file_t **file, apr_os_file_t *thefile, apr_pool_t *pool) { return apr_os_pipe_put_ex(file, thefile, 0, pool); } APR_DECLARE(apr_status_t) apr_file_pipe_create(apr_file_t **in, apr_file_t **out, apr_pool_t *pool) { int filedes[2]; int err; if (pipe(filedes) == -1) { return errno; } (*in) = (apr_file_t *)apr_pcalloc(pool, sizeof(apr_file_t)); (*out) = (apr_file_t *)apr_pcalloc(pool, sizeof(apr_file_t)); (*in)->pool = (*out)->pool = pool; (*in)->filedes = filedes[0]; (*out)->filedes = filedes[1]; (*in)->flags = APR_INHERIT; (*out)->flags = APR_INHERIT; (*in)->is_pipe = (*out)->is_pipe = 1; (*out)->fname = (*in)->fname = NULL; (*in)->buffered = (*out)->buffered = 0; (*in)->blocking = (*out)->blocking = BLK_ON; (*in)->timeout = (*out)->timeout = -1; (*in)->ungetchar = -1; (*in)->thlock = (*out)->thlock = NULL; (void) apr_pollset_create(&(*in)->pollset, 1, pool, 0); (void) apr_pollset_create(&(*out)->pollset, 1, pool, 0); apr_pool_cleanup_register((*in)->pool, (void *)(*in), apr_unix_file_cleanup, apr_pool_cleanup_null); apr_pool_cleanup_register((*out)->pool, (void *)(*out), apr_unix_file_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_namedpipe_create(const char *filename, apr_fileperms_t perm, apr_pool_t *pool) { return APR_ENOTIMPL; }
001-log4cxx
trunk/src/apr/file_io/netware/pipe.c
C
asf20
5,351
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_private.h" #include "apr_file_io.h" /* prototype of apr_mkstemp() */ #include "apr_strings.h" /* prototype of apr_mkstemp() */ #include "apr_arch_file_io.h" /* prototype of apr_mkstemp() */ #include "apr_portable.h" /* for apr_os_file_put() */ #include <stdlib.h> /* for mkstemp() - Single Unix */ APR_DECLARE(apr_status_t) apr_file_mktemp(apr_file_t **fp, char *template, apr_int32_t flags, apr_pool_t *p) { int fd; apr_status_t rv; flags = (!flags) ? APR_CREATE | APR_READ | APR_WRITE | APR_DELONCLOSE : flags & ~APR_EXCL; fd = mkstemp(template); if (fd == -1) { return errno; } /* We need to reopen the file to get rid of the o_excl flag. * Otherwise file locking will not allow the file to be shared. */ close(fd); if ((rv = apr_file_open(fp, template, flags|APR_FILE_NOCLEANUP, APR_UREAD | APR_UWRITE, p)) == APR_SUCCESS) { apr_pool_cleanup_register((*fp)->pool, (void *)(*fp), apr_unix_file_cleanup, apr_unix_file_cleanup); } return rv; }
001-log4cxx
trunk/src/apr/file_io/netware/mktemp.c
C
asf20
1,923
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <nks/fsio.h> #include "apr_arch_file_io.h" apr_status_t apr_file_lock(apr_file_t *thefile, int type) { int fc; fc = (type & APR_FLOCK_NONBLOCK) ? NX_RANGE_LOCK_TRYLOCK : NX_RANGE_LOCK_CHECK; if(NXFileRangeLock(thefile->filedes,fc, 0, 0) == -1) return errno; return APR_SUCCESS; } apr_status_t apr_file_unlock(apr_file_t *thefile) { if(NXFileRangeUnlock(thefile->filedes,NX_RANGE_LOCK_CANCEL,0 , 0) == -1) return errno; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/netware/flock.c
C
asf20
1,294
/* NetWare & Win32 have much in common with regards to file names (both are * DOSish) so it makes sense to share some code */ #include "../win32/filepath.c"
001-log4cxx
trunk/src/apr/file_io/netware/filepath.c
C
asf20
161
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_arch_file_io.h" #include "apr_strings.h" apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p) { /* See the Windows code to figure out what to do here. It probably checks to make sure that the root exists and case it correctly according to the file system. */ *rootpath = apr_pstrdup(p, root); return APR_SUCCESS; } apr_status_t filepath_has_drive(const char *rootpath, int only, apr_pool_t *p) { char *s; if (rootpath) { s = strchr (rootpath, ':'); if (only) /* Test if the path only has a drive/volume and nothing else */ return (s && (s != rootpath) && !s[1]); else /* Test if the path includes a drive/volume */ return (s && (s != rootpath)); } return 0; } apr_status_t filepath_compare_drive(const char *path1, const char *path2, apr_pool_t *p) { char *s1, *s2; if (path1 && path2) { s1 = strchr (path1, ':'); s2 = strchr (path2, ':'); /* Make sure that they both have a drive/volume delimiter and are the same size. Then see if they match. */ if (s1 && s2 && ((s1-path1) == (s2-path2))) { return strnicmp (s1, s2, s1-path1); } } return -1; } APR_DECLARE(apr_status_t) apr_filepath_get(char **rootpath, apr_int32_t flags, apr_pool_t *p) { char path[APR_PATH_MAX]; char *ptr; /* use getcwdpath to make sure that we get the volume name*/ if (!getcwdpath(path, NULL, 0)) { if (errno == ERANGE) return APR_ENAMETOOLONG; else return errno; } /* Strip off the server name if there is one*/ ptr = strpbrk(path, "\\/:"); if (!ptr) { return APR_ENOENT; } if (*ptr == ':') { ptr = path; } *rootpath = apr_pstrdup(p, ptr); if (!(flags & APR_FILEPATH_NATIVE)) { for (ptr = *rootpath; *ptr; ++ptr) { if (*ptr == '\\') *ptr = '/'; } } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_filepath_set(const char *rootpath, apr_pool_t *p) { if (chdir2(rootpath) != 0) return errno; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/netware/filesys.c
C
asf20
3,137
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" #include "apr_file_io.h" #include "apr_lib.h" #include <string.h> #include <io.h> static apr_status_t setptr(apr_file_t *thefile, unsigned long pos ) { long newbufpos; ULONG rc; if (thefile->direction == 1) { apr_status_t rv = apr_file_flush(thefile); if (rv != APR_SUCCESS) { return rv; } thefile->bufpos = thefile->direction = thefile->dataRead = 0; } newbufpos = pos - (thefile->filePtr - thefile->dataRead); if (newbufpos >= 0 && newbufpos <= thefile->dataRead) { thefile->bufpos = newbufpos; rc = 0; } else { rc = DosSetFilePtr(thefile->filedes, pos, FILE_BEGIN, &thefile->filePtr ); if ( !rc ) thefile->bufpos = thefile->dataRead = 0; } return APR_FROM_OS_ERROR(rc); } APR_DECLARE(apr_status_t) apr_file_seek(apr_file_t *thefile, apr_seek_where_t where, apr_off_t *offset) { if (!thefile->isopen) { return APR_EBADF; } thefile->eof_hit = 0; if (thefile->buffered) { int rc = EINVAL; apr_finfo_t finfo; switch (where) { case APR_SET: rc = setptr(thefile, *offset); break; case APR_CUR: rc = setptr(thefile, thefile->filePtr - thefile->dataRead + thefile->bufpos + *offset); break; case APR_END: rc = apr_file_info_get(&finfo, APR_FINFO_NORM, thefile); if (rc == APR_SUCCESS) rc = setptr(thefile, finfo.size + *offset); break; } *offset = thefile->filePtr - thefile->dataRead + thefile->bufpos; return rc; } else { switch (where) { case APR_SET: where = FILE_BEGIN; break; case APR_CUR: where = FILE_CURRENT; break; case APR_END: where = FILE_END; break; } return APR_FROM_OS_ERROR(DosSetFilePtr(thefile->filedes, *offset, where, (ULONG *)offset)); } } APR_DECLARE(apr_status_t) apr_file_trunc(apr_file_t *fp, apr_off_t offset) { int rc = DosSetFileSize(fp->filedes, offset); if (rc != 0) { return APR_FROM_OS_ERROR(rc); } if (fp->buffered) { return setptr(fp, offset); } return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/os2/seek.c
C
asf20
3,142
#include "../unix/copy.c"
001-log4cxx
trunk/src/apr/file_io/os2/copy.c
C
asf20
26
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" #include "apr_file_io.h" #include "apr_lib.h" #include "apr_strings.h" #include <string.h> #include "apr_arch_inherit.h" static apr_status_t file_dup(apr_file_t **new_file, apr_file_t *old_file, apr_pool_t *p) { int rv; apr_file_t *dup_file; if (*new_file == NULL) { dup_file = (apr_file_t *)apr_palloc(p, sizeof(apr_file_t)); if (dup_file == NULL) { return APR_ENOMEM; } dup_file->filedes = -1; } else { dup_file = *new_file; } dup_file->pool = p; rv = DosDupHandle(old_file->filedes, &dup_file->filedes); if (rv) { return APR_FROM_OS_ERROR(rv); } dup_file->fname = apr_pstrdup(dup_file->pool, old_file->fname); dup_file->buffered = old_file->buffered; dup_file->isopen = old_file->isopen; dup_file->flags = old_file->flags & ~APR_INHERIT; /* TODO - dup pipes correctly */ dup_file->pipe = old_file->pipe; if (*new_file == NULL) { apr_pool_cleanup_register(dup_file->pool, dup_file, apr_file_cleanup, apr_pool_cleanup_null); *new_file = dup_file; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_dup(apr_file_t **new_file, apr_file_t *old_file, apr_pool_t *p) { if (*new_file) { apr_file_close(*new_file); (*new_file)->filedes = -1; } return file_dup(new_file, old_file, p); } APR_DECLARE(apr_status_t) apr_file_dup2(apr_file_t *new_file, apr_file_t *old_file, apr_pool_t *p) { return file_dup(&new_file, old_file, p); } APR_DECLARE(apr_status_t) apr_file_setaside(apr_file_t **new_file, apr_file_t *old_file, apr_pool_t *p) { *new_file = (apr_file_t *)apr_palloc(p, sizeof(apr_file_t)); memcpy(*new_file, old_file, sizeof(apr_file_t)); (*new_file)->pool = p; if (old_file->buffered) { (*new_file)->buffer = apr_palloc(p, APR_FILE_BUFSIZE); if (old_file->direction == 1) { memcpy((*new_file)->buffer, old_file->buffer, old_file->bufpos); } else { memcpy((*new_file)->buffer, old_file->buffer, old_file->dataRead); } if (old_file->mutex) { apr_thread_mutex_create(&((*new_file)->mutex), APR_THREAD_MUTEX_DEFAULT, p); apr_thread_mutex_destroy(old_file->mutex); } } if (old_file->fname) { (*new_file)->fname = apr_pstrdup(p, old_file->fname); } if (!(old_file->flags & APR_FILE_NOCLEANUP)) { apr_pool_cleanup_register(p, (void *)(*new_file), apr_file_cleanup, apr_file_cleanup); } old_file->filedes = -1; apr_pool_cleanup_kill(old_file->pool, (void *)old_file, apr_file_cleanup); return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/os2/filedup.c
C
asf20
3,747
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define INCL_DOS #define INCL_DOSERRORS #include "apr_arch_file_io.h" #include "apr_file_io.h" #include "apr_lib.h" #include <sys/time.h> #include "apr_strings.h" static void FS3_to_finfo(apr_finfo_t *finfo, FILESTATUS3 *fstatus) { finfo->protection = (fstatus->attrFile & FILE_READONLY) ? 0x555 : 0x777; if (fstatus->attrFile & FILE_DIRECTORY) finfo->filetype = APR_DIR; else finfo->filetype = APR_REG; /* XXX: No other possible types from FS3? */ finfo->user = 0; finfo->group = 0; finfo->inode = 0; finfo->device = 0; finfo->size = fstatus->cbFile; finfo->csize = fstatus->cbFileAlloc; apr_os2_time_to_apr_time(&finfo->atime, fstatus->fdateLastAccess, fstatus->ftimeLastAccess ); apr_os2_time_to_apr_time(&finfo->mtime, fstatus->fdateLastWrite, fstatus->ftimeLastWrite ); apr_os2_time_to_apr_time(&finfo->ctime, fstatus->fdateCreation, fstatus->ftimeCreation ); finfo->valid = APR_FINFO_TYPE | APR_FINFO_PROT | APR_FINFO_SIZE | APR_FINFO_CSIZE | APR_FINFO_MTIME | APR_FINFO_CTIME | APR_FINFO_ATIME | APR_FINFO_LINK; } static apr_status_t handle_type(apr_filetype_e *ftype, HFILE file) { ULONG filetype, fileattr, rc; rc = DosQueryHType(file, &filetype, &fileattr); if (rc == 0) { switch (filetype & 0xff) { case 0: *ftype = APR_REG; break; case 1: *ftype = APR_CHR; break; case 2: *ftype = APR_PIPE; break; default: /* Brian, is this correct??? */ *ftype = APR_UNKFILE; break; } return APR_SUCCESS; } return APR_FROM_OS_ERROR(rc); } APR_DECLARE(apr_status_t) apr_file_info_get(apr_finfo_t *finfo, apr_int32_t wanted, apr_file_t *thefile) { ULONG rc; FILESTATUS3 fstatus; if (thefile->isopen) { if (thefile->buffered) { apr_status_t rv = apr_file_flush(thefile); if (rv != APR_SUCCESS) { return rv; } } rc = DosQueryFileInfo(thefile->filedes, FIL_STANDARD, &fstatus, sizeof(fstatus)); } else rc = DosQueryPathInfo(thefile->fname, FIL_STANDARD, &fstatus, sizeof(fstatus)); if (rc == 0) { FS3_to_finfo(finfo, &fstatus); finfo->fname = thefile->fname; if (finfo->filetype == APR_REG) { if (thefile->isopen) { return handle_type(&finfo->filetype, thefile->filedes); } } else { return APR_SUCCESS; } } finfo->protection = 0; finfo->filetype = APR_NOFILE; return APR_FROM_OS_ERROR(rc); } APR_DECLARE(apr_status_t) apr_file_perms_set(const char *fname, apr_fileperms_t perms) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_stat(apr_finfo_t *finfo, const char *fname, apr_int32_t wanted, apr_pool_t *cont) { ULONG rc; FILESTATUS3 fstatus; finfo->protection = 0; finfo->filetype = APR_NOFILE; finfo->name = NULL; rc = DosQueryPathInfo(fname, FIL_STANDARD, &fstatus, sizeof(fstatus)); if (rc == 0) { FS3_to_finfo(finfo, &fstatus); finfo->fname = fname; if (wanted & APR_FINFO_NAME) { ULONG count = 1; HDIR hDir = HDIR_SYSTEM; FILEFINDBUF3 ffb; rc = DosFindFirst(fname, &hDir, FILE_DIRECTORY|FILE_HIDDEN|FILE_SYSTEM|FILE_ARCHIVED, &ffb, sizeof(ffb), &count, FIL_STANDARD); if (rc == 0 && count == 1) { finfo->name = apr_pstrdup(cont, ffb.achName); finfo->valid |= APR_FINFO_NAME; } } } else if (rc == ERROR_INVALID_ACCESS) { memset(finfo, 0, sizeof(apr_finfo_t)); finfo->valid = APR_FINFO_TYPE | APR_FINFO_PROT; finfo->protection = 0666; finfo->filetype = APR_CHR; if (wanted & APR_FINFO_NAME) { finfo->name = apr_pstrdup(cont, fname); finfo->valid |= APR_FINFO_NAME; } } else { return APR_FROM_OS_ERROR(rc); } return (wanted & ~finfo->valid) ? APR_INCOMPLETE : APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_attrs_set(const char *fname, apr_fileattrs_t attributes, apr_fileattrs_t attr_mask, apr_pool_t *cont) { FILESTATUS3 fs3; ULONG rc; /* Don't do anything if we can't handle the requested attributes */ if (!(attr_mask & (APR_FILE_ATTR_READONLY | APR_FILE_ATTR_HIDDEN))) return APR_SUCCESS; rc = DosQueryPathInfo(fname, FIL_STANDARD, &fs3, sizeof(fs3)); if (rc == 0) { ULONG old_attr = fs3.attrFile; if (attr_mask & APR_FILE_ATTR_READONLY) { if (attributes & APR_FILE_ATTR_READONLY) { fs3.attrFile |= FILE_READONLY; } else { fs3.attrFile &= ~FILE_READONLY; } } if (attr_mask & APR_FILE_ATTR_HIDDEN) { if (attributes & APR_FILE_ATTR_HIDDEN) { fs3.attrFile |= FILE_HIDDEN; } else { fs3.attrFile &= ~FILE_HIDDEN; } } if (fs3.attrFile != old_attr) { rc = DosSetPathInfo(fname, FIL_STANDARD, &fs3, sizeof(fs3), 0); } } return APR_FROM_OS_ERROR(rc); } /* ### Somebody please write this! */ APR_DECLARE(apr_status_t) apr_file_mtime_set(const char *fname, apr_time_t mtime, apr_pool_t *pool) { FILESTATUS3 fs3; ULONG rc; rc = DosQueryPathInfo(fname, FIL_STANDARD, &fs3, sizeof(fs3)); if (rc) { return APR_FROM_OS_ERROR(rc); } apr_apr_time_to_os2_time(&fs3.fdateLastWrite, &fs3.ftimeLastWrite, mtime); rc = DosSetPathInfo(fname, FIL_STANDARD, &fs3, sizeof(fs3), 0); return APR_FROM_OS_ERROR(rc); }
001-log4cxx
trunk/src/apr/file_io/os2/filestat.c
C
asf20
7,101
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_file_io.h" #include "apr_lib.h" #include "apr_strings.h" #include <string.h> #define IS_SEP(c) (c == '/' || c == '\\') /* Remove trailing separators that don't affect the meaning of PATH. */ static const char *path_canonicalize(const char *path, apr_pool_t *pool) { /* At some point this could eliminate redundant components. For * now, it just makes sure there is no trailing slash. */ apr_size_t len = strlen(path); apr_size_t orig_len = len; while ((len > 0) && IS_SEP(path[len - 1])) { len--; } if (len != orig_len) { return apr_pstrndup(pool, path, len); } else { return path; } } /* Remove one component off the end of PATH. */ static char *path_remove_last_component(const char *path, apr_pool_t *pool) { const char *newpath = path_canonicalize(path, pool); int i; for (i = strlen(newpath) - 1; i >= 0; i--) { if (IS_SEP(path[i])) { break; } } return apr_pstrndup(pool, path, (i < 0) ? 0 : i); } apr_status_t apr_dir_make_recursive(const char *path, apr_fileperms_t perm, apr_pool_t *pool) { apr_status_t apr_err = APR_SUCCESS; apr_err = apr_dir_make(path, perm, pool); /* Try to make PATH right out */ if (APR_STATUS_IS_EEXIST(apr_err)) { /* It's OK if PATH exists */ return APR_SUCCESS; } if (APR_STATUS_IS_ENOENT(apr_err)) { /* Missing an intermediate dir */ char *dir; dir = path_remove_last_component(path, pool); apr_err = apr_dir_make_recursive(dir, perm, pool); if (!apr_err) { apr_err = apr_dir_make(path, perm, pool); } } return apr_err; }
001-log4cxx
trunk/src/apr/file_io/os2/dir_make_recurse.c
C
asf20
2,531
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../unix/fileacc.c"
001-log4cxx
trunk/src/apr/file_io/os2/fileacc.c
C
asf20
830
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define INCL_DOSERRORS #include "apr_arch_file_io.h" #include "apr_file_io.h" #include <errno.h> #include <string.h> #include "apr_errno.h" static int errormap[][2] = { { NO_ERROR, APR_SUCCESS }, { ERROR_FILE_NOT_FOUND, APR_ENOENT }, { ERROR_PATH_NOT_FOUND, APR_ENOENT }, { ERROR_TOO_MANY_OPEN_FILES, APR_EMFILE }, { ERROR_ACCESS_DENIED, APR_EACCES }, { ERROR_SHARING_VIOLATION, APR_EACCES }, { ERROR_INVALID_PARAMETER, APR_EINVAL }, { ERROR_OPEN_FAILED, APR_ENOENT }, { ERROR_DISK_FULL, APR_ENOSPC }, { ERROR_FILENAME_EXCED_RANGE, APR_ENAMETOOLONG }, { ERROR_INVALID_FUNCTION, APR_EINVAL }, { ERROR_INVALID_HANDLE, APR_EBADF }, { ERROR_NEGATIVE_SEEK, APR_ESPIPE }, { ERROR_NO_SIGNAL_SENT, ESRCH }, { ERROR_NO_DATA, APR_EAGAIN }, { SOCEINTR, EINTR }, { SOCEWOULDBLOCK, EWOULDBLOCK }, { SOCEINPROGRESS, EINPROGRESS }, { SOCEALREADY, EALREADY }, { SOCENOTSOCK, ENOTSOCK }, { SOCEDESTADDRREQ, EDESTADDRREQ }, { SOCEMSGSIZE, EMSGSIZE }, { SOCEPROTOTYPE, EPROTOTYPE }, { SOCENOPROTOOPT, ENOPROTOOPT }, { SOCEPROTONOSUPPORT, EPROTONOSUPPORT }, { SOCESOCKTNOSUPPORT, ESOCKTNOSUPPORT }, { SOCEOPNOTSUPP, EOPNOTSUPP }, { SOCEPFNOSUPPORT, EPFNOSUPPORT }, { SOCEAFNOSUPPORT, EAFNOSUPPORT }, { SOCEADDRINUSE, EADDRINUSE }, { SOCEADDRNOTAVAIL, EADDRNOTAVAIL }, { SOCENETDOWN, ENETDOWN }, { SOCENETUNREACH, ENETUNREACH }, { SOCENETRESET, ENETRESET }, { SOCECONNABORTED, ECONNABORTED }, { SOCECONNRESET, ECONNRESET }, { SOCENOBUFS, ENOBUFS }, { SOCEISCONN, EISCONN }, { SOCENOTCONN, ENOTCONN }, { SOCESHUTDOWN, ESHUTDOWN }, { SOCETOOMANYREFS, ETOOMANYREFS }, { SOCETIMEDOUT, ETIMEDOUT }, { SOCECONNREFUSED, ECONNREFUSED }, { SOCELOOP, ELOOP }, { SOCENAMETOOLONG, ENAMETOOLONG }, { SOCEHOSTDOWN, EHOSTDOWN }, { SOCEHOSTUNREACH, EHOSTUNREACH }, { SOCENOTEMPTY, ENOTEMPTY }, { SOCEPIPE, EPIPE } }; #define MAPSIZE (sizeof(errormap)/sizeof(errormap[0])) int apr_canonical_error(apr_status_t err) { int rv = -1, index; if (err < APR_OS_START_SYSERR) return err; err -= APR_OS_START_SYSERR; for (index=0; index<MAPSIZE && errormap[index][0] != err; index++); if (index<MAPSIZE) rv = errormap[index][1]; else fprintf(stderr, "apr_canonical_error: Unknown OS/2 error code %d\n", err ); return rv; }
001-log4cxx
trunk/src/apr/file_io/os2/maperrorcode.c
C
asf20
3,983
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" #include "apr_file_io.h" #include "apr_lib.h" #include "apr_portable.h" #include "apr_strings.h" #include "apr_arch_inherit.h" #include <string.h> apr_status_t apr_file_cleanup(void *thefile) { apr_file_t *file = thefile; return apr_file_close(file); } APR_DECLARE(apr_status_t) apr_file_open(apr_file_t **new, const char *fname, apr_int32_t flag, apr_fileperms_t perm, apr_pool_t *pool) { int oflags = 0; int mflags = OPEN_FLAGS_FAIL_ON_ERROR|OPEN_SHARE_DENYNONE; int rv; ULONG action; apr_file_t *dafile = (apr_file_t *)apr_palloc(pool, sizeof(apr_file_t)); dafile->pool = pool; dafile->isopen = FALSE; dafile->eof_hit = FALSE; dafile->buffer = NULL; dafile->flags = flag; dafile->blocking = BLK_ON; if ((flag & APR_READ) && (flag & APR_WRITE)) { mflags |= OPEN_ACCESS_READWRITE; } else if (flag & APR_READ) { mflags |= OPEN_ACCESS_READONLY; } else if (flag & APR_WRITE) { mflags |= OPEN_ACCESS_WRITEONLY; } else { dafile->filedes = -1; return APR_EACCES; } dafile->buffered = (flag & APR_BUFFERED) > 0; if (dafile->buffered) { dafile->buffer = apr_palloc(pool, APR_FILE_BUFSIZE); rv = apr_thread_mutex_create(&dafile->mutex, 0, pool); if (rv) return rv; } if (flag & APR_CREATE) { oflags |= OPEN_ACTION_CREATE_IF_NEW; if (!(flag & APR_EXCL) && !(flag & APR_TRUNCATE)) { oflags |= OPEN_ACTION_OPEN_IF_EXISTS; } } if ((flag & APR_EXCL) && !(flag & APR_CREATE)) return APR_EACCES; if (flag & APR_TRUNCATE) { oflags |= OPEN_ACTION_REPLACE_IF_EXISTS; } else if ((oflags & 0xFF) == 0) { oflags |= OPEN_ACTION_OPEN_IF_EXISTS; } rv = DosOpen(fname, &(dafile->filedes), &action, 0, 0, oflags, mflags, NULL); if (rv == 0 && (flag & APR_APPEND)) { ULONG newptr; rv = DosSetFilePtr(dafile->filedes, 0, FILE_END, &newptr ); if (rv) DosClose(dafile->filedes); } if (rv != 0) return APR_FROM_OS_ERROR(rv); dafile->isopen = TRUE; dafile->fname = apr_pstrdup(pool, fname); dafile->filePtr = 0; dafile->bufpos = 0; dafile->dataRead = 0; dafile->direction = 0; dafile->pipe = FALSE; if (!(flag & APR_FILE_NOCLEANUP)) { apr_pool_cleanup_register(dafile->pool, dafile, apr_file_cleanup, apr_file_cleanup); } *new = dafile; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_close(apr_file_t *file) { ULONG rc; apr_status_t status; if (file && file->isopen) { apr_file_flush(file); rc = DosClose(file->filedes); if (rc == 0) { file->isopen = FALSE; status = APR_SUCCESS; if (file->flags & APR_DELONCLOSE) { status = APR_FROM_OS_ERROR(DosDelete(file->fname)); } } else { return APR_FROM_OS_ERROR(rc); } } if (file->buffered) apr_thread_mutex_destroy(file->mutex); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_remove(const char *path, apr_pool_t *pool) { ULONG rc = DosDelete(path); return APR_FROM_OS_ERROR(rc); } APR_DECLARE(apr_status_t) apr_file_rename(const char *from_path, const char *to_path, apr_pool_t *p) { ULONG rc = DosMove(from_path, to_path); if (rc == ERROR_ACCESS_DENIED || rc == ERROR_ALREADY_EXISTS) { rc = DosDelete(to_path); if (rc == 0 || rc == ERROR_FILE_NOT_FOUND) { rc = DosMove(from_path, to_path); } } return APR_FROM_OS_ERROR(rc); } APR_DECLARE(apr_status_t) apr_os_file_get(apr_os_file_t *thefile, apr_file_t *file) { *thefile = file->filedes; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_file_put(apr_file_t **file, apr_os_file_t *thefile, apr_int32_t flags, apr_pool_t *pool) { apr_os_file_t *dafile = thefile; (*file) = apr_palloc(pool, sizeof(apr_file_t)); (*file)->pool = pool; (*file)->filedes = *dafile; (*file)->isopen = TRUE; (*file)->eof_hit = FALSE; (*file)->flags = flags; (*file)->pipe = FALSE; (*file)->buffered = (flags & APR_BUFFERED) > 0; if ((*file)->buffered) { apr_status_t rv; (*file)->buffer = apr_palloc(pool, APR_FILE_BUFSIZE); rv = apr_thread_mutex_create(&(*file)->mutex, 0, pool); if (rv) return rv; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_eof(apr_file_t *fptr) { if (!fptr->isopen || fptr->eof_hit == 1) { return APR_EOF; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_open_stderr(apr_file_t **thefile, apr_pool_t *pool) { apr_os_file_t fd = 2; return apr_os_file_put(thefile, &fd, 0, pool); } APR_DECLARE(apr_status_t) apr_file_open_stdout(apr_file_t **thefile, apr_pool_t *pool) { apr_os_file_t fd = 1; return apr_os_file_put(thefile, &fd, 0, pool); } APR_DECLARE(apr_status_t) apr_file_open_stdin(apr_file_t **thefile, apr_pool_t *pool) { apr_os_file_t fd = 0; return apr_os_file_put(thefile, &fd, 0, pool); } APR_POOL_IMPLEMENT_ACCESSOR(file); APR_IMPLEMENT_INHERIT_SET(file, flags, pool, apr_file_cleanup) APR_IMPLEMENT_INHERIT_UNSET(file, flags, pool, apr_file_cleanup)
001-log4cxx
trunk/src/apr/file_io/os2/open.c
C
asf20
6,257
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define INCL_DOSERRORS #include "apr_arch_file_io.h" #include "apr_file_io.h" #include "apr_general.h" #include "apr_lib.h" #include "apr_strings.h" #include "apr_portable.h" #include <string.h> #include <process.h> APR_DECLARE(apr_status_t) apr_file_pipe_create(apr_file_t **in, apr_file_t **out, apr_pool_t *pool) { ULONG filedes[2]; ULONG rc, action; static int id = 0; char pipename[50]; sprintf(pipename, "/pipe/%d.%d", getpid(), id++); rc = DosCreateNPipe(pipename, filedes, NP_ACCESS_INBOUND, NP_NOWAIT|1, 4096, 4096, 0); if (rc) return APR_FROM_OS_ERROR(rc); rc = DosConnectNPipe(filedes[0]); if (rc && rc != ERROR_PIPE_NOT_CONNECTED) { DosClose(filedes[0]); return APR_FROM_OS_ERROR(rc); } rc = DosOpen (pipename, filedes+1, &action, 0, FILE_NORMAL, OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW, OPEN_ACCESS_WRITEONLY | OPEN_SHARE_DENYREADWRITE, NULL); if (rc) { DosClose(filedes[0]); return APR_FROM_OS_ERROR(rc); } (*in) = (apr_file_t *)apr_palloc(pool, sizeof(apr_file_t)); rc = DosCreateEventSem(NULL, &(*in)->pipeSem, DC_SEM_SHARED, FALSE); if (rc) { DosClose(filedes[0]); DosClose(filedes[1]); return APR_FROM_OS_ERROR(rc); } rc = DosSetNPipeSem(filedes[0], (HSEM)(*in)->pipeSem, 1); if (!rc) { rc = DosSetNPHState(filedes[0], NP_WAIT); } if (rc) { DosClose(filedes[0]); DosClose(filedes[1]); DosCloseEventSem((*in)->pipeSem); return APR_FROM_OS_ERROR(rc); } (*in)->pool = pool; (*in)->filedes = filedes[0]; (*in)->fname = apr_pstrdup(pool, pipename); (*in)->isopen = TRUE; (*in)->buffered = FALSE; (*in)->flags = 0; (*in)->pipe = 1; (*in)->timeout = -1; (*in)->blocking = BLK_ON; apr_pool_cleanup_register(pool, *in, apr_file_cleanup, apr_pool_cleanup_null); (*out) = (apr_file_t *)apr_palloc(pool, sizeof(apr_file_t)); (*out)->pool = pool; (*out)->filedes = filedes[1]; (*out)->fname = apr_pstrdup(pool, pipename); (*out)->isopen = TRUE; (*out)->buffered = FALSE; (*out)->flags = 0; (*out)->pipe = 1; (*out)->timeout = -1; (*out)->blocking = BLK_ON; apr_pool_cleanup_register(pool, *out, apr_file_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_namedpipe_create(const char *filename, apr_fileperms_t perm, apr_pool_t *pool) { /* Not yet implemented, interface not suitable */ return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_file_pipe_timeout_set(apr_file_t *thepipe, apr_interval_time_t timeout) { if (thepipe->pipe == 1) { thepipe->timeout = timeout; if (thepipe->timeout >= 0) { if (thepipe->blocking != BLK_OFF) { thepipe->blocking = BLK_OFF; return APR_FROM_OS_ERROR(DosSetNPHState(thepipe->filedes, NP_NOWAIT)); } } else if (thepipe->timeout == -1) { if (thepipe->blocking != BLK_ON) { thepipe->blocking = BLK_ON; return APR_FROM_OS_ERROR(DosSetNPHState(thepipe->filedes, NP_WAIT)); } } } return APR_EINVAL; } APR_DECLARE(apr_status_t) apr_file_pipe_timeout_get(apr_file_t *thepipe, apr_interval_time_t *timeout) { if (thepipe->pipe == 1) { *timeout = thepipe->timeout; return APR_SUCCESS; } return APR_EINVAL; } APR_DECLARE(apr_status_t) apr_os_pipe_put_ex(apr_file_t **file, apr_os_file_t *thefile, int register_cleanup, apr_pool_t *pool) { (*file) = apr_pcalloc(pool, sizeof(apr_file_t)); (*file)->pool = pool; (*file)->isopen = TRUE; (*file)->pipe = 1; (*file)->blocking = BLK_UNKNOWN; /* app needs to make a timeout call */ (*file)->timeout = -1; (*file)->filedes = *thefile; if (register_cleanup) { apr_pool_cleanup_register(pool, *file, apr_file_cleanup, apr_pool_cleanup_null); } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_pipe_put(apr_file_t **file, apr_os_file_t *thefile, apr_pool_t *pool) { return apr_os_pipe_put_ex(file, thefile, 0, pool); }
001-log4cxx
trunk/src/apr/file_io/os2/pipe.c
C
asf20
5,319
#include "../unix/mktemp.c"
001-log4cxx
trunk/src/apr/file_io/os2/mktemp.c
C
asf20
28
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" #include "apr_file_io.h" #include "apr_lib.h" #include "apr_strings.h" #include "apr_portable.h" #include <string.h> static apr_status_t dir_cleanup(void *thedir) { apr_dir_t *dir = thedir; return apr_dir_close(dir); } APR_DECLARE(apr_status_t) apr_dir_open(apr_dir_t **new, const char *dirname, apr_pool_t *pool) { apr_dir_t *thedir = (apr_dir_t *)apr_palloc(pool, sizeof(apr_dir_t)); if (thedir == NULL) return APR_ENOMEM; thedir->pool = pool; thedir->dirname = apr_pstrdup(pool, dirname); if (thedir->dirname == NULL) return APR_ENOMEM; thedir->handle = 0; thedir->validentry = FALSE; *new = thedir; apr_pool_cleanup_register(pool, thedir, dir_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_dir_close(apr_dir_t *thedir) { int rv = 0; if (thedir->handle) { rv = DosFindClose(thedir->handle); if (rv == 0) { thedir->handle = 0; } } return APR_FROM_OS_ERROR(rv); } APR_DECLARE(apr_status_t) apr_dir_read(apr_finfo_t *finfo, apr_int32_t wanted, apr_dir_t *thedir) { int rv; ULONG entries = 1; if (thedir->handle == 0) { thedir->handle = HDIR_CREATE; rv = DosFindFirst(apr_pstrcat(thedir->pool, thedir->dirname, "/*", NULL), &thedir->handle, FILE_ARCHIVED|FILE_DIRECTORY|FILE_SYSTEM|FILE_HIDDEN|FILE_READONLY, &thedir->entry, sizeof(thedir->entry), &entries, FIL_STANDARD); } else { rv = DosFindNext(thedir->handle, &thedir->entry, sizeof(thedir->entry), &entries); } finfo->pool = thedir->pool; finfo->fname = NULL; finfo->valid = 0; if (rv == 0 && entries == 1) { thedir->validentry = TRUE; /* We passed a name off the stack that has popped */ finfo->fname = NULL; finfo->size = thedir->entry.cbFile; finfo->csize = thedir->entry.cbFileAlloc; /* Only directories & regular files show up in directory listings */ finfo->filetype = (thedir->entry.attrFile & FILE_DIRECTORY) ? APR_DIR : APR_REG; apr_os2_time_to_apr_time(&finfo->mtime, thedir->entry.fdateLastWrite, thedir->entry.ftimeLastWrite); apr_os2_time_to_apr_time(&finfo->atime, thedir->entry.fdateLastAccess, thedir->entry.ftimeLastAccess); apr_os2_time_to_apr_time(&finfo->ctime, thedir->entry.fdateCreation, thedir->entry.ftimeCreation); finfo->name = thedir->entry.achName; finfo->valid = APR_FINFO_NAME | APR_FINFO_MTIME | APR_FINFO_ATIME | APR_FINFO_CTIME | APR_FINFO_TYPE | APR_FINFO_SIZE | APR_FINFO_CSIZE; return APR_SUCCESS; } thedir->validentry = FALSE; if (rv) return APR_FROM_OS_ERROR(rv); return APR_ENOENT; } APR_DECLARE(apr_status_t) apr_dir_rewind(apr_dir_t *thedir) { return apr_dir_close(thedir); } APR_DECLARE(apr_status_t) apr_dir_make(const char *path, apr_fileperms_t perm, apr_pool_t *pool) { return APR_FROM_OS_ERROR(DosCreateDir(path, NULL)); } APR_DECLARE(apr_status_t) apr_dir_remove(const char *path, apr_pool_t *pool) { return APR_FROM_OS_ERROR(DosDeleteDir(path)); } APR_DECLARE(apr_status_t) apr_os_dir_get(apr_os_dir_t **thedir, apr_dir_t *dir) { if (dir == NULL) { return APR_ENODIR; } *thedir = &dir->handle; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_dir_put(apr_dir_t **dir, apr_os_dir_t *thedir, apr_pool_t *pool) { if ((*dir) == NULL) { (*dir) = (apr_dir_t *)apr_pcalloc(pool, sizeof(apr_dir_t)); (*dir)->pool = pool; } (*dir)->handle = *thedir; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/file_io/os2/dir.c
C
asf20
4,739
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define INCL_DOS #define INCL_DOSERRORS #include "apr_arch_file_io.h" #include "apr_file_io.h" #include "apr_lib.h" #include "apr_strings.h" #include <malloc.h> APR_DECLARE(apr_status_t) apr_file_read(apr_file_t *thefile, void *buf, apr_size_t *nbytes) { ULONG rc = 0; ULONG bytesread; if (!thefile->isopen) { *nbytes = 0; return APR_EBADF; } if (thefile->buffered) { char *pos = (char *)buf; ULONG blocksize; ULONG size = *nbytes; apr_thread_mutex_lock(thefile->mutex); if (thefile->direction == 1) { int rv = apr_file_flush(thefile); if (rv != APR_SUCCESS) { apr_thread_mutex_unlock(thefile->mutex); return rv; } thefile->bufpos = 0; thefile->direction = 0; thefile->dataRead = 0; } while (rc == 0 && size > 0) { if (thefile->bufpos >= thefile->dataRead) { ULONG bytesread; rc = DosRead(thefile->filedes, thefile->buffer, APR_FILE_BUFSIZE, &bytesread); if (bytesread == 0) { if (rc == 0) thefile->eof_hit = TRUE; break; } thefile->dataRead = bytesread; thefile->filePtr += thefile->dataRead; thefile->bufpos = 0; } blocksize = size > thefile->dataRead - thefile->bufpos ? thefile->dataRead - thefile->bufpos : size; memcpy(pos, thefile->buffer + thefile->bufpos, blocksize); thefile->bufpos += blocksize; pos += blocksize; size -= blocksize; } *nbytes = rc == 0 ? pos - (char *)buf : 0; apr_thread_mutex_unlock(thefile->mutex); if (*nbytes == 0 && rc == 0 && thefile->eof_hit) { return APR_EOF; } return APR_FROM_OS_ERROR(rc); } else { if (thefile->pipe) DosResetEventSem(thefile->pipeSem, &rc); rc = DosRead(thefile->filedes, buf, *nbytes, &bytesread); if (rc == ERROR_NO_DATA && thefile->timeout != 0) { int rcwait = DosWaitEventSem(thefile->pipeSem, thefile->timeout >= 0 ? thefile->timeout / 1000 : SEM_INDEFINITE_WAIT); if (rcwait == 0) { rc = DosRead(thefile->filedes, buf, *nbytes, &bytesread); } else if (rcwait == ERROR_TIMEOUT) { *nbytes = 0; return APR_TIMEUP; } } if (rc) { *nbytes = 0; return APR_FROM_OS_ERROR(rc); } *nbytes = bytesread; if (bytesread == 0) { thefile->eof_hit = TRUE; return APR_EOF; } return APR_SUCCESS; } } APR_DECLARE(apr_status_t) apr_file_write(apr_file_t *thefile, const void *buf, apr_size_t *nbytes) { ULONG rc = 0; ULONG byteswritten; if (!thefile->isopen) { *nbytes = 0; return APR_EBADF; } if (thefile->buffered) { char *pos = (char *)buf; int blocksize; int size = *nbytes; apr_thread_mutex_lock(thefile->mutex); if ( thefile->direction == 0 ) { // Position file pointer for writing at the offset we are logically reading from ULONG offset = thefile->filePtr - thefile->dataRead + thefile->bufpos; if (offset != thefile->filePtr) DosSetFilePtr(thefile->filedes, offset, FILE_BEGIN, &thefile->filePtr ); thefile->bufpos = thefile->dataRead = 0; thefile->direction = 1; } while (rc == 0 && size > 0) { if (thefile->bufpos == APR_FILE_BUFSIZE) // write buffer is full rc = apr_file_flush(thefile); blocksize = size > APR_FILE_BUFSIZE - thefile->bufpos ? APR_FILE_BUFSIZE - thefile->bufpos : size; memcpy(thefile->buffer + thefile->bufpos, pos, blocksize); thefile->bufpos += blocksize; pos += blocksize; size -= blocksize; } apr_thread_mutex_unlock(thefile->mutex); return APR_FROM_OS_ERROR(rc); } else { if (thefile->flags & APR_APPEND) { FILELOCK all = { 0, 0x7fffffff }; ULONG newpos; rc = DosSetFileLocks(thefile->filedes, NULL, &all, -1, 0); if (rc == 0) { rc = DosSetFilePtr(thefile->filedes, 0, FILE_END, &newpos); if (rc == 0) { rc = DosWrite(thefile->filedes, buf, *nbytes, &byteswritten); } DosSetFileLocks(thefile->filedes, &all, NULL, -1, 0); } } else { rc = DosWrite(thefile->filedes, buf, *nbytes, &byteswritten); } if (rc) { *nbytes = 0; return APR_FROM_OS_ERROR(rc); } *nbytes = byteswritten; return APR_SUCCESS; } } #ifdef HAVE_WRITEV APR_DECLARE(apr_status_t) apr_file_writev(apr_file_t *thefile, const struct iovec *vec, apr_size_t nvec, apr_size_t *nbytes) { int bytes; if ((bytes = writev(thefile->filedes, vec, nvec)) < 0) { *nbytes = 0; return errno; } else { *nbytes = bytes; return APR_SUCCESS; } } #endif APR_DECLARE(apr_status_t) apr_file_putc(char ch, apr_file_t *thefile) { ULONG rc; ULONG byteswritten; if (!thefile->isopen) { return APR_EBADF; } rc = DosWrite(thefile->filedes, &ch, 1, &byteswritten); if (rc) { return APR_FROM_OS_ERROR(rc); } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_ungetc(char ch, apr_file_t *thefile) { apr_off_t offset = -1; return apr_file_seek(thefile, APR_CUR, &offset); } APR_DECLARE(apr_status_t) apr_file_getc(char *ch, apr_file_t *thefile) { ULONG rc; apr_size_t bytesread; if (!thefile->isopen) { return APR_EBADF; } bytesread = 1; rc = apr_file_read(thefile, ch, &bytesread); if (rc) { return rc; } if (bytesread == 0) { thefile->eof_hit = TRUE; return APR_EOF; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_file_puts(const char *str, apr_file_t *thefile) { apr_size_t len; len = strlen(str); return apr_file_write(thefile, str, &len); } APR_DECLARE(apr_status_t) apr_file_flush(apr_file_t *thefile) { if (thefile->buffered) { ULONG written = 0; int rc = 0; if (thefile->direction == 1 && thefile->bufpos) { rc = DosWrite(thefile->filedes, thefile->buffer, thefile->bufpos, &written); thefile->filePtr += written; if (rc == 0) thefile->bufpos = 0; } return APR_FROM_OS_ERROR(rc); } else { /* There isn't anything to do if we aren't buffering the output * so just return success. */ return APR_SUCCESS; } } APR_DECLARE(apr_status_t) apr_file_gets(char *str, int len, apr_file_t *thefile) { apr_size_t readlen; apr_status_t rv = APR_SUCCESS; int i; for (i = 0; i < len-1; i++) { readlen = 1; rv = apr_file_read(thefile, str+i, &readlen); if (rv != APR_SUCCESS) { break; } if (readlen != 1) { rv = APR_EOF; break; } if (str[i] == '\n') { i++; break; } } str[i] = 0; if (i > 0) { /* we stored chars; don't report EOF or any other errors; * the app will find out about that on the next call */ return APR_SUCCESS; } return rv; } APR_DECLARE_NONSTD(int) apr_file_printf(apr_file_t *fptr, const char *format, ...) { int cc; va_list ap; char *buf; int len; buf = malloc(HUGE_STRING_LEN); if (buf == NULL) { return 0; } va_start(ap, format); len = apr_vsnprintf(buf, HUGE_STRING_LEN, format, ap); cc = apr_file_puts(buf, fptr); va_end(ap); free(buf); return (cc == APR_SUCCESS) ? len : -1; } apr_status_t apr_file_check_read(apr_file_t *fd) { int rc; if (!fd->pipe) return APR_SUCCESS; /* Not a pipe, assume no waiting */ rc = DosWaitEventSem(fd->pipeSem, SEM_IMMEDIATE_RETURN); if (rc == ERROR_TIMEOUT) return APR_TIMEUP; return APR_FROM_OS_ERROR(rc); }
001-log4cxx
trunk/src/apr/file_io/os2/readwrite.c
C
asf20
9,385
#include "../unix/filepath_util.c"
001-log4cxx
trunk/src/apr/file_io/os2/filepath_util.c
C
asf20
35
#include "../unix/tempdir.c"
001-log4cxx
trunk/src/apr/file_io/os2/tempdir.c
C
asf20
29
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" APR_DECLARE(apr_status_t) apr_file_lock(apr_file_t *thefile, int type) { FILELOCK lockrange = { 0, 0x7fffffff }; ULONG rc; rc = DosSetFileLocks(thefile->filedes, NULL, &lockrange, (type & APR_FLOCK_NONBLOCK) ? 0 : (ULONG)-1, (type & APR_FLOCK_TYPEMASK) == APR_FLOCK_SHARED); return APR_FROM_OS_ERROR(rc); } APR_DECLARE(apr_status_t) apr_file_unlock(apr_file_t *thefile) { FILELOCK unlockrange = { 0, 0x7fffffff }; ULONG rc; rc = DosSetFileLocks(thefile->filedes, &unlockrange, NULL, 0, 0); return APR_FROM_OS_ERROR(rc); }
001-log4cxx
trunk/src/apr/file_io/os2/flock.c
C
asf20
1,438
#include "../unix/fullrw.c"
001-log4cxx
trunk/src/apr/file_io/os2/fullrw.c
C
asf20
28
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../win32/filepath.c"
001-log4cxx
trunk/src/apr/file_io/os2/filepath.c
C
asf20
830
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_arch_file_io.h" #include "apr_strings.h" #include "apr_lib.h" #include <ctype.h> /* OS/2 Exceptions: * * Note that trailing spaces and trailing periods are never recorded * in the file system. * * Leading spaces and periods are accepted, however. * The * ? < > codes all have wildcard side effects * The " / \ : are exclusively component separator tokens * The system doesn't accept | for any (known) purpose * Oddly, \x7f _is_ acceptable ;) */ const char c_is_fnchar[256] = {/* Reject all ctrl codes... */ 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, /* " * / : < > ? */ 1,1,0,1,1,1,1,1,1,1,0,1,1,1,1,0, 1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0, /* \ */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1, /* | */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1, /* High bit codes are accepted */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }; #define IS_SLASH(c) (c == '/' || c == '\\') apr_status_t filepath_root_test(char *path, apr_pool_t *p) { char drive = apr_toupper(path[0]); if (drive >= 'A' && drive <= 'Z' && path[1] == ':' && IS_SLASH(path[2])) return APR_SUCCESS; return APR_EBADPATH; } apr_status_t filepath_drive_get(char **rootpath, char drive, apr_int32_t flags, apr_pool_t *p) { char path[APR_PATH_MAX]; char *pos; ULONG rc; ULONG bufsize = sizeof(path) - 3; path[0] = drive; path[1] = ':'; path[2] = '/'; rc = DosQueryCurrentDir(apr_toupper(drive) - 'A', path+3, &bufsize); if (rc) { return APR_FROM_OS_ERROR(rc); } if (!(flags & APR_FILEPATH_NATIVE)) { for (pos=path; *pos; pos++) { if (*pos == '\\') *pos = '/'; } } *rootpath = apr_pstrdup(p, path); return APR_SUCCESS; } apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p) { if (root[0] && apr_islower(root[0]) && root[1] == ':') { *rootpath = apr_pstrdup(p, root); (*rootpath)[0] = apr_toupper((*rootpath)[0]); } else { *rootpath = root; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_filepath_get(char **defpath, apr_int32_t flags, apr_pool_t *p) { char path[APR_PATH_MAX]; ULONG drive; ULONG drivemap; ULONG rv, pathlen = sizeof(path) - 3; char *pos; DosQueryCurrentDisk(&drive, &drivemap); path[0] = '@' + drive; strcpy(path+1, ":\\"); rv = DosQueryCurrentDir(drive, path+3, &pathlen); *defpath = apr_pstrdup(p, path); if (!(flags & APR_FILEPATH_NATIVE)) { for (pos=*defpath; *pos; pos++) { if (*pos == '\\') *pos = '/'; } } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_filepath_set(const char *path, apr_pool_t *p) { ULONG rv = 0; if (path[1] == ':') rv = DosSetDefaultDisk(apr_toupper(path[0]) - '@'); if (rv == 0) rv = DosSetCurrentDir(path); return APR_FROM_OS_ERROR(rv); }
001-log4cxx
trunk/src/apr/file_io/os2/filesys.c
C
asf20
4,396
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_file_io.h" #include "apr_arch_networkio.h" #include "apr_poll.h" #include "apr_errno.h" #include "apr_support.h" /* The only case where we don't use wait_for_io_or_timeout is on * pre-BONE BeOS, so this check should be sufficient and simpler */ #if !BEOS_R5 #define USE_WAIT_FOR_IO #endif #ifdef USE_WAIT_FOR_IO #ifdef WAITIO_USES_POLL #ifdef HAVE_POLL_H #include <poll.h> #endif #ifdef HAVE_SYS_POLL_H #include <sys/poll.h> #endif apr_status_t apr_wait_for_io_or_timeout(apr_file_t *f, apr_socket_t *s, int for_read) { struct pollfd pfd; int rc, timeout; timeout = f ? f->timeout / 1000 : s->timeout / 1000; pfd.fd = f ? f->filedes : s->socketdes; pfd.events = for_read ? POLLIN : POLLOUT; do { rc = poll(&pfd, 1, timeout); } while (rc == -1 && errno == EINTR); if (rc == 0) { return APR_TIMEUP; } else if (rc > 0) { return APR_SUCCESS; } else { return errno; } } #else /* !WAITIO_USES_POLL */ apr_status_t apr_wait_for_io_or_timeout(apr_file_t *f, apr_socket_t *s, int for_read) { apr_interval_time_t timeout; apr_pollfd_t pfd; int type = for_read ? APR_POLLIN : APR_POLLOUT; apr_pollset_t *pollset; apr_status_t status; /* TODO - timeout should be less each time through this loop */ if (f) { pfd.desc_type = APR_POLL_FILE; pfd.desc.f = f; pollset = f->pollset; if (pollset == NULL) { status = apr_pollset_create(&(f->pollset), 1, f->pool, 0); if (status != APR_SUCCESS) { return status; } pollset = f->pollset; } timeout = f->timeout; } else { pfd.desc_type = APR_POLL_SOCKET; pfd.desc.s = s; pollset = s->pollset; timeout = s->timeout; } pfd.reqevents = type; /* Remove the object if it was in the pollset, then add in the new * object with the correct reqevents value. Ignore the status result * on the remove, because it might not be in there (yet). */ (void) apr_pollset_remove(pollset, &pfd); /* ### check status code */ (void) apr_pollset_add(pollset, &pfd); do { int numdesc; const apr_pollfd_t *pdesc; status = apr_pollset_poll(pollset, timeout, &numdesc, &pdesc); if (numdesc == 1 && (pdesc[0].rtnevents & type) != 0) { return APR_SUCCESS; } } while (APR_STATUS_IS_EINTR(status)); return status; } #endif /* WAITIO_USES_POLL */ #endif /* USE_WAIT_FOR_IO */
001-log4cxx
trunk/src/apr/support/unix/waitio.c
C
asf20
3,495
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_private.h" #include "apr_strings.h" #include "apr_portable.h" #include "apr_user.h" #include "apr_arch_file_io.h" #if APR_HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifndef _WIN32_WCE /* Internal sid binary to string translation, see MSKB Q131320. * Several user related operations require our SID to access * the registry, but in a string format. All error handling * depends on IsValidSid(), which internally we better test long * before we get here! */ void get_sid_string(char *buf, apr_size_t blen, apr_uid_t id) { PSID_IDENTIFIER_AUTHORITY psia; DWORD nsa; DWORD sa; int slen; /* Determine authority values (these is a big-endian value, * and NT records the value as hex if the value is > 2^32.) */ psia = GetSidIdentifierAuthority(id); nsa = (DWORD)(psia->Value[5]) + ((DWORD)(psia->Value[4]) << 8) + ((DWORD)(psia->Value[3]) << 16) + ((DWORD)(psia->Value[2]) << 24); sa = (DWORD)(psia->Value[1]) + ((DWORD)(psia->Value[0]) << 8); if (sa) { slen = apr_snprintf(buf, blen, "S-%lu-0x%04x%08x", SID_REVISION, sa, nsa); } else { slen = apr_snprintf(buf, blen, "S-%lu-%lu", SID_REVISION, nsa); } /* Now append all the subauthority strings. */ nsa = *GetSidSubAuthorityCount(id); for (sa = 0; sa < nsa; ++sa) { slen += apr_snprintf(buf + slen, blen - slen, "-%lu", *GetSidSubAuthority(id, sa)); } } #endif /* Query the ProfileImagePath from the version-specific branch, where the * regkey uses the user's name on 9x, and user's sid string on NT. */ APR_DECLARE(apr_status_t) apr_uid_homepath_get(char **dirname, const char *username, apr_pool_t *p) { #ifdef _WIN32_WCE *dirname = apr_pstrdup(p, "/My Documents"); return APR_SUCCESS; #else apr_status_t rv; char regkey[MAX_PATH * 2]; char *fixch; DWORD keylen; DWORD type; HKEY key; if (apr_os_level >= APR_WIN_NT) { apr_uid_t uid; apr_gid_t gid; if ((rv = apr_uid_get(&uid, &gid, username, p)) != APR_SUCCESS) return rv; strcpy(regkey, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\" "ProfileList\\"); keylen = (DWORD)strlen(regkey); get_sid_string(regkey + keylen, sizeof(regkey) - keylen, uid); } else { strcpy(regkey, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\" "ProfileList\\"); keylen = (DWORD)strlen(regkey); apr_cpystrn(regkey + keylen, username, sizeof(regkey) - keylen); } if ((rv = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey, 0, KEY_QUERY_VALUE, &key)) != ERROR_SUCCESS) return APR_FROM_OS_ERROR(rv); #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { keylen = sizeof(regkey); rv = RegQueryValueExW(key, L"ProfileImagePath", NULL, &type, (void*)regkey, &keylen); RegCloseKey(key); if (rv != ERROR_SUCCESS) return APR_FROM_OS_ERROR(rv); if (type == REG_SZ) { char retdir[MAX_PATH]; if ((rv = unicode_to_utf8_path(retdir, sizeof(retdir), (apr_wchar_t*)regkey)) != APR_SUCCESS) return rv; *dirname = apr_pstrdup(p, retdir); } else if (type == REG_EXPAND_SZ) { apr_wchar_t path[MAX_PATH]; char retdir[MAX_PATH]; ExpandEnvironmentStringsW((apr_wchar_t*)regkey, path, sizeof(path)); if ((rv = unicode_to_utf8_path(retdir, sizeof(retdir), path)) != APR_SUCCESS) return rv; *dirname = apr_pstrdup(p, retdir); } else return APR_ENOENT; } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { keylen = sizeof(regkey); rv = RegQueryValueEx(key, "ProfileImagePath", NULL, &type, (void*)regkey, &keylen); RegCloseKey(key); if (rv != ERROR_SUCCESS) return APR_FROM_OS_ERROR(rv); if (type == REG_SZ) { *dirname = apr_pstrdup(p, regkey); } else if (type == REG_EXPAND_SZ) { char path[MAX_PATH]; ExpandEnvironmentStrings(regkey, path, sizeof(path)); *dirname = apr_pstrdup(p, path); } else return APR_ENOENT; } #endif /* APR_HAS_ANSI_FS */ for (fixch = *dirname; *fixch; ++fixch) if (*fixch == '\\') *fixch = '/'; return APR_SUCCESS; #endif /* _WIN32_WCE */ } APR_DECLARE(apr_status_t) apr_uid_current(apr_uid_t *uid, apr_gid_t *gid, apr_pool_t *p) { #ifdef _WIN32_WCE return APR_ENOTIMPL; #else HANDLE threadtok; DWORD needed; TOKEN_USER *usr; TOKEN_PRIMARY_GROUP *grp; if(!OpenProcessToken(GetCurrentProcess(), STANDARD_RIGHTS_READ | READ_CONTROL | TOKEN_QUERY, &threadtok)) { return apr_get_os_error(); } *uid = NULL; if (!GetTokenInformation(threadtok, TokenUser, NULL, 0, &needed) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER) && (usr = apr_palloc(p, needed)) && GetTokenInformation(threadtok, TokenUser, usr, needed, &needed)) *uid = usr->User.Sid; else return apr_get_os_error(); if (!GetTokenInformation(threadtok, TokenPrimaryGroup, NULL, 0, &needed) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER) && (grp = apr_palloc(p, needed)) && GetTokenInformation(threadtok, TokenPrimaryGroup, grp, needed, &needed)) *gid = grp->PrimaryGroup; else return apr_get_os_error(); return APR_SUCCESS; #endif } APR_DECLARE(apr_status_t) apr_uid_get(apr_uid_t *uid, apr_gid_t *gid, const char *username, apr_pool_t *p) { #ifdef _WIN32_WCE return APR_ENOTIMPL; #else SID_NAME_USE sidtype; char anydomain[256]; char *domain; DWORD sidlen = 0; DWORD domlen = sizeof(anydomain); DWORD rv; char *pos; if (pos = strchr(username, '/')) { domain = apr_pstrndup(p, username, pos - username); username = pos + 1; } else if (pos = strchr(username, '\\')) { domain = apr_pstrndup(p, username, pos - username); username = pos + 1; } else { domain = NULL; } /* Get nothing on the first pass ... need to size the sid buffer */ rv = LookupAccountName(domain, username, domain, &sidlen, anydomain, &domlen, &sidtype); if (sidlen) { /* Give it back on the second pass */ *uid = apr_palloc(p, sidlen); domlen = sizeof(anydomain); rv = LookupAccountName(domain, username, *uid, &sidlen, anydomain, &domlen, &sidtype); } if (!sidlen || !rv) { return apr_get_os_error(); } /* There doesn't seem to be a simple way to retrieve the primary group sid */ *gid = NULL; return APR_SUCCESS; #endif } APR_DECLARE(apr_status_t) apr_uid_name_get(char **username, apr_uid_t userid, apr_pool_t *p) { #ifdef _WIN32_WCE *username = apr_pstrdup(p, "Administrator"); return APR_SUCCESS; #else SID_NAME_USE type; char name[MAX_PATH], domain[MAX_PATH]; DWORD cbname = sizeof(name), cbdomain = sizeof(domain); if (!userid) return APR_EINVAL; if (!LookupAccountSid(NULL, userid, name, &cbname, domain, &cbdomain, &type)) return apr_get_os_error(); if (type != SidTypeUser && type != SidTypeAlias && type != SidTypeWellKnownGroup) return APR_EINVAL; *username = apr_pstrdup(p, name); return APR_SUCCESS; #endif } APR_DECLARE(apr_status_t) apr_uid_compare(apr_uid_t left, apr_uid_t right) { if (!left || !right) return APR_EINVAL; #ifndef _WIN32_WCE if (!IsValidSid(left) || !IsValidSid(right)) return APR_EINVAL; if (!EqualSid(left, right)) return APR_EMISMATCH; #endif return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/user/win32/userinfo.c
C
asf20
9,183
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_strings.h" #include "apr_portable.h" #include "apr_user.h" #include "apr_private.h" #if APR_HAVE_SYS_TYPES_H #include <sys/types.h> #endif APR_DECLARE(apr_status_t) apr_gid_get(apr_gid_t *gid, const char *groupname, apr_pool_t *p) { #ifdef _WIN32_WCE return APR_ENOTIMPL; #else SID_NAME_USE sidtype; char anydomain[256]; char *domain; DWORD sidlen = 0; DWORD domlen = sizeof(anydomain); DWORD rv; char *pos; if (pos = strchr(groupname, '/')) { domain = apr_pstrndup(p, groupname, pos - groupname); groupname = pos + 1; } else if (pos = strchr(groupname, '\\')) { domain = apr_pstrndup(p, groupname, pos - groupname); groupname = pos + 1; } else { domain = NULL; } /* Get nothing on the first pass ... need to size the sid buffer */ rv = LookupAccountName(domain, groupname, domain, &sidlen, anydomain, &domlen, &sidtype); if (sidlen) { /* Give it back on the second pass */ *gid = apr_palloc(p, sidlen); domlen = sizeof(anydomain); rv = LookupAccountName(domain, groupname, *gid, &sidlen, anydomain, &domlen, &sidtype); } if (!sidlen || !rv) { return apr_get_os_error(); } return APR_SUCCESS; #endif } APR_DECLARE(apr_status_t) apr_gid_name_get(char **groupname, apr_gid_t groupid, apr_pool_t *p) { #ifdef _WIN32_WCE *groupname = apr_pstrdup(p, "Administrators"); #else SID_NAME_USE type; char name[MAX_PATH], domain[MAX_PATH]; DWORD cbname = sizeof(name), cbdomain = sizeof(domain); if (!groupid) return APR_EINVAL; if (!LookupAccountSid(NULL, groupid, name, &cbname, domain, &cbdomain, &type)) return apr_get_os_error(); if (type != SidTypeGroup && type != SidTypeWellKnownGroup && type != SidTypeAlias) return APR_EINVAL; *groupname = apr_pstrdup(p, name); #endif return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_gid_compare(apr_gid_t left, apr_gid_t right) { if (!left || !right) return APR_EINVAL; #ifndef _WIN32_WCE if (!IsValidSid(left) || !IsValidSid(right)) return APR_EINVAL; if (!EqualSid(left, right)) return APR_EMISMATCH; #endif return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/user/win32/groupinfo.c
C
asf20
3,196
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_strings.h" #include "apr_portable.h" #include "apr_user.h" #include "apr_private.h" #ifdef HAVE_PWD_H #include <pwd.h> #endif #if APR_HAVE_SYS_TYPES_H #include <sys/types.h> #endif #if APR_HAVE_UNISTD_H #include <unistd.h> /* for _POSIX_THREAD_SAFE_FUNCTIONS */ #endif #define APR_WANT_MEMFUNC #include "apr_want.h" #define PWBUF_SIZE 512 static apr_status_t getpwnam_safe(const char *username, struct passwd *pw, char pwbuf[PWBUF_SIZE]) { struct passwd *pwptr; #if APR_HAS_THREADS && defined(_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R) apr_status_t rv; /* POSIX defines getpwnam_r() et al to return the error number * rather than set errno, and requires pwptr to be set to NULL if * the entry is not found, imply that "not found" is not an error * condition; some implementations do return 0 with pwptr set to * NULL. */ rv = getpwnam_r(username, pw, pwbuf, PWBUF_SIZE, &pwptr); if (rv) { return rv; } if (pwptr == NULL) { return APR_ENOENT; } #else /* Some platforms (e.g. FreeBSD 4.x) do not set errno on NULL "not * found" return values for the non-threadsafe function either. */ errno = 0; if ((pwptr = getpwnam(username)) != NULL) { memcpy(pw, pwptr, sizeof *pw); } else { return errno ? errno : APR_ENOENT; } #endif return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_uid_homepath_get(char **dirname, const char *username, apr_pool_t *p) { struct passwd pw; char pwbuf[PWBUF_SIZE]; apr_status_t rv; if ((rv = getpwnam_safe(username, &pw, pwbuf)) != APR_SUCCESS) return rv; #ifdef OS2 /* Need to manually add user name for OS/2 */ *dirname = apr_pstrcat(p, pw.pw_dir, pw.pw_name, NULL); #else *dirname = apr_pstrdup(p, pw.pw_dir); #endif return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_uid_current(apr_uid_t *uid, apr_gid_t *gid, apr_pool_t *p) { *uid = getuid(); *gid = getgid(); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_uid_get(apr_uid_t *uid, apr_gid_t *gid, const char *username, apr_pool_t *p) { struct passwd pw; char pwbuf[PWBUF_SIZE]; apr_status_t rv; if ((rv = getpwnam_safe(username, &pw, pwbuf)) != APR_SUCCESS) return rv; *uid = pw.pw_uid; *gid = pw.pw_gid; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_uid_name_get(char **username, apr_uid_t userid, apr_pool_t *p) { struct passwd *pw; #if APR_HAS_THREADS && defined(_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R) struct passwd pwd; char pwbuf[PWBUF_SIZE]; apr_status_t rv; rv = getpwuid_r(userid, &pwd, pwbuf, sizeof(pwbuf), &pw); if (rv) { return rv; } if (pw == NULL) { return APR_ENOENT; } #else errno = 0; if ((pw = getpwuid(userid)) == NULL) { return errno ? errno : APR_ENOENT; } #endif *username = apr_pstrdup(p, pw->pw_name); return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/user/unix/userinfo.c
C
asf20
4,130
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_strings.h" #include "apr_portable.h" #include "apr_user.h" #include "apr_private.h" #ifdef HAVE_GRP_H #include <grp.h> #endif #if APR_HAVE_SYS_TYPES_H #include <sys/types.h> #endif #if APR_HAVE_UNISTD_H #include <unistd.h> /* for _POSIX_THREAD_SAFE_FUNCTIONS */ #endif APR_DECLARE(apr_status_t) apr_gid_name_get(char **groupname, apr_gid_t groupid, apr_pool_t *p) { struct group *gr; #if APR_HAS_THREADS && defined(_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R) struct group grp; char grbuf[512]; apr_status_t rv; /* See comment in getpwnam_safe on error handling. */ rv = getgrgid_r(groupid, &grp, grbuf, sizeof(grbuf), &gr); if (rv) { return rv; } if (gr == NULL) { return APR_ENOENT; } #else errno = 0; if ((gr = getgrgid(groupid)) == NULL) { return errno ? errno : APR_ENOENT; } #endif *groupname = apr_pstrdup(p, gr->gr_name); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_gid_get(apr_gid_t *groupid, const char *groupname, apr_pool_t *p) { struct group *gr; #if APR_HAS_THREADS && defined(_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRNAM_R) struct group grp; char grbuf[512]; apr_status_t rv; /* See comment in getpwnam_safe on error handling. */ rv = getgrnam_r(groupname, &grp, grbuf, sizeof(grbuf), &gr); if (rv) { return rv; } if (gr == NULL) { return APR_ENOENT; } #else errno = 0; if ((gr = getgrnam(groupname)) == NULL) { return errno ? errno : APR_ENOENT; } #endif *groupid = gr->gr_gid; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/user/unix/groupinfo.c
C
asf20
2,519
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_strings.h" #include "apr_portable.h" #include "apr_user.h" #include "apr_private.h" #ifdef HAVE_PWD_H #include <pwd.h> #endif #if APR_HAVE_SYS_TYPES_H #include <sys/types.h> #endif #if APR_HAVE_UNISTD_H #include <unistd.h> /* for _POSIX_THREAD_SAFE_FUNCTIONS */ #endif #define PWBUF_SIZE 512 static apr_status_t getpwnam_safe(const char *username, struct passwd *pw, char pwbuf[PWBUF_SIZE]) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_uid_homepath_get(char **dirname, const char *username, apr_pool_t *p) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_uid_current(apr_uid_t *uid, apr_gid_t *gid, apr_pool_t *p) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_uid_get(apr_uid_t *uid, apr_gid_t *gid, const char *username, apr_pool_t *p) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_uid_name_get(char **username, apr_uid_t userid, apr_pool_t *p) { return APR_ENOTIMPL; }
001-log4cxx
trunk/src/apr/user/netware/userinfo.c
C
asf20
2,078
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_strings.h" #include "apr_portable.h" #include "apr_user.h" #include "apr_private.h" #ifdef HAVE_GRP_H #include <grp.h> #endif #if APR_HAVE_SYS_TYPES_H #include <sys/types.h> #endif #if APR_HAVE_UNISTD_H #include <unistd.h> /* for _POSIX_THREAD_SAFE_FUNCTIONS */ #endif APR_DECLARE(apr_status_t) apr_gid_name_get(char **groupname, apr_gid_t groupid, apr_pool_t *p) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_gid_get(apr_gid_t *groupid, const char *groupname, apr_pool_t *p) { return APR_ENOTIMPL; }
001-log4cxx
trunk/src/apr/user/netware/groupinfo.c
C
asf20
1,418
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* apr_password_get.c: abstraction to provide for obtaining a password from the * command line in whatever way the OS supports. In the best case, it's a * wrapper for the system library's getpass() routine; otherwise, we * use one we define ourselves. */ #include "apr_private.h" #include "apr_strings.h" #include "apr_lib.h" #include "apr_errno.h" #if APR_HAVE_SYS_TYPES_H #include <sys/types.h> #endif #if APR_HAVE_ERRNO_H #include <errno.h> #endif #if APR_HAVE_UNISTD_H #include <unistd.h> #endif #if APR_HAVE_CONIO_H #pragma warning(disable: 4032) #include <conio.h> #pragma warning(default: 4032) #endif #if APR_HAVE_STDLIB_H #include <stdlib.h> #endif #if APR_HAVE_STRING_H #include <string.h> #endif #if APR_HAVE_STRINGS_H #include <strings.h> #endif #if defined(HAVE_TERMIOS_H) && !defined(HAVE_GETPASS) #include <termios.h> #endif #if !APR_CHARSET_EBCDIC #define LF 10 #define CR 13 #else /* APR_CHARSET_EBCDIC */ #define LF '\n' #define CR '\r' #endif /* APR_CHARSET_EBCDIC */ #define MAX_STRING_LEN 256 #define ERR_OVERFLOW 5 #ifndef HAVE_GETPASS /* MPE, Win32, NetWare and BeOS all lack a native getpass() */ #if !defined(HAVE_TERMIOS_H) && !defined(WIN32) && !defined(NETWARE) /* * MPE lacks getpass() and a way to suppress stdin echo. So for now, just * issue the prompt and read the results with echo. (Ugh). */ static char *getpass(const char *prompt) { static char password[MAX_STRING_LEN]; fputs(prompt, stderr); fgets((char *) &password, sizeof(password), stdin); return (char *) &password; } #elif defined (HAVE_TERMIOS_H) #include <stdio.h> static char *getpass(const char *prompt) { struct termios attr; static char password[MAX_STRING_LEN]; int n=0; fputs(prompt, stderr); fflush(stderr); if (tcgetattr(STDIN_FILENO, &attr) != 0) return NULL; attr.c_lflag &= ~(ECHO); if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &attr) != 0) return NULL; while ((password[n] = getchar()) != '\n') { if (n < sizeof(password) - 1 && password[n] >= ' ' && password[n] <= '~') { n++; } else { fprintf(stderr,"\n"); fputs(prompt, stderr); fflush(stderr); n = 0; } } password[n] = '\0'; printf("\n"); if (n > (MAX_STRING_LEN - 1)) { password[MAX_STRING_LEN - 1] = '\0'; } attr.c_lflag |= ECHO; tcsetattr(STDIN_FILENO, TCSANOW, &attr); return (char*) &password; } #else /* * Windows lacks getpass(). So we'll re-implement it here. */ static char *getpass(const char *prompt) { /* WCE lacks console. So the getpass is unsuported * The only way is to use the GUI so the getpass should be implemented * on per-application basis. */ #ifdef _WIN32_WCE return NULL; #else static char password[128]; int n = 0; int ch; fputs(prompt, stderr); while ((ch = _getch()) != '\r') { if (ch == EOF) /* EOF */ { fputs("[EOF]\n", stderr); return NULL; } else if (ch == 0 || ch == 0xE0) { /* FN Keys (0 or E0) are a sentinal for a FN code */ ch = (ch << 4) | _getch(); /* Catch {DELETE}, {<--}, Num{DEL} and Num{<--} */ if ((ch == 0xE53 || ch == 0xE4B || ch == 0x053 || ch == 0x04b) && n) { password[--n] = '\0'; fputs("\b \b", stderr); } else { fputc('\a', stderr); } } else if ((ch == '\b' || ch == 127) && n) /* BS/DEL */ { password[--n] = '\0'; fputs("\b \b", stderr); } else if (ch == 3) /* CTRL+C */ { /* _getch() bypasses Ctrl+C but not Ctrl+Break detection! */ fputs("^C\n", stderr); exit(-1); } else if (ch == 26) /* CTRL+Z */ { fputs("^Z\n", stderr); return NULL; } else if (ch == 27) /* ESC */ { fputc('\n', stderr); fputs(prompt, stderr); n = 0; } else if ((n < sizeof(password) - 1) && !apr_iscntrl(ch)) { password[n++] = ch; fputc('*', stderr); } else { fputc('\a', stderr); } } fputc('\n', stderr); password[n] = '\0'; return password; #endif } #endif /* no getchar or _getch */ #endif /* no getpass */ /* * Use the OS getpass() routine (or our own) to obtain a password from * the input stream. * * Exit values: * 0: Success * 5: Partial success; entered text truncated to the size of the * destination buffer * * Restrictions: Truncation also occurs according to the host system's * getpass() semantics, or at position 255 if our own version is used, * but the caller is *not* made aware of it unless their own buffer is * smaller than our own. */ APR_DECLARE(apr_status_t) apr_password_get(const char *prompt, char *pwbuf, apr_size_t *bufsiz) { #ifdef HAVE_GETPASSPHRASE char *pw_got = getpassphrase(prompt); #else char *pw_got = getpass(prompt); #endif apr_status_t rv = APR_SUCCESS; if (!pw_got) return APR_EINVAL; if (strlen(pw_got) >= *bufsiz) { rv = APR_ENAMETOOLONG; } apr_cpystrn(pwbuf, pw_got, *bufsiz); memset(pw_got, 0, strlen(pw_got)); return rv; }
001-log4cxx
trunk/src/apr/passwd/apr_getpass.c
C
asf20
6,133
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_atomic.h" #include "apr_thread_mutex.h" APR_DECLARE(apr_status_t) apr_atomic_init(apr_pool_t *p) { return APR_SUCCESS; } /* * Remapping function pointer type to accept apr_uint32_t's type-safely * as the arguments for as our apr_atomic_foo32 Functions */ typedef WINBASEAPI apr_uint32_t (WINAPI * apr_atomic_win32_ptr_fn) (apr_uint32_t volatile *); typedef WINBASEAPI apr_uint32_t (WINAPI * apr_atomic_win32_ptr_val_fn) (apr_uint32_t volatile *, apr_uint32_t); typedef WINBASEAPI apr_uint32_t (WINAPI * apr_atomic_win32_ptr_val_val_fn) (apr_uint32_t volatile *, apr_uint32_t, apr_uint32_t); typedef WINBASEAPI void * (WINAPI * apr_atomic_win32_ptr_ptr_ptr_fn) (volatile void **, void *, const void *); APR_DECLARE(apr_uint32_t) apr_atomic_add32(volatile apr_uint32_t *mem, apr_uint32_t val) { #if (defined(_M_IA64) || defined(_M_AMD64)) return InterlockedExchangeAdd(mem, val); #else return ((apr_atomic_win32_ptr_val_fn)InterlockedExchangeAdd)(mem, val); #endif } /* Of course we want the 2's compliment of the unsigned value, val */ #pragma warning(disable: 4146) APR_DECLARE(void) apr_atomic_sub32(volatile apr_uint32_t *mem, apr_uint32_t val) { #if (defined(_M_IA64) || defined(_M_AMD64)) InterlockedExchangeAdd(mem, -val); #else ((apr_atomic_win32_ptr_val_fn)InterlockedExchangeAdd)(mem, -val); #endif } APR_DECLARE(apr_uint32_t) apr_atomic_inc32(volatile apr_uint32_t *mem) { /* we return old value, win32 returns new value :( */ #if (defined(_M_IA64) || defined(_M_AMD64)) && !defined(RC_INVOKED) return InterlockedIncrement(mem) - 1; #else return ((apr_atomic_win32_ptr_fn)InterlockedIncrement)(mem) - 1; #endif } APR_DECLARE(int) apr_atomic_dec32(volatile apr_uint32_t *mem) { #if (defined(_M_IA64) || defined(_M_AMD64)) && !defined(RC_INVOKED) return InterlockedDecrement(mem); #else return ((apr_atomic_win32_ptr_fn)InterlockedDecrement)(mem); #endif } APR_DECLARE(void) apr_atomic_set32(volatile apr_uint32_t *mem, apr_uint32_t val) { #if (defined(_M_IA64) || defined(_M_AMD64)) && !defined(RC_INVOKED) InterlockedExchange(mem, val); #else ((apr_atomic_win32_ptr_val_fn)InterlockedExchange)(mem, val); #endif } APR_DECLARE(apr_uint32_t) apr_atomic_read32(volatile apr_uint32_t *mem) { return *mem; } APR_DECLARE(apr_uint32_t) apr_atomic_cas32(volatile apr_uint32_t *mem, apr_uint32_t with, apr_uint32_t cmp) { #if (defined(_M_IA64) || defined(_M_AMD64)) && !defined(RC_INVOKED) return InterlockedCompareExchange(mem, with, cmp); #else return ((apr_atomic_win32_ptr_val_val_fn)InterlockedCompareExchange)(mem, with, cmp); #endif } APR_DECLARE(void *) apr_atomic_casptr(volatile void **mem, void *with, const void *cmp) { #if (defined(_M_IA64) || defined(_M_AMD64)) && !defined(RC_INVOKED) return InterlockedCompareExchangePointer(mem, with, cmp); #else /* Too many VC6 users have stale win32 API files, stub this */ return ((apr_atomic_win32_ptr_ptr_ptr_fn)InterlockedCompareExchange)(mem, with, cmp); #endif } APR_DECLARE(apr_uint32_t) apr_atomic_xchg32(volatile apr_uint32_t *mem, apr_uint32_t val) { #if (defined(_M_IA64) || defined(_M_AMD64)) && !defined(RC_INVOKED) return InterlockedExchange(mem, val); #else return ((apr_atomic_win32_ptr_val_fn)InterlockedExchange)(mem, val); #endif }
001-log4cxx
trunk/src/apr/atomic/win32/apr_atomic.c
C
asf20
4,208
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_atomic.h" #include "apr_thread_mutex.h" #include "apr_private.h" #include <stdlib.h> #if defined(__GNUC__) && defined(__STRICT_ANSI__) && !defined(USE_GENERIC_ATOMICS) /* force use of generic atomics if building e.g. with -std=c89, which * doesn't allow inline asm */ #define USE_GENERIC_ATOMICS #endif #if (defined(__i386__) || defined(__x86_64__)) \ && defined(__GNUC__) && !defined(USE_GENERIC_ATOMICS) APR_DECLARE(apr_uint32_t) apr_atomic_cas32(volatile apr_uint32_t *mem, apr_uint32_t with, apr_uint32_t cmp) { apr_uint32_t prev; asm volatile ("lock; cmpxchgl %1, %2" : "=a" (prev) : "r" (with), "m" (*(mem)), "0"(cmp) : "memory", "cc"); return prev; } #define APR_OVERRIDE_ATOMIC_CAS32 static apr_uint32_t inline intel_atomic_add32(volatile apr_uint32_t *mem, apr_uint32_t val) { asm volatile ("lock; xaddl %0,%1" : "=r"(val), "=m"(*mem) /* outputs */ : "0"(val), "m"(*mem) /* inputs */ : "memory", "cc"); return val; } APR_DECLARE(apr_uint32_t) apr_atomic_add32(volatile apr_uint32_t *mem, apr_uint32_t val) { return intel_atomic_add32(mem, val); } #define APR_OVERRIDE_ATOMIC_ADD32 APR_DECLARE(void) apr_atomic_sub32(volatile apr_uint32_t *mem, apr_uint32_t val) { asm volatile ("lock; subl %1, %0" : : "m" (*(mem)), "r" (val) : "memory", "cc"); } #define APR_OVERRIDE_ATOMIC_SUB32 APR_DECLARE(int) apr_atomic_dec32(volatile apr_uint32_t *mem) { unsigned char prev; asm volatile ("lock; decl %1;\n\t" "setnz %%al" : "=a" (prev) : "m" (*(mem)) : "memory", "cc"); return prev; } #define APR_OVERRIDE_ATOMIC_DEC32 APR_DECLARE(apr_uint32_t) apr_atomic_inc32(volatile apr_uint32_t *mem) { return intel_atomic_add32(mem, 1); } #define APR_OVERRIDE_ATOMIC_INC32 APR_DECLARE(void) apr_atomic_set32(volatile apr_uint32_t *mem, apr_uint32_t val) { *mem = val; } #define APR_OVERRIDE_ATOMIC_SET32 APR_DECLARE(apr_uint32_t) apr_atomic_xchg32(volatile apr_uint32_t *mem, apr_uint32_t val) { apr_uint32_t prev = val; asm volatile ("lock; xchgl %0, %1" : "=r" (prev) : "m" (*(mem)), "0"(prev) : "memory"); return prev; } #define APR_OVERRIDE_ATOMIC_XCHG32 /*#define apr_atomic_init(pool) APR_SUCCESS*/ #endif /* (__linux__ || __EMX__ || __FreeBSD__) && __i386__ */ #if (defined(__PPC__) || defined(__ppc__)) && defined(__GNUC__) \ && !defined(USE_GENERIC_ATOMICS) APR_DECLARE(apr_uint32_t) apr_atomic_cas32(volatile apr_uint32_t *mem, apr_uint32_t swap, apr_uint32_t cmp) { apr_uint32_t prev; asm volatile ("0:\n\t" /* retry local label */ "lwarx %0,0,%1\n\t" /* load prev and reserve */ "cmpw %0,%3\n\t" /* does it match cmp? */ "bne- 1f\n\t" /* ...no, bail out */ "stwcx. %2,0,%1\n\t" /* ...yes, conditionally store swap */ "bne- 0b\n\t" /* start over if we lost the reservation */ "1:" /* exit local label */ : "=&r"(prev) /* output */ : "b" (mem), "r" (swap), "r"(cmp) /* inputs */ : "memory", "cc"); /* clobbered */ return prev; } #define APR_OVERRIDE_ATOMIC_CAS32 APR_DECLARE(apr_uint32_t) apr_atomic_add32(volatile apr_uint32_t *mem, apr_uint32_t delta) { apr_uint32_t prev, temp; asm volatile ("0:\n\t" /* retry local label */ "lwarx %0,0,%2\n\t" /* load prev and reserve */ "add %1,%0,%3\n\t" /* temp = prev + delta */ "stwcx. %1,0,%2\n\t" /* conditionally store */ "bne- 0b" /* start over if we lost the reservation */ /*XXX find a cleaner way to define the temp * it's not an output */ : "=&r" (prev), "=&r" (temp) /* output, temp */ : "b" (mem), "r" (delta) /* inputs */ : "memory", "cc"); /* clobbered */ return prev; } #define APR_OVERRIDE_ATOMIC_ADD32 #endif /* __PPC__ && __GNUC__ */ #if !defined(APR_OVERRIDE_ATOMIC_INIT) #if APR_HAS_THREADS #define NUM_ATOMIC_HASH 7 /* shift by 2 to get rid of alignment issues */ #define ATOMIC_HASH(x) (unsigned int)(((unsigned long)(x)>>2)%(unsigned int)NUM_ATOMIC_HASH) static apr_thread_mutex_t **hash_mutex; #endif /* APR_HAS_THREADS */ apr_status_t apr_atomic_init(apr_pool_t *p) { #if APR_HAS_THREADS int i; apr_status_t rv; hash_mutex = apr_palloc(p, sizeof(apr_thread_mutex_t*) * NUM_ATOMIC_HASH); for (i = 0; i < NUM_ATOMIC_HASH; i++) { rv = apr_thread_mutex_create(&(hash_mutex[i]), APR_THREAD_MUTEX_DEFAULT, p); if (rv != APR_SUCCESS) { return rv; } } #endif /* APR_HAS_THREADS */ return APR_SUCCESS; } #endif /* !defined(APR_OVERRIDE_ATOMIC_INIT) */ /* abort() if 'x' does not evaluate to APR_SUCCESS. */ #define CHECK(x) do { if ((x) != APR_SUCCESS) abort(); } while (0) #if !defined(APR_OVERRIDE_ATOMIC_ADD32) #if defined(APR_OVERRIDE_ATOMIC_CAS32) apr_uint32_t apr_atomic_add32(volatile apr_uint32_t *mem, apr_uint32_t val) { apr_uint32_t old_value, new_value; do { old_value = *mem; new_value = old_value + val; } while (apr_atomic_cas32(mem, new_value, old_value) != old_value); return old_value; } #else apr_uint32_t apr_atomic_add32(volatile apr_uint32_t *mem, apr_uint32_t val) { apr_uint32_t old_value; #if APR_HAS_THREADS apr_thread_mutex_t *lock = hash_mutex[ATOMIC_HASH(mem)]; CHECK(apr_thread_mutex_lock(lock)); old_value = *mem; *mem += val; CHECK(apr_thread_mutex_unlock(lock)); #else old_value = *mem; *mem += val; #endif /* APR_HAS_THREADS */ return old_value; } #endif /* defined(APR_OVERRIDE_ATOMIC_CAS32) */ #endif /* !defined(APR_OVERRIDE_ATOMIC_ADD32) */ #if !defined(APR_OVERRIDE_ATOMIC_SUB32) #if defined(APR_OVERRIDE_ATOMIC_CAS32) void apr_atomic_sub32(volatile apr_uint32_t *mem, apr_uint32_t val) { apr_uint32_t old_value, new_value; do { old_value = *mem; new_value = old_value - val; } while (apr_atomic_cas32(mem, new_value, old_value) != old_value); } #else void apr_atomic_sub32(volatile apr_uint32_t *mem, apr_uint32_t val) { #if APR_HAS_THREADS apr_thread_mutex_t *lock = hash_mutex[ATOMIC_HASH(mem)]; CHECK(apr_thread_mutex_lock(lock)); *mem -= val; CHECK(apr_thread_mutex_unlock(lock)); #else *mem -= val; #endif /* APR_HAS_THREADS */ } #endif /* defined(APR_OVERRIDE_ATOMIC_CAS32) */ #endif /* !defined(APR_OVERRIDE_ATOMIC_SUB32) */ #if !defined(APR_OVERRIDE_ATOMIC_SET32) void apr_atomic_set32(volatile apr_uint32_t *mem, apr_uint32_t val) { #if APR_HAS_THREADS apr_thread_mutex_t *lock = hash_mutex[ATOMIC_HASH(mem)]; CHECK(apr_thread_mutex_lock(lock)); *mem = val; CHECK(apr_thread_mutex_unlock(lock)); #else *mem = val; #endif /* APR_HAS_THREADS */ } #endif /* !defined(APR_OVERRIDE_ATOMIC_SET32) */ #if !defined(APR_OVERRIDE_ATOMIC_INC32) apr_uint32_t apr_atomic_inc32(volatile apr_uint32_t *mem) { return apr_atomic_add32(mem, 1); } #endif /* !defined(APR_OVERRIDE_ATOMIC_INC32) */ #if !defined(APR_OVERRIDE_ATOMIC_DEC32) #if defined(APR_OVERRIDE_ATOMIC_CAS32) int apr_atomic_dec32(volatile apr_uint32_t *mem) { apr_uint32_t old_value, new_value; do { old_value = *mem; new_value = old_value - 1; } while (apr_atomic_cas32(mem, new_value, old_value) != old_value); return old_value != 1; } #else int apr_atomic_dec32(volatile apr_uint32_t *mem) { #if APR_HAS_THREADS apr_thread_mutex_t *lock = hash_mutex[ATOMIC_HASH(mem)]; apr_uint32_t new; CHECK(apr_thread_mutex_lock(lock)); (*mem)--; new = *mem; CHECK(apr_thread_mutex_unlock(lock)); return new; #else (*mem)--; return *mem; #endif /* APR_HAS_THREADS */ } #endif /* defined(APR_OVERRIDE_ATOMIC_CAS32) */ #endif /* !defined(APR_OVERRIDE_ATOMIC_DEC32) */ #if !defined(APR_OVERRIDE_ATOMIC_CAS32) apr_uint32_t apr_atomic_cas32(volatile apr_uint32_t *mem, apr_uint32_t with, apr_uint32_t cmp) { apr_uint32_t prev; #if APR_HAS_THREADS apr_thread_mutex_t *lock = hash_mutex[ATOMIC_HASH(mem)]; CHECK(apr_thread_mutex_lock(lock)); prev = *mem; if (prev == cmp) { *mem = with; } CHECK(apr_thread_mutex_unlock(lock)); #else prev = *mem; if (prev == cmp) { *mem = with; } #endif /* APR_HAS_THREADS */ return prev; } #endif /* !defined(APR_OVERRIDE_ATOMIC_CAS32) */ #if !defined(APR_OVERRIDE_ATOMIC_XCHG32) #if defined(APR_OVERRIDE_ATOMIC_CAS32) apr_uint32_t apr_atomic_xchg32(volatile apr_uint32_t *mem, apr_uint32_t val) { apr_uint32_t prev; do { prev = *mem; } while (apr_atomic_cas32(mem, val, prev) != prev); return prev; } #else apr_uint32_t apr_atomic_xchg32(volatile apr_uint32_t *mem, apr_uint32_t val) { apr_uint32_t prev; #if APR_HAS_THREADS apr_thread_mutex_t *lock = hash_mutex[ATOMIC_HASH(mem)]; CHECK(apr_thread_mutex_lock(lock)); prev = *mem; *mem = val; CHECK(apr_thread_mutex_unlock(lock)); #else prev = *mem; *mem = val; #endif /* APR_HAS_THREADS */ return prev; } #endif /* defined(APR_OVERRIDE_ATOMIC_CAS32) */ #endif /* !defined(APR_OVERRIDE_ATOMIC_XCHG32) */ #if !defined(APR_OVERRIDE_ATOMIC_CASPTR) void *apr_atomic_casptr(volatile void **mem, void *with, const void *cmp) { void *prev; #if APR_HAS_THREADS apr_thread_mutex_t *lock = hash_mutex[ATOMIC_HASH(mem)]; CHECK(apr_thread_mutex_lock(lock)); prev = *(void **)mem; if (prev == cmp) { *mem = with; } CHECK(apr_thread_mutex_unlock(lock)); #else prev = *(void **)mem; if (prev == cmp) { *mem = with; } #endif /* APR_HAS_THREADS */ return prev; } #endif /* !defined(APR_OVERRIDE_ATOMIC_CASPTR) */ #if !defined(APR_OVERRIDE_ATOMIC_READ32) APR_DECLARE(apr_uint32_t) apr_atomic_read32(volatile apr_uint32_t *mem) { return *mem; } #endif
001-log4cxx
trunk/src/apr/atomic/unix/apr_atomic.c
C
asf20
12,044
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_atomic.h" #include <stdlib.h> apr_status_t apr_atomic_init(apr_pool_t *p) { return APR_SUCCESS; } apr_uint32_t apr_atomic_add32(volatile apr_uint32_t *mem, apr_uint32_t val) { apr_uint32_t old, new_val; old = *mem; /* old is automatically updated on cs failure */ do { new_val = old + val; } while (__cs(&old, (cs_t *)mem, new_val)); return old; } void apr_atomic_sub32(volatile apr_uint32_t *mem, apr_uint32_t val) { apr_uint32_t old, new_val; old = *mem; /* old is automatically updated on cs failure */ do { new_val = old - val; } while (__cs(&old, (cs_t *)mem, new_val)); } apr_uint32_t apr_atomic_inc32(volatile apr_uint32_t *mem) { return apr_atomic_add32(mem, 1); } int apr_atomic_dec32(volatile apr_uint32_t *mem) { apr_uint32_t old, new_val; old = *mem; /* old is automatically updated on cs failure */ do { new_val = old - 1; } while (__cs(&old, (cs_t *)mem, new_val)); return new_val != 0; } apr_uint32_t apr_atomic_read32(volatile apr_uint32_t *mem) { return *mem; } void apr_atomic_set32(volatile apr_uint32_t *mem, apr_uint32_t val) { *mem = val; } apr_uint32_t apr_atomic_cas32(volatile apr_uint32_t *mem, apr_uint32_t swap, apr_uint32_t cmp) { apr_uint32_t old = cmp; __cs(&old, (cs_t *)mem, swap); return old; /* old is automatically updated from mem on cs failure */ } apr_uint32_t apr_atomic_xchg32(volatile apr_uint32_t *mem, apr_uint32_t val) { apr_uint32_t old, new_val; old = *mem; /* old is automatically updated on cs failure */ do { new_val = val; } while (__cs(&old, (cs_t *)mem, new_val)); return old; }
001-log4cxx
trunk/src/apr/atomic/os390/atomic.c
C
asf20
2,571
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_atomic.h" #include <stdlib.h> APR_DECLARE(apr_status_t) apr_atomic_init(apr_pool_t *pool) { return APR_SUCCESS; } APR_DECLARE(apr_uint32_t) apr_atomic_add32(volatile apr_uint32_t *mem, apr_uint32_t val) { return atomic_xchgadd((unsigned long *)mem,(unsigned long)val); } APR_DECLARE(void) apr_atomic_sub32(volatile apr_uint32_t *mem, apr_uint32_t val) { atomic_sub((unsigned long *)mem,(unsigned long)val); } APR_DECLARE(apr_uint32_t) apr_atomic_inc32(volatile apr_uint32_t *mem) { return atomic_xchgadd((unsigned long *)mem, 1); } APR_DECLARE(void) apr_atomic_set32(volatile apr_uint32_t *mem, apr_uint32_t val) { *mem = val; } APR_DECLARE(apr_uint32_t) apr_atomic_read32(volatile apr_uint32_t *mem) { return *mem; } APR_DECLARE(apr_uint32_t) apr_atomic_cas32(volatile apr_uint32_t *mem, apr_uint32_t with,apr_uint32_t cmp) { return atomic_cmpxchg((unsigned long *)mem,(unsigned long)cmp,(unsigned long)with); } APR_DECLARE(apr_uint32_t) apr_atomic_xchg32(volatile apr_uint32_t *mem, apr_uint32_t val) { return atomic_xchg((unsigned long *)mem,(unsigned long)val); } APR_DECLARE(int) apr_atomic_dec32(volatile apr_uint32_t *mem) { return (atomic_xchgadd((unsigned long *)mem, 0xFFFFFFFF) - 1); } APR_DECLARE(void *) apr_atomic_casptr(volatile void **mem, void *with, const void *cmp) { return (void*)atomic_cmpxchg((unsigned long *)mem,(unsigned long)cmp,(unsigned long)with); }
001-log4cxx
trunk/src/apr/atomic/netware/apr_atomic.c
C
asf20
2,263
srcdir=@srcdir@ VPATH=@srcdir@ top_srcdir=@apr_srcdir@ top_blddir=@apr_builddir@ # # APR (Apache Portable Runtime) library Makefile. # CPP = @CPP@ # get substituted into some targets APR_MAJOR_VERSION=@APR_MAJOR_VERSION@ # # Macros for supporting directories # INCDIR=./include OSDIR=$(top_srcdir)/include/arch/@OSDIR@ DEFOSDIR=$(INCDIR)/arch/@DEFAULT_OSDIR@ INCLUDES=-I$(INCDIR) -I$(OSDIR) -I$(DEFOSDIR) -I$(top_srcdir)/include # # Macros for target determination # CLEAN_SUBDIRS= test INSTALL_SUBDIRS=@INSTALL_SUBDIRS@ TARGET_LIB = lib@APR_LIBNAME@.la APR_PCFILE = apr-$(APR_MAJOR_VERSION).pc APR_CONFIG = apr-$(APR_MAJOR_VERSION)-config INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ # # Rules for building specific targets, starting with 'all' for # building the entire package. # TARGETS = $(TARGET_LIB) export_vars.c apr.exp # bring in rules.mk for standard functionality @INCLUDE_RULES@ @INCLUDE_OUTPUTS@ CLEAN_TARGETS = apr-config.out apr.exp exports.c export_vars.c .make.dirs \ build/apr_rules.out DISTCLEAN_TARGETS = config.cache config.log config.status \ include/apr.h include/arch/unix/apr_private.h \ libtool $(APR_CONFIG) build/apr_rules.mk apr.pc \ build/pkg/pkginfo EXTRACLEAN_TARGETS = configure aclocal.m4 include/arch/unix/apr_private.h.in \ build-outputs.mk build/ltcf-c.sh build/ltmain.sh build/libtool.m4 prefix=@prefix@ exec_prefix=@exec_prefix@ bindir=@bindir@ libdir=@libdir@ includedir=@includedir@ installbuilddir=@installbuilddir@ # Create apr-config script suitable for the install tree apr-config.out: $(APR_CONFIG) sed 's,^\(location=\).*$$,\1installed,' < $(APR_CONFIG) > $@ # Create apr_rules.mk suitable for the install tree build/apr_rules.out: build/apr_rules.mk sed 's,^\(apr_build.*=\).*$$,\1$(installbuilddir),' < build/apr_rules.mk > $@ install: $(TARGET_LIB) apr-config.out build/apr_rules.out $(APR_MKDIR) $(DESTDIR)$(libdir) $(DESTDIR)$(bindir) $(DESTDIR)$(installbuilddir) \ $(DESTDIR)$(libdir)/pkgconfig $(DESTDIR)$(includedir) $(INSTALL_DATA) $(top_blddir)/include/apr.h $(DESTDIR)$(includedir) for f in $(top_srcdir)/include/apr_*.h; do \ $(INSTALL_DATA) $${f} $(DESTDIR)$(includedir); \ done $(LIBTOOL) --mode=install $(INSTALL) -m 755 $(TARGET_LIB) $(DESTDIR)$(libdir) $(INSTALL_DATA) apr.exp $(DESTDIR)$(libdir)/apr.exp $(INSTALL_DATA) apr.pc $(DESTDIR)$(libdir)/pkgconfig/$(APR_PCFILE) for f in libtool shlibtool; do \ if test -f $${f}; then $(INSTALL) -m 755 $${f} $(DESTDIR)$(installbuilddir); fi; \ done $(INSTALL) -m 755 $(top_srcdir)/build/mkdir.sh $(DESTDIR)$(installbuilddir) for f in make_exports.awk make_var_export.awk; do \ $(INSTALL_DATA) $(top_srcdir)/build/$${f} $(DESTDIR)$(installbuilddir); \ done $(INSTALL_DATA) build/apr_rules.out $(DESTDIR)$(installbuilddir)/apr_rules.mk $(INSTALL) -m 755 apr-config.out $(DESTDIR)$(bindir)/$(APR_CONFIG) @if [ $(INSTALL_SUBDIRS) != "none" ]; then \ for i in $(INSTALL_SUBDIRS); do \ ( cd $$i ; $(MAKE) DESTDIR=$(DESTDIR) install ); \ done \ fi $(TARGET_LIB): $(OBJECTS) $(LINK) @lib_target@ $(ALL_LIBS) exports.c: $(HEADERS) $(APR_MKEXPORT) $(HEADERS) > $@ export_vars.c: $(HEADERS) $(APR_MKVAREXPORT) $(HEADERS) > $@ apr.exp: exports.c export_vars.c @echo "#! lib@APR_LIBNAME@.so" > $@ @echo "* This file was AUTOGENERATED at build time." >> $@ @echo "* Please do not edit by hand." >> $@ $(CPP) $(ALL_CPPFLAGS) $(ALL_INCLUDES) exports.c | grep "ap_hack_" | sed -e 's/^.*[)]\(.*\);$$/\1/' >> $@ $(CPP) $(ALL_CPPFLAGS) $(ALL_INCLUDES) export_vars.c | sed -e 's/^\#[^!]*//' | sed -e '/^$$/d' >> $@ dox: doxygen $(top_srcdir)/docs/doxygen.conf gcov: @build/run-gcov.sh test: check check: $(TARGET_LIB) (cd test && $(MAKE) check) etags: etags `find . -name '*.[ch]'` # DO NOT REMOVE docs: $(INCDIR)/*.h
001-log4cxx
trunk/src/apr/Makefile.in
Makefile
asf20
3,817
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_dso.h" #include "apr_strings.h" #include "apr_private.h" #include "apr_arch_file_io.h" #include "apr_arch_utf8.h" #if APR_HAS_DSO APR_DECLARE(apr_status_t) apr_os_dso_handle_put(apr_dso_handle_t **aprdso, apr_os_dso_handle_t osdso, apr_pool_t *pool) { *aprdso = apr_pcalloc(pool, sizeof **aprdso); (*aprdso)->handle = osdso; (*aprdso)->cont = pool; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_dso_handle_get(apr_os_dso_handle_t *osdso, apr_dso_handle_t *aprdso) { *osdso = aprdso->handle; return APR_SUCCESS; } static apr_status_t dso_cleanup(void *thedso) { apr_dso_handle_t *dso = thedso; if (dso->handle != NULL && !FreeLibrary(dso->handle)) { return apr_get_os_error(); } dso->handle = NULL; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_dso_load(struct apr_dso_handle_t **res_handle, const char *path, apr_pool_t *ctx) { HINSTANCE os_handle; apr_status_t rv; #ifndef _WIN32_WCE UINT em; #endif #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { apr_wchar_t wpath[APR_PATH_MAX]; if ((rv = utf8_to_unicode_path(wpath, sizeof(wpath) / sizeof(apr_wchar_t), path)) != APR_SUCCESS) { *res_handle = apr_pcalloc(ctx, sizeof(**res_handle)); return ((*res_handle)->load_error = rv); } /* Prevent ugly popups from killing our app */ #ifndef _WIN32_WCE em = SetErrorMode(SEM_FAILCRITICALERRORS); #endif os_handle = LoadLibraryExW(wpath, NULL, 0); if (!os_handle) os_handle = LoadLibraryExW(wpath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); if (!os_handle) rv = apr_get_os_error(); #ifndef _WIN32_WCE SetErrorMode(em); #endif } #endif /* APR_HAS_UNICODE_FS */ #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { char fspec[APR_PATH_MAX], *p = fspec; /* Must convert path from / to \ notation. * Per PR2555, the LoadLibraryEx function is very picky about slashes. * Debugging on NT 4 SP 6a reveals First Chance Exception within NTDLL. * LoadLibrary in the MS PSDK also reveals that it -explicitly- states * that backslashes must be used for the LoadLibrary family of calls. */ apr_cpystrn(fspec, path, sizeof(fspec)); while ((p = strchr(p, '/')) != NULL) *p = '\\'; /* Prevent ugly popups from killing our app */ em = SetErrorMode(SEM_FAILCRITICALERRORS); os_handle = LoadLibraryEx(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); if (!os_handle) os_handle = LoadLibraryEx(path, NULL, 0); if (!os_handle) rv = apr_get_os_error(); else rv = APR_SUCCESS; SetErrorMode(em); } #endif *res_handle = apr_pcalloc(ctx, sizeof(**res_handle)); (*res_handle)->cont = ctx; if (rv) { return ((*res_handle)->load_error = rv); } (*res_handle)->handle = (void*)os_handle; (*res_handle)->load_error = APR_SUCCESS; apr_pool_cleanup_register(ctx, *res_handle, dso_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_dso_unload(struct apr_dso_handle_t *handle) { return apr_pool_cleanup_run(handle->cont, handle, dso_cleanup); } APR_DECLARE(apr_status_t) apr_dso_sym(apr_dso_handle_sym_t *ressym, struct apr_dso_handle_t *handle, const char *symname) { #ifdef _WIN32_WCE apr_size_t symlen = strlen(symname) + 1; apr_size_t wsymlen = 256; apr_wchar_t wsymname[256]; apr_status_t rv; rv = apr_conv_utf8_to_ucs2(wsymname, &wsymlen, symname, &symlen); if (rv != APR_SUCCESS) { return rv; } else if (symlen) { return APR_ENAMETOOLONG; } *ressym = (apr_dso_handle_sym_t)GetProcAddressW(handle->handle, wsymname); #else *ressym = (apr_dso_handle_sym_t)GetProcAddress(handle->handle, symname); #endif if (!*ressym) { return apr_get_os_error(); } return APR_SUCCESS; } APR_DECLARE(const char *) apr_dso_error(apr_dso_handle_t *dso, char *buf, apr_size_t bufsize) { return apr_strerror(dso->load_error, buf, bufsize); } #endif
001-log4cxx
trunk/src/apr/dso/win32/dso.c
C
asf20
5,279
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_dso.h" #include "apr_portable.h" #if APR_HAS_DSO static apr_status_t dso_cleanup(void *thedso) { apr_dso_handle_t *dso = thedso; if (dso->handle > 0 && unload_add_on(dso->handle) < B_NO_ERROR) return APR_EINIT; dso->handle = -1; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_dso_load(apr_dso_handle_t **res_handle, const char *path, apr_pool_t *pool) { image_id newid = -1; *res_handle = apr_pcalloc(pool, sizeof(*res_handle)); if((newid = load_add_on(path)) < B_NO_ERROR) { (*res_handle)->errormsg = strerror(newid); return APR_EDSOOPEN; } (*res_handle)->pool = pool; (*res_handle)->handle = newid; apr_pool_cleanup_register(pool, *res_handle, dso_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_dso_unload(apr_dso_handle_t *handle) { return apr_pool_cleanup_run(handle->pool, handle, dso_cleanup); } APR_DECLARE(apr_status_t) apr_dso_sym(apr_dso_handle_sym_t *ressym, apr_dso_handle_t *handle, const char *symname) { int err; if (symname == NULL) return APR_ESYMNOTFOUND; err = get_image_symbol(handle->handle, symname, B_SYMBOL_TYPE_ANY, ressym); if(err != B_OK) return APR_ESYMNOTFOUND; return APR_SUCCESS; } APR_DECLARE(const char *) apr_dso_error(apr_dso_handle_t *dso, char *buffer, apr_size_t buflen) { strncpy(buffer, strerror(errno), buflen); return buffer; } APR_DECLARE(apr_status_t) apr_os_dso_handle_put(apr_dso_handle_t **aprdso, apr_os_dso_handle_t osdso, apr_pool_t *pool) { *aprdso = apr_pcalloc(pool, sizeof **aprdso); (*aprdso)->handle = osdso; (*aprdso)->pool = pool; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_dso_handle_get(apr_os_dso_handle_t *osdso, apr_dso_handle_t *aprdso) { *osdso = aprdso->handle; return APR_SUCCESS; } #endif
001-log4cxx
trunk/src/apr/dso/beos/dso.c
C
asf20
2,897
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_dso.h" #include "apr_strings.h" #include "apr_portable.h" #if APR_HAS_DSO #if !defined(DSO_USE_DLFCN) && !defined(DSO_USE_SHL) && !defined(DSO_USE_DYLD) #error No DSO implementation specified. #endif #ifdef HAVE_STDDEF_H #include <stddef.h> #endif #if APR_HAVE_STDLIB_H #include <stdlib.h> /* malloc(), free() */ #endif #if APR_HAVE_STRING_H #include <string.h> /* for strerror() on HP-UX */ #endif #if defined(DSO_USE_DYLD) #define DYLD_LIBRARY_HANDLE (void *)-1 #endif APR_DECLARE(apr_status_t) apr_os_dso_handle_put(apr_dso_handle_t **aprdso, apr_os_dso_handle_t osdso, apr_pool_t *pool) { *aprdso = apr_pcalloc(pool, sizeof **aprdso); (*aprdso)->handle = osdso; (*aprdso)->pool = pool; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_dso_handle_get(apr_os_dso_handle_t *osdso, apr_dso_handle_t *aprdso) { *osdso = aprdso->handle; return APR_SUCCESS; } static apr_status_t dso_cleanup(void *thedso) { apr_dso_handle_t *dso = thedso; if (dso->handle == NULL) return APR_SUCCESS; #if defined(DSO_USE_SHL) shl_unload((shl_t)dso->handle); #elif defined(DSO_USE_DYLD) if (dso->handle != DYLD_LIBRARY_HANDLE) { NSUnLinkModule(dso->handle, FALSE); } #elif defined(DSO_USE_DLFCN) if (dlclose(dso->handle) != 0) return APR_EINIT; #endif dso->handle = NULL; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_dso_load(apr_dso_handle_t **res_handle, const char *path, apr_pool_t *pool) { #if defined(DSO_USE_SHL) shl_t os_handle = shl_load(path, BIND_IMMEDIATE, 0L); #elif defined(DSO_USE_DYLD) NSObjectFileImage image; NSModule os_handle = NULL; NSObjectFileImageReturnCode dsoerr; const char* err_msg = NULL; dsoerr = NSCreateObjectFileImageFromFile(path, &image); if (dsoerr == NSObjectFileImageSuccess) { #if defined(NSLINKMODULE_OPTION_RETURN_ON_ERROR) && defined(NSLINKMODULE_OPTION_NONE) os_handle = NSLinkModule(image, path, NSLINKMODULE_OPTION_RETURN_ON_ERROR | NSLINKMODULE_OPTION_NONE); /* If something went wrong, get the errors... */ if (!os_handle) { NSLinkEditErrors errors; int errorNumber; const char *fileName; NSLinkEditError(&errors, &errorNumber, &fileName, &err_msg); } #else os_handle = NSLinkModule(image, path, FALSE); #endif NSDestroyObjectFileImage(image); } else if ((dsoerr == NSObjectFileImageFormat || dsoerr == NSObjectFileImageInappropriateFile) && NSAddLibrary(path) == TRUE) { os_handle = (NSModule)DYLD_LIBRARY_HANDLE; } else { err_msg = "cannot create object file image or add library"; } #elif defined(DSO_USE_DLFCN) #if defined(OSF1) || defined(SEQUENT) || defined(SNI) ||\ (defined(__FreeBSD_version) && (__FreeBSD_version >= 220000)) ||\ defined(__DragonFly__) void *os_handle = dlopen((char *)path, RTLD_NOW | RTLD_GLOBAL); #else int flags = RTLD_NOW | RTLD_GLOBAL; void *os_handle; #ifdef _AIX if (strchr(path + 1, '(') && path[strlen(path) - 1] == ')') { /* This special archive.a(dso.so) syntax is required for * the way libtool likes to build shared libraries on AIX. * dlopen() support for such a library requires that the * RTLD_MEMBER flag be enabled. */ flags |= RTLD_MEMBER; } #endif os_handle = dlopen(path, flags); #endif #endif /* DSO_USE_x */ *res_handle = apr_pcalloc(pool, sizeof(**res_handle)); if(os_handle == NULL) { #if defined(DSO_USE_SHL) (*res_handle)->errormsg = strerror(errno); return APR_EDSOOPEN; #elif defined(DSO_USE_DYLD) (*res_handle)->errormsg = (err_msg) ? err_msg : "link failed"; return APR_EDSOOPEN; #elif defined(DSO_USE_DLFCN) (*res_handle)->errormsg = dlerror(); return APR_EDSOOPEN; #endif } (*res_handle)->handle = (void*)os_handle; (*res_handle)->pool = pool; (*res_handle)->errormsg = NULL; apr_pool_cleanup_register(pool, *res_handle, dso_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_dso_unload(apr_dso_handle_t *handle) { return apr_pool_cleanup_run(handle->pool, handle, dso_cleanup); } APR_DECLARE(apr_status_t) apr_dso_sym(apr_dso_handle_sym_t *ressym, apr_dso_handle_t *handle, const char *symname) { #if defined(DSO_USE_SHL) void *symaddr = NULL; int status; errno = 0; status = shl_findsym((shl_t *)&handle->handle, symname, TYPE_PROCEDURE, &symaddr); if (status == -1 && errno == 0) /* try TYPE_DATA instead */ status = shl_findsym((shl_t *)&handle->handle, symname, TYPE_DATA, &symaddr); if (status == -1) return APR_ESYMNOTFOUND; *ressym = symaddr; return APR_SUCCESS; #elif defined(DSO_USE_DYLD) void *retval = NULL; NSSymbol symbol; char *symname2 = (char*)malloc(sizeof(char)*(strlen(symname)+2)); sprintf(symname2, "_%s", symname); #ifdef NSLINKMODULE_OPTION_PRIVATE if (handle->handle == DYLD_LIBRARY_HANDLE) { symbol = NSLookupAndBindSymbol(symname2); } else { symbol = NSLookupSymbolInModule((NSModule)handle->handle, symname2); } #else symbol = NSLookupAndBindSymbol(symname2); #endif free(symname2); if (symbol == NULL) { handle->errormsg = "undefined symbol"; return APR_ESYMNOTFOUND; } retval = NSAddressOfSymbol(symbol); if (retval == NULL) { handle->errormsg = "cannot resolve symbol"; return APR_ESYMNOTFOUND; } *ressym = retval; return APR_SUCCESS; #elif defined(DSO_USE_DLFCN) #if defined(DLSYM_NEEDS_UNDERSCORE) void *retval; char *symbol = (char*)malloc(sizeof(char)*(strlen(symname)+2)); sprintf(symbol, "_%s", symname); retval = dlsym(handle->handle, symbol); free(symbol); #elif defined(SEQUENT) || defined(SNI) void *retval = dlsym(handle->handle, (char *)symname); #else void *retval = dlsym(handle->handle, symname); #endif /* DLSYM_NEEDS_UNDERSCORE */ if (retval == NULL) { handle->errormsg = dlerror(); return APR_ESYMNOTFOUND; } *ressym = retval; return APR_SUCCESS; #endif /* DSO_USE_x */ } APR_DECLARE(const char *) apr_dso_error(apr_dso_handle_t *dso, char *buffer, apr_size_t buflen) { if (dso->errormsg) { apr_cpystrn(buffer, dso->errormsg, buflen); return dso->errormsg; } return "No Error"; } #endif
001-log4cxx
trunk/src/apr/dso/unix/dso.c
C
asf20
7,676
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_portable.h" #include "apr_strings.h" #include "apr_arch_dso.h" #include <errno.h> #include <string.h> #if APR_HAS_DSO APR_DECLARE(apr_status_t) apr_os_dso_handle_put(apr_dso_handle_t **aprdso, apr_os_dso_handle_t osdso, apr_pool_t *pool) { *aprdso = apr_pcalloc(pool, sizeof **aprdso); (*aprdso)->handle = osdso; (*aprdso)->pool = pool; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_dso_handle_get(apr_os_dso_handle_t *osdso, apr_dso_handle_t *aprdso) { *osdso = aprdso->handle; return APR_SUCCESS; } static apr_status_t dso_cleanup(void *thedso) { apr_dso_handle_t *dso = thedso; int rc; if (dso->handle == 0) return APR_SUCCESS; rc = dllfree(dso->handle); if (rc == 0) { dso->handle = 0; return APR_SUCCESS; } dso->failing_errno = errno; return errno; } APR_DECLARE(apr_status_t) apr_dso_load(apr_dso_handle_t **res_handle, const char *path, apr_pool_t *ctx) { dllhandle *handle; int rc; *res_handle = apr_pcalloc(ctx, sizeof(*res_handle)); (*res_handle)->pool = ctx; if ((handle = dllload(path)) != NULL) { (*res_handle)->handle = handle; apr_pool_cleanup_register(ctx, *res_handle, dso_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } (*res_handle)->failing_errno = errno; return errno; } APR_DECLARE(apr_status_t) apr_dso_unload(apr_dso_handle_t *handle) { return apr_pool_cleanup_run(handle->pool, handle, dso_cleanup); } APR_DECLARE(apr_status_t) apr_dso_sym(apr_dso_handle_sym_t *ressym, apr_dso_handle_t *handle, const char *symname) { void *func_ptr; void *var_ptr; if ((var_ptr = dllqueryvar(handle->handle, symname)) != NULL) { *ressym = var_ptr; return APR_SUCCESS; } if ((func_ptr = (void *)dllqueryfn(handle->handle, symname)) != NULL) { *ressym = func_ptr; return APR_SUCCESS; } handle->failing_errno = errno; return errno; } APR_DECLARE(const char *) apr_dso_error(apr_dso_handle_t *handle, char *buffer, apr_size_t buflen) { apr_cpystrn(buffer, strerror(handle->failing_errno), buflen); return buffer; } #endif
001-log4cxx
trunk/src/apr/dso/os390/dso.c
C
asf20
3,286
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_dso.h" #include "apr_strings.h" #include "apr_portable.h" #include <library.h> #include <unistd.h> APR_DECLARE(apr_status_t) apr_os_dso_handle_put(apr_dso_handle_t **aprdso, apr_os_dso_handle_t osdso, apr_pool_t *pool) { *aprdso = apr_pcalloc(pool, sizeof **aprdso); (*aprdso)->handle = osdso; (*aprdso)->pool = pool; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_dso_handle_get(apr_os_dso_handle_t *osdso, apr_dso_handle_t *aprdso) { *osdso = aprdso->handle; return APR_SUCCESS; } static apr_status_t dso_cleanup(void *thedso) { apr_dso_handle_t *dso = thedso; sym_list *symbol = NULL; void *NLMHandle = getnlmhandle(); if (dso->handle == NULL) return APR_SUCCESS; if (dso->symbols != NULL) { symbol = dso->symbols; while (symbol) { UnImportPublicObject(NLMHandle, symbol->symbol); symbol = symbol->next; } } if (dlclose(dso->handle) != 0) return APR_EINIT; dso->handle = NULL; dso->symbols = NULL; dso->path = NULL; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_dso_load(apr_dso_handle_t **res_handle, const char *path, apr_pool_t *pool) { void *os_handle = NULL; char *fullpath = NULL; apr_status_t rv; if ((rv = apr_filepath_merge(&fullpath, NULL, path, APR_FILEPATH_NATIVE, pool)) != APR_SUCCESS) { return rv; } os_handle = dlopen(fullpath, RTLD_NOW | RTLD_LOCAL); *res_handle = apr_pcalloc(pool, sizeof(**res_handle)); if(os_handle == NULL) { (*res_handle)->errormsg = dlerror(); return APR_EDSOOPEN; } (*res_handle)->handle = (void*)os_handle; (*res_handle)->pool = pool; (*res_handle)->errormsg = NULL; (*res_handle)->symbols = NULL; (*res_handle)->path = apr_pstrdup(pool, fullpath); apr_pool_cleanup_register(pool, *res_handle, dso_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_dso_unload(apr_dso_handle_t *handle) { return apr_pool_cleanup_run(handle->pool, handle, dso_cleanup); } APR_DECLARE(apr_status_t) apr_dso_sym(apr_dso_handle_sym_t *ressym, apr_dso_handle_t *handle, const char *symname) { sym_list *symbol = NULL; void *retval = dlsym(handle->handle, symname); if (retval == NULL) { handle->errormsg = dlerror(); return APR_ESYMNOTFOUND; } symbol = apr_pcalloc(handle->pool, sizeof(sym_list)); symbol->next = handle->symbols; handle->symbols = symbol; symbol->symbol = apr_pstrdup(handle->pool, symname); *ressym = retval; return APR_SUCCESS; } APR_DECLARE(const char *) apr_dso_error(apr_dso_handle_t *dso, char *buffer, apr_size_t buflen) { if (dso->errormsg) { apr_cpystrn(buffer, dso->errormsg, buflen); return dso->errormsg; } return "No Error"; }
001-log4cxx
trunk/src/apr/dso/netware/dso.c
C
asf20
4,026
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * dso.c -- DSO system function emulation for AIX * * This is *only* intended for AIX < 4.3. */ /* * Based on libdl (dlfcn.c/dlfcn.h) which is * Copyright (c) 1992,1993,1995,1996,1997,1988 * Jens-Uwe Mager, Helios Software GmbH, Hannover, Germany. * * Not derived from licensed software. * * Permission is granted to freely use, copy, modify, and redistribute * this software, provided that the author is not construed to be liable * for any results of using the software, alterations are clearly marked * as such, and this notice is not modified. * * Changes marked with `--jwe' were made on April 7 1996 by * John W. Eaton <jwe@bevo.che.wisc.edu> to support g++ * * Bundled, stripped and adjusted on April 1998 as one single source file * for inclusion into the Apache HTTP server by * Ralf S. Engelschall <rse@apache.org> * * Added to APR by David Reid April 2000 */ #include <stdio.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <sys/ldr.h> #include <a.out.h> #include "apr_arch_dso.h" #include "apr_portable.h" #if APR_HAS_DSO #undef FREAD #undef FWRITE #include <ldfcn.h> /* * AIX 4.3 does remove some useful definitions from ldfcn.h. Define * these here to compensate for that lossage. */ #ifndef BEGINNING #define BEGINNING SEEK_SET #endif #ifndef FSEEK #define FSEEK(ldptr,o,p) fseek(IOPTR(ldptr),(p==BEGINNING)?(OFFSET(ldptr) +o):o,p) #endif #ifndef FREAD #define FREAD(p,s,n,ldptr) fread(p,s,n,IOPTR(ldptr)) #endif /* * Mode flags for the dlopen routine. */ #undef RTLD_LAZY #define RTLD_LAZY 1 /* lazy function call binding */ #undef RTLD_NOW #define RTLD_NOW 2 /* immediate function call binding */ #undef RTLD_GLOBAL #define RTLD_GLOBAL 0x100 /* allow symbols to be global */ /* * To be able to initialize, a library may provide a dl_info structure * that contains functions to be called to initialize and terminate. */ struct dl_info { void (*init) (void); void (*fini) (void); }; /* APR functions... * * As the AIX functions have been declared in the header file we just * add the basic "wrappers" here. */ APR_DECLARE(apr_status_t) apr_os_dso_handle_put(apr_dso_handle_t **aprdso, apr_os_dso_handle_t osdso, apr_pool_t *pool) { *aprdso = apr_pcalloc(pool, sizeof **aprdso); (*aprdso)->handle = osdso; (*aprdso)->pool = pool; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_dso_handle_get(apr_os_dso_handle_t *osdso, apr_dso_handle_t *aprdso) { *osdso = aprdso->handle; return APR_SUCCESS; } static apr_status_t dso_cleanup(void *thedso) { apr_dso_handle_t *dso = thedso; if (dso->handle != NULL && dlclose(dso->handle) != 0) return APR_EINIT; dso->handle = NULL; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_dso_load(apr_dso_handle_t **res_handle, const char *path, apr_pool_t *ctx) { void *os_handle = dlopen((char *)path, RTLD_NOW | RTLD_GLOBAL); *res_handle = apr_pcalloc(ctx, sizeof(*res_handle)); if(os_handle == NULL) { (*res_handle)->errormsg = dlerror(); return APR_EDSOOPEN; } (*res_handle)->handle = (void*)os_handle; (*res_handle)->pool = ctx; (*res_handle)->errormsg = NULL; apr_pool_cleanup_register(ctx, *res_handle, dso_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_dso_unload(apr_dso_handle_t *handle) { return apr_pool_cleanup_run(handle->pool, handle, dso_cleanup); } APR_DECLARE(apr_status_t) apr_dso_sym(apr_dso_handle_sym_t *ressym, apr_dso_handle_t *handle, const char *symname) { void *retval = dlsym(handle->handle, symname); if (retval == NULL) { handle->errormsg = dlerror(); return APR_ESYMNOTFOUND; } *ressym = retval; return APR_SUCCESS; } APR_DECLARE(const char *) apr_dso_error(apr_dso_handle_t *dso, char *buffer, apr_size_t buflen) { if (dso->errormsg) { apr_cpystrn(buffer, dso->errormsg, buflen); return dso->errormsg; } return "No Error"; } /* * We simulate dlopen() et al. through a call to load. Because AIX has * no call to find an exported symbol we read the loader section of the * loaded module and build a list of exported symbols and their virtual * address. */ typedef struct { char *name; /* the symbols's name */ void *addr; /* its relocated virtual address */ } Export, *ExportPtr; /* * xlC uses the following structure to list its constructors and * destructors. This is gleaned from the output of munch. */ typedef struct { void (*init) (void); /* call static constructors */ void (*term) (void); /* call static destructors */ } Cdtor, *CdtorPtr; typedef void (*GccCDtorPtr) (void); /* * The void * handle returned from dlopen is actually a ModulePtr. */ typedef struct Module { struct Module *next; char *name; /* module name for refcounting */ int refCnt; /* the number of references */ void *entry; /* entry point from load */ struct dl_info *info; /* optional init/terminate functions */ CdtorPtr cdtors; /* optional C++ constructors */ GccCDtorPtr gcc_ctor; /* g++ constructors --jwe */ GccCDtorPtr gcc_dtor; /* g++ destructors --jwe */ int nExports; /* the number of exports found */ ExportPtr exports; /* the array of exports */ } Module, *ModulePtr; /* * We keep a list of all loaded modules to be able to call the fini * handlers and destructors at atexit() time. */ static ModulePtr modList; /* * The last error from one of the dl* routines is kept in static * variables here. Each error is returned only once to the caller. */ static char errbuf[BUFSIZ]; static int errvalid; /* * The `fixed' gcc header files on AIX 3.2.5 provide a prototype for * strdup(). --jwe */ extern char *strdup(const char *); static void caterr(char *); static int readExports(ModulePtr); static void terminate(void); static void *findMain(void); void *dlopen(const char *path, int mode) { register ModulePtr mp; static void *mainModule; /* * Upon the first call register a terminate handler that will * close all libraries. Also get a reference to the main module * for use with loadbind. */ if (!mainModule) { if ((mainModule = findMain()) == NULL) return NULL; atexit(terminate); } /* * Scan the list of modules if we have the module already loaded. */ for (mp = modList; mp; mp = mp->next) if (strcmp(mp->name, path) == 0) { mp->refCnt++; return mp; } if ((mp = (ModulePtr) calloc(1, sizeof(*mp))) == NULL) { errvalid++; strcpy(errbuf, "calloc: "); strcat(errbuf, strerror(errno)); return NULL; } if ((mp->name = strdup(path)) == NULL) { errvalid++; strcpy(errbuf, "strdup: "); strcat(errbuf, strerror(errno)); free(mp); return NULL; } /* * load should be declared load(const char *...). Thus we * cast the path to a normal char *. Ugly. */ if ((mp->entry = (void *) loadAndInit((char *) path, L_NOAUTODEFER, NULL)) == NULL) { free(mp->name); free(mp); errvalid++; strcpy(errbuf, "dlopen: "); strcat(errbuf, path); strcat(errbuf, ": "); /* * If AIX says the file is not executable, the error * can be further described by querying the loader about * the last error. */ if (errno == ENOEXEC) { char *tmp[BUFSIZ / sizeof(char *)]; if (loadquery(L_GETMESSAGES, tmp, sizeof(tmp)) == -1) strcpy(errbuf, strerror(errno)); else { char **p; for (p = tmp; *p; p++) caterr(*p); } } else strcat(errbuf, strerror(errno)); return NULL; } mp->refCnt = 1; mp->next = modList; modList = mp; if (loadbind(0, mainModule, mp->entry) == -1) { dlclose(mp); errvalid++; strcpy(errbuf, "loadbind: "); strcat(errbuf, strerror(errno)); return NULL; } /* * If the user wants global binding, loadbind against all other * loaded modules. */ if (mode & RTLD_GLOBAL) { register ModulePtr mp1; for (mp1 = mp->next; mp1; mp1 = mp1->next) if (loadbind(0, mp1->entry, mp->entry) == -1) { dlclose(mp); errvalid++; strcpy(errbuf, "loadbind: "); strcat(errbuf, strerror(errno)); return NULL; } } if (readExports(mp) == -1) { dlclose(mp); return NULL; } /* * If there is a dl_info structure, call the init function. */ if (mp->info = (struct dl_info *) dlsym(mp, "dl_info")) { if (mp->info->init) (*mp->info->init) (); } else errvalid = 0; /* * If the shared object was compiled using xlC we will need * to call static constructors (and later on dlclose destructors). */ if (mp->cdtors = (CdtorPtr) dlsym(mp, "__cdtors")) { CdtorPtr cp = mp->cdtors; while (cp->init || cp->term) { if (cp->init && cp->init != (void (*)(void)) 0xffffffff) (*cp->init) (); cp++; } /* * If the shared object was compiled using g++, we will need * to call global constructors using the _GLOBAL__DI function, * and later, global destructors using the _GLOBAL_DD * funciton. --jwe */ } else if (mp->gcc_ctor = (GccCDtorPtr) dlsym(mp, "_GLOBAL__DI")) { (*mp->gcc_ctor) (); mp->gcc_dtor = (GccCDtorPtr) dlsym(mp, "_GLOBAL__DD"); } else errvalid = 0; return mp; } /* * Attempt to decipher an AIX loader error message and append it * to our static error message buffer. */ static void caterr(char *s) { register char *p = s; while (*p >= '0' && *p <= '9') p++; switch (atoi(s)) { case L_ERROR_TOOMANY: strcat(errbuf, "to many errors"); break; case L_ERROR_NOLIB: strcat(errbuf, "can't load library"); strcat(errbuf, p); break; case L_ERROR_UNDEF: strcat(errbuf, "can't find symbol"); strcat(errbuf, p); break; case L_ERROR_RLDBAD: strcat(errbuf, "bad RLD"); strcat(errbuf, p); break; case L_ERROR_FORMAT: strcat(errbuf, "bad exec format in"); strcat(errbuf, p); break; case L_ERROR_ERRNO: strcat(errbuf, strerror(atoi(++p))); break; default: strcat(errbuf, s); break; } } void *dlsym(void *handle, const char *symbol) { register ModulePtr mp = (ModulePtr) handle; register ExportPtr ep; register int i; /* * Could speed up the search, but I assume that one assigns * the result to function pointers anyways. */ for (ep = mp->exports, i = mp->nExports; i; i--, ep++) if (strcmp(ep->name, symbol) == 0) return ep->addr; errvalid++; strcpy(errbuf, "dlsym: undefined symbol "); strcat(errbuf, symbol); return NULL; } const char *dlerror(void) { if (errvalid) { errvalid = 0; return errbuf; } return NULL; } int dlclose(void *handle) { register ModulePtr mp = (ModulePtr) handle; int result; register ModulePtr mp1; if (--mp->refCnt > 0) return 0; if (mp->info && mp->info->fini) (*mp->info->fini) (); if (mp->cdtors) { CdtorPtr cp = mp->cdtors; while (cp->init || cp->term) { if (cp->term && cp->init != (void (*)(void)) 0xffffffff) (*cp->term) (); cp++; } /* * If the function to handle global destructors for g++ * exists, call it. --jwe */ } else if (mp->gcc_dtor) { (*mp->gcc_dtor) (); } result = unload(mp->entry); if (result == -1) { errvalid++; strcpy(errbuf, strerror(errno)); } if (mp->exports) { register ExportPtr ep; register int i; for (ep = mp->exports, i = mp->nExports; i; i--, ep++) if (ep->name) free(ep->name); free(mp->exports); } if (mp == modList) modList = mp->next; else { for (mp1 = modList; mp1; mp1 = mp1->next) if (mp1->next == mp) { mp1->next = mp->next; break; } } free(mp->name); free(mp); return result; } static void terminate(void) { while (modList) dlclose(modList); } /* * Build the export table from the XCOFF .loader section. */ static int readExports(ModulePtr mp) { LDFILE *ldp = NULL; SCNHDR sh, shdata; LDHDR *lhp; char *ldbuf; LDSYM *ls; int i; ExportPtr ep; struct ld_info *lp; char *buf; int size = 4 * 1024; void *dataorg; /* * The module might be loaded due to the LIBPATH * environment variable. Search for the loaded * module using L_GETINFO. */ if ((buf = malloc(size)) == NULL) { errvalid++; strcpy(errbuf, "readExports: "); strcat(errbuf, strerror(errno)); return -1; } while ((i = loadquery(L_GETINFO, buf, size)) == -1 && errno == ENOMEM) { free(buf); size += 4 * 1024; if ((buf = malloc(size)) == NULL) { errvalid++; strcpy(errbuf, "readExports: "); strcat(errbuf, strerror(errno)); return -1; } } if (i == -1) { errvalid++; strcpy(errbuf, "readExports: "); strcat(errbuf, strerror(errno)); free(buf); return -1; } /* * Traverse the list of loaded modules. The entry point * returned by load() does actually point to the TOC * entry contained in the data segment. */ lp = (struct ld_info *) buf; while (lp) { if ((unsigned long) mp->entry >= (unsigned long) lp->ldinfo_dataorg && (unsigned long) mp->entry < (unsigned long) lp->ldinfo_dataorg + lp->ldinfo_datasize) { dataorg = lp->ldinfo_dataorg; ldp = ldopen(lp->ldinfo_filename, ldp); break; } if (lp->ldinfo_next == 0) lp = NULL; else lp = (struct ld_info *) ((char *) lp + lp->ldinfo_next); } free(buf); if (!ldp) { errvalid++; strcpy(errbuf, "readExports: "); strcat(errbuf, strerror(errno)); return -1; } if (TYPE(ldp) != U802TOCMAGIC) { errvalid++; strcpy(errbuf, "readExports: bad magic"); while (ldclose(ldp) == FAILURE); return -1; } /* * Get the padding for the data section. This is needed for * AIX 4.1 compilers. This is used when building the final * function pointer to the exported symbol. */ if (ldnshread(ldp, _DATA, &shdata) != SUCCESS) { errvalid++; strcpy(errbuf, "readExports: cannot read data section header"); while (ldclose(ldp) == FAILURE); return -1; } if (ldnshread(ldp, _LOADER, &sh) != SUCCESS) { errvalid++; strcpy(errbuf, "readExports: cannot read loader section header"); while (ldclose(ldp) == FAILURE); return -1; } /* * We read the complete loader section in one chunk, this makes * finding long symbol names residing in the string table easier. */ if ((ldbuf = (char *) malloc(sh.s_size)) == NULL) { errvalid++; strcpy(errbuf, "readExports: "); strcat(errbuf, strerror(errno)); while (ldclose(ldp) == FAILURE); return -1; } if (FSEEK(ldp, sh.s_scnptr, BEGINNING) != OKFSEEK) { errvalid++; strcpy(errbuf, "readExports: cannot seek to loader section"); free(ldbuf); while (ldclose(ldp) == FAILURE); return -1; } if (FREAD(ldbuf, sh.s_size, 1, ldp) != 1) { errvalid++; strcpy(errbuf, "readExports: cannot read loader section"); free(ldbuf); while (ldclose(ldp) == FAILURE); return -1; } lhp = (LDHDR *) ldbuf; ls = (LDSYM *) (ldbuf + LDHDRSZ); /* * Count the number of exports to include in our export table. */ for (i = lhp->l_nsyms; i; i--, ls++) { if (!LDR_EXPORT(*ls)) continue; mp->nExports++; } if ((mp->exports = (ExportPtr) calloc(mp->nExports, sizeof(*mp->exports))) == NULL) { errvalid++; strcpy(errbuf, "readExports: "); strcat(errbuf, strerror(errno)); free(ldbuf); while (ldclose(ldp) == FAILURE); return -1; } /* * Fill in the export table. All entries are relative to * the beginning of the data origin. */ ep = mp->exports; ls = (LDSYM *) (ldbuf + LDHDRSZ); for (i = lhp->l_nsyms; i; i--, ls++) { char *symname; char tmpsym[SYMNMLEN + 1]; if (!LDR_EXPORT(*ls)) continue; if (ls->l_zeroes == 0) symname = ls->l_offset + lhp->l_stoff + ldbuf; else { /* * The l_name member is not zero terminated, we * must copy the first SYMNMLEN chars and make * sure we have a zero byte at the end. */ strncpy(tmpsym, ls->l_name, SYMNMLEN); tmpsym[SYMNMLEN] = '\0'; symname = tmpsym; } ep->name = strdup(symname); ep->addr = (void *) ((unsigned long) dataorg + ls->l_value - shdata.s_vaddr); ep++; } free(ldbuf); while (ldclose(ldp) == FAILURE); return 0; } /* * Find the main modules data origin. This is used as export pointer * for loadbind() to be able to resolve references to the main part. */ static void *findMain(void) { struct ld_info *lp; char *buf; int size = 4 * 1024; int i; void *ret; if ((buf = malloc(size)) == NULL) { errvalid++; strcpy(errbuf, "findMain: "); strcat(errbuf, strerror(errno)); return NULL; } while ((i = loadquery(L_GETINFO, buf, size)) == -1 && errno == ENOMEM) { free(buf); size += 4 * 1024; if ((buf = malloc(size)) == NULL) { errvalid++; strcpy(errbuf, "findMain: "); strcat(errbuf, strerror(errno)); return NULL; } } if (i == -1) { errvalid++; strcpy(errbuf, "findMain: "); strcat(errbuf, strerror(errno)); free(buf); return NULL; } /* * The first entry is the main module. The data segment * starts with the TOC entries for all exports, so the * data segment origin works as argument for loadbind. */ lp = (struct ld_info *) buf; ret = lp->ldinfo_dataorg; free(buf); return ret; } #endif
001-log4cxx
trunk/src/apr/dso/aix/dso.c
C
asf20
18,482
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_dso.h" #include "apr_strings.h" #include "apr_portable.h" #include <stdio.h> #include <string.h> #if APR_HAS_DSO static apr_status_t dso_cleanup(void *thedso) { apr_dso_handle_t *dso = thedso; int rc; if (dso->handle == 0) return APR_SUCCESS; rc = DosFreeModule(dso->handle); if (rc == 0) dso->handle = 0; return APR_FROM_OS_ERROR(rc); } APR_DECLARE(apr_status_t) apr_dso_load(apr_dso_handle_t **res_handle, const char *path, apr_pool_t *ctx) { char failed_module[200]; HMODULE handle; int rc; *res_handle = apr_pcalloc(ctx, sizeof(**res_handle)); (*res_handle)->cont = ctx; (*res_handle)->load_error = APR_SUCCESS; (*res_handle)->failed_module = NULL; if ((rc = DosLoadModule(failed_module, sizeof(failed_module), path, &handle)) != 0) { (*res_handle)->load_error = APR_FROM_OS_ERROR(rc); (*res_handle)->failed_module = apr_pstrdup(ctx, failed_module); return APR_FROM_OS_ERROR(rc); } (*res_handle)->handle = handle; apr_pool_cleanup_register(ctx, *res_handle, dso_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_dso_unload(apr_dso_handle_t *handle) { return apr_pool_cleanup_run(handle->cont, handle, dso_cleanup); } APR_DECLARE(apr_status_t) apr_dso_sym(apr_dso_handle_sym_t *ressym, apr_dso_handle_t *handle, const char *symname) { PFN func; int rc; if (symname == NULL || ressym == NULL) return APR_ESYMNOTFOUND; if ((rc = DosQueryProcAddr(handle->handle, 0, symname, &func)) != 0) { handle->load_error = APR_FROM_OS_ERROR(rc); return handle->load_error; } *ressym = func; return APR_SUCCESS; } APR_DECLARE(const char *) apr_dso_error(apr_dso_handle_t *dso, char *buffer, apr_size_t buflen) { char message[200]; apr_strerror(dso->load_error, message, sizeof(message)); if (dso->failed_module != NULL) { strcat(message, " ("); strcat(message, dso->failed_module); strcat(message, ")"); } apr_cpystrn(buffer, message, buflen); return buffer; } APR_DECLARE(apr_status_t) apr_os_dso_handle_put(apr_dso_handle_t **aprdso, apr_os_dso_handle_t osdso, apr_pool_t *pool) { *aprdso = apr_pcalloc(pool, sizeof **aprdso); (*aprdso)->handle = osdso; (*aprdso)->cont = pool; (*aprdso)->load_error = APR_SUCCESS; (*aprdso)->failed_module = NULL; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_dso_handle_get(apr_os_dso_handle_t *osdso, apr_dso_handle_t *aprdso) { *osdso = aprdso->handle; return APR_SUCCESS; } #endif
001-log4cxx
trunk/src/apr/dso/os2/dso.c
C
asf20
3,682
<HTML> <HEAD><TITLE>APR Canonical Filenames</TITLE></HEAD> <BODY> <h1>APR Canonical Filename</h1> <h2>Requirements</h2> <p>APR porters need to address the underlying discrepancies between file systems. To achieve a reasonable degree of security, the program depending upon APR needs to know that two paths may be compared, and that a mismatch is guarenteed to reflect that the two paths do not return the same resource</p>. <p>The first discrepancy is in volume roots. Unix and pure deriviates have only one root path, "/". Win32 and OS2 share root paths of the form "D:/", D: is the volume designation. However, this can be specified as "//./D:/" as well, indicating D: volume of the 'this' machine. Win32 and OS2 also may employ a UNC root path, of the form "//server/share/" where share is a share-point of the specified network server. Finally, NetWare root paths are of the form "server/volume:/", or the simpler "volume:/" syntax for 'this' machine. All these non-Unix file systems accept volume:path, without a slash following the colon, as a path relative to the current working directory, which APR will treat as ambigious, that is, neither an absolute nor a relative path per se.</p> <p>The second discrepancy is in the meaning of the 'this' directory. In general, 'this' must be eliminated from the path where it occurs. The syntax "path/./" and "path/" are both aliases to path. However, this isn't file system independent, since the double slash "//" has a special meaning on OS2 and Win32 at the start of the path name, and is invalid on those platforms before the "//server/share/" UNC root path is completed. Finally, as noted above, "//./volume/" is legal root syntax on WinNT, and perhaps others.</p> <p>The third discrepancy is in the context of the 'parent' directory. When "parent/path/.." occurs, the path must be unwound to "parent". It's also critical to simply truncate leading "/../" paths to "/", since the parent of the root is root. This gets tricky on the Win32 and OS2 platforms, since the ".." element is invalid before the "//server/share/" is complete, and the "//server/share/../" seqence is the complete UNC root "//server/share/". In relative paths, leading ".." elements are significant, until they are merged with an absolute path. The relative form must only retain the ".." segments as leading segments, to be resolved once merged to another relative or an absolute path.</p> <p>The fourth discrepancy occurs with acceptance of alternate character codes for the same element. Path seperators are not retained within the APR canonical forms. The OS filesystem and APR (slashed) forms can both be returned as strings, to be used in the proper context. Unix, Win32 and Netware all accept slashes and backslashes as the same path seperator symbol, although unix strictly accepts slashes. While the APR form of the name strictly uses slashes, always consider that there could be a platform that actually accepts slashes as a character within a segment name.</p> <p>The fifth and worst discrepancy plauges Win32, OS2, Netware, and some filesystems mounted in Unix. Case insensitivity can permit the same file to slip through in both it's proper case and alternate cases. Simply changing the case is insufficient for any character set beyond ASCII, since various dilectic forms of characters suffer from one to many or many to one translations. An example would be u-umlaut, which might be accepted as a single character u-umlaut, a two character sequence u and the zero-width umlaut, the upper case form of the same, or perhaps even a captial U alone. This can be handled in different ways depending on the purposes of the APR based program, but the one requirement is that the path must be absolute in order to resolve these ambiguities. Methods employed include comparison of device and inode file uniqifiers, which is a fairly fast operation, or quering the OS for the true form of the name, which can be much slower. Only the acknowledgement of the file names by the OS can validate the equality of two different cases of the same filename.</p> <p>The sixth discrepancy, illegal or insignificant characters, is especially significant in non-unix file systems. Trailing periods are accepted but never stored, therefore trailing periods must be ignored for any form of comparison. And all OS's have certain expectations of what characters are illegal (or undesireable due to confusion.)</p> <p>A final warning, canonical functions don't transform or resolve case or character ambiguity issues until they are resolved into an absolute path. The relative canonical path, while useful, while useful for URL or similar identifiers, cannot be used for testing or comparison of file system objects.</p> <hr> <h2>Canonical API</h2> Functions to manipulate the apr_canon_file_t (an opaque type) include: <ul> <li>Create canon_file_t (from char* path and canon_file_t parent path) <li>Merged canon_file_t (from path and parent, both canon_file_t) <li>Get char* path of all or some segments <li>Get path flags of IsRelative, IsVirtualRoot, and IsAbsolute <li>Compare two canon_file_t structures for file equality </ul> <p>The path is corrected to the file system case only if is in absolute form. The apr_canon_file_t should be preserved as long as possible and used as the parent to create child entries to reduce the number of expensive stat and case canonicalization calls to the OS.</p> <p>The comparison operation provides that the APR can postpone correction of case by simply relying upon the device and inode for equivilance. The stat implementation provides that two files are the same, while their strings are not equivilant, and eliminates the need for the operating system to return the proper form of the name.</p> <p>In any case, returning the char* path, with a flag to request the proper case, forces the OS calls to resolve the true names of each segment. Where there is a penality for this operation and the stat device and inode test is faster, case correction is postponed until the char* result is requested. On platforms that identify the inode, device, or proper name interchangably with no penalities, this may occur when the name is initially processed.</p> <hr> <h2>Unix Example</h2> <p>First the simplest case:</p> <pre> Parse Canonical Name accepts parent path as canonical_t this path as string Split this path Segments on '/' For each of this path Segments If first Segment If this Segment is Empty ([nothing]/) Append this Root Segment (don't merge) Continue to next Segment Else is relative Append parent Segments (to merge) Continue with this Segment If Segment is '.' or empty (2 slashes) Discard this Segment Continue with next Segment If Segment is '..' If no previous Segment or previous Segment is '..' Append this Segment Continue with next Segment If previous Segment and previous is not Root Segment Discard previous Segment Discard this Segment Continue with next Segment Append this Relative Segment Continue with next Segment </pre> </BODY> </HTML>
001-log4cxx
trunk/src/apr/docs/canonical_filenames.html
HTML
asf20
7,174
<HTML> <HEAD><TITLE>APR Design Document</TITLE></HEAD> <BODY> <h1>Design of APR</h1> <p>The Apache Portable Run-time libraries have been designed to provide a common interface to low level routines across any platform. The original goal of APR was to combine all code in Apache to one common code base. This is not the correct approach however, so the goal of APR has changed. There are places where common code is not a good thing. For example, how to map requests to either threads or processes should be platform specific. APR's place is now to combine any code that can be safely combined without sacrificing performance.</p> <p>To this end we have created a set of operations that are required for cross platform development. There may be other types that are desired and those will be implemented in the future.</p> <p>This document will discuss the structure of APR, and how best to contribute code to the effort.</p> <h2>APR On Windows and Netware</h2> <p>APR on Windows and Netware is different from APR on all other systems, because those platforms don't use autoconf. On Unix, apr_private.h (private to APR) and apr.h (public, used by applications that use APR) are generated by autoconf from acconfig.h and apr.h.in respectively. On Windows (and Netware), apr_private.h and apr.h are created from apr_private.hw (apr_private.hwn) and apr.hw (apr.hwn) respectively.</p> <p> <strong> If you add code to acconfig.h or tests to configure.in or aclocal.m4, please give some thought to whether or not Windows and Netware need these additions as well. A general rule of thumb, is that if it is a feature macro, such as APR_HAS_THREADS, Windows and Netware need it. In other words, if the definition is going to be used in a public APR header file, such as apr_general.h, Windows needs it. The only time it is safe to add a macro or test without also adding the macro to apr*.h[n]w, is if the macro tells APR how to build. For example, a test for a header file does not need to be added to Windows. </strong></p> <h2>APR Features</h2> <p>One of the goals of APR is to provide a common set of features across all platforms. This is an admirable goal, it is also not realistic. We cannot expect to be able to implement ALL features on ALL platforms. So we are going to do the next best thing. Provide a common interface to ALL APR features on MOST platforms.</p> <p>APR developers should create FEATURE MACROS for any feature that is not available on ALL platforms. This should be a simple definition which has the form:</p> <code>APR_HAS_FEATURE</code> <p>This macro should evaluate to true if APR has this feature on this platform. For example, Linux and Windows have mmap'ed files, and APR is providing an interface for mmapp'ing a file. On both Linux and Windows, APR_HAS_MMAP should evaluate to one, and the ap_mmap_* functions should map files into memory and return the appropriate status codes.</p> <p>If your OS of choice does not have mmap'ed files, APR_HAS_MMAP should evaluate to zero, and all ap_mmap_* functions should not be defined. The second step is a precaution that will allow us to break at compile time if a programmer tries to use unsupported functions.</p> <h2>APR types</h2> <p>The base types in APR</p> <ul> <li>dso<br> Shared library routines <li>mmap<br> Memory-mapped files <li>poll<br> Polling I/O <li>time<br> Time <li>user<br> Users and groups <li>locks<br> Process and thread locks (critical sections) <li>shmem<br> Shared memory <li>file_io<br> File I/O, including pipes <li>atomic<br> Atomic integer operations <li>strings<br> String handling routines <li>memory<br> Pool-based memory allocation <li>passwd<br> Reading passwords from the terminal <li>tables<br> Tables and hashes <li>network_io<br> Network I/O <li>threadproc<br> Threads and processes <li>misc<br> Any APR type which doesn't have any other place to belong. This should be used sparingly. <li>support<br> Functions meant to be used across multiple APR types. This area is for internal functions only. If a function is exposed, it should not be put here. </ul> <h2>Directory Structure</h2> <p>Each type has a base directory. Inside this base directory, are subdirectories, which contain the actual code. These subdirectories are named after the platforms the are compiled on. Unix is also used as a common directory. If the code you are writing is POSIX based, you should look at the code in the unix directory. A good rule of thumb, is that if more than half your code needs to be ifdef'ed out, and the structures required for your code are substantively different from the POSIX code, you should create a new directory.</p> <p>Currently, the APR code is written for Unix, BeOS, Windows, and OS/2. An example of the directory structure is the file I/O directory:</p> <pre> apr | -> file_io | -> unix The Unix and common base code | -> win32 The Windows code | -> os2 The OS/2 code </pre> <p>Obviously, BeOS does not have a directory. This is because BeOS is currently using the Unix directory for it's file_io.</p> <p>There are a few special top level directories. These are test and include. Test is a directory which stores all test programs. It is expected that if a new type is developed, there will also be a new test program, to help people port this new type to different platforms. A small document describing how to create new tests that integrate with the test suite can be found in the test/ directory. Include is a directory which stores all required APR header files for external use.</p> <h2>Creating an APR Type</h2> <p>The current design of APR requires that most APR types be incomplete. It is not possible to write flexible portable code if programs can access the internals of APR types. This is because different platforms are likely to define different native types. There are only two execptions to this rule:</p> <ul> <li>The first exception to this rule is if the type can only reasonably be implemented one way. For example, time is a complete type because there is only one reasonable time implementation. <li>The second exception to the incomplete type rule can be found in apr_portable.h. This file defines the native types for each platform. Using these types, it is possible to extract native types for any APR type.</p> </ul> <p>For this reason, each platform defines a structure in their own directories. Those structures are then typedef'ed in an external header file. For example in file_io/unix/fileio.h:</p> <pre> struct ap_file_t { apr_pool_t *cntxt; int filedes; FILE *filehand; ... } </pre> <p>In include/apr_file_io.h:</p> </pre> typedef struct ap_file_t ap_file_t; </pre> <p> This will cause a compiler error if somebody tries to access the filedes field in this structure. Windows does not have a filedes field, so obviously, it is important that programs not be able to access these.</p> <p>You may notice the apr_pool_t field. Most APR types have this field. This type is used to allocate memory within APR. Because every APR type has a pool, any APR function can allocate memory if it needs to. This is very important and it is one of the reasons that APR works. If you create a new type, you must add a pool to it. If you do not, then all functions that operate on that type will need a pool argument.</p> <h2>New Function</h2> <p>When creating a new function, please try to adhere to these rules.</p> <ul> <li> Result arguments should be the first arguments. <li> If a function needs a pool, it should be the last argument. <li> These rules are flexible, especially if it makes the code easier to understand because it mimics a standard function. </ul> <h2>Documentation</h2> <p>Whenever a new function is added to APR, it MUST be documented. New functions will not be committed unless there are docs to go along with them. The documentation should be a comment block above the function in the header file.</p> <p>The format for the comment block is:</p> <pre> /** * Brief description of the function * @param parma_1_name explanation * @param parma_2_name explanation * @param parma_n_name explanation * @tip Any extra information people should know. * @deffunc function prototype if required */ </pre> <p>For an actual example, look at any file in the include directory. The reason the docs are in the header files is to ensure that the docs always reflect the current code. If you change paramters or return values for a function, please be sure to update the documentation.</p> <h2>APR Error reporting</h2> <p>Most APR functions should return an ap_status_t type. The only time an APR function does not return an ap_status_t is if it absolutely CAN NOT fail. Examples of this would be filling out an array when you know you are not beyond the array's range. If it cannot fail on your platform, but it could conceivably fail on another platform, it should return an ap_status_t. Unless you are sure, return an ap_status_t.</p> <strong> This includes functions that return TRUE/FALSE values. How that is handled is discussed below </strong> <p>All platforms return errno values unchanged. Each platform can also have one system error type, which can be returned after an offset is added. There are five types of error values in APR, each with it's own offset.</p> <!-- This should be turned into a table, but I am lazy today --> <pre> Name Purpose 0) This is 0 for all platforms and isn't really defined anywhere, but it is the offset for errno values. (This has no name because it isn't actually defined, but for completeness we are discussing it here). 1) APR_OS_START_ERROR This is platform dependent, and is the offset at which APR errors start to be defined. Error values are defined as anything which caused the APR function to fail. APR errors in this range should be named APR_E* (i.e. APR_ENOSOCKET) 2) APR_OS_START_STATUS This is platform dependent, and is the offset at which APR status values start. Status values do not indicate success or failure, and should be returned if APR_SUCCESS does not make sense. APR status codes in this range should be name APR_* (i.e. APR_DETACH) 4) APR_OS_START_USEERR This is platform dependent, and is the offset at which APR apps can begin to add their own error codes. 3) APR_OS_START_SYSERR This is platform dependent, and is the offset at which system error values begin. </pre> <strong>The difference in naming between APR_OS_START_ERROR and APR_OS_START_STATUS mentioned above allows programmers to easily determine if the error code indicates an error condition or a status codition.</strong> <p>If your function has multiple return codes that all indicate success, but with different results, or if your function can only return PASS/FAIL, you should still return an apr_status_t. In the first case, define one APR status code for each return value, an example of this is <code>apr_proc_wait</code>, which can only return APR_CHILDDONE, APR_CHILDNOTDONE, or an error code. In the second case, please return APR_SUCCESS for PASS, and define a new APR status code for failure, an example of this is <code>apr_compare_users</code>, which can only return APR_SUCCESS, APR_EMISMATCH, or an error code.</p> <p>All of these definitions can be found in apr_errno.h for all platforms. When an error occurs in an APR function, the function must return an error code. If the error occurred in a system call and that system call uses errno to report an error, then the code is returned unchanged. For example: </p> <pre> if (open(fname, oflags, 0777) < 0) return errno; </pre> <p>The next place an error can occur is a system call that uses some error value other than the primary error value on a platform. This can also be handled by APR applications. For example:</p> <pre> if (CreateFile(fname, oflags, sharemod, NULL, createflags, attributes, 0) == INVALID_HANDLE_VALUE return (GetLAstError() + APR_OS_START_SYSERR); </pre> <p>These two examples implement the same function for two different platforms. Obviously even if the underlying problem is the same on both platforms, this will result in two different error codes being returned. This is OKAY, and is correct for APR. APR relies on the fact that most of the time an error occurs, the program logs the error and continues, it does not try to programatically solve the problem. This does not mean we have not provided support for programmatically solving the problem, it just isn't the default case. We'll get to how this problem is solved in a little while.</p> <p>If the error occurs in an APR function but it is not due to a system call, but it is actually an APR error or just a status code from APR, then the appropriate code should be returned. These codes are defined in apr_errno.h and should be self explanatory.</p> <p>No APR code should ever return a code between APR_OS_START_USEERR and APR_OS_START_SYSERR, those codes are reserved for APR applications.</p> <p>To programmatically correct an error in a running application, the error codes need to be consistent across platforms. This should make sense. APR has provided macros to test for status code equivalency. For example, to determine if the code that you received from the APR function means EOF, you would use the macro APR_STATUS_IS_EOF().</p> <p>Why did APR take this approach? There are two ways to deal with error codes portably.</p> <ol type=1> <li> Return the same error code across all platforms. <li> Return platform specific error codes and convert them when necessary. </ol> <p>The problem with option number one is that it takes time to convert error codes to a common code, and most of the time programs want to just output an error string. If we convert all errors to a common subset, we have four steps to output an error string:</p> <p>The seocnd problem with option 1, is that it is a lossy conversion. For example, Windows and OS/2 have a couple hundred error codes, but POSIX errno only defines about 50 errno values. This means that if we convert to a canonical error value immediately, there is no way for the programmer to get the actual system error.</p> <pre> make syscall that fails convert to common error code step 1 return common error code check for success call error output function step 2 convert back to system error step 3 output error string step 4 </pre> <p>By keeping the errors platform specific, we can output error strings in two steps.</p> <pre> make syscall that fails return error code check for success call error output function step 1 output error string step 2 </pre> <p>Less often, programs change their execution based on what error was returned. This is no more expensive using option 2 than it is using option 1, but we put the onus of converting the error code on the programmer themselves. For example, using option 1:</p> <pre> make syscall that fails convert to common error code return common error code decide execution based on common error code </pre> <p>Using option 2:</p> <pre> make syscall that fails return error code convert to common error code (using ap_canonical_error) decide execution based on common error code </pre> <p>Finally, there is one more operation on error codes. You can get a string that explains in human readable form what has happened. To do this using APR, call ap_strerror().</p>
001-log4cxx
trunk/src/apr/docs/APRDesign.html
HTML
asf20
16,092
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head> <title>Using APR Pools</title> </head> <body> <div align="right"> Last modified at [$Date: 2004-11-24 16:51:51 -0600 (Wed, 24 Nov 2004) $] </div> <h1>Using APR Pools</h1> <p> From <a href="http://subversion.tigris.org/">Subversion</a>, we have learned a <em>lot</em> about how to use pools in a heavily structured/object-based environment. <a href="http://httpd.apache.org/">Apache httpd</a> is a completely different beast: "allocate a request pool. use it. destroy it." </p> <p> In a complex app, that request-style of behavior is not present. Luckily, the "proper" use of pools can be described in just a few rules: </p> <ul> <li> Objects should not have their own pools. An object is allocated into a pool defined by the constructor's caller. The <strong>caller</strong> knows the lifetime of the object and will manage it via the pool. Generally, this also means that objects will not have a "close" or a "free" since those operations will happen implicitly as part of the destruction of the pool the objects live within. </li> <li> <p> Functions should not create/destroy pools for their operation; they should use a pool provided by the caller. Again, the <strong>caller</strong> knows more about how the function will be used, how often, how many times, etc. Thus, it should be in charge of the function's memory usage. </p> <p> As an example, the caller might know that the app will exit upon the function's return. Thus, the function would be creating extra work if it built and destroyed a pool. Instead, it should use the passed-in pool, which the caller is going to be tossing as part of app-exit anyways. </p> </li> <li> <p> Whenever an unbounded iteration occurs, a subpool should be used. The general pattern is: </p> <blockquote> <pre> subpool = apr_create_subpool(pool); for (i = 0; i < n; ++i) { apr_pool_clear(subpool); do_operation(..., subpool); } apr_pool_destroy(subpool);</pre> </blockquote> <p> This pattern prevents the 'pool' from growing unbounded and consuming all of memory. Note that it is slightly more optimal to clear the pool on loop-entry. This pattern also allows for a '<tt>continue</tt>' to occur within the loop, yet still ensure the pool will be cleared. </p> </li> <li> Given all of the above, it is pretty well mandatory to pass a pool to <em>every</em> function. Since objects are not recording pools for themselves, and the caller is always supposed to be managing memory, then each function needs a pool, rather than relying on some hidden magic pool. In limited cases, objects may record the pool used for their construction so that they can construct sub-parts, but these cases should be examined carefully. Internal pools can lead to unbounded pool usage if the object is not careful. </li> </ul> <hr> <address>Greg Stein</address> <!-- Created: Wed Jun 25 14:39:57 PDT 2003 --> <!-- hhmts start --> Last modified: Wed Jun 25 14:50:19 PDT 2003 <!-- hhmts end --> </body></html>
001-log4cxx
trunk/src/apr/docs/pool-design.html
HTML
asf20
3,585
<HTML> <HEAD><TITLE>APR Win32 Builds and Debugging</TITLE></HEAD> <BODY> <h1>APR Win32 Builds and Debugging</h1> <h2>Configuration and Flavors</h2> <p>The Win32 APR Developer Studio projects consist of</p> <dl> <dt>apr/apr.dsp</dt> <dd>Builds the static apr.lib library (-D APR_DECLARE_STATIC)</dd> <dt>apr/libapr.dsp</dt> <dd>Builds the dynamic libapr.dll library (no define required)</dd> <dt>apr-util/aprutil.dsp</dt> <dd>Builds the static aprutil.lib library (-D APU_DECLARE_STATIC)</dd> <dt>apr-util/libaprutil.dsp</dt> <dd>Builds the dynamic libaprutil.dll library (no define required)</dd> <dt>apr-iconv/apriconv.dsp</dt> <dd>Builds the static apriconv.lib library (-D API_DECLARE_STATIC)</dd> <dt>apr-iconv/libapriconv.dsp</dt> <dd>Builds the dynamic libapriconv.dll library (no define required)</dd> </dl> <p>In order to prepare to use one of the <em>static</em> libraries above, your application must be compiled with the define shown above, so that the correct linkage is created. The APR authors intended the use of dynamic libraries by default, so application authors do not need any special defines in order to link to the dynamic library flavors.</p> <p>In order to build APR, you must use the proper dependencies. A good example of those dependencies is given in the apr-util/aprutil.dsw Developer Studio workspace. You can borrow the parts of that structure your application needs, that workspace defines both the dynamic and static library dependencies.</p> <p>The APR libraries (dynamic and static) are compiled with debugging symbols, even in Release builds. The dynamic library symbols are always usable, simply keep the correspond .pdb file in the same path as the library .dll. (E.g. both libapr.dll and libapr.pdb should be copied to the same path.)</p> <p>The static symbols will only be fully usable if your application does <em>not<em> link with the /pdbtype:sept flag! At the time your application links to an APR library, the corresponding _src.pdb file should exist in the original path the library was built, or it may be sufficient to keep the _src.pdb file in the same path as the library file. (E.g. apr.lib and apr_src.pdb should reside together in your lib directory.) The later option is unconfirmed.</p> <p>In order to keep the symbols compiled into the static library, your application must use the linker's /debug flag. If you do not want the application to be debuggable with its corresponding .pdb file, omit the /debug flag and all debug symbolic information is discarded. Note that your application can only be debugged with the corresponding .pdb file created by the linker, unless you use /debugtype:coff or /debugtype:both in your link options.</p> </BODY> </HTML>
001-log4cxx
trunk/src/apr/docs/win32_builds.html
HTML
asf20
2,830
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_private.h" #include "apr_arch_misc.h" #include "crtdbg.h" #include "apr_arch_file_io.h" #include "assert.h" #include "apr_lib.h" APR_DECLARE_DATA apr_oslevel_e apr_os_level = APR_WIN_UNK; apr_status_t apr_get_oslevel(apr_oslevel_e *level) { if (apr_os_level == APR_WIN_UNK) { static OSVERSIONINFO oslev; oslev.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&oslev); if (oslev.dwPlatformId == VER_PLATFORM_WIN32_NT) { static unsigned int servpack = 0; char *pservpack; if (pservpack = oslev.szCSDVersion) { while (*pservpack && !apr_isdigit(*pservpack)) { pservpack++; } if (*pservpack) servpack = atoi(pservpack); } if (oslev.dwMajorVersion < 3) { apr_os_level = APR_WIN_UNSUP; } else if (oslev.dwMajorVersion == 3) { if (oslev.dwMajorVersion < 50) { apr_os_level = APR_WIN_UNSUP; } else if (oslev.dwMajorVersion == 50) { apr_os_level = APR_WIN_NT_3_5; } else { apr_os_level = APR_WIN_NT_3_51; } } else if (oslev.dwMajorVersion == 4) { if (servpack < 2) apr_os_level = APR_WIN_NT_4; else if (servpack <= 2) apr_os_level = APR_WIN_NT_4_SP2; else if (servpack <= 3) apr_os_level = APR_WIN_NT_4_SP3; else if (servpack <= 4) apr_os_level = APR_WIN_NT_4_SP4; else if (servpack <= 5) apr_os_level = APR_WIN_NT_4_SP5; else apr_os_level = APR_WIN_NT_4_SP6; } else if (oslev.dwMajorVersion == 5) { if (oslev.dwMinorVersion == 0) { if (servpack == 0) apr_os_level = APR_WIN_2000; else if (servpack == 1) apr_os_level = APR_WIN_2000_SP1; else apr_os_level = APR_WIN_2000_SP2; } else if (oslev.dwMinorVersion == 2) { apr_os_level = APR_WIN_2003; } else { if (servpack < 1) apr_os_level = APR_WIN_XP; else if (servpack == 1) apr_os_level = APR_WIN_XP_SP1; else apr_os_level = APR_WIN_XP_SP2; } } else { apr_os_level = APR_WIN_XP; } } #ifndef WINNT else if (oslev.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) { char *prevision; if (prevision = oslev.szCSDVersion) { while (*prevision && !apr_isupper(*prevision)) { prevision++; } } else prevision = ""; if (oslev.dwMinorVersion < 10) { if (*prevision < 'C') apr_os_level = APR_WIN_95; else apr_os_level = APR_WIN_95_OSR2; } else if (oslev.dwMinorVersion < 90) { if (*prevision < 'A') apr_os_level = APR_WIN_98; else apr_os_level = APR_WIN_98_SE; } else { apr_os_level = APR_WIN_ME; } } #endif #ifdef _WIN32_WCE else if (oslev.dwPlatformId == VER_PLATFORM_WIN32_CE) { if (oslev.dwMajorVersion < 3) { apr_os_level = APR_WIN_UNSUP; } else { apr_os_level = APR_WIN_CE_3; } } #endif else { apr_os_level = APR_WIN_UNSUP; } } *level = apr_os_level; if (apr_os_level < APR_WIN_UNSUP) { return APR_EGENERAL; } return APR_SUCCESS; } /* This is the helper code to resolve late bound entry points * missing from one or more releases of the Win32 API */ static const char* const lateDllName[DLL_defined] = { "kernel32", "advapi32", "mswsock", "ws2_32", "shell32", "ntdll.dll" }; static HMODULE lateDllHandle[DLL_defined] = { NULL, NULL, NULL, NULL, NULL, NULL }; FARPROC apr_load_dll_func(apr_dlltoken_e fnLib, char* fnName, int ordinal) { if (!lateDllHandle[fnLib]) { lateDllHandle[fnLib] = LoadLibrary(lateDllName[fnLib]); if (!lateDllHandle[fnLib]) return NULL; } if (ordinal) return GetProcAddress(lateDllHandle[fnLib], (char *) ordinal); else return GetProcAddress(lateDllHandle[fnLib], fnName); } /* Declared in include/arch/win32/apr_dbg_win32_handles.h */ APR_DECLARE_NONSTD(HANDLE) apr_dbg_log(char* fn, HANDLE ha, char* fl, int ln, int nh, /* HANDLE hv, char *dsc */...) { static DWORD tlsid = 0xFFFFFFFF; static HANDLE fh = NULL; static long ctr = 0; static CRITICAL_SECTION cs; long seq; DWORD wrote; char *sbuf; seq = (InterlockedIncrement)(&ctr); if (tlsid == 0xFFFFFFFF) { tlsid = (TlsAlloc)(); } sbuf = (TlsGetValue)(tlsid); if (!fh || !sbuf) { sbuf = (malloc)(1024); (TlsSetValue)(tlsid, sbuf); sbuf[1023] = '\0'; if (!fh) { (GetModuleFileName)(NULL, sbuf, 250); sprintf(strchr(sbuf, '\0'), ".%d", (GetCurrentProcessId)()); fh = (CreateFile)(sbuf, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); (InitializeCriticalSection)(&cs); } } if (!nh) { (sprintf)(sbuf, "%08x %08x %08x %s() %s:%d\n", (DWORD)ha, seq, GetCurrentThreadId(), fn, fl, ln); (EnterCriticalSection)(&cs); (WriteFile)(fh, sbuf, (DWORD)strlen(sbuf), &wrote, NULL); (LeaveCriticalSection)(&cs); } else { va_list a; va_start(a,nh); (EnterCriticalSection)(&cs); do { HANDLE *hv = va_arg(a, HANDLE*); char *dsc = va_arg(a, char*); if (strcmp(dsc, "Signaled") == 0) { if ((DWORD)ha >= STATUS_WAIT_0 && (DWORD)ha < STATUS_ABANDONED_WAIT_0) { hv += (DWORD)ha; } else if ((DWORD)ha >= STATUS_ABANDONED_WAIT_0 && (DWORD)ha < STATUS_USER_APC) { hv += (DWORD)ha - STATUS_ABANDONED_WAIT_0; dsc = "Abandoned"; } else if ((DWORD)ha == WAIT_TIMEOUT) { dsc = "Timed Out"; } } (sprintf)(sbuf, "%08x %08x %08x %s(%s) %s:%d\n", (DWORD*)*hv, seq, GetCurrentThreadId(), fn, dsc, fl, ln); (WriteFile)(fh, sbuf, (DWORD)strlen(sbuf), &wrote, NULL); } while (--nh); (LeaveCriticalSection)(&cs); va_end(a); } return ha; }
001-log4cxx
trunk/src/apr/misc/win32/misc.c
C
asf20
8,195
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_private.h" #include "apr_arch_misc.h" #include "apr_arch_file_io.h" #include <crtdbg.h> #include <assert.h> /* This module is the source of -static- helper functions that are * entirely internal to apr. If the fn is exported - it does not * belong here. * * Namespace decoration is still required to protect us from symbol * clashes in static linkages. */ /* Shared by apr_app.c and start.c * * An internal apr function to convert an array of strings (either * a counted or NULL terminated list, such as an argv[argc] or env[] * list respectively) from wide Unicode strings to narrow utf-8 strings. * These are allocated from the MSVCRT's _CRT_BLOCK to trick the system * into trusting our store. */ int apr_wastrtoastr(char const * const * *retarr, wchar_t const * const *arr, int args) { apr_size_t elesize = 0; char **newarr; char *elements; char *ele; int arg; if (args < 0) { for (args = 0; arr[args]; ++args) ; } newarr = _malloc_dbg((args + 1) * sizeof(char *), _CRT_BLOCK, __FILE__, __LINE__); for (arg = 0; arg < args; ++arg) { newarr[arg] = (void*)(wcslen(arr[arg]) + 1); elesize += (apr_size_t)newarr[arg]; } /* This is a safe max allocation, we will realloc after * processing and return the excess to the free store. * 3 ucs bytes hold any single wchar_t value (16 bits) * 4 ucs bytes will hold a wchar_t pair value (20 bits) */ elesize = elesize * 3 + 1; ele = elements = _malloc_dbg(elesize * sizeof(char), _CRT_BLOCK, __FILE__, __LINE__); for (arg = 0; arg < args; ++arg) { apr_size_t len = (apr_size_t)newarr[arg]; apr_size_t newlen = elesize; newarr[arg] = ele; (void)apr_conv_ucs2_to_utf8(arr[arg], &len, newarr[arg], &elesize); newlen -= elesize; ele += newlen; assert(elesize && (len == 0)); } newarr[arg] = NULL; *(ele++) = '\0'; /* Return to the free store if the heap realloc is the least bit optimized */ ele = _realloc_dbg(elements, ele - elements, _CRT_BLOCK, __FILE__, __LINE__); if (ele != elements) { apr_size_t diff = ele - elements; for (arg = 0; arg < args; ++arg) { newarr[arg] += diff; } } *retarr = newarr; return args; }
001-log4cxx
trunk/src/apr/misc/win32/internal.c
C
asf20
3,287
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_strings.h" #include "apr_portable.h" APR_DECLARE(const char*) apr_os_default_encoding (apr_pool_t *pool) { return apr_psprintf(pool, "CP%u", (unsigned) GetACP()); } APR_DECLARE(const char*) apr_os_locale_encoding (apr_pool_t *pool) { LCID locale = GetThreadLocale(); int len = GetLocaleInfo(locale, LOCALE_IDEFAULTANSICODEPAGE, NULL, 0); char *cp = apr_palloc(pool, len + 2); if (0 < GetLocaleInfo(locale, LOCALE_IDEFAULTANSICODEPAGE, cp + 2, len)) { /* Fix up the returned number to make a valid codepage name of the form "CPnnnn". */ cp[0] = 'C'; cp[1] = 'P'; return cp; } return apr_os_default_encoding(pool); }
001-log4cxx
trunk/src/apr/misc/win32/charset.c
C
asf20
1,525
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_private.h" #include "apr_errno.h" #include "apr_arch_utf8.h" /* Implement the design principal specified by RFC 2718 2.2.5 * Guidelines for new URL Schemes - within the APR. * * Since many architectures support unicode, and UCS2 is the most * efficient storage used by those archictures, these functions * exist to validate a UCS string. It is up to the operating system * to determine the validitity of the string in the context of it's * native language support. File systems that support filename * characters of 0x80-0xff but have no support of Unicode will find * this function useful only for validating the character sequences * and rejecting poorly encoded strings, if RFC 2718 2.2.5 naming is * desired. * * from RFC 2279 UTF-8, a transformation format of ISO 10646 * * UCS-4 range (hex.) UTF-8 octet sequence (binary) * 1:2 0000 0000-0000 007F 0xxxxxxx * 2:2 0000 0080-0000 07FF 110XXXXx 10xxxxxx * 3:2 0000 0800-0000 FFFF 1110XXXX 10Xxxxxx 10xxxxxx * 4:4 0001 0000-001F FFFF 11110zXX 10XXxxxx 10xxxxxx 10xxxxxx * inv 0020 0000-03FF FFFF 111110XX 10XXXxxx 10xxxxxx 10xxxxxx 10xxxxxx * inv 0400 0000-7FFF FFFF 1111110X 10XXXXxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx * * One of the X values must be one for the encoding length to be legit. * Neither the z bit, nor the final two forms, are used for ucs-2 * * "Pairs of UCS-2 values between D800 and DFFF (surrogate pairs in * Unicode parlance), being actually UCS-4 characters transformed * through UTF-16, need special treatment: the UTF-16 transformation * must be undone, yielding a UCS-4 character that is then transformed * as above." * * from RFC2781 UTF-16: the compressed ISO 10646 encoding bitmask * * U' = U - 0x10000 * U' = 000000000000yyyyyyyyyyxxxxxxxxxx * W1 = 110110yyyyyyyyyy * W2 = 110111xxxxxxxxxx * * apr_conv_utf8_to_ucs2 out bytes:sizeof(in) * 1 <= Req <= sizeof(in) * 2 * * apr_conv_ucs2_to_utf8 out words:sizeof(in) / 2 <= Req <= sizeof(in) * 3 / 2 */ APR_DECLARE(apr_status_t) apr_conv_utf8_to_ucs2(const char *in, apr_size_t *inbytes, apr_wchar_t *out, apr_size_t *outwords) { apr_int64_t newch, mask; apr_size_t expect, eating; int ch; while (*inbytes && *outwords) { ch = (unsigned char)(*in++); if (!(ch & 0200)) { /* US-ASCII-7 plain text */ --*inbytes; --*outwords; *(out++) = ch; } else { if ((ch & 0300) != 0300) { /* Multibyte Continuation is out of place */ return APR_EINVAL; } else { /* Multibyte Sequence Lead Character * * Compute the expected bytes while adjusting * or lead byte and leading zeros mask. */ mask = 0340; expect = 1; while ((ch & mask) == mask) { mask |= mask >> 1; if (++expect > 3) /* (truly 5 for ucs-4) */ return APR_EINVAL; } newch = ch & ~mask; eating = expect + 1; if (*inbytes <= expect) return APR_INCOMPLETE; /* Reject values of excessive leading 0 bits * utf-8 _demands_ the shortest possible byte length */ if (expect == 1) { if (!(newch & 0036)) return APR_EINVAL; } else { /* Reject values of excessive leading 0 bits */ if (!newch && !((unsigned char)*in & 0077 & (mask << 1))) return APR_EINVAL; if (expect == 2) { /* Reject values D800-DFFF when not utf16 encoded * (may not be an appropriate restriction for ucs-4) */ if (newch == 0015 && ((unsigned char)*in & 0040)) return APR_EINVAL; } else if (expect == 3) { /* Short circuit values > 110000 */ if (newch > 4) return APR_EINVAL; if (newch == 4 && ((unsigned char)*in & 0060)) return APR_EINVAL; } } /* Where the boolean (expect > 2) is true, we will need * an extra word for the output. */ if (*outwords < (apr_size_t)(expect > 2) + 1) break; /* buffer full */ while (expect--) { /* Multibyte Continuation must be legal */ if (((ch = (unsigned char)*(in++)) & 0300) != 0200) return APR_EINVAL; newch <<= 6; newch |= (ch & 0077); } *inbytes -= eating; /* newch is now a true ucs-4 character * * now we need to fold to ucs-2 */ if (newch < 0x10000) { --*outwords; *(out++) = (apr_wchar_t) newch; } else { *outwords -= 2; newch -= 0x10000; *(out++) = (apr_wchar_t) (0xD800 | (newch >> 10)); *(out++) = (apr_wchar_t) (0xDC00 | (newch & 0x03FF)); } } } } /* Buffer full 'errors' aren't errors, the client must inspect both * the inbytes and outwords values */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_conv_ucs2_to_utf8(const apr_wchar_t *in, apr_size_t *inwords, char *out, apr_size_t *outbytes) { apr_int64_t newch, require; apr_size_t need; char *invout; int ch; while (*inwords && *outbytes) { ch = (unsigned short)(*in++); if (ch < 0x80) { --*inwords; --*outbytes; *(out++) = (unsigned char) ch; } else { if ((ch & 0xFC00) == 0xDC00) { /* Invalid Leading ucs-2 Multiword Continuation Character */ return APR_EINVAL; } if ((ch & 0xFC00) == 0xD800) { /* Leading ucs-2 Multiword Character */ if (*inwords < 2) { /* Missing ucs-2 Multiword Continuation Character */ return APR_INCOMPLETE; } if (((unsigned short)(*in) & 0xFC00) != 0xDC00) { /* Invalid ucs-2 Multiword Continuation Character */ return APR_EINVAL; } newch = (ch & 0x03FF) << 10 | ((unsigned short)(*in++) & 0x03FF); newch += 0x10000; } else { /* ucs-2 Single Word Character */ newch = ch; } /* Determine the absolute minimum utf-8 bytes required */ require = newch >> 11; need = 1; while (require) require >>= 5, ++need; if (need >= *outbytes) break; /* Insufficient buffer */ *inwords -= (need > 2) + 1; *outbytes -= need + 1; /* Compute the utf-8 characters in last to first order, * calculating the lead character length bits along the way. */ ch = 0200; out += need + 1; invout = out; while (need--) { ch |= ch >> 1; *(--invout) = (unsigned char)(0200 | (newch & 0077)); newch >>= 6; } /* Compute the lead utf-8 character and move the dest offset */ *(--invout) = (unsigned char)(ch | newch); } } /* Buffer full 'errors' aren't errors, the client must inspect both * the inwords and outbytes values */ return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/misc/win32/utf8.c
C
asf20
9,615
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_private.h" #include "apr_general.h" #include "apr_pools.h" #include "apr_signal.h" #include "ShellAPI.h" #include "apr_arch_misc.h" /* for WSAHighByte / WSALowByte */ #include "wchar.h" #include "apr_arch_file_io.h" #include "crtdbg.h" #include "assert.h" /* This symbol is _private_, although it must be exported. */ int APR_DECLARE_DATA apr_app_init_complete = 0; /* Used by apr_app_initialize to reprocess the environment * * An internal apr function to convert a double-null terminated set * of single-null terminated strings from wide Unicode to narrow utf-8 * as a list of strings. These are allocated from the MSVCRT's * _CRT_BLOCK to trick the system into trusting our store. */ static int warrsztoastr(const char * const * *retarr, const wchar_t * arrsz, int args) { const apr_wchar_t *wch; apr_size_t totlen; apr_size_t newlen; apr_size_t wsize; char **newarr; int arg; if (args < 0) { for (args = 1, wch = arrsz; wch[0] || wch[1]; ++wch) if (!*wch) ++args; } wsize = 1 + wch - arrsz; newarr = _malloc_dbg((args + 1) * sizeof(char *), _CRT_BLOCK, __FILE__, __LINE__); /* This is a safe max allocation, we will realloc after * processing and return the excess to the free store. * 3 ucs bytes hold any single wchar_t value (16 bits) * 4 ucs bytes will hold a wchar_t pair value (20 bits) */ newlen = totlen = wsize * 3 + 1; newarr[0] = _malloc_dbg(newlen * sizeof(char), _CRT_BLOCK, __FILE__, __LINE__); (void)apr_conv_ucs2_to_utf8(arrsz, &wsize, newarr[0], &newlen); assert(newlen && !wsize); /* Return to the free store if the heap realloc is the least bit optimized */ newarr[0] = _realloc_dbg(newarr[0], totlen - newlen, _CRT_BLOCK, __FILE__, __LINE__); for (arg = 1; arg < args; ++arg) { newarr[arg] = newarr[arg - 1] + 2; while (*(newarr[arg]++)) { /* continue */; } } newarr[arg] = NULL; *retarr = newarr; return args; } /* Reprocess the arguments to main() for a completely apr-ized application */ APR_DECLARE(apr_status_t) apr_app_initialize(int *argc, const char * const * *argv, const char * const * *env) { apr_status_t rv = apr_initialize(); if (rv != APR_SUCCESS) { return rv; } #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { apr_wchar_t **wstrs; apr_wchar_t *sysstr; int wstrc; int dupenv; if (apr_app_init_complete) { return rv; } apr_app_init_complete = 1; sysstr = GetCommandLineW(); if (sysstr) { wstrs = CommandLineToArgvW(sysstr, &wstrc); if (wstrs) { *argc = apr_wastrtoastr(argv, wstrs, wstrc); GlobalFree(wstrs); } } sysstr = GetEnvironmentStringsW(); dupenv = warrsztoastr(&_environ, sysstr, -1); if (env) { *env = _malloc_dbg((dupenv + 1) * sizeof (char *), _CRT_BLOCK, __FILE__, __LINE__ ); memcpy((void*)*env, _environ, (dupenv + 1) * sizeof (char *)); } else { } FreeEnvironmentStringsW(sysstr); /* MSVCRT will attempt to maintain the wide environment calls * on _putenv(), which is bogus if we've passed a non-ascii * string to _putenv(), since they use MultiByteToWideChar * and breaking the implicit utf-8 assumption we've built. * * Reset _wenviron for good measure. */ if (_wenviron) { apr_wchar_t **wenv = _wenviron; _wenviron = NULL; free(wenv); } } #endif return rv; } static int initialized = 0; /* Provide to win32/thread.c */ extern DWORD tls_apr_thread; APR_DECLARE(apr_status_t) apr_initialize(void) { apr_pool_t *pool; apr_status_t status; int iVersionRequested; WSADATA wsaData; int err; apr_oslevel_e osver; if (initialized++) { return APR_SUCCESS; } /* Initialize apr_os_level global */ if (apr_get_oslevel(&osver) != APR_SUCCESS) { return APR_EEXIST; } tls_apr_thread = TlsAlloc(); if ((status = apr_pool_initialize()) != APR_SUCCESS) return status; if (apr_pool_create(&pool, NULL) != APR_SUCCESS) { return APR_ENOPOOL; } apr_pool_tag(pool, "apr_initialize"); iVersionRequested = MAKEWORD(WSAHighByte, WSALowByte); err = WSAStartup((WORD) iVersionRequested, &wsaData); if (err) { return err; } if (LOBYTE(wsaData.wVersion) != WSAHighByte || HIBYTE(wsaData.wVersion) != WSALowByte) { WSACleanup(); return APR_EEXIST; } apr_signal_init(pool); return APR_SUCCESS; } APR_DECLARE_NONSTD(void) apr_terminate(void) { initialized--; if (initialized) { return; } apr_pool_terminate(); WSACleanup(); TlsFree(tls_apr_thread); } APR_DECLARE(void) apr_terminate2(void) { apr_terminate(); }
001-log4cxx
trunk/src/apr/misc/win32/start.c
C
asf20
6,130
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_private.h" #include "apr_general.h" #include "apr_portable.h" #include "apr_arch_misc.h" #include <wincrypt.h> APR_DECLARE(apr_status_t) apr_generate_random_bytes(unsigned char * buf, apr_size_t length) { HCRYPTPROV hProv; apr_status_t res = APR_SUCCESS; /* 0x40 bit = CRYPT_SILENT, only introduced in more recent PSDKs * and will only work for Win2K and later. */ DWORD flags = CRYPT_VERIFYCONTEXT | ((apr_os_level >= APR_WIN_2000) ? 0x40 : 0); if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, flags)) { return apr_get_os_error(); } /* XXX: An ugly hack for Win64, randomness is such that noone should * ever expect > 2^31 bytes of data at once without the prng * coming to a complete halt. */ if (!CryptGenRandom(hProv, (DWORD)length, buf)) { res = apr_get_os_error(); } CryptReleaseContext(hProv, 0); return res; } APR_DECLARE(apr_status_t) apr_os_uuid_get(unsigned char *uuid_data) { /* Note: this call doesn't actually require CoInitialize() first * * XXX: we should scramble the bytes or some such to eliminate the * possible misuse/abuse since uuid is based on the NIC address, and * is therefore not only a uniqifier, but an identity (which might not * be appropriate in all cases. * * Note that Win2000, XP and later no longer suffer from this problem, * a scrambling fix is only needed for (apr_os_level < APR_WIN_2000) */ if (FAILED(UuidCreate((UUID *)uuid_data))) { return APR_EGENERAL; } return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/misc/win32/rand.c
C
asf20
2,485
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define APR_WANT_STRFUNC #include "apr_want.h" #include "apr.h" #include "apr_arch_misc.h" #include "apr_arch_utf8.h" #include "apr_env.h" #include "apr_errno.h" #include "apr_pools.h" #include "apr_strings.h" #if APR_HAS_UNICODE_FS static apr_status_t widen_envvar_name (apr_wchar_t *buffer, apr_size_t bufflen, const char *envvar) { apr_size_t inchars; apr_status_t status; inchars = strlen(envvar) + 1; status = apr_conv_utf8_to_ucs2(envvar, &inchars, buffer, &bufflen); if (status == APR_INCOMPLETE) status = APR_ENAMETOOLONG; return status; } #endif APR_DECLARE(apr_status_t) apr_env_get(char **value, const char *envvar, apr_pool_t *pool) { char *val = NULL; DWORD size; #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { apr_wchar_t wenvvar[APR_PATH_MAX]; apr_size_t inchars, outchars; apr_wchar_t *wvalue, dummy; apr_status_t status; status = widen_envvar_name(wenvvar, APR_PATH_MAX, envvar); if (status) return status; SetLastError(0); size = GetEnvironmentVariableW(wenvvar, &dummy, 0); if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) /* The environment variable doesn't exist. */ return APR_ENOENT; if (size == 0) { /* The environment value exists, but is zero-length. */ *value = apr_pstrdup(pool, ""); return APR_SUCCESS; } wvalue = apr_palloc(pool, size * sizeof(*wvalue)); size = GetEnvironmentVariableW(wenvvar, wvalue, size); if (size == 0) /* Mid-air collision?. Somebody must've changed the env. var. */ return APR_INCOMPLETE; inchars = wcslen(wvalue) + 1; outchars = 3 * inchars; /* Enougn for any UTF-8 representation */ val = apr_palloc(pool, outchars); status = apr_conv_ucs2_to_utf8(wvalue, &inchars, val, &outchars); if (status) return status; } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { char dummy; SetLastError(0); size = GetEnvironmentVariableA(envvar, &dummy, 0); if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) /* The environment variable doesn't exist. */ return APR_ENOENT; if (size == 0) { /* The environment value exists, but is zero-length. */ *value = apr_pstrdup(pool, ""); return APR_SUCCESS; } val = apr_palloc(pool, size); size = GetEnvironmentVariableA(envvar, val, size); if (size == 0) /* Mid-air collision?. Somebody must've changed the env. var. */ return APR_INCOMPLETE; } #endif *value = val; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_env_set(const char *envvar, const char *value, apr_pool_t *pool) { #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { apr_wchar_t wenvvar[APR_PATH_MAX]; apr_wchar_t *wvalue; apr_size_t inchars, outchars; apr_status_t status; status = widen_envvar_name(wenvvar, APR_PATH_MAX, envvar); if (status) return status; outchars = inchars = strlen(value) + 1; wvalue = apr_palloc(pool, outchars * sizeof(*wvalue)); status = apr_conv_utf8_to_ucs2(value, &inchars, wvalue, &outchars); if (status) return status; if (!SetEnvironmentVariableW(wenvvar, wvalue)) return apr_get_os_error(); } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { if (!SetEnvironmentVariableA(envvar, value)) return apr_get_os_error(); } #endif return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_env_delete(const char *envvar, apr_pool_t *pool) { #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { apr_wchar_t wenvvar[APR_PATH_MAX]; apr_status_t status; status = widen_envvar_name(wenvvar, APR_PATH_MAX, envvar); if (status) return status; if (!SetEnvironmentVariableW(wenvvar, NULL)) return apr_get_os_error(); } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { if (!SetEnvironmentVariableA(envvar, NULL)) return apr_get_os_error(); } #endif return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/misc/win32/env.c
C
asf20
5,337
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Usage Notes: * * this module, and the misc/win32/utf8.c modules must be * compiled APR_EXPORT_STATIC and linked to an application with * the /entry:wmainCRTStartup flag. This module becomes the true * wmain entry point, and passes utf-8 reformatted argv and env * arrays to the application's main function. * * This module is only compatible with Unicode-only executables. * Mixed (Win9x backwards compatible) binaries should refer instead * to the apr_startup.c module. * * _dbg_malloc/realloc is used in place of the usual API, in order * to convince the MSVCRT that they created these entities. If we * do not create them as _CRT_BLOCK entities, the crt will fault * on an assert. We are not worrying about the crt's locks here, * since we are single threaded [so far]. */ #include "apr_general.h" #include "ShellAPI.h" #include "crtdbg.h" #include "wchar.h" #include "apr_arch_file_io.h" #include "assert.h" #include "apr_private.h" #include "apr_arch_misc.h" /* This symbol is _private_, although it must be exported. */ extern int main(int argc, const char **argv, const char **env); int wmain(int argc, const wchar_t **wargv, const wchar_t **wenv) { char **argv; char **env; int dupenv; (void)apr_wastrtoastr(&argv, wargv, argc); dupenv = apr_wastrtoastr(&env, wenv, -1); _environ = _malloc_dbg((dupenv + 1) * sizeof (char *), _CRT_BLOCK, __FILE__, __LINE__ ); memcpy(_environ, env, (dupenv + 1) * sizeof (char *)); /* MSVCRT will attempt to maintain the wide environment calls * on _putenv(), which is bogus if we've passed a non-ascii * string to _putenv(), since they use MultiByteToWideChar * and breaking the implicit utf-8 assumption we've built. * * Reset _wenviron for good measure. */ if (_wenviron) { wenv = _wenviron; _wenviron = NULL; free((wchar_t **)wenv); } apr_app_init_complete = 1; return main(argc, argv, env); }
001-log4cxx
trunk/src/apr/misc/win32/apr_app.c
C
asf20
2,831
/* * Copyright (c) 1987, 1993, 1994 * 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. */ #include "apr_arch_misc.h" #include "apr_strings.h" #include "apr_lib.h" #define EMSG "" APR_DECLARE(apr_status_t) apr_getopt_init(apr_getopt_t **os, apr_pool_t *cont, int argc, const char *const *argv) { void *argv_buff; *os = apr_palloc(cont, sizeof(apr_getopt_t)); (*os)->cont = cont; (*os)->reset = 0; (*os)->errfn = (apr_getopt_err_fn_t*)(fprintf); (*os)->errarg = (void*)(stderr); (*os)->place = EMSG; (*os)->argc = argc; /* The argv parameter must be compatible with main()'s argv, since that's the primary purpose of this function. But people might want to use this function with arrays other than the main argv, and we shouldn't touch the caller's data. So we copy. */ argv_buff = apr_palloc(cont, (argc + 1) * sizeof(const char *)); memcpy(argv_buff, argv, argc * sizeof(const char *)); (*os)->argv = argv_buff; (*os)->argv[argc] = NULL; (*os)->interleave = 0; (*os)->ind = 1; (*os)->skip_start = 1; (*os)->skip_end = 1; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_getopt(apr_getopt_t *os, const char *opts, char *optch, const char **optarg) { const char *oli; /* option letter list index */ if (os->reset || !*os->place) { /* update scanning pointer */ os->reset = 0; if (os->ind >= os->argc || *(os->place = os->argv[os->ind]) != '-') { os->place = EMSG; *optch = os->opt; return (APR_EOF); } if (os->place[1] && *++os->place == '-') { /* found "--" */ ++os->ind; os->place = EMSG; *optch = os->opt; return (APR_EOF); } } /* option letter okay? */ if ((os->opt = (int) *os->place++) == (int) ':' || !(oli = strchr(opts, os->opt))) { /* * if the user didn't specify '-' as an option, * assume it means -1. */ if (os->opt == (int) '-') { *optch = os->opt; return (APR_EOF); } if (!*os->place) ++os->ind; if (os->errfn && *opts != ':') { (os->errfn)(os->errarg, "%s: illegal option -- %c\n", apr_filepath_name_get(*os->argv), os->opt); } *optch = os->opt; return (APR_BADCH); } if (*++oli != ':') { /* don't need argument */ *optarg = NULL; if (!*os->place) ++os->ind; } else { /* need an argument */ if (*os->place) /* no white space */ *optarg = os->place; else if (os->argc <= ++os->ind) { /* no arg */ os->place = EMSG; if (*opts == ':') { *optch = os->opt; return (APR_BADARG); } if (os->errfn) { (os->errfn)(os->errarg, "%s: option requires an argument -- %c\n", apr_filepath_name_get(*os->argv), os->opt); } *optch = os->opt; return (APR_BADCH); } else /* white space */ *optarg = os->argv[os->ind]; os->place = EMSG; ++os->ind; } *optch = os->opt; return APR_SUCCESS; } /* Reverse the sequence argv[start..start+len-1]. */ static void reverse(const char **argv, int start, int len) { const char *temp; for (; len >= 2; start++, len -= 2) { temp = argv[start]; argv[start] = argv[start + len - 1]; argv[start + len - 1] = temp; } } /* * Permute os->argv with the goal that non-option arguments will all * appear at the end. os->skip_start is where we started skipping * non-option arguments, os->skip_end is where we stopped, and os->ind * is where we are now. */ static void permute(apr_getopt_t *os) { int len1 = os->skip_end - os->skip_start; int len2 = os->ind - os->skip_end; if (os->interleave) { /* * Exchange the sequences argv[os->skip_start..os->skip_end-1] and * argv[os->skip_end..os->ind-1]. The easiest way to do that is * to reverse the entire range and then reverse the two * sub-ranges. */ reverse(os->argv, os->skip_start, len1 + len2); reverse(os->argv, os->skip_start, len2); reverse(os->argv, os->skip_start + len2, len1); } /* Reset skip range to the new location of the non-option sequence. */ os->skip_start += len2; os->skip_end += len2; } /* Helper function to print out an error involving a long option */ static apr_status_t serr(apr_getopt_t *os, const char *err, const char *str, apr_status_t status) { if (os->errfn) (os->errfn)(os->errarg, "%s: %s: %s\n", apr_filepath_name_get(*os->argv), err, str); return status; } /* Helper function to print out an error involving a short option */ static apr_status_t cerr(apr_getopt_t *os, const char *err, int ch, apr_status_t status) { if (os->errfn) (os->errfn)(os->errarg, "%s: %s: %c\n", apr_filepath_name_get(*os->argv), err, ch); return status; } APR_DECLARE(apr_status_t) apr_getopt_long(apr_getopt_t *os, const apr_getopt_option_t *opts, int *optch, const char **optarg) { const char *p; int i; /* Let the calling program reset option processing. */ if (os->reset) { os->place = EMSG; os->ind = 1; os->reset = 0; } /* * We can be in one of two states: in the middle of processing a * run of short options, or about to process a new argument. * Since the second case can lead to the first one, handle that * one first. */ p = os->place; if (*p == '\0') { /* If we are interleaving, skip non-option arguments. */ if (os->interleave) { while (os->ind < os->argc && *os->argv[os->ind] != '-') os->ind++; os->skip_end = os->ind; } if (os->ind >= os->argc || *os->argv[os->ind] != '-') { os->ind = os->skip_start; return APR_EOF; } p = os->argv[os->ind++] + 1; if (*p == '-' && p[1] != '\0') { /* Long option */ /* Search for the long option name in the caller's table. */ apr_size_t len = 0; p++; for (i = 0; ; i++) { if (opts[i].optch == 0) /* No match */ return serr(os, "invalid option", p - 2, APR_BADCH); if (opts[i].name) { len = strlen(opts[i].name); if (strncmp(p, opts[i].name, len) == 0 && (p[len] == '\0' || p[len] == '=')) break; } } *optch = opts[i].optch; if (opts[i].has_arg) { if (p[len] == '=') /* Argument inline */ *optarg = p + len + 1; else { if (os->ind >= os->argc) /* Argument missing */ return serr(os, "missing argument", p - 2, APR_BADARG); else /* Argument in next arg */ *optarg = os->argv[os->ind++]; } } else { *optarg = NULL; if (p[len] == '=') return serr(os, "erroneous argument", p - 2, APR_BADARG); } permute(os); return APR_SUCCESS; } else { if (*p == '-') { /* Bare "--"; we're done */ permute(os); os->ind = os->skip_start; return APR_EOF; } else if (*p == '\0') /* Bare "-" is illegal */ return serr(os, "invalid option", p, APR_BADCH); } } /* * Now we're in a run of short options, and *p is the next one. * Look for it in the caller's table. */ for (i = 0; ; i++) { if (opts[i].optch == 0) /* No match */ return cerr(os, "invalid option character", *p, APR_BADCH); if (*p == opts[i].optch) break; } *optch = *p++; if (opts[i].has_arg) { if (*p != '\0') /* Argument inline */ *optarg = p; else { if (os->ind >= os->argc) /* Argument missing */ return cerr(os, "missing argument", *optch, APR_BADARG); else /* Argument in next arg */ *optarg = os->argv[os->ind++]; } os->place = EMSG; } else { *optarg = NULL; os->place = p; } permute(os); return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/misc/unix/getopt.c
C
asf20
10,973
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_private.h" #include "apr_strings.h" #include "apr_portable.h" #ifdef HAVE_LANGINFO_H #include <langinfo.h> #endif /* * simple heuristic to determine codepage of source code so that * literal strings (e.g., "GET /\r\n") in source code can be translated * properly * * If appropriate, a symbol can be set at configure time to determine * this. On EBCDIC platforms, it will be important how the code was * unpacked. */ APR_DECLARE(const char*) apr_os_default_encoding (apr_pool_t *pool) { #ifdef __MVS__ # ifdef __CODESET__ return __CODESET__; # else return "IBM-1047"; # endif #endif if ('}' == 0xD0) { return "IBM-1047"; } if ('{' == 0xFB) { return "EDF04"; } if ('A' == 0xC1) { return "EBCDIC"; /* not useful */ } if ('A' == 0x41) { return "ISO-8859-1"; /* not necessarily true */ } return "unknown"; } APR_DECLARE(const char*) apr_os_locale_encoding (apr_pool_t *pool) { #if defined(HAVE_NL_LANGINFO) && defined(CODESET) const char *charset; charset = nl_langinfo(CODESET); if (charset && *charset) { #ifdef _OSD_POSIX /* Bug workaround - delete as soon as fixed in OSD_POSIX */ /* Some versions of OSD_POSIX return nl_langinfo(CODESET)="^[nN]" */ /* Ignore the bogus information and use apr_os_default_encoding() */ if (charset[0] != '^') #endif return charset; } #endif return apr_os_default_encoding(pool); }
001-log4cxx
trunk/src/apr/misc/unix/charset.c
C
asf20
2,310
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_arch_misc.h" #include "apr_arch_threadproc.h" #include "apr_arch_file_io.h" #if APR_HAS_OTHER_CHILD #ifdef HAVE_TIME_H #include <sys/time.h> #endif #ifdef HAVE_SYS_SELECT_H #include <sys/select.h> #endif #if APR_HAVE_SYS_WAIT_H #include <sys/wait.h> #endif #ifdef BEOS #include <sys/socket.h> /* for fd_set definition! */ #endif static apr_other_child_rec_t *other_children = NULL; static apr_status_t other_child_cleanup(void *data) { apr_other_child_rec_t **pocr, *nocr; for (pocr = &other_children; *pocr; pocr = &(*pocr)->next) { if ((*pocr)->data == data) { nocr = (*pocr)->next; (*(*pocr)->maintenance) (APR_OC_REASON_UNREGISTER, (*pocr)->data, -1); *pocr = nocr; /* XXX: um, well we've just wasted some space in pconf ? */ return APR_SUCCESS; } } return APR_SUCCESS; } APR_DECLARE(void) apr_proc_other_child_register(apr_proc_t *proc, void (*maintenance) (int reason, void *, int status), void *data, apr_file_t *write_fd, apr_pool_t *p) { apr_other_child_rec_t *ocr; ocr = apr_palloc(p, sizeof(*ocr)); ocr->p = p; ocr->proc = proc; ocr->maintenance = maintenance; ocr->data = data; if (write_fd == NULL) { ocr->write_fd = (apr_os_file_t) -1; } else { #ifdef WIN32 /* This should either go away as part of eliminating apr_proc_probe_writable_fds * or write_fd should point to an apr_file_t */ ocr->write_fd = write_fd->filehand; #else ocr->write_fd = write_fd->filedes; #endif } ocr->next = other_children; other_children = ocr; apr_pool_cleanup_register(p, ocr->data, other_child_cleanup, apr_pool_cleanup_null); } APR_DECLARE(void) apr_proc_other_child_unregister(void *data) { apr_other_child_rec_t *cur; cur = other_children; while (cur) { if (cur->data == data) { break; } cur = cur->next; } /* segfault if this function called with invalid parm */ apr_pool_cleanup_kill(cur->p, cur->data, other_child_cleanup); other_child_cleanup(data); } APR_DECLARE(apr_status_t) apr_proc_other_child_alert(apr_proc_t *proc, int reason, int status) { apr_other_child_rec_t *ocr, *nocr; for (ocr = other_children; ocr; ocr = nocr) { nocr = ocr->next; if (ocr->proc->pid != proc->pid) continue; ocr->proc = NULL; (*ocr->maintenance) (reason, ocr->data, status); return APR_SUCCESS; } return APR_EPROC_UNKNOWN; } APR_DECLARE(void) apr_proc_other_child_refresh(apr_other_child_rec_t *ocr, int reason) { /* Todo: * Implement code to detect if pipes are still alive. */ #ifdef WIN32 DWORD status; if (ocr->proc == NULL) return; if (!ocr->proc->hproc) { /* Already mopped up, perhaps we apr_proc_kill'ed it, * they should have already unregistered! */ ocr->proc = NULL; (*ocr->maintenance) (APR_OC_REASON_LOST, ocr->data, -1); } else if (!GetExitCodeProcess(ocr->proc->hproc, &status)) { CloseHandle(ocr->proc->hproc); ocr->proc->hproc = NULL; ocr->proc = NULL; (*ocr->maintenance) (APR_OC_REASON_LOST, ocr->data, -1); } else if (status == STILL_ACTIVE) { (*ocr->maintenance) (reason, ocr->data, -1); } else { CloseHandle(ocr->proc->hproc); ocr->proc->hproc = NULL; ocr->proc = NULL; (*ocr->maintenance) (APR_OC_REASON_DEATH, ocr->data, status); } #else /* ndef Win32 */ pid_t waitret; int status; if (ocr->proc == NULL) return; waitret = waitpid(ocr->proc->pid, &status, WNOHANG); if (waitret == ocr->proc->pid) { ocr->proc = NULL; (*ocr->maintenance) (APR_OC_REASON_DEATH, ocr->data, status); } else if (waitret == 0) { (*ocr->maintenance) (reason, ocr->data, -1); } else if (waitret == -1) { /* uh what the heck? they didn't call unregister? */ ocr->proc = NULL; (*ocr->maintenance) (APR_OC_REASON_LOST, ocr->data, -1); } #endif } APR_DECLARE(void) apr_proc_other_child_refresh_all(int reason) { apr_other_child_rec_t *ocr, *next_ocr; for (ocr = other_children; ocr; ocr = next_ocr) { next_ocr = ocr->next; apr_proc_other_child_refresh(ocr, reason); } } #else /* !APR_HAS_OTHER_CHILD */ APR_DECLARE(void) apr_proc_other_child_register(apr_proc_t *proc, void (*maintenance) (int reason, void *, int status), void *data, apr_file_t *write_fd, apr_pool_t *p) { return; } APR_DECLARE(void) apr_proc_other_child_unregister(void *data) { return; } APR_DECLARE(apr_status_t) apr_proc_other_child_alert(apr_proc_t *proc, int reason, int status) { return APR_ENOTIMPL; } APR_DECLARE(void) apr_proc_other_child_refresh(apr_other_child_rec_t *ocr, int reason) { return; } APR_DECLARE(void) apr_proc_other_child_refresh_all(int reason) { return; } #endif /* APR_HAS_OTHER_CHILD */
001-log4cxx
trunk/src/apr/misc/unix/otherchild.c
C
asf20
6,294
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_arch_misc.h" #include "apr_strings.h" #include "apr_lib.h" #include "apr_dso.h" #if APR_HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_DLFCN_H #include <dlfcn.h> #endif /* * stuffbuffer - like apr_cpystrn() but returns the address of the * dest buffer instead of the address of the terminating '\0' */ static char *stuffbuffer(char *buf, apr_size_t bufsize, const char *s) { apr_cpystrn(buf,s,bufsize); return buf; } static char *apr_error_string(apr_status_t statcode) { switch (statcode) { case APR_ENOPOOL: return "A new pool could not be created."; case APR_EBADDATE: return "An invalid date has been provided"; case APR_EINVALSOCK: return "An invalid socket was returned"; case APR_ENOPROC: return "No process was provided and one was required."; case APR_ENOTIME: return "No time was provided and one was required."; case APR_ENODIR: return "No directory was provided and one was required."; case APR_ENOLOCK: return "No lock was provided and one was required."; case APR_ENOPOLL: return "No poll structure was provided and one was required."; case APR_ENOSOCKET: return "No socket was provided and one was required."; case APR_ENOTHREAD: return "No thread was provided and one was required."; case APR_ENOTHDKEY: return "No thread key structure was provided and one was required."; case APR_ENOSHMAVAIL: return "No shared memory is currently available"; case APR_EDSOOPEN: #if APR_HAS_DSO && defined(HAVE_LIBDL) return dlerror(); #else return "DSO load failed"; #endif /* HAVE_LIBDL */ case APR_EBADIP: return "The specified IP address is invalid."; case APR_EBADMASK: return "The specified network mask is invalid."; case APR_INCHILD: return "Your code just forked, and you are currently executing in the " "child process"; case APR_INPARENT: return "Your code just forked, and you are currently executing in the " "parent process"; case APR_DETACH: return "The specified thread is detached"; case APR_NOTDETACH: return "The specified thread is not detached"; case APR_CHILD_DONE: return "The specified child process is done executing"; case APR_CHILD_NOTDONE: return "The specified child process is not done executing"; case APR_TIMEUP: return "The timeout specified has expired"; case APR_INCOMPLETE: return "Partial results are valid but processing is incomplete"; case APR_BADCH: return "Bad character specified on command line"; case APR_BADARG: return "Missing parameter for the specified command line option"; case APR_EOF: return "End of file found"; case APR_NOTFOUND: return "Could not find specified socket in poll list."; case APR_ANONYMOUS: return "Shared memory is implemented anonymously"; case APR_FILEBASED: return "Shared memory is implemented using files"; case APR_KEYBASED: return "Shared memory is implemented using a key system"; case APR_EINIT: return "There is no error, this value signifies an initialized " "error code"; case APR_ENOTIMPL: return "This function has not been implemented on this platform"; case APR_EMISMATCH: return "passwords do not match"; case APR_EABSOLUTE: return "The given path is absolute"; case APR_ERELATIVE: return "The given path is relative"; case APR_EINCOMPLETE: return "The given path is incomplete"; case APR_EABOVEROOT: return "The given path was above the root path"; case APR_EBADPATH: return "The given path misformatted or contained invalid characters"; case APR_EPATHWILD: return "The given path contained wildcard characters"; case APR_EPROC_UNKNOWN: return "The process is not recognized."; case APR_EGENERAL: return "Internal error"; default: return "Error string not specified yet"; } } #ifdef OS2 #include <ctype.h> int apr_canonical_error(apr_status_t err); static char *apr_os_strerror(char* buf, apr_size_t bufsize, int err) { char result[200]; unsigned char message[HUGE_STRING_LEN]; ULONG len; char *pos; int c; if (err >= 10000 && err < 12000) { /* socket error codes */ return stuffbuffer(buf, bufsize, strerror(apr_canonical_error(err+APR_OS_START_SYSERR))); } else if (DosGetMessage(NULL, 0, message, HUGE_STRING_LEN, err, "OSO001.MSG", &len) == 0) { len--; message[len] = 0; pos = result; if (len >= sizeof(result)) len = sizeof(result-1); for (c=0; c<len; c++) { /* skip multiple whitespace */ while (apr_isspace(message[c]) && apr_isspace(message[c+1])) c++; *(pos++) = apr_isspace(message[c]) ? ' ' : message[c]; } *pos = 0; } else { sprintf(result, "OS/2 error %d", err); } /* Stuff the string into the caller supplied buffer, then return * a pointer to it. */ return stuffbuffer(buf, bufsize, result); } #elif defined(WIN32) || (defined(NETWARE) && defined(USE_WINSOCK)) static const struct { apr_status_t code; const char *msg; } gaErrorList[] = { WSAEINTR, "Interrupted system call", WSAEBADF, "Bad file number", WSAEACCES, "Permission denied", WSAEFAULT, "Bad address", WSAEINVAL, "Invalid argument", WSAEMFILE, "Too many open sockets", WSAEWOULDBLOCK, "Operation would block", WSAEINPROGRESS, "Operation now in progress", WSAEALREADY, "Operation already in progress", WSAENOTSOCK, "Socket operation on non-socket", WSAEDESTADDRREQ, "Destination address required", WSAEMSGSIZE, "Message too long", WSAEPROTOTYPE, "Protocol wrong type for socket", WSAENOPROTOOPT, "Bad protocol option", WSAEPROTONOSUPPORT, "Protocol not supported", WSAESOCKTNOSUPPORT, "Socket type not supported", WSAEOPNOTSUPP, "Operation not supported on socket", WSAEPFNOSUPPORT, "Protocol family not supported", WSAEAFNOSUPPORT, "Address family not supported", WSAEADDRINUSE, "Address already in use", WSAEADDRNOTAVAIL, "Can't assign requested address", WSAENETDOWN, "Network is down", WSAENETUNREACH, "Network is unreachable", WSAENETRESET, "Net connection reset", WSAECONNABORTED, "Software caused connection abort", WSAECONNRESET, "Connection reset by peer", WSAENOBUFS, "No buffer space available", WSAEISCONN, "Socket is already connected", WSAENOTCONN, "Socket is not connected", WSAESHUTDOWN, "Can't send after socket shutdown", WSAETOOMANYREFS, "Too many references, can't splice", WSAETIMEDOUT, "Connection timed out", WSAECONNREFUSED, "Connection refused", WSAELOOP, "Too many levels of symbolic links", WSAENAMETOOLONG, "File name too long", WSAEHOSTDOWN, "Host is down", WSAEHOSTUNREACH, "No route to host", WSAENOTEMPTY, "Directory not empty", WSAEPROCLIM, "Too many processes", WSAEUSERS, "Too many users", WSAEDQUOT, "Disc quota exceeded", WSAESTALE, "Stale NFS file handle", WSAEREMOTE, "Too many levels of remote in path", WSASYSNOTREADY, "Network system is unavailable", WSAVERNOTSUPPORTED, "Winsock version out of range", WSANOTINITIALISED, "WSAStartup not yet called", WSAEDISCON, "Graceful shutdown in progress", WSAHOST_NOT_FOUND, "Host not found", WSANO_DATA, "No host data of that type was found", 0, NULL }; static char *apr_os_strerror(char *buf, apr_size_t bufsize, apr_status_t errcode) { apr_size_t len=0, i; #ifndef NETWARE len = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errcode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ (LPTSTR) buf, (DWORD)bufsize, NULL); #endif if (!len) { for (i = 0; gaErrorList[i].msg; ++i) { if (gaErrorList[i].code == errcode) { apr_cpystrn(buf, gaErrorList[i].msg, bufsize); len = strlen(buf); break; } } } if (len) { /* FormatMessage put the message in the buffer, but it may * have embedded a newline (\r\n), and possible more than one. * Remove the newlines replacing them with a space. This is not * as visually perfect as moving all the remaining message over, * but more efficient. */ i = len; while (i) { i--; if ((buf[i] == '\r') || (buf[i] == '\n')) buf[i] = ' '; } } else { /* Windows didn't provide us with a message. Even stuff like * WSAECONNREFUSED won't get a message. */ apr_snprintf(buf, bufsize, "Unrecognized Win32 error code %d", errcode); } return buf; } #else /* On Unix, apr_os_strerror() handles error codes from the resolver * (h_errno). */ static char *apr_os_strerror(char* buf, apr_size_t bufsize, int err) { #ifdef HAVE_HSTRERROR return stuffbuffer(buf, bufsize, hstrerror(err)); #else /* HAVE_HSTRERROR */ const char *msg; switch(err) { case HOST_NOT_FOUND: msg = "Unknown host"; break; #if defined(NO_DATA) case NO_DATA: #if defined(NO_ADDRESS) && (NO_DATA != NO_ADDRESS) case NO_ADDRESS: #endif msg = "No address for host"; break; #elif defined(NO_ADDRESS) case NO_ADDRESS: msg = "No address for host"; break; #endif /* NO_DATA */ default: msg = "Unrecognized resolver error"; } return stuffbuffer(buf, bufsize, msg); #endif /* HAVE_STRERROR */ } #endif #if defined(HAVE_STRERROR_R) && defined(STRERROR_R_RC_INT) && !defined(BEOS) /* AIX and Tru64 style */ static char *native_strerror(apr_status_t statcode, char *buf, apr_size_t bufsize) { if (strerror_r(statcode, buf, bufsize) < 0) { return stuffbuffer(buf, bufsize, "APR does not understand this error code"); } else { return buf; } } #elif defined(HAVE_STRERROR_R) /* glibc style */ /* BeOS has the function available, but it doesn't provide * the prototype publically (doh!), so to avoid a build warning * we add a suitable prototype here. */ #if defined(BEOS) const char *strerror_r(apr_status_t, char *, apr_size_t); #endif static char *native_strerror(apr_status_t statcode, char *buf, apr_size_t bufsize) { const char *msg; buf[0] = '\0'; msg = strerror_r(statcode, buf, bufsize); if (buf[0] == '\0') { /* libc didn't use our buffer */ return stuffbuffer(buf, bufsize, msg); } else { return buf; } } #else /* plain old strerror(); * thread-safe on some platforms (e.g., Solaris, OS/390) */ static char *native_strerror(apr_status_t statcode, char *buf, apr_size_t bufsize) { #ifdef _WIN32_WCE static char err[32]; sprintf(err, "Native Error #%d", statcode); return stuffbuffer(buf, bufsize, err); #else const char *err = strerror(statcode); if (err) { return stuffbuffer(buf, bufsize, err); } else { return stuffbuffer(buf, bufsize, "APR does not understand this error code"); } #endif } #endif APR_DECLARE(char *) apr_strerror(apr_status_t statcode, char *buf, apr_size_t bufsize) { if (statcode < APR_OS_START_ERROR) { return native_strerror(statcode, buf, bufsize); } else if (statcode < APR_OS_START_USERERR) { return stuffbuffer(buf, bufsize, apr_error_string(statcode)); } else if (statcode < APR_OS_START_EAIERR) { return stuffbuffer(buf, bufsize, "APR does not understand this error code"); } else if (statcode < APR_OS_START_SYSERR) { #if defined(HAVE_GAI_STRERROR) statcode -= APR_OS_START_EAIERR; #if defined(NEGATIVE_EAI) statcode = -statcode; #endif return stuffbuffer(buf, bufsize, gai_strerror(statcode)); #else return stuffbuffer(buf, bufsize, "APR does not understand this error code"); #endif } else { return apr_os_strerror(buf, bufsize, statcode - APR_OS_START_SYSERR); } }
001-log4cxx
trunk/src/apr/misc/unix/errorcodes.c
C
asf20
13,714
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr_version.h" #include "apr_general.h" /* for APR_STRINGIFY */ APR_DECLARE(void) apr_version(apr_version_t *pvsn) { pvsn->major = APR_MAJOR_VERSION; pvsn->minor = APR_MINOR_VERSION; pvsn->patch = APR_PATCH_VERSION; #ifdef APR_IS_DEV_VERSION pvsn->is_dev = 1; #else pvsn->is_dev = 0; #endif } APR_DECLARE(const char *) apr_version_string(void) { return APR_VERSION_STRING; }
001-log4cxx
trunk/src/apr/misc/unix/version.c
C
asf20
1,211
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* The high resolution timer API provides access to the hardware timer * running at around 1.1MHz. The amount this changes in a time slice is * varies randomly due to system events, hardware interrupts etc */ static UCHAR randbyte_hrtimer() { QWORD t1, t2; UCHAR byte; DosTmrQueryTime(&t1); DosSleep(5); DosTmrQueryTime(&t2); byte = (t2.ulLo - t1.ulLo) & 0xFF; byte ^= (t2.ulLo - t1.ulLo) >> 8; return byte; } /* A bunch of system information like memory & process stats. * Not highly random but every bit helps.... */ static UCHAR randbyte_sysinfo() { UCHAR byte = 0; UCHAR SysVars[100]; int b; DosQuerySysInfo(1, QSV_FOREGROUND_PROCESS, SysVars, sizeof(SysVars)); for (b = 0; b < 100; b++) { byte ^= SysVars[b]; } return byte; } /* Similar in concept to randbyte_hrtimer() but accesses the CPU's internal * counters which run at the CPU's MHz speed. We get separate * idle / busy / interrupt cycle counts which should provide very good * randomness due to interference of hardware events. * This only works on newer CPUs (at least PPro or K6) and newer OS/2 versions * which is why it's run-time linked. */ static APIRET APIENTRY(*DosPerfSysCall) (ULONG ulCommand, ULONG ulParm1, ULONG ulParm2, ULONG ulParm3) = NULL; static HMODULE hDoscalls = 0; #define CMD_KI_RDCNT (0x63) typedef struct _CPUUTIL { ULONG ulTimeLow; /* Low 32 bits of time stamp */ ULONG ulTimeHigh; /* High 32 bits of time stamp */ ULONG ulIdleLow; /* Low 32 bits of idle time */ ULONG ulIdleHigh; /* High 32 bits of idle time */ ULONG ulBusyLow; /* Low 32 bits of busy time */ ULONG ulBusyHigh; /* High 32 bits of busy time */ ULONG ulIntrLow; /* Low 32 bits of interrupt time */ ULONG ulIntrHigh; /* High 32 bits of interrupt time */ } CPUUTIL; static UCHAR randbyte_perf() { UCHAR byte = 0; CPUUTIL util; int c; if (hDoscalls == 0) { char failed_module[20]; ULONG rc; rc = DosLoadModule(failed_module, sizeof(failed_module), "DOSCALLS", &hDoscalls); if (rc == 0) { rc = DosQueryProcAddr(hDoscalls, 976, NULL, (PFN *)&DosPerfSysCall); if (rc) { DosPerfSysCall = NULL; } } } if (DosPerfSysCall) { if (DosPerfSysCall(CMD_KI_RDCNT, (ULONG)&util, 0, 0) == 0) { for (c = 0; c < sizeof(util); c++) { byte ^= ((UCHAR *)&util)[c]; } } else { DosPerfSysCall = NULL; } } return byte; } static UCHAR randbyte() { return randbyte_hrtimer() ^ randbyte_sysinfo() ^ randbyte_perf(); }
001-log4cxx
trunk/src/apr/misc/unix/randbyte_os2.inc
C++
asf20
3,683
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_general.h" #include "apr_pools.h" #include "apr_signal.h" #include "apr_atomic.h" #include "apr_arch_proc_mutex.h" /* for apr_proc_mutex_unix_setup_lock() */ #include "apr_arch_internal_time.h" APR_DECLARE(apr_status_t) apr_app_initialize(int *argc, const char * const * *argv, const char * const * *env) { /* An absolute noop. At present, only Win32 requires this stub, but it's * required in order to move command arguments passed through the service * control manager into the process, and it's required to fix the char* * data passed in from win32 unicode into utf-8, win32's apr internal fmt. */ return apr_initialize(); } static int initialized = 0; APR_DECLARE(apr_status_t) apr_initialize(void) { apr_pool_t *pool; apr_status_t status; if (initialized++) { return APR_SUCCESS; } #if !defined(BEOS) && !defined(OS2) apr_proc_mutex_unix_setup_lock(); apr_unix_setup_time(); #endif if ((status = apr_pool_initialize()) != APR_SUCCESS) return status; if (apr_pool_create(&pool, NULL) != APR_SUCCESS) { return APR_ENOPOOL; } apr_pool_tag(pool, "apr_initialize"); /* apr_atomic_init() used to be called from here aswell. * Pools rely on mutexes though, which can be backed by * atomics. Due to this circular dependency * apr_pool_initialize() is taking care of calling * apr_atomic_init() at the correct time. */ apr_signal_init(pool); return APR_SUCCESS; } APR_DECLARE_NONSTD(void) apr_terminate(void) { initialized--; if (initialized) { return; } apr_pool_terminate(); } APR_DECLARE(void) apr_terminate2(void) { apr_terminate(); }
001-log4cxx
trunk/src/apr/misc/unix/start.c
C
asf20
2,641
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define APR_WANT_MEMFUNC #include "apr_want.h" #include "apr_general.h" #include "apr_arch_misc.h" #include <sys/stat.h> #if APR_HAVE_SYS_TYPES_H #include <sys/types.h> #endif #if APR_HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #if APR_HAVE_FCNTL_H #include <fcntl.h> #endif #if APR_HAVE_UNISTD_H #include <unistd.h> #endif #if APR_HAVE_SYS_UN_H #include <sys/un.h> #endif #if defined(HAVE_UUID_H) #include <uuid.h> #elif defined(HAVE_UUID_UUID_H) #include <uuid/uuid.h> #elif defined(HAVE_SYS_UUID_H) #include <sys/uuid.h> #endif #ifndef SHUT_RDWR #define SHUT_RDWR 2 #endif #if APR_HAS_OS_UUID #if defined(HAVE_UUID_CREATE) APR_DECLARE(apr_status_t) apr_os_uuid_get(unsigned char *uuid_data) { uint32_t rv; uuid_t g; uuid_create(&g, &rv); if (rv != uuid_s_ok) return APR_EGENERAL; memcpy(uuid_data, &g, sizeof(uuid_t)); return APR_SUCCESS; } #elif defined(HAVE_UUID_GENERATE) APR_DECLARE(apr_status_t) apr_os_uuid_get(unsigned char *uuid_data) { uuid_t g; uuid_generate(g); memcpy(uuid_data, g, sizeof(uuid_t)); return APR_SUCCESS; } #endif #endif /* APR_HAS_OS_UUID */ #if APR_HAS_RANDOM APR_DECLARE(apr_status_t) apr_generate_random_bytes(unsigned char *buf, apr_size_t length) { #ifdef DEV_RANDOM int fd = -1; /* On BSD/OS 4.1, /dev/random gives out 8 bytes at a time, then * gives EOF, so reading 'length' bytes may require opening the * device several times. */ do { apr_ssize_t rc; if (fd == -1) if ((fd = open(DEV_RANDOM, O_RDONLY)) == -1) return errno; rc = read(fd, buf, length); if (rc < 0) { int errnum = errno; close(fd); return errnum; } else if (rc == 0) { close(fd); fd = -1; /* force open() again */ } else { buf += rc; length -= rc; } } while (length > 0); close(fd); #elif defined(OS2) static UCHAR randbyte(); unsigned int idx; for (idx=0; idx<length; idx++) buf[idx] = randbyte(); #elif defined(HAVE_EGD) /* use EGD-compatible socket daemon (such as EGD or PRNGd). * message format: * 0x00 (get entropy level) * 0xMM (msb) 0xmm 0xll 0xLL (lsb) * 0x01 (read entropy nonblocking) 0xNN (bytes requested) * 0xMM (bytes granted) MM bytes * 0x02 (read entropy blocking) 0xNN (bytes desired) * [block] NN bytes * 0x03 (write entropy) 0xMM 0xLL (bits of entropy) 0xNN (bytes of data) * NN bytes * (no response - write only) * 0x04 (report PID) * 0xMM (length of PID string, not null-terminated) MM chars */ static const char *egd_sockets[] = { EGD_DEFAULT_SOCKET, NULL }; const char **egdsockname = NULL; int egd_socket, egd_path_len, rv, bad_errno; struct sockaddr_un addr; apr_socklen_t egd_addr_len; apr_size_t resp_expected; unsigned char req[2], resp[255]; unsigned char *curbuf = buf; for (egdsockname = egd_sockets; *egdsockname && length > 0; egdsockname++) { egd_path_len = strlen(*egdsockname); if (egd_path_len > sizeof(addr.sun_path)) { return APR_EINVAL; } memset(&addr, 0, sizeof(struct sockaddr_un)); addr.sun_family = AF_UNIX; memcpy(addr.sun_path, *egdsockname, egd_path_len); egd_addr_len = APR_OFFSETOF(struct sockaddr_un, sun_path) + egd_path_len; egd_socket = socket(PF_UNIX, SOCK_STREAM, 0); if (egd_socket == -1) { return errno; } rv = connect(egd_socket, (struct sockaddr*)&addr, egd_addr_len); if (rv == -1) { bad_errno = errno; continue; } /* EGD can only return 255 bytes of data at a time. Silly. */ while (length > 0) { apr_ssize_t srv; req[0] = 2; /* We'll block for now. */ req[1] = length > 255 ? 255: length; srv = write(egd_socket, req, 2); if (srv == -1) { bad_errno = errno; shutdown(egd_socket, SHUT_RDWR); close(egd_socket); break; } if (srv != 2) { shutdown(egd_socket, SHUT_RDWR); close(egd_socket); return APR_EGENERAL; } resp_expected = req[1]; srv = read(egd_socket, resp, resp_expected); if (srv == -1) { bad_errno = errno; shutdown(egd_socket, SHUT_RDWR); close(egd_socket); return bad_errno; } memcpy(curbuf, resp, srv); curbuf += srv; length -= srv; } shutdown(egd_socket, SHUT_RDWR); close(egd_socket); } if (length > 0) { /* We must have iterated through the list of sockets, * and no go. Return the errno. */ return bad_errno; } #elif defined(HAVE_TRUERAND) /* use truerand */ extern int randbyte(void); /* from the truerand library */ unsigned int idx; /* this will increase the startup time of the server, unfortunately... * (generating 20 bytes takes about 8 seconds) */ for (idx=0; idx<length; idx++) buf[idx] = (unsigned char) randbyte(); #endif /* DEV_RANDOM */ return APR_SUCCESS; } #undef STR #undef XSTR #ifdef OS2 #include "randbyte_os2.inc" #endif #endif /* APR_HAS_RANDOM */
001-log4cxx
trunk/src/apr/misc/unix/rand.c
C
asf20
6,444
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define APR_WANT_STRFUNC #include "apr_want.h" #include "apr.h" #include "apr_private.h" #include "apr_env.h" #if APR_HAVE_UNISTD_H #include <unistd.h> #endif #if APR_HAVE_STDLIB_H #include <stdlib.h> #endif APR_DECLARE(apr_status_t) apr_env_get(char **value, const char *envvar, apr_pool_t *pool) { #ifdef HAVE_GETENV char *val = getenv(envvar); if (!val) return APR_ENOENT; *value = val; return APR_SUCCESS; #else return APR_ENOTIMPL; #endif } APR_DECLARE(apr_status_t) apr_env_set(const char *envvar, const char *value, apr_pool_t *pool) { #if defined(HAVE_SETENV) if (0 > setenv(envvar, value, 1)) return APR_ENOMEM; return APR_SUCCESS; #elif defined(HAVE_PUTENV) apr_size_t elen = strlen(envvar); apr_size_t vlen = strlen(value); char *env = apr_palloc(pool, elen + vlen + 2); char *p = env + elen; memcpy(env, envvar, elen); *p++ = '='; memcpy(p, value, vlen); p[vlen] = '\0'; if (0 > putenv(env)) return APR_ENOMEM; return APR_SUCCESS; #else return APR_ENOTIMPL; #endif } APR_DECLARE(apr_status_t) apr_env_delete(const char *envvar, apr_pool_t *pool) { #ifdef HAVE_UNSETENV unsetenv(envvar); return APR_SUCCESS; #else /* hint: some platforms allow envvars to be unset via * putenv("varname")... that isn't Single Unix spec, * but if your platform doesn't have unsetenv() it is * worth investigating and potentially adding a * configure check to decide when to use that form of * putenv() here */ return APR_ENOTIMPL; #endif }
001-log4cxx
trunk/src/apr/misc/unix/env.c
C
asf20
2,574
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <netware.h> #include <library.h> #include <nks/synch.h> #ifdef USE_WINSOCK #include "novsock2.h" #endif #include "apr_pools.h" #include "apr_private.h" /* library-private data...*/ int gLibId = -1; void *gLibHandle = (void *) NULL; NXMutex_t *gLibLock = (NXMutex_t *) NULL; /* internal library function prototypes...*/ int DisposeLibraryData(void *); int _NonAppStart ( void *NLMHandle, void *errorScreen, const char *cmdLine, const char *loadDirPath, size_t uninitializedDataLength, void *NLMFileHandle, int (*readRoutineP)( int conn, void *fileHandle, size_t offset, size_t nbytes, size_t *bytesRead, void *buffer ), size_t customDataOffset, size_t customDataSize, int messageCount, const char **messages ) { #ifdef USE_WINSOCK WSADATA wsaData; #endif apr_status_t status; NX_LOCK_INFO_ALLOC(liblock, "Per-Application Data Lock", 0); #pragma unused(cmdLine) #pragma unused(loadDirPath) #pragma unused(uninitializedDataLength) #pragma unused(NLMFileHandle) #pragma unused(readRoutineP) #pragma unused(customDataOffset) #pragma unused(customDataSize) #pragma unused(messageCount) #pragma unused(messages) gLibId = register_library(DisposeLibraryData); if (gLibId < -1) { OutputToScreen(errorScreen, "Unable to register library with kernel.\n"); return -1; } gLibHandle = NLMHandle; gLibLock = NXMutexAlloc(0, 0, &liblock); if (!gLibLock) { OutputToScreen(errorScreen, "Unable to allocate library data lock.\n"); return -1; } apr_netware_setup_time(); if ((status = apr_pool_initialize()) != APR_SUCCESS) return status; #ifdef USE_WINSOCK return WSAStartup((WORD) MAKEWORD(2, 0), &wsaData); #else return 0; #endif } void _NonAppStop( void ) { apr_pool_terminate(); #ifdef USE_WINSOCK WSACleanup(); #endif unregister_library(gLibId); NXMutexFree(gLibLock); } int _NonAppCheckUnload( void ) { return 0; } int register_NLM(void *NLMHandle) { APP_DATA *app_data = (APP_DATA*) get_app_data(gLibId); NXLock(gLibLock); if (!app_data) { app_data = (APP_DATA*)library_malloc(gLibHandle, sizeof(APP_DATA)); if (app_data) { memset (app_data, 0, sizeof(APP_DATA)); set_app_data(gLibId, app_data); app_data->gs_nlmhandle = NLMHandle; } } if (app_data && (!app_data->initialized)) { app_data->initialized = 1; NXUnlock(gLibLock); return 0; } NXUnlock(gLibLock); return 1; } int unregister_NLM(void *NLMHandle) { APP_DATA *app_data = (APP_DATA*) get_app_data(gLibId); NXLock(gLibLock); if (app_data) { app_data->initialized = 0; NXUnlock(gLibLock); return 0; } NXUnlock(gLibLock); return 1; } int DisposeLibraryData(void *data) { if (data) { library_free(data); } return 0; } int setGlobalPool(void *data) { APP_DATA *app_data = (APP_DATA*) get_app_data(gLibId); NXLock(gLibLock); if (app_data && !app_data->gPool) { app_data->gPool = data; } NXUnlock(gLibLock); return 1; } void* getGlobalPool() { APP_DATA *app_data = (APP_DATA*) get_app_data(gLibId); if (app_data) { return app_data->gPool; } return NULL; }
001-log4cxx
trunk/src/apr/misc/netware/libprews.c
C
asf20
4,251
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "apr.h" #include "apr_strings.h" #include "apr_portable.h" /* static struct utsname sysinfo; */ /* XXX This needs to be fixed to produce the correct system language */ APR_DECLARE(const char*) apr_os_default_encoding (apr_pool_t *pool) { return apr_pstrdup(pool, "CP1252"); } APR_DECLARE(const char*) apr_os_locale_encoding (apr_pool_t *pool) { return apr_os_default_encoding(pool); }
001-log4cxx
trunk/src/apr/misc/netware/charset.c
C
asf20
1,207