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
/* 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. */ #ifndef DSO_H #define DSO_H #include "apr_private.h" #include "apr_general.h" #include "apr_pools.h" #include "apr_dso.h" #include "apr.h" #if APR_HAS_DSO #include <dll.h> struct apr_dso_handle_t { dllhandle *handle; /* Handle to the DSO loaded */ int failing_errno; /* Don't save the buffer returned by strerror(); it gets reused */ apr_pool_t *pool; }; #endif #endif
001-log4cxx
trunk/src/apr/include/arch/os390/apr_arch_dso.h
C
asf20
1,248
/* 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. */ #ifndef DSO_H #define DSO_H #include "apr_private.h" #include "apr_general.h" #include "apr_pools.h" #include "apr_dso.h" #include "apr.h" #include <dlfcn.h> typedef struct sym_list sym_list; struct sym_list { sym_list *next; char *symbol; }; struct apr_dso_handle_t { apr_pool_t *pool; void *handle; const char *errormsg; sym_list *symbols; char *path; }; #endif
001-log4cxx
trunk/src/apr/include/arch/netware/apr_arch_dso.h
C
asf20
1,217
/* 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. */ #ifndef PROC_MUTEX_H #define PROC_MUTEX_H #include "apr_proc_mutex.h" #include "apr_thread_mutex.h" struct apr_proc_mutex_t { apr_pool_t *pool; apr_thread_mutex_t *mutex; }; #endif /* PROC_MUTEX_H */
001-log4cxx
trunk/src/apr/include/arch/netware/apr_arch_proc_mutex.h
C
asf20
1,013
#ifndef __pre_nw__ #define __pre_nw__ #include <stdint.h> #ifndef __GNUC__ #pragma precompile_target "precomp.mch" #endif #define NETWARE #define N_PLAT_NLM /* 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 FAR #define far /* no-op for Codewarrior C compiler; a functions are cdecl by default */ #define cdecl /* if we have wchar_t enabled in C++, predefine this type to avoid a conflict in Novell's header files */ #ifndef __GNUC__ #ifndef DOXYGEN #if (__option(cplusplus) && __option(wchar_type)) #define _WCHAR_T #endif #endif #endif /* C9X defintion used by MSL C++ library */ #define DECIMAL_DIG 17 /* some code may want to use the MS convention for long long */ #ifndef __int64 #define __int64 long long #endif /* expat version */ #define VERSION "expat_1.95.1" #define EXPAT_MAJOR_VERSION 1 #define EXPAT_MINOR_VERSION 95 #define EXPAT_EDIT 2 #define XML_MAJOR_VERSION EXPAT_MAJOR_VERSION #define XML_MINOR_VERSION EXPAT_MINOR_VERSION #define XML_MICRO_VERSION EXPAT_EDIT #endif
001-log4cxx
trunk/src/apr/include/arch/netware/apr_arch_pre_nw.h
C
asf20
1,804
/* 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. */ #ifndef NETWORK_IO_H #ifdef USE_WINSOCK /* Making sure that we include the correct networkio.h since the the project file is configured to first look for headers in arch/netware and then arch/unix. But in this specific case we want arch/win32. */ #include <../win32/apr_arch_networkio.h> #else #include <../unix/apr_arch_networkio.h> #endif #endif /* ! NETWORK_IO_H */
001-log4cxx
trunk/src/apr/include/arch/netware/apr_arch_networkio.h
C
asf20
1,186
/* 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. */ #ifndef GLOBAL_MUTEX_H #define GLOBAL_MUTEX_H #include "apr_global_mutex.h" #include "apr_thread_mutex.h" struct apr_global_mutex_t { apr_pool_t *pool; apr_thread_mutex_t *mutex; }; #endif /* GLOBAL_MUTEX_H */
001-log4cxx
trunk/src/apr/include/arch/netware/apr_arch_global_mutex.h
C
asf20
1,023
/* 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. */ #ifndef TIME_INTERNAL_H #define TIME_INTERNAL_H #include "apr.h" #define TZONE (*___timezone()) void apr_netware_setup_time(void); #endif /* TIME_INTERNAL_H */
001-log4cxx
trunk/src/apr/include/arch/netware/apr_arch_internal_time.h
C
asf20
975
/* 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_thread_proc.h" #include "apr_file_io.h" #include <sys/wait.h> #ifndef THREAD_PROC_H #define THREAD_PROC_H #define SHELL_PATH "" #define APR_DEFAULT_STACK_SIZE 65536 struct apr_thread_t { apr_pool_t *pool; NXContext_t ctx; NXThreadId_t td; char *thread_name; apr_int32_t cancel; apr_int32_t cancel_how; void *data; apr_thread_start_t func; apr_status_t exitval; }; struct apr_threadattr_t { apr_pool_t *pool; apr_size_t stack_size; apr_int32_t detach; char *thread_name; }; struct apr_threadkey_t { apr_pool_t *pool; NXKey_t key; }; struct apr_procattr_t { apr_pool_t *pool; apr_file_t *parent_in; apr_file_t *child_in; apr_file_t *parent_out; apr_file_t *child_out; apr_file_t *parent_err; apr_file_t *child_err; char *currdir; apr_int32_t cmdtype; apr_int32_t detached; apr_int32_t addrspace; }; struct apr_thread_once_t { unsigned long value; }; //struct apr_proc_t { // apr_pool_t *pool; // pid_t pid; // apr_procattr_t *attr; //}; #endif /* ! THREAD_PROC_H */
001-log4cxx
trunk/src/apr/include/arch/netware/apr_arch_threadproc.h
C
asf20
1,925
/* 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. */ #ifndef THREAD_RWLOCK_H #define THREAD_RWLOCK_H #include "apr_thread_rwlock.h" #include <nks/synch.h> struct apr_thread_rwlock_t { apr_pool_t *pool; NXRwLock_t *rwlock; }; #endif /* THREAD_RWLOCK_H */
001-log4cxx
trunk/src/apr/include/arch/netware/apr_arch_thread_rwlock.h
C
asf20
1,014
/* 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. */ #ifndef THREAD_MUTEX_H #define THREAD_MUTEX_H #include "apr_thread_mutex.h" #include <nks/synch.h> struct apr_thread_mutex_t { apr_pool_t *pool; NXMutex_t *mutex; }; #endif /* THREAD_MUTEX_H */
001-log4cxx
trunk/src/apr/include/arch/netware/apr_arch_thread_mutex.h
C
asf20
1,007
/* 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. */ #ifndef THREAD_COND_H #define THREAD_COND_H #include "apr_thread_cond.h" #include <nks/synch.h> struct apr_thread_cond_t { apr_pool_t *pool; NXCond_t *cond; }; #endif /* THREAD_COND_H */
001-log4cxx
trunk/src/apr/include/arch/netware/apr_arch_thread_cond.h
C
asf20
1,000
/* 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. */ /* * Note: * This is the windows specific autoconf-like config file * which unix would create at build time. */ #ifdef NETWARE #ifndef APR_PRIVATE_H #define APR_PRIVATE_H /* Include the public APR symbols, include our idea of the 'right' * subset of the Windows.h header. This saves us repetition. */ #include "apr.h" #include <sys/types.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <library.h> #include <netware.h> /* Use this section to define all of the HAVE_FOO_H * that are required to build properly. */ #define HAVE_DLFCN_H 1 #define HAVE_LIMITS_H 1 #define HAVE_SIGNAL_H 1 #define HAVE_STDDEF_H 1 #define HAVE_STDLIB_H 1 #ifndef USE_WINSOCK #define HAVE_SYS_SELECT_H 1 #define HAVE_WRITEV 1 #endif #define HAVE_SYS_STAT_H 1 #define HAVE_SYS_MMAN_H 1 #define HAVE_FCNTL_H 1 #define HAVE_ICONV_H 1 #define HAVE_UTIME_H 1 #define HAVE_STRICMP 1 #define HAVE_STRNICMP 1 #define HAVE_STRDUP 1 #define HAVE_STRSTR 1 #define HAVE_MEMCHR 1 #define HAVE_CALLOC 1 #define HAVE_UTIME 1 #define HAVE_GETENV 1 #define HAVE_SETENV 1 #define HAVE_UNSETENV 1 #define HAVE_WRITEV 1 /* 64-bit integer conversion function */ #define APR_INT64_STRFN strtoll /*#define DSO_USE_DLFCN */ #ifdef NW_BUILD_IPV6 #define HAVE_GETADDRINFO 1 #define HAVE_GETNAMEINFO 1 #endif /* 1 is used for SIGABRT on netware */ /* 2 is used for SIGFPE on netware */ /* 3 is used for SIGILL on netware */ /* 4 is used for SIGINT on netware */ /* 5 is used for SIGSEGV on netware */ /* 6 is used for SIGTERM on netware */ /* 7 is used for SIGPOLL on netware */ #define SIGKILL 11 #define SA_NOCLDSTOP 12 #define SIGALRM 13 #define SIGCHLD 14 #define SIGCONT 15 #define SIGHUP 16 #define SIGPIPE 17 #define SIGQUIT 18 #define SIGSTOP 19 #define SIGTSTP 20 #define SIGTTIN 21 #define SIGTTOU 22 #define SIGUSR1 23 #define SIGUSR2 24 #define SIGTRAP 25 #define SIGIOT 26 #define SIGBUS 27 #define SIGSTKFLT 28 #define SIGURG 29 #define SIGXCPU 30 #define SIGXFSZ 31 #define SIGVTALRM 32 #define SIGPROF 33 #define SIGWINCH 34 #define SIGIO 35 #if 0 #define __attribute__(__x) /* APR COMPATABILITY FUNCTIONS * This section should be used to define functions and * macros which are need to make Windows features look * like POSIX features. */ typedef void (Sigfunc)(int); #endif #define strcasecmp(s1, s2) stricmp(s1, s2) #define Sleep(t) delay(t) #define lstat(a,b) stat(a,b) #define _getch() getcharacter() #define SIZEOF_SHORT 2 #define SIZEOF_INT 4 #define SIZEOF_LONGLONG 8 #define SIZEOF_CHAR 1 #define SIZEOF_SSIZE_T SIZEOF_INT void netware_pool_proc_cleanup (); /* NLM registration routines for managing which NLMs are using the library. */ int register_NLM(void *NLMHandle); int unregister_NLM(void *NLMHandle); /* Application global data management */ extern int gLibId; extern void *gLibHandle; typedef struct app_data { int initialized; void* gPool; void* gs_aHooksToSort; void* gs_phOptionalHooks; void* gs_phOptionalFunctions; void* gs_nlmhandle; rtag_t gs_startup_rtag; rtag_t gs_socket_rtag; rtag_t gs_lookup_rtag; rtag_t gs_event_rtag; rtag_t gs_pcp_rtag; } APP_DATA; int setGlobalPool(void *data); void* getGlobalPool(); int setStatCache(void *data); void* getStatCache(); /* Redefine malloc to use the library malloc call so that all of the memory resources will be owned and can be shared by the library. */ #undef malloc #define malloc(x) library_malloc(gLibHandle,x) #if APR_HAS_LARGE_FILES #define APR_OFF_T_STRFN strtoll #else #define APR_OFF_T_STRFN strtol #endif /* used to check DWORD overflow for 64bit compiles */ #define APR_DWORD_MAX 0xFFFFFFFFUL /* * Include common private declarations. */ #include "../apr_private_common.h" #endif /*APR_PRIVATE_H*/ #endif /*NETWARE*/
001-log4cxx
trunk/src/apr/include/arch/netware/apr_private.h
C
asf20
5,014
/* 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. */ #ifndef FILE_IO_H #define FILE_IO_H #include "apr.h" #include "apr_private.h" #include "apr_general.h" #include "apr_tables.h" #include "apr_file_io.h" #include "apr_file_info.h" #include "apr_errno.h" #include "apr_lib.h" #include "apr_poll.h" /* System headers the file I/O library needs */ #if APR_HAVE_FCNTL_H #include <fcntl.h> #endif #if APR_HAVE_SYS_TYPES_H #include <sys/types.h> #endif #if APR_HAVE_ERRNO_H #include <errno.h> #endif #if APR_HAVE_STRING_H #include <string.h> #endif #if APR_HAVE_STRINGS_H #include <strings.h> #endif #if APR_HAVE_DIRENT_H #include <dirent.h> #endif #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #if APR_HAVE_UNISTD_H #include <unistd.h> #endif #if APR_HAVE_STDIO_H #include <stdio.h> #endif #if APR_HAVE_STDLIB_H #include <stdlib.h> #endif #if APR_HAVE_SYS_UIO_H #include <sys/uio.h> #endif #if APR_HAVE_SYS_TIME_H #include <sys/time.h> #endif #include <fsio.h> /* End System headers */ #define APR_FILE_BUFSIZE 4096 #if APR_HAS_LARGE_FILES #define lseek(f,o,w) lseek64(f,o,w) #define ftruncate(f,l) ftruncate64(f,l) #endif typedef struct stat struct_stat; struct apr_file_t { apr_pool_t *pool; int filedes; char *fname; apr_int32_t flags; int eof_hit; int is_pipe; apr_interval_time_t timeout; int buffered; enum {BLK_UNKNOWN, BLK_OFF, BLK_ON } blocking; int ungetchar; /* Last char provided by an unget op. (-1 = no char)*/ /* if there is a timeout set, then this pollset is used */ apr_pollset_t *pollset; /* Stuff for buffered mode */ char *buffer; int bufpos; /* Read/Write position in buffer */ apr_off_t dataRead; /* amount of valid data read into buffer */ int direction; /* buffer being used for 0 = read, 1 = write */ apr_off_t filePtr; /* position in file of handle */ #if APR_HAS_THREADS struct apr_thread_mutex_t *thlock; #endif }; struct apr_dir_t { apr_pool_t *pool; char *dirname; DIR *dirstruct; struct dirent *entry; }; typedef struct apr_stat_entry_t apr_stat_entry_t; struct apr_stat_entry_t { struct stat info; char *casedName; apr_time_t expire; NXPathCtx_t pathCtx; }; #define MAX_SERVER_NAME 64 #define MAX_VOLUME_NAME 64 #define MAX_PATH_NAME 256 #define MAX_FILE_NAME 256 #define DRIVE_ONLY 1 /* If the user passes d: vs. D: (or //mach/share vs. //MACH/SHARE), * we need to fold the case to canonical form. This function is * supposed to do so. */ apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p); /* This function check to see of the given path includes a drive/volume * specifier. If the _only_ parameter is set to DRIVE_ONLY then it * check to see of the path only contains a drive/volume specifier and * nothing else. */ apr_status_t filepath_has_drive(const char *rootpath, int only, apr_pool_t *p); /* This function compares the drive/volume specifiers for each given path. * It returns zero if they match or non-zero if not. */ apr_status_t filepath_compare_drive(const char *path1, const char *path2, apr_pool_t *p); apr_status_t apr_unix_file_cleanup(void *); #endif /* ! FILE_IO_H */
001-log4cxx
trunk/src/apr/include/arch/netware/apr_arch_file_io.h
C
asf20
4,000
/* 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. */ #ifndef DSO_H #define DSO_H #include "apr_private.h" #include "apr_general.h" #include "apr_pools.h" #include "apr_dso.h" #include "apr.h" #if APR_HAS_DSO void *dlopen(const char *path, int mode); void *dlsym(void *handle, const char *symbol); const char *dlerror(void); int dlclose(void *handle); struct apr_dso_handle_t { apr_pool_t *pool; void *handle; const char *errormsg; }; #endif #endif
001-log4cxx
trunk/src/apr/include/arch/aix/apr_arch_dso.h
C
asf20
1,223
/* 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. */ #ifndef DSO_H #define DSO_H #include "apr_private.h" #include "apr_general.h" #include "apr_pools.h" #include "apr_dso.h" #include "apr.h" #if APR_HAS_DSO struct apr_dso_handle_t { apr_pool_t *cont; /* Context for returning error strings */ HMODULE handle; /* Handle to the DSO loaded */ apr_status_t load_error; char *failed_module; }; #endif #endif
001-log4cxx
trunk/src/apr/include/arch/os2/apr_arch_dso.h
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. */ #ifndef PROC_MUTEX_H #define PROC_MUTEX_H #include "apr_proc_mutex.h" #include "apr_file_io.h" struct apr_proc_mutex_t { apr_pool_t *pool; HMTX hMutex; TID owner; int lock_count; }; #endif /* PROC_MUTEX_H */
001-log4cxx
trunk/src/apr/include/arch/os2/apr_arch_proc_mutex.h
C
asf20
1,029
/* 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. */ #ifndef NETWORK_IO_H #define NETWORK_IO_H #include "apr_private.h" #include "apr_network_io.h" #include "apr_general.h" #include "apr_arch_os2calls.h" #include "apr_poll.h" #if APR_HAVE_NETDB_H #include <netdb.h> #endif typedef struct sock_userdata_t sock_userdata_t; struct sock_userdata_t { sock_userdata_t *next; const char *key; void *data; }; struct apr_socket_t { apr_pool_t *pool; int socketdes; int type; int protocol; apr_sockaddr_t *local_addr; apr_sockaddr_t *remote_addr; apr_interval_time_t timeout; int nonblock; int local_port_unknown; int local_interface_unknown; int remote_addr_unknown; apr_int32_t options; apr_int32_t inherit; sock_userdata_t *userdata; /* if there is a timeout set, then this pollset is used */ apr_pollset_t *pollset; }; /* Error codes returned from sock_errno() */ #define SOCBASEERR 10000 #define SOCEPERM (SOCBASEERR+1) /* Not owner */ #define SOCESRCH (SOCBASEERR+3) /* No such process */ #define SOCEINTR (SOCBASEERR+4) /* Interrupted system call */ #define SOCENXIO (SOCBASEERR+6) /* No such device or address */ #define SOCEBADF (SOCBASEERR+9) /* Bad file number */ #define SOCEACCES (SOCBASEERR+13) /* Permission denied */ #define SOCEFAULT (SOCBASEERR+14) /* Bad address */ #define SOCEINVAL (SOCBASEERR+22) /* Invalid argument */ #define SOCEMFILE (SOCBASEERR+24) /* Too many open files */ #define SOCEPIPE (SOCBASEERR+32) /* Broken pipe */ #define SOCEOS2ERR (SOCBASEERR+100) /* OS/2 Error */ const char *apr_inet_ntop(int af, const void *src, char *dst, apr_size_t size); int apr_inet_pton(int af, const char *src, void *dst); void apr_sockaddr_vars_set(apr_sockaddr_t *, int, apr_port_t); #endif /* ! NETWORK_IO_H */
001-log4cxx
trunk/src/apr/include/arch/os2/apr_arch_networkio.h
C
asf20
2,853
/* 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_errno.h" #include <sys/types.h> #include <sys/socket.h> extern int (*apr_os2_socket)(int, int, int); extern int (*apr_os2_select)(int *, int, int, int, long); extern int (*apr_os2_sock_errno)(); extern int (*apr_os2_accept)(int, struct sockaddr *, int *); extern int (*apr_os2_bind)(int, struct sockaddr *, int); extern int (*apr_os2_connect)(int, struct sockaddr *, int); extern int (*apr_os2_getpeername)(int, struct sockaddr *, int *); extern int (*apr_os2_getsockname)(int, struct sockaddr *, int *); extern int (*apr_os2_getsockopt)(int, int, int, char *, int *); extern int (*apr_os2_ioctl)(int, int, caddr_t, int); extern int (*apr_os2_listen)(int, int); extern int (*apr_os2_recv)(int, char *, int, int); extern int (*apr_os2_send)(int, const char *, int, int); extern int (*apr_os2_setsockopt)(int, int, int, char *, int); extern int (*apr_os2_shutdown)(int, int); extern int (*apr_os2_soclose)(int); extern int (*apr_os2_writev)(int, struct iovec *, int); extern int (*apr_os2_sendto)(int, const char *, int, int, const struct sockaddr *, int); extern int (*apr_os2_recvfrom)(int, char *, int, int, struct sockaddr *, int *); #define socket apr_os2_socket #define select apr_os2_select #define sock_errno apr_os2_sock_errno #define accept apr_os2_accept #define bind apr_os2_bind #define connect apr_os2_connect #define getpeername apr_os2_getpeername #define getsockname apr_os2_getsockname #define getsockopt apr_os2_getsockopt #define ioctl apr_os2_ioctl #define listen apr_os2_listen #define recv apr_os2_recv #define send apr_os2_send #define setsockopt apr_os2_setsockopt #define shutdown apr_os2_shutdown #define soclose apr_os2_soclose #define writev apr_os2_writev #define sendto apr_os2_sendto #define recvfrom apr_os2_recvfrom
001-log4cxx
trunk/src/apr/include/arch/os2/apr_arch_os2calls.h
C
asf20
2,564
/* 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_thread_proc.h" #include "apr_file_io.h" #ifndef THREAD_PROC_H #define THREAD_PROC_H #define APR_THREADATTR_DETACHED 1 #define SHELL_PATH "cmd.exe" #define APR_THREAD_STACKSIZE 65536 struct apr_threadattr_t { apr_pool_t *pool; unsigned long attr; apr_size_t stacksize; }; struct apr_thread_t { apr_pool_t *pool; struct apr_threadattr_t *attr; unsigned long tid; apr_thread_start_t func; void *data; apr_status_t exitval; }; struct apr_threadkey_t { apr_pool_t *pool; unsigned long *key; }; struct apr_procattr_t { apr_pool_t *pool; apr_file_t *parent_in; apr_file_t *child_in; apr_file_t *parent_out; apr_file_t *child_out; apr_file_t *parent_err; apr_file_t *child_err; char *currdir; apr_int32_t cmdtype; apr_int32_t detached; }; struct apr_thread_once_t { unsigned long sem; char hit; }; #endif /* ! THREAD_PROC_H */
001-log4cxx
trunk/src/apr/include/arch/os2/apr_arch_threadproc.h
C
asf20
1,736
/* 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. */ #ifndef THREAD_RWLOCK_H #define THREAD_RWLOCK_H #include "apr_thread_rwlock.h" #include "apr_file_io.h" struct apr_thread_rwlock_t { apr_pool_t *pool; int readers; HMTX write_lock; HEV read_done; }; #endif /* THREAD_RWLOCK_H */
001-log4cxx
trunk/src/apr/include/arch/os2/apr_arch_thread_rwlock.h
C
asf20
1,049
/* 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. */ #ifndef THREAD_MUTEX_H #define THREAD_MUTEX_H #include "apr_thread_mutex.h" #include "apr_file_io.h" struct apr_thread_mutex_t { apr_pool_t *pool; HMTX hMutex; }; #endif /* THREAD_MUTEX_H */
001-log4cxx
trunk/src/apr/include/arch/os2/apr_arch_thread_mutex.h
C
asf20
1,004
/* 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. */ #ifndef THREAD_COND_H #define THREAD_COND_H #include "apr_thread_cond.h" #include "apr_file_io.h" struct apr_thread_cond_t { apr_pool_t *pool; }; #endif /* THREAD_COND_H */
001-log4cxx
trunk/src/apr/include/arch/os2/apr_arch_thread_cond.h
C
asf20
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. */ #ifndef FILE_IO_H #define FILE_IO_H #include "apr_private.h" #include "apr_general.h" #include "apr_thread_mutex.h" #include "apr_file_io.h" #include "apr_file_info.h" #include "apr_errno.h" #include "apr_poll.h" /* We have an implementation of mkstemp but it's not very multi-threading * friendly & is part of the POSIX emulation rather than native so don't * use it. */ #undef HAVE_MKSTEMP #define APR_FILE_BUFSIZE 4096 struct apr_file_t { apr_pool_t *pool; HFILE filedes; char * fname; int isopen; int buffered; int eof_hit; apr_int32_t flags; int timeout; int pipe; HEV pipeSem; enum { BLK_UNKNOWN, BLK_OFF, BLK_ON } blocking; /* Stuff for buffered mode */ char *buffer; int bufpos; // Read/Write position in buffer unsigned long dataRead; // amount of valid data read into buffer int direction; // buffer being used for 0 = read, 1 = write unsigned long filePtr; // position in file of handle apr_thread_mutex_t *mutex;// mutex semaphore, must be owned to access the above fields }; struct apr_dir_t { apr_pool_t *pool; char *dirname; ULONG handle; FILEFINDBUF3 entry; int validentry; }; apr_status_t apr_file_cleanup(void *); apr_status_t apr_os2_time_to_apr_time(apr_time_t *result, FDATE os2date, FTIME os2time); apr_status_t apr_apr_time_to_os2_time(FDATE *os2date, FTIME *os2time, apr_time_t aprtime); /* see win32/fileio.h for description of these */ extern const char c_is_fnchar[256]; #define IS_FNCHAR(c) c_is_fnchar[(unsigned char)c] apr_status_t filepath_root_test(char *path, apr_pool_t *p); apr_status_t filepath_drive_get(char **rootpath, char drive, apr_int32_t flags, apr_pool_t *p); apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p); #endif /* ! FILE_IO_H */
001-log4cxx
trunk/src/apr/include/arch/os2/apr_arch_file_io.h
C
asf20
2,756
/* 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. */ /* * This file contains private declarations common to all architectures. */ #ifndef APR_PRIVATE_COMMON_H #define APR_PRIVATE_COMMON_H #include "apr_pools.h" #include "apr_tables.h" apr_status_t apr_filepath_list_split_impl(apr_array_header_t **pathelts, const char *liststr, char separator, apr_pool_t *p); apr_status_t apr_filepath_list_merge_impl(char **liststr, apr_array_header_t *pathelts, char separator, apr_pool_t *p); /* temporary defines to handle 64bit compile mismatches */ #define APR_INT_TRUNC_CAST int #define APR_UINT32_TRUNC_CAST apr_uint32_t #define APR_UINT32_MAX 0xFFFFFFFFUL #endif /*APR_PRIVATE_COMMON_H*/
001-log4cxx
trunk/src/apr/include/arch/apr_private_common.h
C
asf20
1,700
/* 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. */ #ifndef APR_NETWORK_IO_H #define APR_NETWORK_IO_H /** * @file apr_network_io.h * @brief APR Network library */ #include "apr.h" #include "apr_pools.h" #include "apr_file_io.h" #include "apr_errno.h" #include "apr_inherit.h" #if APR_HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** * @defgroup apr_network_io Network Routines * @ingroup APR * @{ */ #ifndef APR_MAX_SECS_TO_LINGER /** Maximum seconds to linger */ #define APR_MAX_SECS_TO_LINGER 30 #endif #ifndef APRMAXHOSTLEN /** Maximum hostname length */ #define APRMAXHOSTLEN 256 #endif #ifndef APR_ANYADDR /** Default 'any' address */ #define APR_ANYADDR "0.0.0.0" #endif /** * @defgroup apr_sockopt Socket option definitions * @{ */ #define APR_SO_LINGER 1 /**< Linger */ #define APR_SO_KEEPALIVE 2 /**< Keepalive */ #define APR_SO_DEBUG 4 /**< Debug */ #define APR_SO_NONBLOCK 8 /**< Non-blocking IO */ #define APR_SO_REUSEADDR 16 /**< Reuse addresses */ #define APR_SO_SNDBUF 64 /**< Send buffer */ #define APR_SO_RCVBUF 128 /**< Receive buffer */ #define APR_SO_DISCONNECTED 256 /**< Disconnected */ #define APR_TCP_NODELAY 512 /**< For SCTP sockets, this is mapped * to STCP_NODELAY internally. */ #define APR_TCP_NOPUSH 1024 /**< No push */ #define APR_RESET_NODELAY 2048 /**< This flag is ONLY set internally * when we set APR_TCP_NOPUSH with * APR_TCP_NODELAY set to tell us that * APR_TCP_NODELAY should be turned on * again when NOPUSH is turned off */ #define APR_INCOMPLETE_READ 4096 /**< Set on non-blocking sockets * (timeout != 0) on which the * previous read() did not fill a buffer * completely. the next apr_socket_recv() * will first call select()/poll() rather than * going straight into read(). (Can also * be set by an application to force a * select()/poll() call before the next * read, in cases where the app expects * that an immediate read would fail.) */ #define APR_INCOMPLETE_WRITE 8192 /**< like APR_INCOMPLETE_READ, but for write * @see APR_INCOMPLETE_READ */ #define APR_IPV6_V6ONLY 16384 /**< Don't accept IPv4 connections on an * IPv6 listening socket. */ #define APR_TCP_DEFER_ACCEPT 32768 /**< Delay accepting of new connections * until data is available. * @see apr_socket_accept_filter */ /** @} */ /** Define what type of socket shutdown should occur. */ typedef enum { APR_SHUTDOWN_READ, /**< no longer allow read request */ APR_SHUTDOWN_WRITE, /**< no longer allow write requests */ APR_SHUTDOWN_READWRITE /**< no longer allow read or write requests */ } apr_shutdown_how_e; #define APR_IPV4_ADDR_OK 0x01 /**< @see apr_sockaddr_info_get() */ #define APR_IPV6_ADDR_OK 0x02 /**< @see apr_sockaddr_info_get() */ #if (!APR_HAVE_IN_ADDR) /** * We need to make sure we always have an in_addr type, so APR will just * define it ourselves, if the platform doesn't provide it. */ struct in_addr { apr_uint32_t s_addr; /**< storage to hold the IP# */ }; #endif /** @def APR_INADDR_NONE * Not all platforms have a real INADDR_NONE. This macro replaces * INADDR_NONE on all platforms. */ #ifdef INADDR_NONE #define APR_INADDR_NONE INADDR_NONE #else #define APR_INADDR_NONE ((unsigned int) 0xffffffff) #endif /** * @def APR_INET * Not all platforms have these defined, so we'll define them here * The default values come from FreeBSD 4.1.1 */ #define APR_INET AF_INET /** @def APR_UNSPEC * Let the system decide which address family to use */ #ifdef AF_UNSPEC #define APR_UNSPEC AF_UNSPEC #else #define APR_UNSPEC 0 #endif #if APR_HAVE_IPV6 /** @def APR_INET6 * IPv6 Address Family. Not all platforms may have this defined. */ #define APR_INET6 AF_INET6 #endif /** * @defgroup IP_Proto IP Protocol Definitions for use when creating sockets * @{ */ #define APR_PROTO_TCP 6 /**< TCP */ #define APR_PROTO_UDP 17 /**< UDP */ #define APR_PROTO_SCTP 132 /**< SCTP */ /** @} */ /** * Enum to tell us if we're interested in remote or local socket */ typedef enum { APR_LOCAL, APR_REMOTE } apr_interface_e; /** * The specific declaration of inet_addr's ... some platforms fall back * inet_network (this is not good, but necessary) */ #if APR_HAVE_INET_ADDR #define apr_inet_addr inet_addr #elif APR_HAVE_INET_NETWORK /* only DGUX, as far as I know */ /** * @warning * not generally safe... inet_network() and inet_addr() perform * different functions */ #define apr_inet_addr inet_network #endif /** A structure to represent sockets */ typedef struct apr_socket_t apr_socket_t; /** * A structure to encapsulate headers and trailers for apr_socket_sendfile */ typedef struct apr_hdtr_t apr_hdtr_t; /** A structure to represent in_addr */ typedef struct in_addr apr_in_addr_t; /** A structure to represent an IP subnet */ typedef struct apr_ipsubnet_t apr_ipsubnet_t; /** @remark use apr_uint16_t just in case some system has a short that isn't 16 bits... */ typedef apr_uint16_t apr_port_t; /** @remark It's defined here as I think it should all be platform safe... * @see apr_sockaddr_t */ typedef struct apr_sockaddr_t apr_sockaddr_t; /** * APRs socket address type, used to ensure protocol independence */ struct apr_sockaddr_t { /** The pool to use... */ apr_pool_t *pool; /** The hostname */ char *hostname; /** Either a string of the port number or the service name for the port */ char *servname; /** The numeric port */ apr_port_t port; /** The family */ apr_int32_t family; /** How big is the sockaddr we're using? */ apr_socklen_t salen; /** How big is the ip address structure we're using? */ int ipaddr_len; /** How big should the address buffer be? 16 for v4 or 46 for v6 * used in inet_ntop... */ int addr_str_len; /** This points to the IP address structure within the appropriate * sockaddr structure. */ void *ipaddr_ptr; /** If multiple addresses were found by apr_sockaddr_info_get(), this * points to a representation of the next address. */ apr_sockaddr_t *next; /** Union of either IPv4 or IPv6 sockaddr. */ union { /** IPv4 sockaddr structure */ struct sockaddr_in sin; #if APR_HAVE_IPV6 /** IPv6 sockaddr structure */ struct sockaddr_in6 sin6; #endif #if APR_HAVE_SA_STORAGE /** Placeholder to ensure that the size of this union is not * dependent on whether APR_HAVE_IPV6 is defined. */ struct sockaddr_storage sas; #endif } sa; }; #if APR_HAS_SENDFILE /** * Support reusing the socket on platforms which support it (from disconnect, * specifically Win32. * @remark Optional flag passed into apr_socket_sendfile() */ #define APR_SENDFILE_DISCONNECT_SOCKET 1 #endif /** A structure to encapsulate headers and trailers for apr_socket_sendfile */ struct apr_hdtr_t { /** An iovec to store the headers sent before the file. */ struct iovec* headers; /** number of headers in the iovec */ int numheaders; /** An iovec to store the trailers sent after the file. */ struct iovec* trailers; /** number of trailers in the iovec */ int numtrailers; }; /* function definitions */ /** * Create a socket. * @param new_sock The new socket that has been set up. * @param family The address family of the socket (e.g., APR_INET). * @param type The type of the socket (e.g., SOCK_STREAM). * @param protocol The protocol of the socket (e.g., APR_PROTO_TCP). * @param cont The pool to use */ APR_DECLARE(apr_status_t) apr_socket_create(apr_socket_t **new_sock, int family, int type, int protocol, apr_pool_t *cont); /** * Shutdown either reading, writing, or both sides of a socket. * @param thesocket The socket to close * @param how How to shutdown the socket. One of: * <PRE> * APR_SHUTDOWN_READ no longer allow read requests * APR_SHUTDOWN_WRITE no longer allow write requests * APR_SHUTDOWN_READWRITE no longer allow read or write requests * </PRE> * @see apr_shutdown_how_e * @remark This does not actually close the socket descriptor, it just * controls which calls are still valid on the socket. */ APR_DECLARE(apr_status_t) apr_socket_shutdown(apr_socket_t *thesocket, apr_shutdown_how_e how); /** * Close a socket. * @param thesocket The socket to close */ APR_DECLARE(apr_status_t) apr_socket_close(apr_socket_t *thesocket); /** * Bind the socket to its associated port * @param sock The socket to bind * @param sa The socket address to bind to * @remark This may be where we will find out if there is any other process * using the selected port. */ APR_DECLARE(apr_status_t) apr_socket_bind(apr_socket_t *sock, apr_sockaddr_t *sa); /** * Listen to a bound socket for connections. * @param sock The socket to listen on * @param backlog The number of outstanding connections allowed in the sockets * listen queue. If this value is less than zero, the listen * queue size is set to zero. */ APR_DECLARE(apr_status_t) apr_socket_listen(apr_socket_t *sock, apr_int32_t backlog); /** * Accept a new connection request * @param new_sock A copy of the socket that is connected to the socket that * made the connection request. This is the socket which should * be used for all future communication. * @param sock The socket we are listening on. * @param connection_pool The pool for the new socket. */ APR_DECLARE(apr_status_t) apr_socket_accept(apr_socket_t **new_sock, apr_socket_t *sock, apr_pool_t *connection_pool); /** * Issue a connection request to a socket either on the same machine * or a different one. * @param sock The socket we wish to use for our side of the connection * @param sa The address of the machine we wish to connect to. */ APR_DECLARE(apr_status_t) apr_socket_connect(apr_socket_t *sock, apr_sockaddr_t *sa); /** * Create apr_sockaddr_t from hostname, address family, and port. * @param sa The new apr_sockaddr_t. * @param hostname The hostname or numeric address string to resolve/parse, or * NULL to build an address that corresponds to 0.0.0.0 or :: * @param family The address family to use, or APR_UNSPEC if the system should * decide. * @param port The port number. * @param flags Special processing flags: * <PRE> * APR_IPV4_ADDR_OK first query for IPv4 addresses; only look * for IPv6 addresses if the first query failed; * only valid if family is APR_UNSPEC and hostname * isn't NULL; mutually exclusive with * APR_IPV6_ADDR_OK * APR_IPV6_ADDR_OK first query for IPv6 addresses; only look * for IPv4 addresses if the first query failed; * only valid if family is APR_UNSPEC and hostname * isn't NULL and APR_HAVE_IPV6; mutually exclusive * with APR_IPV4_ADDR_OK * </PRE> * @param p The pool for the apr_sockaddr_t and associated storage. */ APR_DECLARE(apr_status_t) apr_sockaddr_info_get(apr_sockaddr_t **sa, const char *hostname, apr_int32_t family, apr_port_t port, apr_int32_t flags, apr_pool_t *p); /** * Look up the host name from an apr_sockaddr_t. * @param hostname The hostname. * @param sa The apr_sockaddr_t. * @param flags Special processing flags. */ APR_DECLARE(apr_status_t) apr_getnameinfo(char **hostname, apr_sockaddr_t *sa, apr_int32_t flags); /** * Parse hostname/IP address with scope id and port. * * Any of the following strings are accepted: * 8080 (just the port number) * www.apache.org (just the hostname) * www.apache.org:8080 (hostname and port number) * [fe80::1]:80 (IPv6 numeric address string only) * [fe80::1%eth0] (IPv6 numeric address string and scope id) * * Invalid strings: * (empty string) * [abc] (not valid IPv6 numeric address string) * abc:65536 (invalid port number) * * @param addr The new buffer containing just the hostname. On output, *addr * will be NULL if no hostname/IP address was specfied. * @param scope_id The new buffer containing just the scope id. On output, * *scope_id will be NULL if no scope id was specified. * @param port The port number. On output, *port will be 0 if no port was * specified. * ### FIXME: 0 is a legal port (per RFC 1700). this should * ### return something besides zero if the port is missing. * @param str The input string to be parsed. * @param p The pool from which *addr and *scope_id are allocated. * @remark If scope id shouldn't be allowed, check for scope_id != NULL in * addition to checking the return code. If addr/hostname should be * required, check for addr == NULL in addition to checking the * return code. */ APR_DECLARE(apr_status_t) apr_parse_addr_port(char **addr, char **scope_id, apr_port_t *port, const char *str, apr_pool_t *p); /** * Get name of the current machine * @param buf A buffer to store the hostname in. * @param len The maximum length of the hostname that can be stored in the * buffer provided. The suggested length is APRMAXHOSTLEN + 1. * @param cont The pool to use. * @remark If the buffer was not large enough, an error will be returned. */ APR_DECLARE(apr_status_t) apr_gethostname(char *buf, int len, apr_pool_t *cont); /** * Return the data associated with the current socket * @param data The user data associated with the socket. * @param key The key to associate with the user data. * @param sock The currently open socket. */ APR_DECLARE(apr_status_t) apr_socket_data_get(void **data, const char *key, apr_socket_t *sock); /** * Set the data associated with the current socket. * @param sock The currently open socket. * @param data The user data to associate with the socket. * @param key The key to associate with the data. * @param cleanup The cleanup to call when the socket is destroyed. */ APR_DECLARE(apr_status_t) apr_socket_data_set(apr_socket_t *sock, void *data, const char *key, apr_status_t (*cleanup)(void*)); /** * Send data over a network. * @param sock The socket to send the data over. * @param buf The buffer which contains the data to be sent. * @param len On entry, the number of bytes to send; on exit, the number * of bytes sent. * @remark * <PRE> * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * </PRE> */ APR_DECLARE(apr_status_t) apr_socket_send(apr_socket_t *sock, const char *buf, apr_size_t *len); /** * Send multiple packets of data over a network. * @param sock The socket to send the data over. * @param vec The array of iovec structs containing the data to send * @param nvec The number of iovec structs in the array * @param len Receives the number of bytes actually written * @remark * <PRE> * This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually sent is stored in argument 3. * * It is possible for both bytes to be sent and an error to be returned. * * APR_EINTR is never returned. * </PRE> */ APR_DECLARE(apr_status_t) apr_socket_sendv(apr_socket_t *sock, const struct iovec *vec, apr_int32_t nvec, apr_size_t *len); /** * @param sock The socket to send from * @param where The apr_sockaddr_t describing where to send the data * @param flags The flags to use * @param buf The data to send * @param len The length of the data to send */ 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); /** * @param from The apr_sockaddr_t to fill in the recipient info * @param sock The socket to use * @param flags The flags to use * @param buf The buffer to use * @param len The length of the available buffer */ 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); #if APR_HAS_SENDFILE || defined(DOXYGEN) /** * Send a file from an open file descriptor to a socket, along with * optional headers and trailers * @param sock The socket to which we're writing * @param file The open file from which to read * @param hdtr A structure containing the headers and trailers to send * @param offset Offset into the file where we should begin writing * @param len (input) - Number of bytes to send from the file * (output) - Number of bytes actually sent, * including headers, file, and trailers * @param flags APR flags that are mapped to OS specific flags * @remark This functions acts like a blocking write by default. To change * this behavior, use apr_socket_timeout_set() or the * APR_SO_NONBLOCK socket option. * The number of bytes actually sent is stored in the len parameter. * The offset parameter is passed by reference for no reason; its * value will never be modified by the apr_socket_sendfile() function. */ APR_DECLARE(apr_status_t) apr_socket_sendfile(apr_socket_t *sock, apr_file_t *file, apr_hdtr_t *hdtr, apr_off_t *offset, apr_size_t *len, apr_int32_t flags); #endif /* APR_HAS_SENDFILE */ /** * Read data from a network. * @param sock The socket to read the data from. * @param buf The buffer to store the data in. * @param len On entry, the number of bytes to receive; on exit, the number * of bytes received. * @remark * <PRE> * This functions acts like a blocking read by default. To change * this behavior, use apr_socket_timeout_set() or the APR_SO_NONBLOCK * socket option. * The number of bytes actually received is stored in argument 3. * * It is possible for both bytes to be received and an APR_EOF or * other error to be returned. * * APR_EINTR is never returned. * </PRE> */ APR_DECLARE(apr_status_t) apr_socket_recv(apr_socket_t *sock, char *buf, apr_size_t *len); /** * Setup socket options for the specified socket * @param sock The socket to set up. * @param opt The option we would like to configure. One of: * <PRE> * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * When this option is enabled, use * the APR_STATUS_IS_EAGAIN() macro to * see if a send or receive function * could not transfer data without * blocking. * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * </PRE> * @param on Value for the option. */ APR_DECLARE(apr_status_t) apr_socket_opt_set(apr_socket_t *sock, apr_int32_t opt, apr_int32_t on); /** * Setup socket timeout for the specified socket * @param sock The socket to set up. * @param t Value for the timeout. * <PRE> * t > 0 -- read and write calls return APR_TIMEUP if specified time * elapsess with no data read or written * t == 0 -- read and write calls never block * t < 0 -- read and write calls block * </PRE> */ APR_DECLARE(apr_status_t) apr_socket_timeout_set(apr_socket_t *sock, apr_interval_time_t t); /** * Query socket options for the specified socket * @param sock The socket to query * @param opt The option we would like to query. One of: * <PRE> * APR_SO_DEBUG -- turn on debugging information * APR_SO_KEEPALIVE -- keep connections active * APR_SO_LINGER -- lingers on close if data is present * APR_SO_NONBLOCK -- Turns blocking on/off for socket * APR_SO_REUSEADDR -- The rules used in validating addresses * supplied to bind should allow reuse * of local addresses. * APR_SO_SNDBUF -- Set the SendBufferSize * APR_SO_RCVBUF -- Set the ReceiveBufferSize * APR_SO_DISCONNECTED -- Query the disconnected state of the socket. * (Currently only used on Windows) * </PRE> * @param on Socket option returned on the call. */ APR_DECLARE(apr_status_t) apr_socket_opt_get(apr_socket_t *sock, apr_int32_t opt, apr_int32_t *on); /** * Query socket timeout for the specified socket * @param sock The socket to query * @param t Socket timeout returned from the query. */ APR_DECLARE(apr_status_t) apr_socket_timeout_get(apr_socket_t *sock, apr_interval_time_t *t); /** * Query the specified socket if at the OOB/Urgent data mark * @param sock The socket to query * @param atmark Is set to true if socket is at the OOB/urgent mark, * otherwise is set to false. */ APR_DECLARE(apr_status_t) apr_socket_atmark(apr_socket_t *sock, int *atmark); /** * Return an apr_sockaddr_t from an apr_socket_t * @param sa The returned apr_sockaddr_t. * @param which Which interface do we want the apr_sockaddr_t for? * @param sock The socket to use */ APR_DECLARE(apr_status_t) apr_socket_addr_get(apr_sockaddr_t **sa, apr_interface_e which, apr_socket_t *sock); /** * Return the IP address (in numeric address string format) in * an APR socket address. APR will allocate storage for the IP address * string from the pool of the apr_sockaddr_t. * @param addr The IP address. * @param sockaddr The socket address to reference. */ APR_DECLARE(apr_status_t) apr_sockaddr_ip_get(char **addr, apr_sockaddr_t *sockaddr); /** * See if the IP addresses in two APR socket addresses are * equivalent. Appropriate logic is present for comparing * IPv4-mapped IPv6 addresses with IPv4 addresses. * * @param addr1 One of the APR socket addresses. * @param addr2 The other APR socket address. * @remark The return value will be non-zero if the addresses * are equivalent. */ APR_DECLARE(int) apr_sockaddr_equal(const apr_sockaddr_t *addr1, const apr_sockaddr_t *addr2); /** * Return the type of the socket. * @param sock The socket to query. * @param type The returned type (e.g., SOCK_STREAM). */ APR_DECLARE(apr_status_t) apr_socket_type_get(apr_socket_t *sock, int *type); /** * Given an apr_sockaddr_t and a service name, set the port for the service * @param sockaddr The apr_sockaddr_t that will have its port set * @param servname The name of the service you wish to use */ APR_DECLARE(apr_status_t) apr_getservbyname(apr_sockaddr_t *sockaddr, const char *servname); /** * Build an ip-subnet representation from an IP address and optional netmask or * number-of-bits. * @param ipsub The new ip-subnet representation * @param ipstr The input IP address string * @param mask_or_numbits The input netmask or number-of-bits string, or NULL * @param p The pool to allocate from */ APR_DECLARE(apr_status_t) apr_ipsubnet_create(apr_ipsubnet_t **ipsub, const char *ipstr, const char *mask_or_numbits, apr_pool_t *p); /** * Test the IP address in an apr_sockaddr_t against a pre-built ip-subnet * representation. * @param ipsub The ip-subnet representation * @param sa The socket address to test * @return non-zero if the socket address is within the subnet, 0 otherwise */ APR_DECLARE(int) apr_ipsubnet_test(apr_ipsubnet_t *ipsub, apr_sockaddr_t *sa); #if APR_HAS_SO_ACCEPTFILTER || defined(DOXYGEN) /** * Set an OS level accept filter. * @param sock The socket to put the accept filter on. * @param name The accept filter * @param args Any extra args to the accept filter. Passing NULL here removes * the accept filter. */ apr_status_t apr_socket_accept_filter(apr_socket_t *sock, char *name, char *args); #endif /** * Return the protocol of the socket. * @param sock The socket to query. * @param protocol The returned protocol (e.g., APR_PROTO_TCP). */ APR_DECLARE(apr_status_t) apr_socket_protocol_get(apr_socket_t *sock, int *protocol); /** * Get the pool used by the socket. */ APR_POOL_DECLARE_ACCESSOR(socket); /** * Set a socket to be inherited by child processes. */ APR_DECLARE_INHERIT_SET(socket); /** * Unset a socket from being inherited by child processes. */ APR_DECLARE_INHERIT_UNSET(socket); /** * @defgroup apr_mcast IP Multicast * @{ */ /** * Join a Multicast Group * @param sock The socket to join a multicast group * @param join The address of the multicast group to join * @param iface Address of the interface to use. If NULL is passed, the * default multicast interface will be used. (OS Dependent) * @param source Source Address to accept transmissions from (non-NULL * implies Source-Specific Multicast) */ APR_DECLARE(apr_status_t) apr_mcast_join(apr_socket_t *sock, apr_sockaddr_t *join, apr_sockaddr_t *iface, apr_sockaddr_t *source); /** * Leave a Multicast Group. All arguments must be the same as * apr_mcast_join. * @param sock The socket to leave a multicast group * @param addr The address of the multicast group to leave * @param iface Address of the interface to use. If NULL is passed, the * default multicast interface will be used. (OS Dependent) * @param source Source Address to accept transmissions from (non-NULL * implies Source-Specific Multicast) */ APR_DECLARE(apr_status_t) apr_mcast_leave(apr_socket_t *sock, apr_sockaddr_t *addr, apr_sockaddr_t *iface, apr_sockaddr_t *source); /** * Set the Multicast Time to Live (ttl) for a multicast transmission. * @param sock The socket to set the multicast ttl * @param ttl Time to live to Assign. 0-255, default=1 * @remark If the TTL is 0, packets will only be seen by sockets on * the local machine, and only when multicast loopback is enabled. */ APR_DECLARE(apr_status_t) apr_mcast_hops(apr_socket_t *sock, apr_byte_t ttl); /** * Toggle IP Multicast Loopback * @param sock The socket to set multicast loopback * @param opt 0=disable, 1=enable */ APR_DECLARE(apr_status_t) apr_mcast_loopback(apr_socket_t *sock, apr_byte_t opt); /** * Set the Interface to be used for outgoing Multicast Transmissions. * @param sock The socket to set the multicast interface on * @param iface Address of the interface to use for Multicast */ APR_DECLARE(apr_status_t) apr_mcast_interface(apr_socket_t *sock, apr_sockaddr_t *iface); /** @} */ /** @} */ #ifdef __cplusplus } #endif #endif /* ! APR_NETWORK_IO_H */
001-log4cxx
trunk/src/apr/include/apr_network_io.h
C
asf20
31,597
/* 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. */ #ifndef APR_LIB_H #define APR_LIB_H /** * @file apr_lib.h * This is collection of oddballs that didn't fit anywhere else, * and might move to more appropriate headers with the release * of APR 1.0. * @brief APR general purpose library routines */ #include "apr.h" #include "apr_errno.h" #if APR_HAVE_CTYPE_H #include <ctype.h> #endif #if APR_HAVE_STDARG_H #include <stdarg.h> #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** * @defgroup apr_lib General Purpose Library Routines * @ingroup APR * This is collection of oddballs that didn't fit anywhere else, * and might move to more appropriate headers with the release * of APR 1.0. * @{ */ /** A constant representing a 'large' string. */ #define HUGE_STRING_LEN 8192 /* * Define the structures used by the APR general-purpose library. */ /** @see apr_vformatter_buff_t */ typedef struct apr_vformatter_buff_t apr_vformatter_buff_t; /** * Structure used by the variable-formatter routines. */ struct apr_vformatter_buff_t { /** The current position */ char *curpos; /** The end position of the format string */ char *endpos; }; /** * return the final element of the pathname * @param pathname The path to get the final element of * @return the final element of the path * @remark * <PRE> * For example: * "/foo/bar/gum" -> "gum" * "/foo/bar/gum/" -> "" * "gum" -> "gum" * "bs\\path\\stuff" -> "stuff" * </PRE> */ APR_DECLARE(const char *) apr_filepath_name_get(const char *pathname); /** * apr_killpg * Small utility macros to make things easier to read. Not usually a * goal, to be sure.. */ #ifdef WIN32 #define apr_killpg(x, y) #else /* WIN32 */ #ifdef NO_KILLPG #define apr_killpg(x, y) (kill (-(x), (y))) #else /* NO_KILLPG */ #define apr_killpg(x, y) (killpg ((x), (y))) #endif /* NO_KILLPG */ #endif /* WIN32 */ /** * apr_vformatter() is a generic printf-style formatting routine * with some extensions. * @param flush_func The function to call when the buffer is full * @param c The buffer to write to * @param fmt The format string * @param ap The arguments to use to fill out the format string. * * @remark * <PRE> * The extensions are: * * %%pA takes a struct in_addr *, and prints it as a.b.c.d * %%pI takes an apr_sockaddr_t * and prints it as a.b.c.d:port or * [ipv6-address]:port * %%pT takes an apr_os_thread_t * and prints it in decimal * ('0' is printed if !APR_HAS_THREADS) * %%pt takes an apr_os_thread_t * and prints it in hexadecimal * ('0' is printed if !APR_HAS_THREADS) * %%pp takes a void * and outputs it in hex * * The %%p hacks are to force gcc's printf warning code to skip * over a pointer argument without complaining. This does * mean that the ANSI-style %%p (output a void * in hex format) won't * work as expected at all, but that seems to be a fair trade-off * for the increased robustness of having printf-warnings work. * * Additionally, apr_vformatter allows for arbitrary output methods * using the apr_vformatter_buff and flush_func. * * The apr_vformatter_buff has two elements curpos and endpos. * curpos is where apr_vformatter will write the next byte of output. * It proceeds writing output to curpos, and updating curpos, until * either the end of output is reached, or curpos == endpos (i.e. the * buffer is full). * * If the end of output is reached, apr_vformatter returns the * number of bytes written. * * When the buffer is full, the flush_func is called. The flush_func * can return -1 to indicate that no further output should be attempted, * and apr_vformatter will return immediately with -1. Otherwise * the flush_func should flush the buffer in whatever manner is * appropriate, re apr_pool_t nitialize curpos and endpos, and return 0. * * Note that flush_func is only invoked as a result of attempting to * write another byte at curpos when curpos >= endpos. So for * example, it's possible when the output exactly matches the buffer * space available that curpos == endpos will be true when * apr_vformatter returns. * * apr_vformatter does not call out to any other code, it is entirely * self-contained. This allows the callers to do things which are * otherwise "unsafe". For example, apr_psprintf uses the "scratch" * space at the unallocated end of a block, and doesn't actually * complete the allocation until apr_vformatter returns. apr_psprintf * would be completely broken if apr_vformatter were to call anything * that used this same pool. Similarly http_bprintf() uses the "scratch" * space at the end of its output buffer, and doesn't actually note * that the space is in use until it either has to flush the buffer * or until apr_vformatter returns. * </PRE> */ APR_DECLARE(int) apr_vformatter(int (*flush_func)(apr_vformatter_buff_t *b), apr_vformatter_buff_t *c, const char *fmt, va_list ap); /** * Display a prompt and read in the password from stdin. * @param prompt The prompt to display * @param pwbuf Buffer to store the password * @param bufsize The length of the password buffer. * @remark If the password entered must be truncated to fit in * the provided buffer, APR_ENAMETOOLONG will be returned. * Note that the bufsize paramater is passed by reference for no * reason; its value will never be modified by the apr_password_get() * function. */ APR_DECLARE(apr_status_t) apr_password_get(const char *prompt, char *pwbuf, apr_size_t *bufsize); /** @} */ /** * @defgroup apr_ctype ctype functions * These macros allow correct support of 8-bit characters on systems which * support 8-bit characters. Pretty dumb how the cast is required, but * that's legacy libc for ya. These new macros do not support EOF like * the standard macros do. Tough. * @{ */ /** @see isalnum */ #define apr_isalnum(c) (isalnum(((unsigned char)(c)))) /** @see isalpha */ #define apr_isalpha(c) (isalpha(((unsigned char)(c)))) /** @see iscntrl */ #define apr_iscntrl(c) (iscntrl(((unsigned char)(c)))) /** @see isdigit */ #define apr_isdigit(c) (isdigit(((unsigned char)(c)))) /** @see isgraph */ #define apr_isgraph(c) (isgraph(((unsigned char)(c)))) /** @see islower*/ #define apr_islower(c) (islower(((unsigned char)(c)))) /** @see isascii */ #ifdef isascii #define apr_isascii(c) (isascii(((unsigned char)(c)))) #else #define apr_isascii(c) (((c) & ~0x7f)==0) #endif /** @see isprint */ #define apr_isprint(c) (isprint(((unsigned char)(c)))) /** @see ispunct */ #define apr_ispunct(c) (ispunct(((unsigned char)(c)))) /** @see isspace */ #define apr_isspace(c) (isspace(((unsigned char)(c)))) /** @see isupper */ #define apr_isupper(c) (isupper(((unsigned char)(c)))) /** @see isxdigit */ #define apr_isxdigit(c) (isxdigit(((unsigned char)(c)))) /** @see tolower */ #define apr_tolower(c) (tolower(((unsigned char)(c)))) /** @see toupper */ #define apr_toupper(c) (toupper(((unsigned char)(c)))) /** @} */ #ifdef __cplusplus } #endif #endif /* ! APR_LIB_H */
001-log4cxx
trunk/src/apr/include/apr_lib.h
C
asf20
7,927
/* 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. */ #ifndef APR_GLOBAL_MUTEX_H #define APR_GLOBAL_MUTEX_H /** * @file apr_global_mutex.h * @brief APR Global Locking Routines */ #include "apr.h" #include "apr_proc_mutex.h" /* only for apr_lockmech_e */ #include "apr_pools.h" #include "apr_errno.h" #if APR_PROC_MUTEX_IS_GLOBAL #include "apr_proc_mutex.h" #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** * @defgroup APR_GlobalMutex Global Locking Routines * @ingroup APR * @{ */ #if !APR_PROC_MUTEX_IS_GLOBAL || defined(DOXYGEN) /** Opaque global mutex structure. */ typedef struct apr_global_mutex_t apr_global_mutex_t; /* Function definitions */ /** * Create and initialize a mutex that can be used to synchronize both * processes and threads. Note: There is considerable overhead in using * this API if only cross-process or cross-thread mutual exclusion is * required. See apr_proc_mutex.h and apr_thread_mutex.h for more * specialized lock routines. * @param mutex the memory address where the newly created mutex will be * stored. * @param fname A file name to use if the lock mechanism requires one. This * argument should always be provided. The lock code itself will * determine if it should be used. * @param mech The mechanism to use for the interprocess lock, if any; one of * <PRE> * APR_LOCK_FCNTL * APR_LOCK_FLOCK * APR_LOCK_SYSVSEM * APR_LOCK_POSIXSEM * APR_LOCK_PROC_PTHREAD * APR_LOCK_DEFAULT pick the default mechanism for the platform * </PRE> * @param pool the pool from which to allocate the mutex. * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. */ APR_DECLARE(apr_status_t) apr_global_mutex_create(apr_global_mutex_t **mutex, const char *fname, apr_lockmech_e mech, apr_pool_t *pool); /** * Re-open a mutex in a child process. * @param mutex The newly re-opened mutex structure. * @param fname A file name to use if the mutex mechanism requires one. This * argument should always be provided. The mutex code itself will * determine if it should be used. This filename should be the * same one that was passed to apr_global_mutex_create(). * @param pool The pool to operate on. * @remark This function must be called to maintain portability, even * if the underlying lock mechanism does not require it. */ APR_DECLARE(apr_status_t) apr_global_mutex_child_init( apr_global_mutex_t **mutex, const char *fname, apr_pool_t *pool); /** * Acquire the lock for the given mutex. If the mutex is already locked, * the current thread will be put to sleep until the lock becomes available. * @param mutex the mutex on which to acquire the lock. */ APR_DECLARE(apr_status_t) apr_global_mutex_lock(apr_global_mutex_t *mutex); /** * Attempt to acquire the lock for the given mutex. If the mutex has already * been acquired, the call returns immediately with APR_EBUSY. Note: it * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine * if the return value was APR_EBUSY, for portability reasons. * @param mutex the mutex on which to attempt the lock acquiring. */ APR_DECLARE(apr_status_t) apr_global_mutex_trylock(apr_global_mutex_t *mutex); /** * Release the lock for the given mutex. * @param mutex the mutex from which to release the lock. */ APR_DECLARE(apr_status_t) apr_global_mutex_unlock(apr_global_mutex_t *mutex); /** * Destroy the mutex and free the memory associated with the lock. * @param mutex the mutex to destroy. */ APR_DECLARE(apr_status_t) apr_global_mutex_destroy(apr_global_mutex_t *mutex); /** * Get the pool used by this global_mutex. * @return apr_pool_t the pool */ APR_POOL_DECLARE_ACCESSOR(global_mutex); #else /* APR_PROC_MUTEX_IS_GLOBAL */ /* Some platforms [e.g. Win32] have cross process locks that are truly * global locks, since there isn't the concept of cross-process locks. * Define these platforms in terms of an apr_proc_mutex_t. */ #define apr_global_mutex_t apr_proc_mutex_t #define apr_global_mutex_create apr_proc_mutex_create #define apr_global_mutex_child_init apr_proc_mutex_child_init #define apr_global_mutex_lock apr_proc_mutex_lock #define apr_global_mutex_trylock apr_proc_mutex_trylock #define apr_global_mutex_unlock apr_proc_mutex_unlock #define apr_global_mutex_destroy apr_proc_mutex_destroy #define apr_global_mutex_pool_get apr_proc_mutex_pool_get #endif /** @} */ #ifdef __cplusplus } #endif #endif /* ndef APR_GLOBAL_MUTEX_H */
001-log4cxx
trunk/src/apr/include/apr_global_mutex.h
C
asf20
5,680
/* 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. */ #ifndef APR_H #define APR_H /* GENERATED FILE WARNING! DO NOT EDIT apr.h * * You must modify apr.hw instead. * * And please, make an effort to stub apr.hnw and apr.h.in in the process. * * This is the Win32 specific version of apr.h. It is copied from * apr.hw by the apr.dsp and libapr.dsp projects. */ /** * @file apr.h * @brief APR Platform Definitions * @remark This is a generated header generated from include/apr.h.in by * ./configure, or copied from include/apr.hw or include/apr.hnw * for Win32 or Netware by those build environments, respectively. */ #if defined(WIN32) || defined(DOXYGEN) /* Ignore most warnings (back down to /W3) for poorly constructed headers */ #if defined(_MSC_VER) && _MSC_VER >= 1200 #pragma warning(push, 3) #endif /* disable or reduce the frequency of... * C4057: indirection to slightly different base types * C4075: slight indirection changes (unsigned short* vs short[]) * C4100: unreferenced formal parameter * C4127: conditional expression is constant * C4163: '_rotl64' : not available as an intrinsic function * C4201: nonstandard extension nameless struct/unions * C4244: int to char/short - precision loss * C4514: unreferenced inline function removed */ #pragma warning(disable: 4100 4127 4163 4201 4514; once: 4057 4075 4244) /* Ignore Microsoft's interpretation of secure development * and the POSIX string handling API */ #if defined(_MSC_VER) && _MSC_VER >= 1400 #ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE #endif #pragma warning(disable: 4996) #endif /* Has windows.h already been included? If so, our preferences don't matter, * but we will still need the winsock things no matter what was included. * If not, include a restricted set of windows headers to our tastes. */ #ifndef _WINDOWS_ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef _WIN32_WINNT /* Restrict the server to a subset of Windows NT 4.0 header files by default */ #define _WIN32_WINNT 0x0400 #endif #ifndef NOUSER #define NOUSER #endif #ifndef NOMCX #define NOMCX #endif #ifndef NOIME #define NOIME #endif #include <windows.h> /* * Add a _very_few_ declarations missing from the restricted set of headers * (If this list becomes extensive, re-enable the required headers above!) * winsock headers were excluded by WIN32_LEAN_AND_MEAN, so include them now */ #define SW_HIDE 0 #ifndef _WIN32_WCE #include <winsock2.h> #include <mswsock.h> #include <ws2tcpip.h> #else #include <winsock.h> #endif #endif /* !_WINDOWS_ */ /** * @defgroup apr_platform Platform Definitions * @ingroup APR * @{ */ #define APR_INLINE __inline #define APR_HAS_INLINE 1 #ifndef __attribute__ #define __attribute__(__x) #endif #ifndef _WIN32_WCE #define APR_HAVE_ARPA_INET_H 0 #define APR_HAVE_CONIO_H 1 #define APR_HAVE_CRYPT_H 0 #define APR_HAVE_CTYPE_H 1 #define APR_HAVE_DIRENT_H 0 #define APR_HAVE_ERRNO_H 1 #define APR_HAVE_FCNTL_H 1 #define APR_HAVE_IO_H 1 #define APR_HAVE_LIMITS_H 1 #define APR_HAVE_NETDB_H 0 #define APR_HAVE_NETINET_IN_H 0 #define APR_HAVE_NETINET_SCTP_H 0 #define APR_HAVE_NETINET_SCTP_UIO_H 0 #define APR_HAVE_NETINET_TCP_H 0 #define APR_HAVE_PTHREAD_H 0 #define APR_HAVE_SIGNAL_H 1 #define APR_HAVE_STDARG_H 1 #define APR_HAVE_STDINT_H 0 #define APR_HAVE_STDIO_H 1 #define APR_HAVE_STDLIB_H 1 #define APR_HAVE_STRING_H 1 #define APR_HAVE_STRINGS_H 0 #define APR_HAVE_SYS_SENDFILE_H 0 #define APR_HAVE_SYS_SIGNAL_H 0 #define APR_HAVE_SYS_SOCKET_H 0 #define APR_HAVE_SYS_SOCKIO_H 0 #define APR_HAVE_SYS_SYSLIMITS_H 0 #define APR_HAVE_SYS_TIME_H 0 #define APR_HAVE_SYS_TYPES_H 1 #define APR_HAVE_SYS_UIO_H 0 #define APR_HAVE_SYS_WAIT_H 0 #define APR_HAVE_UNISTD_H 0 #define APR_HAVE_STDDEF_H 1 #define APR_HAVE_PROCESS_H 1 #define APR_HAVE_TIME_H 1 #else #define APR_HAVE_ARPA_INET_H 0 #define APR_HAVE_CONIO_H 0 #define APR_HAVE_CRYPT_H 0 #define APR_HAVE_CTYPE_H 0 #define APR_HAVE_DIRENT_H 0 #define APR_HAVE_ERRNO_H 0 #define APR_HAVE_FCNTL_H 0 #define APR_HAVE_IO_H 0 #define APR_HAVE_LIMITS_H 0 #define APR_HAVE_NETDB_H 0 #define APR_HAVE_NETINET_IN_H 0 #define APR_HAVE_NETINET_TCP_H 0 #define APR_HAVE_PTHREAD_H 0 #define APR_HAVE_SIGNAL_H 0 #define APR_HAVE_STDARG_H 0 #define APR_HAVE_STDINT_H 0 #define APR_HAVE_STDIO_H 1 #define APR_HAVE_STDLIB_H 1 #define APR_HAVE_STRING_H 1 #define APR_HAVE_STRINGS_H 0 #define APR_HAVE_SYS_SENDFILE_H 0 #define APR_HAVE_SYS_SIGNAL_H 0 #define APR_HAVE_SYS_SOCKET_H 0 #define APR_HAVE_SYS_SYSLIMITS_H 0 #define APR_HAVE_SYS_TIME_H 0 #define APR_HAVE_SYS_TYPES_H 0 #define APR_HAVE_SYS_UIO_H 0 #define APR_HAVE_SYS_WAIT_H 0 #define APR_HAVE_UNISTD_H 0 #define APR_HAVE_STDDEF_H 0 #define APR_HAVE_PROCESS_H 0 #define APR_HAVE_TIME_H 0 #endif #define APR_USE_FLOCK_SERIALIZE 0 #define APR_USE_SYSVSEM_SERIALIZE 0 #define APR_USE_FCNTL_SERIALIZE 0 #define APR_USE_PROC_PTHREAD_SERIALIZE 0 #define APR_USE_PTHREAD_SERIALIZE 0 #define APR_HAS_FLOCK_SERIALIZE 0 #define APR_HAS_SYSVSEM_SERIALIZE 0 #define APR_HAS_FCNTL_SERIALIZE 0 #define APR_HAS_PROC_PTHREAD_SERIALIZE 0 #define APR_HAS_RWLOCK_SERIALIZE 0 #define APR_HAS_LOCK_CREATE_NP 0 #define APR_PROCESS_LOCK_IS_GLOBAL 0 #define APR_USES_ANONYMOUS_SHM 0 #define APR_USES_FILEBASED_SHM 0 #define APR_USES_KEYBASED_SHM 0 #define APR_FILE_BASED_SHM 0 #define APR_MEM_BASED_SHM 0 #define APR_HAVE_CORKABLE_TCP 0 #define APR_HAVE_GETRLIMIT 0 #define APR_HAVE_ICONV 0 #define APR_HAVE_IN_ADDR 1 #define APR_HAVE_INET_ADDR 1 #define APR_HAVE_INET_NETWORK 0 #define APR_HAVE_IPV6 0 #define APR_HAVE_MEMMOVE 1 #define APR_HAVE_SETRLIMIT 0 #define APR_HAVE_SIGACTION 0 #define APR_HAVE_SIGSUSPEND 0 #define APR_HAVE_SIGWAIT 0 #define APR_HAVE_STRCASECMP 0 #define APR_HAVE_STRDUP 1 #define APR_HAVE_STRNCASECMP 0 #define APR_HAVE_STRSTR 1 #define APR_HAVE_MEMCHR 1 #define APR_HAVE_STRUCT_RLIMIT 0 #define APR_HAVE_UNION_SEMUN 0 #define APR_HAVE_SCTP 0 #ifndef _WIN32_WCE #define APR_HAVE_STRICMP 1 #define APR_HAVE_STRNICMP 1 #define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 1 #else #define APR_HAVE_STRICMP 0 #define APR_HAVE_STRNICMP 0 #define APR_PROCATTR_USER_SET_REQUIRES_PASSWORD 0 #endif /** @} */ /* We don't include our conditional headers within the doxyblocks * or the extern "C" namespace */ #if APR_HAVE_STDLIB_H #include <stdlib.h> #endif #if APR_HAVE_STDIO_H #include <stdio.h> #endif #if APR_HAVE_SYS_TYPES_H #include <sys/types.h> #endif #if APR_HAVE_STDDEF_H #include <stddef.h> #endif #if APR_HAVE_TIME_H #include <time.h> #endif #if APR_HAVE_PROCESS_H #include <process.h> #endif #if APR_HAVE_IPV6 #include <ws2tcpip.h> #endif #ifdef __cplusplus extern "C" { #endif /** * @addtogroup apr_platform * @ingroup APR * @{ */ /* APR Feature Macros */ #define APR_HAS_SHARED_MEMORY 1 #define APR_HAS_THREADS 1 #define APR_HAS_MMAP 1 #define APR_HAS_FORK 0 #define APR_HAS_RANDOM 1 #define APR_HAS_OTHER_CHILD 1 #define APR_HAS_DSO 1 #define APR_HAS_SO_ACCEPTFILTER 0 #define APR_HAS_UNICODE_FS 1 #define APR_HAS_PROC_INVOKED 1 #ifndef _WIN32_WCE #define APR_HAS_SENDFILE 1 #define APR_HAS_USER 1 #define APR_HAS_LARGE_FILES 1 #define APR_HAS_XTHREAD_FILES 1 #else #define APR_HAS_SENDFILE 0 #define APR_HAS_USER 0 #define APR_HAS_LARGE_FILES 0 #define APR_HAS_XTHREAD_FILES 0 #endif #define APR_HAS_OS_UUID 1 /* Win32 cannot poll [just yet] on files/pipes. */ #define APR_FILES_AS_SOCKETS 0 /* This macro indicates whether or not EBCDIC is the native character set. */ #define APR_CHARSET_EBCDIC 0 /* Is the TCP_NODELAY socket option inherited from listening sockets? */ #define APR_TCP_NODELAY_INHERITED 1 /* Is the O_NONBLOCK flag inherited from listening sockets? */ #define APR_O_NONBLOCK_INHERITED 1 /* Typedefs that APR needs. */ typedef unsigned char apr_byte_t; typedef short apr_int16_t; typedef unsigned short apr_uint16_t; typedef int apr_int32_t; typedef unsigned int apr_uint32_t; typedef __int64 apr_int64_t; typedef unsigned __int64 apr_uint64_t; typedef size_t apr_size_t; #if APR_HAVE_STDDEF_H typedef ptrdiff_t apr_ssize_t; #else typedef int apr_ssize_t; #endif #if APR_HAS_LARGE_FILES typedef __int64 apr_off_t; #else typedef int apr_off_t; #endif typedef int apr_socklen_t; /* Are we big endian? */ /* XXX: Fatal assumption on Alpha platforms */ #define APR_IS_BIGENDIAN 0 #ifdef WIN64 #define APR_SIZEOF_VOIDP 8 #else #define APR_SIZEOF_VOIDP 4 #endif /* XXX These simply don't belong here, perhaps in apr_portable.h * based on some APR_HAVE_PID/GID/UID? */ typedef int pid_t; /* typedef int uid_t */ /* typedef int gid_t */ /* Mechanisms to properly type numeric literals */ #define APR_INT64_C(val) (val##i64) #define APR_UINT64_C(val) (val##Ui64) #if APR_HAVE_IPV6 /* Appears in later flavors, not the originals. */ #ifndef in_addr6 #define in6_addr in_addr6 #endif #ifndef WS2TCPIP_INLINE #define IN6_IS_ADDR_V4MAPPED(a) \ ( (*(const apr_uint64_t *)(const void *)(&(a)->s6_addr[0]) == 0) \ && (*(const apr_uint32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff))) #endif #endif /* APR_HAS_IPV6 */ /* Definitions that APR programs need to work properly. */ /** * Thread callbacks from APR functions must be declared with APR_THREAD_FUNC, * so that they follow the platform's calling convention. * @example */ /** void* APR_THREAD_FUNC my_thread_entry_fn(apr_thread_t *thd, void *data); */ #define APR_THREAD_FUNC __stdcall #if defined(DOXYGEN) || !defined(WIN32) /** * The public APR functions are declared with APR_DECLARE(), so they may * use the most appropriate calling convention. Public APR functions with * variable arguments must use APR_DECLARE_NONSTD(). * * @remark Both the declaration and implementations must use the same macro. * @example */ /** APR_DECLARE(rettype) apr_func(args) * @see APR_DECLARE_NONSTD @see APR_DECLARE_DATA * @remark Note that when APR compiles the library itself, it passes the * symbol -DAPR_DECLARE_EXPORT to the compiler on some platforms (e.g. Win32) * to export public symbols from the dynamic library build.\n * The user must define the APR_DECLARE_STATIC when compiling to target * the static APR library on some platforms (e.g. Win32.) The public symbols * are neither exported nor imported when APR_DECLARE_STATIC is defined.\n * By default, compiling an application and including the APR public * headers, without defining APR_DECLARE_STATIC, will prepare the code to be * linked to the dynamic library. */ #define APR_DECLARE(type) type /** * The public APR functions using variable arguments are declared with * APR_DECLARE_NONSTD(), as they must follow the C language calling convention. * @see APR_DECLARE @see APR_DECLARE_DATA * @remark Both the declaration and implementations must use the same macro. * @example */ /** APR_DECLARE_NONSTD(rettype) apr_func(args, ...); */ #define APR_DECLARE_NONSTD(type) type /** * The public APR variables are declared with AP_MODULE_DECLARE_DATA. * This assures the appropriate indirection is invoked at compile time. * @see APR_DECLARE @see APR_DECLARE_NONSTD * @remark Note that the declaration and implementations use different forms, * but both must include the macro. * @example */ /** extern APR_DECLARE_DATA type apr_variable;\n * APR_DECLARE_DATA type apr_variable = value; */ #define APR_DECLARE_DATA #elif defined(APR_DECLARE_STATIC) #define APR_DECLARE(type) type __stdcall #define APR_DECLARE_NONSTD(type) type __cdecl #define APR_DECLARE_DATA #elif defined(APR_DECLARE_EXPORT) #define APR_DECLARE(type) __declspec(dllexport) type __stdcall #define APR_DECLARE_NONSTD(type) __declspec(dllexport) type __cdecl #define APR_DECLARE_DATA __declspec(dllexport) #else #define APR_DECLARE(type) __declspec(dllimport) type __stdcall #define APR_DECLARE_NONSTD(type) __declspec(dllimport) type __cdecl #define APR_DECLARE_DATA __declspec(dllimport) #endif #ifdef WIN64 #define APR_SSIZE_T_FMT "I64d" #define APR_SIZE_T_FMT "I64d" #else #define APR_SSIZE_T_FMT "d" #define APR_SIZE_T_FMT "d" #endif #if APR_HAS_LARGE_FILES #define APR_OFF_T_FMT "I64d" #else #define APR_OFF_T_FMT "d" #endif #define APR_PID_T_FMT "d" #define APR_INT64_T_FMT "I64d" #define APR_UINT64_T_FMT "I64u" #define APR_UINT64_T_HEX_FMT "I64x" /* Local machine definition for console and log output. */ #define APR_EOL_STR "\r\n" /* No difference between PROC and GLOBAL mutex */ #define APR_PROC_MUTEX_IS_GLOBAL 1 typedef int apr_wait_t; /* struct iovec is needed to emulate Unix writev */ struct iovec { char* iov_base; apr_size_t iov_len; }; /* Nasty Win32 .h ommissions we really need */ #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #if APR_HAS_UNICODE_FS /* An arbitrary size that is digestable. True max is a bit less than 32000 */ #define APR_PATH_MAX 8192 #else /* !APR_HAS_UNICODE_FS */ #define APR_PATH_MAX MAX_PATH #endif /** @} */ #ifdef __cplusplus } #endif /* Done with badly written headers */ #if defined(_MSC_VER) && _MSC_VER >= 1200 #pragma warning(pop) #pragma warning(disable: 4996) #endif #endif /* WIN32 */ #endif /* APR_H */
001-log4cxx
trunk/src/apr/include/apr.h
C
asf20
15,066
/* 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. */ #ifndef APR_ENV_H #define APR_ENV_H /** * @file apr_env.h * @brief APR Environment functions */ #include "apr_errno.h" #include "apr_pools.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** * @defgroup apr_env Functions for manupulating the environment * @ingroup APR * @{ */ /** * Get the value of an environment variable * @param value the returned value, allocated from @a pool * @param envvar the name of the environment variable * @param pool where to allocate @a value and any temporary storage from */ APR_DECLARE(apr_status_t) apr_env_get(char **value, const char *envvar, apr_pool_t *pool); /** * Set the value of an environment variable * @param envvar the name of the environment variable * @param value the value to set * @param pool where to allocate temporary storage from */ APR_DECLARE(apr_status_t) apr_env_set(const char *envvar, const char *value, apr_pool_t *pool); /** * Delete a variable from the environment * @param envvar the name of the environment variable * @param pool where to allocate temporary storage from */ APR_DECLARE(apr_status_t) apr_env_delete(const char *envvar, apr_pool_t *pool); /** @} */ #ifdef __cplusplus } #endif #endif /* ! APR_ENV_H */
001-log4cxx
trunk/src/apr/include/apr_env.h
C
asf20
2,105
/* 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. */ #ifndef APR_POOLS_H #define APR_POOLS_H /** * @file apr_pools.h * @brief APR memory allocation * * Resource allocation routines... * * designed so that we don't have to keep track of EVERYTHING so that * it can be explicitly freed later (a fundamentally unsound strategy --- * particularly in the presence of die()). * * Instead, we maintain pools, and allocate items (both memory and I/O * handlers) from the pools --- currently there are two, one for per * transaction info, and one for config info. When a transaction is over, * we can delete everything in the per-transaction apr_pool_t without fear, * and without thinking too hard about it either. */ #include "apr.h" #include "apr_errno.h" #include "apr_general.h" /* for APR_STRINGIFY */ #define APR_WANT_MEMFUNC /**< for no good reason? */ #include "apr_want.h" #ifdef __cplusplus extern "C" { #endif /** * @defgroup apr_pools Memory Pool Functions * @ingroup APR * @{ */ /** The fundamental pool type */ typedef struct apr_pool_t apr_pool_t; /** * Declaration helper macro to construct apr_foo_pool_get()s. * * This standardized macro is used by opaque (APR) data types to return * the apr_pool_t that is associated with the data type. * * APR_POOL_DECLARE_ACCESSOR() is used in a header file to declare the * accessor function. A typical usage and result would be: * <pre> * APR_POOL_DECLARE_ACCESSOR(file); * becomes: * APR_DECLARE(apr_pool_t *) apr_file_pool_get(apr_file_t *ob); * </pre> * @remark Doxygen unwraps this macro (via doxygen.conf) to provide * actual help for each specific occurance of apr_foo_pool_get. * @remark the linkage is specified for APR. It would be possible to expand * the macros to support other linkages. */ #define APR_POOL_DECLARE_ACCESSOR(type) \ APR_DECLARE(apr_pool_t *) apr_##type##_pool_get \ (const apr_##type##_t *the##type) /** * Implementation helper macro to provide apr_foo_pool_get()s. * * In the implementation, the APR_POOL_IMPLEMENT_ACCESSOR() is used to * actually define the function. It assumes the field is named "pool". */ #define APR_POOL_IMPLEMENT_ACCESSOR(type) \ APR_DECLARE(apr_pool_t *) apr_##type##_pool_get \ (const apr_##type##_t *the##type) \ { return the##type->pool; } /** * Pool debug levels * * <pre> * | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | * --------------------------------- * | | | | | | | | x | General debug code enabled (useful in * combination with --with-efence). * * | | | | | | | x | | Verbose output on stderr (report * CREATE, CLEAR, DESTROY). * * | | | | x | | | | | Verbose output on stderr (report * PALLOC, PCALLOC). * * | | | | | | x | | | Lifetime checking. On each use of a * pool, check its lifetime. If the pool * is out of scope, abort(). * In combination with the verbose flag * above, it will output LIFE in such an * event prior to aborting. * * | | | | | x | | | | Pool owner checking. On each use of a * pool, check if the current thread is the * pools owner. If not, abort(). In * combination with the verbose flag above, * it will output OWNER in such an event * prior to aborting. Use the debug * function apr_pool_owner_set() to switch * a pools ownership. * * When no debug level was specified, assume general debug mode. * If level 0 was specified, debugging is switched off * </pre> */ #if defined(APR_POOL_DEBUG) /* If APR_POOL_DEBUG is blank, we get 1; if it is a number, we get -1. */ #if (APR_POOL_DEBUG - APR_POOL_DEBUG -1 == 1) #undef APR_POOL_DEBUG #define APR_POOL_DEBUG 1 #endif #else #define APR_POOL_DEBUG 0 #endif /** the place in the code where the particular function was called */ #define APR_POOL__FILE_LINE__ __FILE__ ":" APR_STRINGIFY(__LINE__) /** A function that is called when allocation fails. */ typedef int (*apr_abortfunc_t)(int retcode); /* * APR memory structure manipulators (pools, tables, and arrays). */ /* * Initialization */ /** * Setup all of the internal structures required to use pools * @remark Programs do NOT need to call this directly. APR will call this * automatically from apr_initialize. * @internal */ APR_DECLARE(apr_status_t) apr_pool_initialize(void); /** * Tear down all of the internal structures required to use pools * @remark Programs do NOT need to call this directly. APR will call this * automatically from apr_terminate. * @internal */ APR_DECLARE(void) apr_pool_terminate(void); /* * Pool creation/destruction */ #include "apr_allocator.h" /** * Create a new pool. * @param newpool The pool we have just created. * @param parent The parent pool. If this is NULL, the new pool is a root * pool. If it is non-NULL, the new pool will inherit all * of its parent pool's attributes, except the apr_pool_t will * be a sub-pool. * @param abort_fn A function to use if the pool cannot allocate more memory. * @param allocator The allocator to use with the new pool. If NULL the * allocator of the parent pool will be used. */ APR_DECLARE(apr_status_t) apr_pool_create_ex(apr_pool_t **newpool, apr_pool_t *parent, apr_abortfunc_t abort_fn, apr_allocator_t *allocator); /** * Debug version of apr_pool_create_ex. * @param newpool @see apr_pool_create. * @param parent @see apr_pool_create. * @param abort_fn @see apr_pool_create. * @param allocator @see apr_pool_create. * @param file_line Where the function is called from. * This is usually APR_POOL__FILE_LINE__. * @remark Only available when APR_POOL_DEBUG is defined. * Call this directly if you have you apr_pool_create_ex * calls in a wrapper function and wish to override * the file_line argument to reflect the caller of * your wrapper function. If you do not have * apr_pool_create_ex in a wrapper, trust the macro * and don't call apr_pool_create_ex_debug directly. */ APR_DECLARE(apr_status_t) apr_pool_create_ex_debug(apr_pool_t **newpool, apr_pool_t *parent, apr_abortfunc_t abort_fn, apr_allocator_t *allocator, const char *file_line); #if APR_POOL_DEBUG #define apr_pool_create_ex(newpool, parent, abort_fn, allocator) \ apr_pool_create_ex_debug(newpool, parent, abort_fn, allocator, \ APR_POOL__FILE_LINE__) #endif /** * Create a new pool. * @param newpool The pool we have just created. * @param parent The parent pool. If this is NULL, the new pool is a root * pool. If it is non-NULL, the new pool will inherit all * of its parent pool's attributes, except the apr_pool_t will * be a sub-pool. */ #if defined(DOXYGEN) APR_DECLARE(apr_status_t) apr_pool_create(apr_pool_t **newpool, apr_pool_t *parent); #else #if APR_POOL_DEBUG #define apr_pool_create(newpool, parent) \ apr_pool_create_ex_debug(newpool, parent, NULL, NULL, \ APR_POOL__FILE_LINE__) #else #define apr_pool_create(newpool, parent) \ apr_pool_create_ex(newpool, parent, NULL, NULL) #endif #endif /** * Find the pools allocator * @param pool The pool to get the allocator from. */ APR_DECLARE(apr_allocator_t *) apr_pool_allocator_get(apr_pool_t *pool); /** * Clear all memory in the pool and run all the cleanups. This also destroys all * subpools. * @param p The pool to clear * @remark This does not actually free the memory, it just allows the pool * to re-use this memory for the next allocation. * @see apr_pool_destroy() */ APR_DECLARE(void) apr_pool_clear(apr_pool_t *p); /** * Debug version of apr_pool_clear. * @param p See: apr_pool_clear. * @param file_line Where the function is called from. * This is usually APR_POOL__FILE_LINE__. * @remark Only available when APR_POOL_DEBUG is defined. * Call this directly if you have you apr_pool_clear * calls in a wrapper function and wish to override * the file_line argument to reflect the caller of * your wrapper function. If you do not have * apr_pool_clear in a wrapper, trust the macro * and don't call apr_pool_destroy_clear directly. */ APR_DECLARE(void) apr_pool_clear_debug(apr_pool_t *p, const char *file_line); #if APR_POOL_DEBUG #define apr_pool_clear(p) \ apr_pool_clear_debug(p, APR_POOL__FILE_LINE__) #endif /** * Destroy the pool. This takes similar action as apr_pool_clear() and then * frees all the memory. * @param p The pool to destroy * @remark This will actually free the memory */ APR_DECLARE(void) apr_pool_destroy(apr_pool_t *p); /** * Debug version of apr_pool_destroy. * @param p See: apr_pool_destroy. * @param file_line Where the function is called from. * This is usually APR_POOL__FILE_LINE__. * @remark Only available when APR_POOL_DEBUG is defined. * Call this directly if you have you apr_pool_destroy * calls in a wrapper function and wish to override * the file_line argument to reflect the caller of * your wrapper function. If you do not have * apr_pool_destroy in a wrapper, trust the macro * and don't call apr_pool_destroy_debug directly. */ APR_DECLARE(void) apr_pool_destroy_debug(apr_pool_t *p, const char *file_line); #if APR_POOL_DEBUG #define apr_pool_destroy(p) \ apr_pool_destroy_debug(p, APR_POOL__FILE_LINE__) #endif /* * Memory allocation */ /** * Allocate a block of memory from a pool * @param p The pool to allocate from * @param size The amount of memory to allocate * @return The allocated memory */ APR_DECLARE(void *) apr_palloc(apr_pool_t *p, apr_size_t size); /** * Debug version of apr_palloc * @param p See: apr_palloc * @param size See: apr_palloc * @param file_line Where the function is called from. * This is usually APR_POOL__FILE_LINE__. * @return See: apr_palloc */ APR_DECLARE(void *) apr_palloc_debug(apr_pool_t *p, apr_size_t size, const char *file_line); #if APR_POOL_DEBUG #define apr_palloc(p, size) \ apr_palloc_debug(p, size, APR_POOL__FILE_LINE__) #endif /** * Allocate a block of memory from a pool and set all of the memory to 0 * @param p The pool to allocate from * @param size The amount of memory to allocate * @return The allocated memory */ #if defined(DOXYGEN) APR_DECLARE(void *) apr_pcalloc(apr_pool_t *p, apr_size_t size); #elif !APR_POOL_DEBUG #define apr_pcalloc(p, size) memset(apr_palloc(p, size), 0, size) #endif /** * Debug version of apr_pcalloc * @param p See: apr_pcalloc * @param size See: apr_pcalloc * @param file_line Where the function is called from. * This is usually APR_POOL__FILE_LINE__. * @return See: apr_pcalloc */ APR_DECLARE(void *) apr_pcalloc_debug(apr_pool_t *p, apr_size_t size, const char *file_line); #if APR_POOL_DEBUG #define apr_pcalloc(p, size) \ apr_pcalloc_debug(p, size, APR_POOL__FILE_LINE__) #endif /* * Pool Properties */ /** * Set the function to be called when an allocation failure occurs. * @remark If the program wants APR to exit on a memory allocation error, * then this function can be called to set the callback to use (for * performing cleanup and then exiting). If this function is not called, * then APR will return an error and expect the calling program to * deal with the error accordingly. */ APR_DECLARE(void) apr_pool_abort_set(apr_abortfunc_t abortfunc, apr_pool_t *pool); /** * Get the abort function associated with the specified pool. * @param pool The pool for retrieving the abort function. * @return The abort function for the given pool. */ APR_DECLARE(apr_abortfunc_t) apr_pool_abort_get(apr_pool_t *pool); /** * Get the parent pool of the specified pool. * @param pool The pool for retrieving the parent pool. * @return The parent of the given pool. */ APR_DECLARE(apr_pool_t *) apr_pool_parent_get(apr_pool_t *pool); /** * Determine if pool a is an ancestor of pool b. * @param a The pool to search * @param b The pool to search for * @return True if a is an ancestor of b, NULL is considered an ancestor * of all pools. * @remark if compiled with APR_POOL_DEBUG, this function will also * return true if A is a pool which has been guaranteed by the caller * (using apr_pool_join) to have a lifetime at least as long as some * ancestor of pool B. */ APR_DECLARE(int) apr_pool_is_ancestor(apr_pool_t *a, apr_pool_t *b); /** * Tag a pool (give it a name) * @param pool The pool to tag * @param tag The tag */ APR_DECLARE(void) apr_pool_tag(apr_pool_t *pool, const char *tag); /* * User data management */ /** * Set the data associated with the current pool * @param data The user data associated with the pool. * @param key The key to use for association * @param cleanup The cleanup program to use to cleanup the data (NULL if none) * @param pool The current pool * @warning The data to be attached to the pool should have a life span * at least as long as the pool it is being attached to. * * Users of APR must take EXTREME care when choosing a key to * use for their data. It is possible to accidentally overwrite * data by choosing a key that another part of the program is using. * Therefore it is advised that steps are taken to ensure that unique * keys are used for all of the userdata objects in a particular pool * (the same key in two different pools or a pool and one of its * subpools is okay) at all times. Careful namespace prefixing of * key names is a typical way to help ensure this uniqueness. * */ APR_DECLARE(apr_status_t) apr_pool_userdata_set( const void *data, const char *key, apr_status_t (*cleanup)(void *), apr_pool_t *pool); /** * Set the data associated with the current pool * @param data The user data associated with the pool. * @param key The key to use for association * @param cleanup The cleanup program to use to cleanup the data (NULL if none) * @param pool The current pool * @note same as apr_pool_userdata_set(), except that this version doesn't * make a copy of the key (this function is useful, for example, when * the key is a string literal) * @warning This should NOT be used if the key could change addresses by * any means between the apr_pool_userdata_setn() call and a * subsequent apr_pool_userdata_get() on that key, such as if a * static string is used as a userdata key in a DSO and the DSO could * be unloaded and reloaded between the _setn() and the _get(). You * MUST use apr_pool_userdata_set() in such cases. * @warning More generally, the key and the data to be attached to the * pool should have a life span at least as long as the pool itself. * */ APR_DECLARE(apr_status_t) apr_pool_userdata_setn( const void *data, const char *key, apr_status_t (*cleanup)(void *), apr_pool_t *pool); /** * Return the data associated with the current pool. * @param data The user data associated with the pool. * @param key The key for the data to retrieve * @param pool The current pool. */ APR_DECLARE(apr_status_t) apr_pool_userdata_get(void **data, const char *key, apr_pool_t *pool); /** * @defgroup PoolCleanup Pool Cleanup Functions * * Cleanups are performed in the reverse order they were registered. That is: * Last In, First Out. A cleanup function can safely allocate memory from * the pool that is being cleaned up. It can also safely register additional * cleanups which will be run LIFO, directly after the current cleanup * terminates. Cleanups have to take caution in calling functions that * create subpools. Subpools, created during cleanup will NOT automatically * be cleaned up. In other words, cleanups are to clean up after themselves. * * @{ */ /** * Register a function to be called when a pool is cleared or destroyed * @param p The pool register the cleanup with * @param data The data to pass to the cleanup function. * @param plain_cleanup The function to call when the pool is cleared * or destroyed * @param child_cleanup The function to call when a child process is about * to exec - this function is called in the child, obviously! */ APR_DECLARE(void) apr_pool_cleanup_register( apr_pool_t *p, const void *data, apr_status_t (*plain_cleanup)(void *), apr_status_t (*child_cleanup)(void *)); /** * Remove a previously registered cleanup function. * * The cleanup most recently registered with @a p having the same values of * @a data and @a cleanup will be removed. * * @param p The pool to remove the cleanup from * @param data The data of the registered cleanup * @param cleanup The function to remove from cleanup * @remarks For some strange reason only the plain_cleanup is handled by this * function */ APR_DECLARE(void) apr_pool_cleanup_kill(apr_pool_t *p, const void *data, apr_status_t (*cleanup)(void *)); /** * Replace the child cleanup function of a previously registered cleanup. * * The cleanup most recently registered with @a p having the same values of * @a data and @a plain_cleanup will have the registered child cleanup * function replaced with @a child_cleanup. * * @param p The pool of the registered cleanup * @param data The data of the registered cleanup * @param plain_cleanup The plain cleanup function of the registered cleanup * @param child_cleanup The function to register as the child cleanup */ APR_DECLARE(void) apr_pool_child_cleanup_set( apr_pool_t *p, const void *data, apr_status_t (*plain_cleanup)(void *), apr_status_t (*child_cleanup)(void *)); /** * Run the specified cleanup function immediately and unregister it. * * The cleanup most recently registered with @a p having the same values of * @a data and @a cleanup will be removed and @a cleanup will be called * with @a data as the argument. * * @param p The pool to remove the cleanup from * @param data The data to remove from cleanup * @param cleanup The function to remove from cleanup */ APR_DECLARE(apr_status_t) apr_pool_cleanup_run( apr_pool_t *p, void *data, apr_status_t (*cleanup)(void *)); /** * An empty cleanup function. * * Passed to apr_pool_cleanup_register() when no cleanup is required. * * @param data The data to cleanup, will not be used by this function. */ APR_DECLARE_NONSTD(apr_status_t) apr_pool_cleanup_null(void *data); /** * Run all registered child cleanups, in preparation for an exec() * call in a forked child -- close files, etc., but *don't* flush I/O * buffers, *don't* wait for subprocesses, and *don't* free any * memory. */ APR_DECLARE(void) apr_pool_cleanup_for_exec(void); /** @} */ /** * @defgroup PoolDebug Pool Debugging functions. * * pools have nested lifetimes -- sub_pools are destroyed when the * parent pool is cleared. We allow certain liberties with operations * on things such as tables (and on other structures in a more general * sense) where we allow the caller to insert values into a table which * were not allocated from the table's pool. The table's data will * remain valid as long as all the pools from which its values are * allocated remain valid. * * For example, if B is a sub pool of A, and you build a table T in * pool B, then it's safe to insert data allocated in A or B into T * (because B lives at most as long as A does, and T is destroyed when * B is cleared/destroyed). On the other hand, if S is a table in * pool A, it is safe to insert data allocated in A into S, but it * is *not safe* to insert data allocated from B into S... because * B can be cleared/destroyed before A is (which would leave dangling * pointers in T's data structures). * * In general we say that it is safe to insert data into a table T * if the data is allocated in any ancestor of T's pool. This is the * basis on which the APR_POOL_DEBUG code works -- it tests these ancestor * relationships for all data inserted into tables. APR_POOL_DEBUG also * provides tools (apr_pool_find, and apr_pool_is_ancestor) for other * folks to implement similar restrictions for their own data * structures. * * However, sometimes this ancestor requirement is inconvenient -- * sometimes it's necessary to create a sub pool where the sub pool is * guaranteed to have the same lifetime as the parent pool. This is a * guarantee implemented by the *caller*, not by the pool code. That * is, the caller guarantees they won't destroy the sub pool * individually prior to destroying the parent pool. * * In this case the caller must call apr_pool_join() to indicate this * guarantee to the APR_POOL_DEBUG code. * * These functions are only implemented when #APR_POOL_DEBUG is set. * * @{ */ #if APR_POOL_DEBUG || defined(DOXYGEN) /** * Guarantee that a subpool has the same lifetime as the parent. * @param p The parent pool * @param sub The subpool */ APR_DECLARE(void) apr_pool_join(apr_pool_t *p, apr_pool_t *sub); /** * Find a pool from something allocated in it. * @param mem The thing allocated in the pool * @return The pool it is allocated in */ APR_DECLARE(apr_pool_t *) apr_pool_find(const void *mem); /** * Report the number of bytes currently in the pool * @param p The pool to inspect * @param recurse Recurse/include the subpools' sizes * @return The number of bytes */ APR_DECLARE(apr_size_t) apr_pool_num_bytes(apr_pool_t *p, int recurse); /** * Lock a pool * @param pool The pool to lock * @param flag The flag */ APR_DECLARE(void) apr_pool_lock(apr_pool_t *pool, int flag); /* @} */ #else /* APR_POOL_DEBUG or DOXYGEN */ #ifdef apr_pool_join #undef apr_pool_join #endif #define apr_pool_join(a,b) #ifdef apr_pool_lock #undef apr_pool_lock #endif #define apr_pool_lock(pool, lock) #endif /* APR_POOL_DEBUG or DOXYGEN */ /** @} */ #ifdef __cplusplus } #endif #endif /* !APR_POOLS_H */
001-log4cxx
trunk/src/apr/include/apr_pools.h
C
asf20
23,956
/* 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. */ #ifndef APR_MMAP_H #define APR_MMAP_H /** * @file apr_mmap.h * @brief APR MMAP routines */ #include "apr.h" #include "apr_pools.h" #include "apr_errno.h" #include "apr_ring.h" #include "apr_file_io.h" /* for apr_file_t */ #ifdef BEOS #include <kernel/OS.h> #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** * @defgroup apr_mmap MMAP (Memory Map) Routines * @ingroup APR * @{ */ /** MMap opened for reading */ #define APR_MMAP_READ 1 /** MMap opened for writing */ #define APR_MMAP_WRITE 2 /** @see apr_mmap_t */ typedef struct apr_mmap_t apr_mmap_t; /** * @remark * As far as I can tell the only really sane way to store an MMAP is as a * void * and a length. BeOS requires this area_id, but that's just a little * something extra. I am exposing this type, because it doesn't make much * sense to keep it private, and opening it up makes some stuff easier in * Apache. */ /** The MMAP structure */ struct apr_mmap_t { /** The pool the mmap structure was allocated out of. */ apr_pool_t *cntxt; #ifdef BEOS /** An area ID. Only valid on BeOS */ area_id area; #endif #ifdef WIN32 /** The handle of the file mapping */ HANDLE mhandle; /** The start of the real memory page area (mapped view) */ void *mv; /** The physical start, size and offset */ apr_off_t pstart; apr_size_t psize; apr_off_t poffset; #endif /** The start of the memory mapped area */ void *mm; /** The amount of data in the mmap */ apr_size_t size; /** ring of apr_mmap_t's that reference the same * mmap'ed region; acts in place of a reference count */ APR_RING_ENTRY(apr_mmap_t) link; }; #if APR_HAS_MMAP || defined(DOXYGEN) /** @def APR_MMAP_THRESHOLD * Files have to be at least this big before they're mmap()d. This is to deal * with systems where the expense of doing an mmap() and an munmap() outweighs * the benefit for small files. It shouldn't be set lower than 1. */ #ifdef MMAP_THRESHOLD # define APR_MMAP_THRESHOLD MMAP_THRESHOLD #else # ifdef SUNOS4 # define APR_MMAP_THRESHOLD (8*1024) # else # define APR_MMAP_THRESHOLD 1 # endif /* SUNOS4 */ #endif /* MMAP_THRESHOLD */ /** @def APR_MMAP_LIMIT * Maximum size of MMap region */ #ifdef MMAP_LIMIT # define APR_MMAP_LIMIT MMAP_LIMIT #else # define APR_MMAP_LIMIT (4*1024*1024) #endif /* MMAP_LIMIT */ /** Can this file be MMaped */ #define APR_MMAP_CANDIDATE(filelength) \ ((filelength >= APR_MMAP_THRESHOLD) && (filelength < APR_MMAP_LIMIT)) /* Function definitions */ /** * Create a new mmap'ed file out of an existing APR file. * @param newmmap The newly created mmap'ed file. * @param file The file turn into an mmap. * @param offset The offset into the file to start the data pointer at. * @param size The size of the file * @param flag bit-wise or of: * <PRE> * APR_MMAP_READ MMap opened for reading * APR_MMAP_WRITE MMap opened for writing * </PRE> * @param cntxt The pool to use when creating the mmap. */ APR_DECLARE(apr_status_t) apr_mmap_create(apr_mmap_t **newmmap, apr_file_t *file, apr_off_t offset, apr_size_t size, apr_int32_t flag, apr_pool_t *cntxt); /** * Duplicate the specified MMAP. * @param new_mmap The structure to duplicate into. * @param old_mmap The mmap to duplicate. * @param p The pool to use for new_mmap. */ APR_DECLARE(apr_status_t) apr_mmap_dup(apr_mmap_t **new_mmap, apr_mmap_t *old_mmap, apr_pool_t *p); /** * Remove a mmap'ed. * @param mm The mmap'ed file. */ APR_DECLARE(apr_status_t) apr_mmap_delete(apr_mmap_t *mm); /** * Move the pointer into the mmap'ed file to the specified offset. * @param addr The pointer to the offset specified. * @param mm The mmap'ed file. * @param offset The offset to move to. */ APR_DECLARE(apr_status_t) apr_mmap_offset(void **addr, apr_mmap_t *mm, apr_off_t offset); #endif /* APR_HAS_MMAP */ /** @} */ #ifdef __cplusplus } #endif #endif /* ! APR_MMAP_H */
001-log4cxx
trunk/src/apr/include/apr_mmap.h
C
asf20
5,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. */ #ifndef APR_THREAD_MUTEX_H #define APR_THREAD_MUTEX_H /** * @file apr_thread_mutex.h * @brief APR Thread Mutex Routines */ #include "apr.h" #include "apr_errno.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #if APR_HAS_THREADS || defined(DOXYGEN) /** * @defgroup apr_thread_mutex Thread Mutex Routines * @ingroup APR * @{ */ /** Opaque thread-local mutex structure */ typedef struct apr_thread_mutex_t apr_thread_mutex_t; #define APR_THREAD_MUTEX_DEFAULT 0x0 /**< platform-optimal lock behavior */ #define APR_THREAD_MUTEX_NESTED 0x1 /**< enable nested (recursive) locks */ #define APR_THREAD_MUTEX_UNNESTED 0x2 /**< disable nested locks */ /* Delayed the include to avoid a circular reference */ #include "apr_pools.h" /** * Create and initialize a mutex that can be used to synchronize threads. * @param mutex the memory address where the newly created mutex will be * stored. * @param flags Or'ed value of: * <PRE> * APR_THREAD_MUTEX_DEFAULT platform-optimal lock behavior. * APR_THREAD_MUTEX_NESTED enable nested (recursive) locks. * APR_THREAD_MUTEX_UNNESTED disable nested locks (non-recursive). * </PRE> * @param pool the pool from which to allocate the mutex. * @warning Be cautious in using APR_THREAD_MUTEX_DEFAULT. While this is the * most optimial mutex based on a given platform's performance charateristics, * it will behave as either a nested or an unnested lock. */ APR_DECLARE(apr_status_t) apr_thread_mutex_create(apr_thread_mutex_t **mutex, unsigned int flags, apr_pool_t *pool); /** * Acquire the lock for the given mutex. If the mutex is already locked, * the current thread will be put to sleep until the lock becomes available. * @param mutex the mutex on which to acquire the lock. */ APR_DECLARE(apr_status_t) apr_thread_mutex_lock(apr_thread_mutex_t *mutex); /** * Attempt to acquire the lock for the given mutex. If the mutex has already * been acquired, the call returns immediately with APR_EBUSY. Note: it * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine * if the return value was APR_EBUSY, for portability reasons. * @param mutex the mutex on which to attempt the lock acquiring. */ APR_DECLARE(apr_status_t) apr_thread_mutex_trylock(apr_thread_mutex_t *mutex); /** * Release the lock for the given mutex. * @param mutex the mutex from which to release the lock. */ APR_DECLARE(apr_status_t) apr_thread_mutex_unlock(apr_thread_mutex_t *mutex); /** * Destroy the mutex and free the memory associated with the lock. * @param mutex the mutex to destroy. */ APR_DECLARE(apr_status_t) apr_thread_mutex_destroy(apr_thread_mutex_t *mutex); /** * Get the pool used by this thread_mutex. * @return apr_pool_t the pool */ APR_POOL_DECLARE_ACCESSOR(thread_mutex); #endif /* APR_HAS_THREADS */ /** @} */ #ifdef __cplusplus } #endif #endif /* ! APR_THREAD_MUTEX_H */
001-log4cxx
trunk/src/apr/include/apr_thread_mutex.h
C
asf20
3,836
/* 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. */ #ifndef APR_TABLES_H #define APR_TABLES_H /** * @file apr_tables.h * @brief APR Table library */ #include "apr.h" #include "apr_pools.h" #if APR_HAVE_STDARG_H #include <stdarg.h> /* for va_list */ #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** * @defgroup apr_tables Table and Array Functions * @ingroup APR * Tables are used to store entirely opaque structures * for applications, while Arrays are usually used to * deal with string lists. * @{ */ /** the table abstract data type */ typedef struct apr_table_t apr_table_t; /** @see apr_array_header_t */ typedef struct apr_array_header_t apr_array_header_t; /** An opaque array type */ struct apr_array_header_t { /** The pool the array is allocated out of */ apr_pool_t *pool; /** The amount of memory allocated for each element of the array */ int elt_size; /** The number of active elements in the array */ int nelts; /** The number of elements allocated in the array */ int nalloc; /** The elements in the array */ char *elts; }; /** * The (opaque) structure for string-content tables. */ typedef struct apr_table_entry_t apr_table_entry_t; /** The type for each entry in a string-content table */ struct apr_table_entry_t { /** The key for the current table entry */ char *key; /* maybe NULL in future; * check when iterating thru table_elts */ /** The value for the current table entry */ char *val; /** A checksum for the key, for use by the apr_table internals */ apr_uint32_t key_checksum; }; /** * Get the elements from a table * @param t The table * @return An array containing the contents of the table */ APR_DECLARE(const apr_array_header_t *) apr_table_elts(const apr_table_t *t); /** * Determine if the table is empty * @param t The table to check * @return True if empty, False otherwise */ APR_DECLARE(int) apr_is_empty_table(const apr_table_t *t); /** * Determine if the array is empty * @param a The array to check * @return True if empty, False otherwise */ APR_DECLARE(int) apr_is_empty_array(const apr_array_header_t *a); /** * Create an array * @param p The pool to allocate the memory out of * @param nelts the number of elements in the initial array * @param elt_size The size of each element in the array. * @return The new array */ APR_DECLARE(apr_array_header_t *) apr_array_make(apr_pool_t *p, int nelts, int elt_size); /** * Add a new element to an array (as a first-in, last-out stack) * @param arr The array to add an element to. * @return Location for the new element in the array. * @remark If there are no free spots in the array, then this function will * allocate new space for the new element. */ APR_DECLARE(void *) apr_array_push(apr_array_header_t *arr); /** * Remove an element from an array (as a first-in, last-out stack) * @param arr The array to remove an element from. * @return Location of the element in the array. * @remark If there are no elements in the array, NULL is returned. */ APR_DECLARE(void *) apr_array_pop(apr_array_header_t *arr); /** * Concatenate two arrays together * @param dst The destination array, and the one to go first in the combined * array * @param src The source array to add to the destination array */ APR_DECLARE(void) apr_array_cat(apr_array_header_t *dst, const apr_array_header_t *src); /** * Copy the entire array * @param p The pool to allocate the copy of the array out of * @param arr The array to copy * @return An exact copy of the array passed in * @remark The alternate apr_array_copy_hdr copies only the header, and arranges * for the elements to be copied if (and only if) the code subsequently * does a push or arraycat. */ APR_DECLARE(apr_array_header_t *) apr_array_copy(apr_pool_t *p, const apr_array_header_t *arr); /** * Copy the headers of the array, and arrange for the elements to be copied if * and only if the code subsequently does a push or arraycat. * @param p The pool to allocate the copy of the array out of * @param arr The array to copy * @return An exact copy of the array passed in * @remark The alternate apr_array_copy copies the *entire* array. */ APR_DECLARE(apr_array_header_t *) apr_array_copy_hdr(apr_pool_t *p, const apr_array_header_t *arr); /** * Append one array to the end of another, creating a new array in the process. * @param p The pool to allocate the new array out of * @param first The array to put first in the new array. * @param second The array to put second in the new array. * @return A new array containing the data from the two arrays passed in. */ APR_DECLARE(apr_array_header_t *) apr_array_append(apr_pool_t *p, const apr_array_header_t *first, const apr_array_header_t *second); /** * Generates a new string from the apr_pool_t containing the concatenated * sequence of substrings referenced as elements within the array. The string * will be empty if all substrings are empty or null, or if there are no * elements in the array. If sep is non-NUL, it will be inserted between * elements as a separator. * @param p The pool to allocate the string out of * @param arr The array to generate the string from * @param sep The separator to use * @return A string containing all of the data in the array. */ APR_DECLARE(char *) apr_array_pstrcat(apr_pool_t *p, const apr_array_header_t *arr, const char sep); /** * Make a new table * @param p The pool to allocate the pool out of * @param nelts The number of elements in the initial table. * @return The new table. * @warning This table can only store text data */ APR_DECLARE(apr_table_t *) apr_table_make(apr_pool_t *p, int nelts); /** * Create a new table and copy another table into it * @param p The pool to allocate the new table out of * @param t The table to copy * @return A copy of the table passed in */ APR_DECLARE(apr_table_t *) apr_table_copy(apr_pool_t *p, const apr_table_t *t); /** * Delete all of the elements from a table * @param t The table to clear */ APR_DECLARE(void) apr_table_clear(apr_table_t *t); /** * Get the value associated with a given key from the table. After this call, * The data is still in the table * @param t The table to search for the key * @param key The key to search for * @return The value associated with the key, or NULL if the key does not exist. */ APR_DECLARE(const char *) apr_table_get(const apr_table_t *t, const char *key); /** * Add a key/value pair to a table, if another element already exists with the * same key, this will over-write the old data. * @param t The table to add the data to. * @param key The key fo use * @param val The value to add * @remark When adding data, this function makes a copy of both the key and the * value. */ APR_DECLARE(void) apr_table_set(apr_table_t *t, const char *key, const char *val); /** * Add a key/value pair to a table, if another element already exists with the * same key, this will over-write the old data. * @param t The table to add the data to. * @param key The key to use * @param val The value to add * @warning When adding data, this function does not make a copy of the key or * the value, so care should be taken to ensure that the values will * not change after they have been added.. */ APR_DECLARE(void) apr_table_setn(apr_table_t *t, const char *key, const char *val); /** * Remove data from the table * @param t The table to remove data from * @param key The key of the data being removed */ APR_DECLARE(void) apr_table_unset(apr_table_t *t, const char *key); /** * Add data to a table by merging the value with data that has already been * stored * @param t The table to search for the data * @param key The key to merge data for * @param val The data to add * @remark If the key is not found, then this function acts like apr_table_add */ APR_DECLARE(void) apr_table_merge(apr_table_t *t, const char *key, const char *val); /** * Add data to a table by merging the value with data that has already been * stored * @param t The table to search for the data * @param key The key to merge data for * @param val The data to add * @remark If the key is not found, then this function acts like apr_table_addn */ APR_DECLARE(void) apr_table_mergen(apr_table_t *t, const char *key, const char *val); /** * Add data to a table, regardless of whether there is another element with the * same key. * @param t The table to add to * @param key The key to use * @param val The value to add. * @remark When adding data, this function makes a copy of both the key and the * value. */ APR_DECLARE(void) apr_table_add(apr_table_t *t, const char *key, const char *val); /** * Add data to a table, regardless of whether there is another element with the * same key. * @param t The table to add to * @param key The key to use * @param val The value to add. * @remark When adding data, this function does not make a copy of the key or the * value, so care should be taken to ensure that the values will not * change after they have been added.. */ APR_DECLARE(void) apr_table_addn(apr_table_t *t, const char *key, const char *val); /** * Merge two tables into one new table * @param p The pool to use for the new table * @param overlay The first table to put in the new table * @param base The table to add at the end of the new table * @return A new table containing all of the data from the two passed in */ APR_DECLARE(apr_table_t *) apr_table_overlay(apr_pool_t *p, const apr_table_t *overlay, const apr_table_t *base); /** * Declaration prototype for the iterator callback function of apr_table_do() * and apr_table_vdo(). * @param rec The data passed as the first argument to apr_table_[v]do() * @param key The key from this iteration of the table * @param value The value from this iteration of the table * @remark Iteration continues while this callback function returns non-zero. * To export the callback function for apr_table_[v]do() it must be declared * in the _NONSTD convention. */ typedef int (apr_table_do_callback_fn_t)(void *rec, const char *key, const char *value); /** * Iterate over a table running the provided function once for every * element in the table. If there is data passed in as a vararg, then the * function is only run on those elements whose key matches something in * the vararg. If the vararg is NULL, then every element is run through the * function. Iteration continues while the function returns non-zero. * @param comp The function to run * @param rec The data to pass as the first argument to the function * @param t The table to iterate over * @param ... The vararg. If this is NULL, then all elements in the table are * run through the function, otherwise only those whose key matches * are run. * @return FALSE if one of the comp() iterations returned zero; TRUE if all * iterations returned non-zero * @see apr_table_do_callback_fn_t */ APR_DECLARE_NONSTD(int) apr_table_do(apr_table_do_callback_fn_t *comp, void *rec, const apr_table_t *t, ...); /** * Iterate over a table running the provided function once for every * element in the table. If there is data passed in as a vararg, then the * function is only run on those element's whose key matches something in * the vararg. If the vararg is NULL, then every element is run through the * function. Iteration continues while the function returns non-zero. * @param comp The function to run * @param rec The data to pass as the first argument to the function * @param t The table to iterate over * @param vp The vararg table. If this is NULL, then all elements in the * table are run through the function, otherwise only those * whose key matches are run. * @return FALSE if one of the comp() iterations returned zero; TRUE if all * iterations returned non-zero * @see apr_table_do_callback_fn_t */ APR_DECLARE(int) apr_table_vdo(apr_table_do_callback_fn_t *comp, void *rec, const apr_table_t *t, va_list vp); /** flag for overlap to use apr_table_setn */ #define APR_OVERLAP_TABLES_SET (0) /** flag for overlap to use apr_table_mergen */ #define APR_OVERLAP_TABLES_MERGE (1) /** * For each element in table b, either use setn or mergen to add the data * to table a. Which method is used is determined by the flags passed in. * @param a The table to add the data to. * @param b The table to iterate over, adding its data to table a * @param flags How to add the table to table a. One of: * APR_OVERLAP_TABLES_SET Use apr_table_setn * APR_OVERLAP_TABLES_MERGE Use apr_table_mergen * @remark This function is highly optimized, and uses less memory and CPU cycles * than a function that just loops through table b calling other functions. */ /** *<PRE> * Conceptually, apr_table_overlap does this: * * apr_array_header_t *barr = apr_table_elts(b); * apr_table_entry_t *belt = (apr_table_entry_t *)barr->elts; * int i; * * for (i = 0; i < barr->nelts; ++i) { * if (flags & APR_OVERLAP_TABLES_MERGE) { * apr_table_mergen(a, belt[i].key, belt[i].val); * } * else { * apr_table_setn(a, belt[i].key, belt[i].val); * } * } * * Except that it is more efficient (less space and cpu-time) especially * when b has many elements. * * Notice the assumptions on the keys and values in b -- they must be * in an ancestor of a's pool. In practice b and a are usually from * the same pool. * </PRE> */ APR_DECLARE(void) apr_table_overlap(apr_table_t *a, const apr_table_t *b, unsigned flags); /** * Eliminate redundant entries in a table by either overwriting * or merging duplicates * * @param t Table. * @param flags APR_OVERLAP_TABLES_MERGE to merge, or * APR_OVERLAP_TABLES_SET to overwrite */ APR_DECLARE(void) apr_table_compress(apr_table_t *t, unsigned flags); /** @} */ #ifdef __cplusplus } #endif #endif /* ! APR_TABLES_H */
001-log4cxx
trunk/src/apr/include/apr_tables.h
C
asf20
15,698
/* 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. */ #ifndef APR_POLL_H #define APR_POLL_H /** * @file apr_poll.h * @brief APR Poll interface */ #include "apr.h" #include "apr_pools.h" #include "apr_errno.h" #include "apr_inherit.h" #include "apr_file_io.h" #include "apr_network_io.h" #if APR_HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** * @defgroup apr_poll Poll Routines * @ingroup APR * @{ */ /** * Poll options */ #define APR_POLLIN 0x001 /**< Can read without blocking */ #define APR_POLLPRI 0x002 /**< Priority data available */ #define APR_POLLOUT 0x004 /**< Can write without blocking */ #define APR_POLLERR 0x010 /**< Pending error */ #define APR_POLLHUP 0x020 /**< Hangup occurred */ #define APR_POLLNVAL 0x040 /**< Descriptior invalid */ /** * Pollset Flags */ #define APR_POLLSET_THREADSAFE 0x001 /**< Adding or Removing a Descriptor is thread safe */ /** Used in apr_pollfd_t to determine what the apr_descriptor is */ typedef enum { APR_NO_DESC, /**< nothing here */ APR_POLL_SOCKET, /**< descriptor refers to a socket */ APR_POLL_FILE, /**< descriptor refers to a file */ APR_POLL_LASTDESC /**< descriptor is the last one in the list */ } apr_datatype_e ; /** Union of either an APR file or socket. */ typedef union { apr_file_t *f; /**< file */ apr_socket_t *s; /**< socket */ } apr_descriptor; /** @see apr_pollfd_t */ typedef struct apr_pollfd_t apr_pollfd_t; /** Poll descriptor set. */ struct apr_pollfd_t { apr_pool_t *p; /**< associated pool */ apr_datatype_e desc_type; /**< descriptor type */ apr_int16_t reqevents; /**< requested events */ apr_int16_t rtnevents; /**< returned events */ apr_descriptor desc; /**< @see apr_descriptor */ void *client_data; /**< allows app to associate context */ }; /* General-purpose poll API for arbitrarily large numbers of * file descriptors */ /** Opaque structure used for pollset API */ typedef struct apr_pollset_t apr_pollset_t; /** * Setup a pollset object * @param pollset The pointer in which to return the newly created object * @param size The maximum number of descriptors that this pollset can hold * @param p The pool from which to allocate the pollset * @param flags Optional flags to modify the operation of the pollset. * * @remark If flags equals APR_POLLSET_THREADSAFE, then a pollset is * created on which it is safe to make concurrent calls to * apr_pollset_add(), apr_pollset_remove() and apr_pollset_poll() from * separate threads. This feature is only supported on some * platforms; the apr_pollset_create() call will fail with * APR_ENOTIMPL on platforms where it is not supported. */ APR_DECLARE(apr_status_t) apr_pollset_create(apr_pollset_t **pollset, apr_uint32_t size, apr_pool_t *p, apr_uint32_t flags); /** * Destroy a pollset object * @param pollset The pollset to destroy */ APR_DECLARE(apr_status_t) apr_pollset_destroy(apr_pollset_t *pollset); /** * Add a socket or file descriptor to a pollset * @param pollset The pollset to which to add the descriptor * @param descriptor The descriptor to add * @remark If you set client_data in the descriptor, that value * will be returned in the client_data field whenever this * descriptor is signalled in apr_pollset_poll(). * @remark If the pollset has been created with APR_POLLSET_THREADSAFE * and thread T1 is blocked in a call to apr_pollset_poll() for * this same pollset that is being modified via apr_pollset_add() * in thread T2, the currently executing apr_pollset_poll() call in * T1 will either: (1) automatically include the newly added descriptor * in the set of descriptors it is watching or (2) return immediately * with APR_EINTR. Option (1) is recommended, but option (2) is * allowed for implementations where option (1) is impossible * or impractical. */ APR_DECLARE(apr_status_t) apr_pollset_add(apr_pollset_t *pollset, const apr_pollfd_t *descriptor); /** * Remove a descriptor from a pollset * @param pollset The pollset from which to remove the descriptor * @param descriptor The descriptor to remove * @remark If the pollset has been created with APR_POLLSET_THREADSAFE * and thread T1 is blocked in a call to apr_pollset_poll() for * this same pollset that is being modified via apr_pollset_remove() * in thread T2, the currently executing apr_pollset_poll() call in * T1 will either: (1) automatically exclude the newly added descriptor * in the set of descriptors it is watching or (2) return immediately * with APR_EINTR. Option (1) is recommended, but option (2) is * allowed for implementations where option (1) is impossible * or impractical. */ APR_DECLARE(apr_status_t) apr_pollset_remove(apr_pollset_t *pollset, const apr_pollfd_t *descriptor); /** * Block for activity on the descriptor(s) in a pollset * @param pollset The pollset to use * @param timeout Timeout in microseconds * @param num Number of signalled descriptors (output parameter) * @param descriptors Array of signalled descriptors (output parameter) */ APR_DECLARE(apr_status_t) apr_pollset_poll(apr_pollset_t *pollset, apr_interval_time_t timeout, apr_int32_t *num, const apr_pollfd_t **descriptors); /** * Poll the descriptors in the poll structure * @param aprset The poll structure we will be using. * @param numsock The number of descriptors we are polling * @param nsds The number of descriptors signalled. * @param timeout The amount of time in microseconds to wait. This is * a maximum, not a minimum. If a descriptor is signalled, we * will wake up before this time. A negative number means * wait until a descriptor is signalled. * @remark The number of descriptors signalled is returned in the third argument. * This is a blocking call, and it will not return until either a * descriptor has been signalled, or the timeout has expired. * @remark The rtnevents field in the apr_pollfd_t array will only be filled- * in if the return value is APR_SUCCESS. */ APR_DECLARE(apr_status_t) apr_poll(apr_pollfd_t *aprset, apr_int32_t numsock, apr_int32_t *nsds, apr_interval_time_t timeout); /** @} */ #ifdef __cplusplus } #endif #endif /* ! APR_POLL_H */
001-log4cxx
trunk/src/apr/include/apr_poll.h
C
asf20
7,767
/* 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. */ #ifndef APR_DSO_DOT_H #define APR_DSO_DOT_H /** * @file apr_dso.h * @brief APR Dynamic Object Handling Routines */ #include "apr.h" #include "apr_pools.h" #include "apr_errno.h" #ifdef __cplusplus extern "C" { #endif /** * @defgroup apr_dso Dynamic Object Handling * @ingroup APR * @{ */ #if APR_HAS_DSO || defined(DOXYGEN) /** * Structure for referencing dynamic objects */ typedef struct apr_dso_handle_t apr_dso_handle_t; /** * Structure for referencing symbols from dynamic objects */ typedef void * apr_dso_handle_sym_t; /** * Load a DSO library. * @param res_handle Location to store new handle for the DSO. * @param path Path to the DSO library * @param ctx Pool to use. * @bug We aught to provide an alternative to RTLD_GLOBAL, which * is the only supported method of loading DSOs today. */ APR_DECLARE(apr_status_t) apr_dso_load(apr_dso_handle_t **res_handle, const char *path, apr_pool_t *ctx); /** * Close a DSO library. * @param handle handle to close. */ APR_DECLARE(apr_status_t) apr_dso_unload(apr_dso_handle_t *handle); /** * Load a symbol from a DSO handle. * @param ressym Location to store the loaded symbol * @param handle handle to load the symbol from. * @param symname Name of the symbol to load. */ APR_DECLARE(apr_status_t) apr_dso_sym(apr_dso_handle_sym_t *ressym, apr_dso_handle_t *handle, const char *symname); /** * Report more information when a DSO function fails. * @param dso The dso handle that has been opened * @param buf Location to store the dso error * @param bufsize The size of the provided buffer */ APR_DECLARE(const char *) apr_dso_error(apr_dso_handle_t *dso, char *buf, apr_size_t bufsize); #endif /* APR_HAS_DSO */ /** @} */ #ifdef __cplusplus } #endif #endif
001-log4cxx
trunk/src/apr/include/apr_dso.h
C
asf20
2,700
/* 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. */ /* * This code draws heavily from the 4.4BSD <sys/queue.h> macros * and Dean Gaudet's "splim/ring.h". * <http://www.freebsd.org/cgi/cvsweb.cgi/src/sys/sys/queue.h> * <http://www.arctic.org/~dean/splim/> * * We'd use Dean's code directly if we could guarantee the * availability of inline functions. */ #ifndef APR_RING_H #define APR_RING_H /** * @file apr_ring.h * @brief APR Rings */ /* * for offsetof() */ #include "apr_general.h" /** * @defgroup apr_ring Ring Macro Implementations * @ingroup APR * A ring is a kind of doubly-linked list that can be manipulated * without knowing where its head is. * @{ */ /** * The Ring Element * * A ring element struct is linked to the other elements in the ring * through its ring entry field, e.g. * <pre> * struct my_element_t { * APR_RING_ENTRY(my_element_t) link; * int foo; * char *bar; * }; * </pre> * * An element struct may be put on more than one ring if it has more * than one APR_RING_ENTRY field. Each APR_RING_ENTRY has a corresponding * APR_RING_HEAD declaration. * * @warning For strict C standards compliance you should put the APR_RING_ENTRY * first in the element struct unless the head is always part of a larger * object with enough earlier fields to accommodate the offsetof() used * to compute the ring sentinel below. You can usually ignore this caveat. */ #define APR_RING_ENTRY(elem) \ struct { \ struct elem *next; \ struct elem *prev; \ } /** * The Ring Head * * Each ring is managed via its head, which is a struct declared like this: * <pre> * APR_RING_HEAD(my_ring_t, my_element_t); * struct my_ring_t ring, *ringp; * </pre> * * This struct looks just like the element link struct so that we can * be sure that the typecasting games will work as expected. * * The first element in the ring is next after the head, and the last * element is just before the head. */ #define APR_RING_HEAD(head, elem) \ struct head { \ struct elem *next; \ struct elem *prev; \ } /** * The Ring Sentinel * * This is the magic pointer value that occurs before the first and * after the last elements in the ring, computed from the address of * the ring's head. The head itself isn't an element, but in order to * get rid of all the special cases when dealing with the ends of the * ring, we play typecasting games to make it look like one. * * Here is a diagram to illustrate the arrangements of the next and * prev pointers of each element in a single ring. Note that they point * to the start of each element, not to the APR_RING_ENTRY structure. * * <pre> * +->+------+<-+ +->+------+<-+ +->+------+<-+ * | |struct| | | |struct| | | |struct| | * / | elem | \/ | elem | \/ | elem | \ * ... | | /\ | | /\ | | ... * +------+ | | +------+ | | +------+ * ...--|prev | | +--|ring | | +--|prev | * | next|--+ | entry|--+ | next|--... * +------+ +------+ +------+ * | etc. | | etc. | | etc. | * : : : : : : * </pre> * * The APR_RING_HEAD is nothing but a bare APR_RING_ENTRY. The prev * and next pointers in the first and last elements don't actually * point to the head, they point to a phantom place called the * sentinel. Its value is such that last->next->next == first because * the offset from the sentinel to the head's next pointer is the same * as the offset from the start of an element to its next pointer. * This also works in the opposite direction. * * <pre> * last first * +->+------+<-+ +->sentinel<-+ +->+------+<-+ * | |struct| | | | | |struct| | * / | elem | \/ \/ | elem | \ * ... | | /\ /\ | | ... * +------+ | | +------+ | | +------+ * ...--|prev | | +--|ring | | +--|prev | * | next|--+ | head|--+ | next|--... * +------+ +------+ +------+ * | etc. | | etc. | * : : : : * </pre> * * Note that the offset mentioned above is different for each kind of * ring that the element may be on, and each kind of ring has a unique * name for its APR_RING_ENTRY in each element, and has its own type * for its APR_RING_HEAD. * * Note also that if the offset is non-zero (which is required if an * element has more than one APR_RING_ENTRY), the unreality of the * sentinel may have bad implications on very perverse implementations * of C -- see the warning in APR_RING_ENTRY. * * @param hp The head of the ring * @param elem The name of the element struct * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_SENTINEL(hp, elem, link) \ (struct elem *)((char *)(hp) - APR_OFFSETOF(struct elem, link)) /** * The first element of the ring * @param hp The head of the ring */ #define APR_RING_FIRST(hp) (hp)->next /** * The last element of the ring * @param hp The head of the ring */ #define APR_RING_LAST(hp) (hp)->prev /** * The next element in the ring * @param ep The current element * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_NEXT(ep, link) (ep)->link.next /** * The previous element in the ring * @param ep The current element * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_PREV(ep, link) (ep)->link.prev /** * Initialize a ring * @param hp The head of the ring * @param elem The name of the element struct * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_INIT(hp, elem, link) do { \ APR_RING_FIRST((hp)) = APR_RING_SENTINEL((hp), elem, link); \ APR_RING_LAST((hp)) = APR_RING_SENTINEL((hp), elem, link); \ } while (0) /** * Determine if a ring is empty * @param hp The head of the ring * @param elem The name of the element struct * @param link The name of the APR_RING_ENTRY in the element struct * @return true or false */ #define APR_RING_EMPTY(hp, elem, link) \ (APR_RING_FIRST((hp)) == APR_RING_SENTINEL((hp), elem, link)) /** * Initialize a singleton element * @param ep The element * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_ELEM_INIT(ep, link) do { \ APR_RING_NEXT((ep), link) = (ep); \ APR_RING_PREV((ep), link) = (ep); \ } while (0) /** * Splice the sequence ep1..epN into the ring before element lep * (..lep.. becomes ..ep1..epN..lep..) * @warning This doesn't work for splicing before the first element or on * empty rings... see APR_RING_SPLICE_HEAD for one that does * @param lep Element in the ring to splice before * @param ep1 First element in the sequence to splice in * @param epN Last element in the sequence to splice in * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_SPLICE_BEFORE(lep, ep1, epN, link) do { \ APR_RING_NEXT((epN), link) = (lep); \ APR_RING_PREV((ep1), link) = APR_RING_PREV((lep), link); \ APR_RING_NEXT(APR_RING_PREV((lep), link), link) = (ep1); \ APR_RING_PREV((lep), link) = (epN); \ } while (0) /** * Splice the sequence ep1..epN into the ring after element lep * (..lep.. becomes ..lep..ep1..epN..) * @warning This doesn't work for splicing after the last element or on * empty rings... see APR_RING_SPLICE_TAIL for one that does * @param lep Element in the ring to splice after * @param ep1 First element in the sequence to splice in * @param epN Last element in the sequence to splice in * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_SPLICE_AFTER(lep, ep1, epN, link) do { \ APR_RING_PREV((ep1), link) = (lep); \ APR_RING_NEXT((epN), link) = APR_RING_NEXT((lep), link); \ APR_RING_PREV(APR_RING_NEXT((lep), link), link) = (epN); \ APR_RING_NEXT((lep), link) = (ep1); \ } while (0) /** * Insert the element nep into the ring before element lep * (..lep.. becomes ..nep..lep..) * @warning This doesn't work for inserting before the first element or on * empty rings... see APR_RING_INSERT_HEAD for one that does * @param lep Element in the ring to insert before * @param nep Element to insert * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_INSERT_BEFORE(lep, nep, link) \ APR_RING_SPLICE_BEFORE((lep), (nep), (nep), link) /** * Insert the element nep into the ring after element lep * (..lep.. becomes ..lep..nep..) * @warning This doesn't work for inserting after the last element or on * empty rings... see APR_RING_INSERT_TAIL for one that does * @param lep Element in the ring to insert after * @param nep Element to insert * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_INSERT_AFTER(lep, nep, link) \ APR_RING_SPLICE_AFTER((lep), (nep), (nep), link) /** * Splice the sequence ep1..epN into the ring before the first element * (..hp.. becomes ..hp..ep1..epN..) * @param hp Head of the ring * @param ep1 First element in the sequence to splice in * @param epN Last element in the sequence to splice in * @param elem The name of the element struct * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_SPLICE_HEAD(hp, ep1, epN, elem, link) \ APR_RING_SPLICE_AFTER(APR_RING_SENTINEL((hp), elem, link), \ (ep1), (epN), link) /** * Splice the sequence ep1..epN into the ring after the last element * (..hp.. becomes ..ep1..epN..hp..) * @param hp Head of the ring * @param ep1 First element in the sequence to splice in * @param epN Last element in the sequence to splice in * @param elem The name of the element struct * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_SPLICE_TAIL(hp, ep1, epN, elem, link) \ APR_RING_SPLICE_BEFORE(APR_RING_SENTINEL((hp), elem, link), \ (ep1), (epN), link) /** * Insert the element nep into the ring before the first element * (..hp.. becomes ..hp..nep..) * @param hp Head of the ring * @param nep Element to insert * @param elem The name of the element struct * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_INSERT_HEAD(hp, nep, elem, link) \ APR_RING_SPLICE_HEAD((hp), (nep), (nep), elem, link) /** * Insert the element nep into the ring after the last element * (..hp.. becomes ..nep..hp..) * @param hp Head of the ring * @param nep Element to insert * @param elem The name of the element struct * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_INSERT_TAIL(hp, nep, elem, link) \ APR_RING_SPLICE_TAIL((hp), (nep), (nep), elem, link) /** * Concatenate ring h2 onto the end of ring h1, leaving h2 empty. * @param h1 Head of the ring to concatenate onto * @param h2 Head of the ring to concatenate * @param elem The name of the element struct * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_CONCAT(h1, h2, elem, link) do { \ if (!APR_RING_EMPTY((h2), elem, link)) { \ APR_RING_SPLICE_BEFORE(APR_RING_SENTINEL((h1), elem, link), \ APR_RING_FIRST((h2)), \ APR_RING_LAST((h2)), link); \ APR_RING_INIT((h2), elem, link); \ } \ } while (0) /** * Prepend ring h2 onto the beginning of ring h1, leaving h2 empty. * @param h1 Head of the ring to prepend onto * @param h2 Head of the ring to prepend * @param elem The name of the element struct * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_PREPEND(h1, h2, elem, link) do { \ if (!APR_RING_EMPTY((h2), elem, link)) { \ APR_RING_SPLICE_AFTER(APR_RING_SENTINEL((h1), elem, link), \ APR_RING_FIRST((h2)), \ APR_RING_LAST((h2)), link); \ APR_RING_INIT((h2), elem, link); \ } \ } while (0) /** * Unsplice a sequence of elements from a ring * @warning The unspliced sequence is left with dangling pointers at either end * @param ep1 First element in the sequence to unsplice * @param epN Last element in the sequence to unsplice * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_UNSPLICE(ep1, epN, link) do { \ APR_RING_NEXT(APR_RING_PREV((ep1), link), link) = \ APR_RING_NEXT((epN), link); \ APR_RING_PREV(APR_RING_NEXT((epN), link), link) = \ APR_RING_PREV((ep1), link); \ } while (0) /** * Remove a single element from a ring * @warning The unspliced element is left with dangling pointers at either end * @param ep Element to remove * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_REMOVE(ep, link) \ APR_RING_UNSPLICE((ep), (ep), link) /* Debugging tools: */ #ifdef APR_RING_DEBUG #include <stdio.h> #include <assert.h> #define APR_RING_CHECK_ONE(msg, ptr) \ fprintf(stderr, "*** %s %p\n", msg, ptr) #define APR_RING_CHECK(hp, elem, link, msg) \ APR_RING_CHECK_ELEM(APR_RING_SENTINEL(hp, elem, link), elem, link, msg) #define APR_RING_CHECK_ELEM(ep, elem, link, msg) do { \ struct elem *start = (ep); \ struct elem *here = start; \ fprintf(stderr, "*** ring check start -- %s\n", msg); \ do { \ fprintf(stderr, "\telem %p\n", here); \ fprintf(stderr, "\telem->next %p\n", \ APR_RING_NEXT(here, link)); \ fprintf(stderr, "\telem->prev %p\n", \ APR_RING_PREV(here, link)); \ fprintf(stderr, "\telem->next->prev %p\n", \ APR_RING_PREV(APR_RING_NEXT(here, link), link)); \ fprintf(stderr, "\telem->prev->next %p\n", \ APR_RING_NEXT(APR_RING_PREV(here, link), link)); \ if (APR_RING_PREV(APR_RING_NEXT(here, link), link) != here) { \ fprintf(stderr, "\t*** elem->next->prev != elem\n"); \ break; \ } \ if (APR_RING_NEXT(APR_RING_PREV(here, link), link) != here) { \ fprintf(stderr, "\t*** elem->prev->next != elem\n"); \ break; \ } \ here = APR_RING_NEXT(here, link); \ } while (here != start); \ fprintf(stderr, "*** ring check end\n"); \ } while (0) #define APR_RING_CHECK_CONSISTENCY(hp, elem, link) \ APR_RING_CHECK_ELEM_CONSISTENCY(APR_RING_SENTINEL(hp, elem, link),\ elem, link) #define APR_RING_CHECK_ELEM_CONSISTENCY(ep, elem, link) do { \ struct elem *start = (ep); \ struct elem *here = start; \ do { \ assert(APR_RING_PREV(APR_RING_NEXT(here, link), link) == here); \ assert(APR_RING_NEXT(APR_RING_PREV(here, link), link) == here); \ here = APR_RING_NEXT(here, link); \ } while (here != start); \ } while (0) #else /** * Print a single pointer value to STDERR * (This is a no-op unless APR_RING_DEBUG is defined.) * @param msg Descriptive message * @param ptr Pointer value to print */ #define APR_RING_CHECK_ONE(msg, ptr) /** * Dump all ring pointers to STDERR, starting with the head and looping all * the way around the ring back to the head. Aborts if an inconsistency * is found. * (This is a no-op unless APR_RING_DEBUG is defined.) * @param hp Head of the ring * @param elem The name of the element struct * @param link The name of the APR_RING_ENTRY in the element struct * @param msg Descriptive message */ #define APR_RING_CHECK(hp, elem, link, msg) /** * Loops around a ring and checks all the pointers for consistency. Pops * an assertion if any inconsistency is found. Same idea as APR_RING_CHECK() * except that it's silent if all is well. * (This is a no-op unless APR_RING_DEBUG is defined.) * @param hp Head of the ring * @param elem The name of the element struct * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_CHECK_CONSISTENCY(hp, elem, link) /** * Dump all ring pointers to STDERR, starting with the given element and * looping all the way around the ring back to that element. Aborts if * an inconsistency is found. * (This is a no-op unless APR_RING_DEBUG is defined.) * @param ep The element * @param elem The name of the element struct * @param link The name of the APR_RING_ENTRY in the element struct * @param msg Descriptive message */ #define APR_RING_CHECK_ELEM(ep, elem, link, msg) /** * Loops around a ring, starting with the given element, and checks all * the pointers for consistency. Pops an assertion if any inconsistency * is found. Same idea as APR_RING_CHECK_ELEM() except that it's silent * if all is well. * (This is a no-op unless APR_RING_DEBUG is defined.) * @param ep The element * @param elem The name of the element struct * @param link The name of the APR_RING_ENTRY in the element struct */ #define APR_RING_CHECK_ELEM_CONSISTENCY(ep, elem, link) #endif /** @} */ #endif /* !APR_RING_H */
001-log4cxx
trunk/src/apr/include/apr_ring.h
C
asf20
17,930
/* 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. */ #ifndef APR_THREAD_RWLOCK_H #define APR_THREAD_RWLOCK_H /** * @file apr_thread_rwlock.h * @brief APR Reader/Writer Lock Routines */ #include "apr.h" #include "apr_pools.h" #include "apr_errno.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #if APR_HAS_THREADS /** * @defgroup apr_thread_rwlock Reader/Writer Lock Routines * @ingroup APR * @{ */ /** Opaque read-write thread-safe lock. */ typedef struct apr_thread_rwlock_t apr_thread_rwlock_t; /** * Note: The following operations have undefined results: unlocking a * read-write lock which is not locked in the calling thread; write * locking a read-write lock which is already locked by the calling * thread; destroying a read-write lock more than once; clearing or * destroying the pool from which a <b>locked</b> read-write lock is * allocated. */ /** * Create and initialize a read-write lock that can be used to synchronize * threads. * @param rwlock the memory address where the newly created readwrite lock * will be stored. * @param pool the pool from which to allocate the mutex. */ APR_DECLARE(apr_status_t) apr_thread_rwlock_create(apr_thread_rwlock_t **rwlock, apr_pool_t *pool); /** * Acquire a shared-read lock on the given read-write lock. This will allow * multiple threads to enter the same critical section while they have acquired * the read lock. * @param rwlock the read-write lock on which to acquire the shared read. */ APR_DECLARE(apr_status_t) apr_thread_rwlock_rdlock(apr_thread_rwlock_t *rwlock); /** * Attempt to acquire the shared-read lock on the given read-write lock. This * is the same as apr_thread_rwlock_rdlock(), only that the function fails * if there is another thread holding the write lock, or if there are any * write threads blocking on the lock. If the function fails for this case, * APR_EBUSY will be returned. Note: it is important that the * APR_STATUS_IS_EBUSY(s) macro be used to determine if the return value was * APR_EBUSY, for portability reasons. * @param rwlock the rwlock on which to attempt the shared read. */ APR_DECLARE(apr_status_t) apr_thread_rwlock_tryrdlock(apr_thread_rwlock_t *rwlock); /** * Acquire an exclusive-write lock on the given read-write lock. This will * allow only one single thread to enter the critical sections. If there * are any threads currently holding the read-lock, this thread is put to * sleep until it can have exclusive access to the lock. * @param rwlock the read-write lock on which to acquire the exclusive write. */ APR_DECLARE(apr_status_t) apr_thread_rwlock_wrlock(apr_thread_rwlock_t *rwlock); /** * Attempt to acquire the exclusive-write lock on the given read-write lock. * This is the same as apr_thread_rwlock_wrlock(), only that the function fails * if there is any other thread holding the lock (for reading or writing), * in which case the function will return APR_EBUSY. Note: it is important * that the APR_STATUS_IS_EBUSY(s) macro be used to determine if the return * value was APR_EBUSY, for portability reasons. * @param rwlock the rwlock on which to attempt the exclusive write. */ APR_DECLARE(apr_status_t) apr_thread_rwlock_trywrlock(apr_thread_rwlock_t *rwlock); /** * Release either the read or write lock currently held by the calling thread * associated with the given read-write lock. * @param rwlock the read-write lock to be released (unlocked). */ APR_DECLARE(apr_status_t) apr_thread_rwlock_unlock(apr_thread_rwlock_t *rwlock); /** * Destroy the read-write lock and free the associated memory. * @param rwlock the rwlock to destroy. */ APR_DECLARE(apr_status_t) apr_thread_rwlock_destroy(apr_thread_rwlock_t *rwlock); /** * Get the pool used by this thread_rwlock. * @return apr_pool_t the pool */ APR_POOL_DECLARE_ACCESSOR(thread_rwlock); #endif /* APR_HAS_THREADS */ /** @} */ #ifdef __cplusplus } #endif #endif /* ! APR_THREAD_RWLOCK_H */
001-log4cxx
trunk/src/apr/include/apr_thread_rwlock.h
C
asf20
4,766
/* 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. */ /* Portions of this file are covered by */ /* -*- mode: c; c-file-style: "k&r" -*- strnatcmp.c -- Perform 'natural order' comparisons of strings in C. Copyright (C) 2000 by Martin Pool <mbp@humbug.org.au> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef APR_STRINGS_H #define APR_STRINGS_H /** * @file apr_strings.h * @brief APR Strings library */ #include "apr.h" #include "apr_errno.h" #include "apr_pools.h" #define APR_WANT_IOVEC #include "apr_want.h" #if APR_HAVE_STDARG_H #include <stdarg.h> #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** * @defgroup apr_strings String routines * @ingroup APR * @{ */ /** * Do a natural order comparison of two strings. * @param a The first string to compare * @param b The second string to compare * @return Either <0, 0, or >0. If the first string is less than the second * this returns <0, if they are equivalent it returns 0, and if the * first string is greater than second string it retuns >0. */ APR_DECLARE(int) apr_strnatcmp(char const *a, char const *b); /** * Do a natural order comparison of two strings ignoring the case of the * strings. * @param a The first string to compare * @param b The second string to compare * @return Either <0, 0, or >0. If the first string is less than the second * this returns <0, if they are equivalent it returns 0, and if the * first string is greater than second string it retuns >0. */ APR_DECLARE(int) apr_strnatcasecmp(char const *a, char const *b); /** * duplicate a string into memory allocated out of a pool * @param p The pool to allocate out of * @param s The string to duplicate * @return The new string */ APR_DECLARE(char *) apr_pstrdup(apr_pool_t *p, const char *s); /** * Create a null-terminated string by making a copy of a sequence * of characters and appending a null byte * @param p The pool to allocate out of * @param s The block of characters to duplicate * @param n The number of characters to duplicate * @return The new string * @remark This is a faster alternative to apr_pstrndup, for use * when you know that the string being duplicated really * has 'n' or more characters. If the string might contain * fewer characters, use apr_pstrndup. */ APR_DECLARE(char *) apr_pstrmemdup(apr_pool_t *p, const char *s, apr_size_t n); /** * Duplicate at most n characters of a string into memory allocated * out of a pool; the new string will be NUL-terminated * @param p The pool to allocate out of * @param s The string to duplicate * @param n The maximum number of characters to duplicate * @return The new string * @remark The amount of memory allocated from the pool is the length * of the returned string including the NUL terminator */ APR_DECLARE(char *) apr_pstrndup(apr_pool_t *p, const char *s, apr_size_t n); /** * Duplicate a block of memory. * * @param p The pool to allocate from * @param m The memory to duplicate * @param n The number of bytes to duplicate * @return The new block of memory */ APR_DECLARE(void *) apr_pmemdup(apr_pool_t *p, const void *m, apr_size_t n); /** * Concatenate multiple strings, allocating memory out a pool * @param p The pool to allocate out of * @param ... The strings to concatenate. The final string must be NULL * @return The new string */ APR_DECLARE_NONSTD(char *) apr_pstrcat(apr_pool_t *p, ...); /** * Concatenate multiple strings specified in a writev-style vector * @param p The pool from which to allocate * @param vec The strings to concatenate * @param nvec The number of strings to concatenate * @param nbytes (output) strlen of new string (pass in NULL to omit) * @return The new string */ APR_DECLARE(char *) apr_pstrcatv(apr_pool_t *p, const struct iovec *vec, apr_size_t nvec, apr_size_t *nbytes); /** * printf-style style printing routine. The data is output to a string * allocated from a pool * @param p The pool to allocate out of * @param fmt The format of the string * @param ap The arguments to use while printing the data * @return The new string */ APR_DECLARE(char *) apr_pvsprintf(apr_pool_t *p, const char *fmt, va_list ap); /** * printf-style style printing routine. The data is output to a string * allocated from a pool * @param p The pool to allocate out of * @param fmt The format of the string * @param ... The arguments to use while printing the data * @return The new string */ APR_DECLARE_NONSTD(char *) apr_psprintf(apr_pool_t *p, const char *fmt, ...) __attribute__((format(printf,2,3))); /** * Copy up to dst_size characters from src to dst; does not copy * past a NUL terminator in src, but always terminates dst with a NUL * regardless. * @param dst The destination string * @param src The source string * @param dst_size The space available in dst; dst always receives * NUL termination, so if src is longer than * dst_size, the actual number of characters copied is * dst_size - 1. * @return Pointer to the NUL terminator of the destination string, dst * @remark * <PRE> * Note the differences between this function and strncpy(): * 1) strncpy() doesn't always NUL terminate; apr_cpystrn() does. * 2) strncpy() pads the destination string with NULs, which is often * unnecessary; apr_cpystrn() does not. * 3) strncpy() returns a pointer to the beginning of the dst string; * apr_cpystrn() returns a pointer to the NUL terminator of dst, * to allow a check for truncation. * </PRE> */ APR_DECLARE(char *) apr_cpystrn(char *dst, const char *src, apr_size_t dst_size); /** * Strip spaces from a string * @param dest The destination string. It is okay to modify the string * in place. Namely dest == src * @param src The string to rid the spaces from. * @return The destination string, dest. */ APR_DECLARE(char *) apr_collapse_spaces(char *dest, const char *src); /** * Convert the arguments to a program from one string to an array of * strings terminated by a NULL pointer * @param arg_str The arguments to convert * @param argv_out Output location. This is a pointer to an array of strings. * @param token_context Pool to use. */ APR_DECLARE(apr_status_t) apr_tokenize_to_argv(const char *arg_str, char ***argv_out, apr_pool_t *token_context); /** * Split a string into separate null-terminated tokens. The tokens are * delimited in the string by one or more characters from the sep * argument. * @param str The string to separate; this should be specified on the * first call to apr_strtok() for a given string, and NULL * on subsequent calls. * @param sep The set of delimiters * @param last Internal state saved by apr_strtok() between calls. * @return The next token from the string */ APR_DECLARE(char *) apr_strtok(char *str, const char *sep, char **last); /** * @defgroup APR_Strings_Snprintf snprintf implementations * @warning * These are snprintf implementations based on apr_vformatter(). * * Note that various standards and implementations disagree on the return * value of snprintf, and side-effects due to %n in the formatting string. * apr_snprintf (and apr_vsnprintf) behaves as follows: * * Process the format string until the entire string is exhausted, or * the buffer fills. If the buffer fills then stop processing immediately * (so no further %n arguments are processed), and return the buffer * length. In all cases the buffer is NUL terminated. It will return the * number of characters inserted into the buffer, not including the * terminating NUL. As a special case, if len is 0, apr_snprintf will * return the number of characters that would have been inserted if * the buffer had been infinite (in this case, *buffer can be NULL) * * In no event does apr_snprintf return a negative number. * @{ */ /** * snprintf routine based on apr_vformatter. This means it understands the * same extensions. * @param buf The buffer to write to * @param len The size of the buffer * @param format The format string * @param ... The arguments to use to fill out the format string. */ APR_DECLARE_NONSTD(int) apr_snprintf(char *buf, apr_size_t len, const char *format, ...) __attribute__((format(printf,3,4))); /** * vsnprintf routine based on apr_vformatter. This means it understands the * same extensions. * @param buf The buffer to write to * @param len The size of the buffer * @param format The format string * @param ap The arguments to use to fill out the format string. */ APR_DECLARE(int) apr_vsnprintf(char *buf, apr_size_t len, const char *format, va_list ap); /** @} */ /** * create a string representation of an int, allocated from a pool * @param p The pool from which to allocate * @param n The number to format * @return The string representation of the number */ APR_DECLARE(char *) apr_itoa(apr_pool_t *p, int n); /** * create a string representation of a long, allocated from a pool * @param p The pool from which to allocate * @param n The number to format * @return The string representation of the number */ APR_DECLARE(char *) apr_ltoa(apr_pool_t *p, long n); /** * create a string representation of an apr_off_t, allocated from a pool * @param p The pool from which to allocate * @param n The number to format * @return The string representation of the number */ APR_DECLARE(char *) apr_off_t_toa(apr_pool_t *p, apr_off_t n); /** * Convert a numeric string into an apr_off_t numeric value. * @param offset The value of the parsed string. * @param buf The string to parse. It may contain optional whitespace, * followed by an optional '+' (positive, default) or '-' (negative) * character, followed by an optional '0x' prefix if base is 0 or 16, * followed by numeric digits appropriate for base. * @param end A pointer to the end of the valid character in buf. If * not NULL, it is set to the first invalid character in buf. * @param base A numeric base in the range between 2 and 36 inclusive, * or 0. If base is zero, buf will be treated as base ten unless its * digits are prefixed with '0x', in which case it will be treated as * base 16. */ APR_DECLARE(apr_status_t) apr_strtoff(apr_off_t *offset, const char *buf, char **end, int base); /** * parse a numeric string into a 64-bit numeric value * @param buf The string to parse. It may contain optional whitespace, * followed by an optional '+' (positive, default) or '-' (negative) * character, followed by an optional '0x' prefix if base is 0 or 16, * followed by numeric digits appropriate for base. * @param end A pointer to the end of the valid character in buf. If * not NULL, it is set to the first invalid character in buf. * @param base A numeric base in the range between 2 and 36 inclusive, * or 0. If base is zero, buf will be treated as base ten unless its * digits are prefixed with '0x', in which case it will be treated as * base 16. * @return The numeric value of the string. On overflow, errno is set * to ERANGE. */ APR_DECLARE(apr_int64_t) apr_strtoi64(const char *buf, char **end, int base); /** * parse a base-10 numeric string into a 64-bit numeric value. * Equivalent to apr_strtoi64(buf, (char**)NULL, 10). * @param buf The string to parse * @return The numeric value of the string */ APR_DECLARE(apr_int64_t) apr_atoi64(const char *buf); /** * Format a binary size (magnitiudes are 2^10 rather than 10^3) from an apr_off_t, * as bytes, K, M, T, etc, to a four character compacted human readable string. * @param size The size to format * @param buf The 5 byte text buffer (counting the trailing null) * @return The buf passed to apr_strfsize() * @remark All negative sizes report ' - ', apr_strfsize only formats positive values. */ APR_DECLARE(char *) apr_strfsize(apr_off_t size, char *buf); /** @} */ #ifdef __cplusplus } #endif #endif /* !APR_STRINGS_H */
001-log4cxx
trunk/src/apr/include/apr_strings.h
C
asf20
13,853
/* 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. */ /* This header file is where you should put ANY platform specific information. * This should be the only header file that programs need to include that * actually has platform dependant code which refers to the . */ #ifndef APR_PORTABLE_H #define APR_PORTABLE_H /** * @file apr_portable.h * @brief APR Portability Routines */ #include "apr.h" #include "apr_pools.h" #include "apr_thread_proc.h" #include "apr_file_io.h" #include "apr_network_io.h" #include "apr_errno.h" #include "apr_global_mutex.h" #include "apr_proc_mutex.h" #include "apr_time.h" #include "apr_dso.h" #include "apr_shm.h" #if APR_HAVE_DIRENT_H #include <dirent.h> #endif #if APR_HAVE_FCNTL_H #include <fcntl.h> #endif #if APR_HAVE_PTHREAD_H #include <pthread.h> #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** * @defgroup apr_portabile Portability Routines * @ingroup APR * @{ */ #ifdef WIN32 /* The primitives for Windows types */ typedef HANDLE apr_os_file_t; typedef HANDLE apr_os_dir_t; typedef SOCKET apr_os_sock_t; typedef HANDLE apr_os_proc_mutex_t; typedef HANDLE apr_os_thread_t; typedef HANDLE apr_os_proc_t; typedef DWORD apr_os_threadkey_t; typedef FILETIME apr_os_imp_time_t; typedef SYSTEMTIME apr_os_exp_time_t; typedef HANDLE apr_os_dso_handle_t; typedef HANDLE apr_os_shm_t; #elif defined(OS2) typedef HFILE apr_os_file_t; typedef HDIR apr_os_dir_t; typedef int apr_os_sock_t; typedef HMTX apr_os_proc_mutex_t; typedef TID apr_os_thread_t; typedef PID apr_os_proc_t; typedef PULONG apr_os_threadkey_t; typedef struct timeval apr_os_imp_time_t; typedef struct tm apr_os_exp_time_t; typedef HMODULE apr_os_dso_handle_t; typedef void* apr_os_shm_t; #elif defined(__BEOS__) #include <kernel/OS.h> #include <kernel/image.h> struct apr_os_proc_mutex_t { sem_id sem; int32 ben; }; typedef int apr_os_file_t; typedef DIR apr_os_dir_t; typedef int apr_os_sock_t; typedef struct apr_os_proc_mutex_t apr_os_proc_mutex_t; typedef thread_id apr_os_thread_t; typedef thread_id apr_os_proc_t; typedef int apr_os_threadkey_t; typedef struct timeval apr_os_imp_time_t; typedef struct tm apr_os_exp_time_t; typedef image_id apr_os_dso_handle_t; typedef void* apr_os_shm_t; #elif defined(NETWARE) typedef int apr_os_file_t; typedef DIR apr_os_dir_t; typedef int apr_os_sock_t; typedef NXMutex_t apr_os_proc_mutex_t; typedef NXThreadId_t apr_os_thread_t; typedef long apr_os_proc_t; typedef NXKey_t apr_os_threadkey_t; typedef struct timeval apr_os_imp_time_t; typedef struct tm apr_os_exp_time_t; typedef void * apr_os_dso_handle_t; typedef void* apr_os_shm_t; #else /* Any other OS should go above this one. This is the lowest common * denominator typedefs for all UNIX-like systems. :) */ /** Basic OS process mutex structure. */ struct apr_os_proc_mutex_t { #if APR_HAS_SYSVSEM_SERIALIZE || APR_HAS_FCNTL_SERIALIZE || APR_HAS_FLOCK_SERIALIZE /** Value used for SYS V Semaphore, FCNTL and FLOCK serialization */ int crossproc; #endif #if APR_HAS_PROC_PTHREAD_SERIALIZE /** Value used for PTHREAD serialization */ pthread_mutex_t *pthread_interproc; #endif #if APR_HAS_THREADS /* If no threads, no need for thread locks */ #if APR_USE_PTHREAD_SERIALIZE /** This value is currently unused within APR and Apache */ pthread_mutex_t *intraproc; #endif #endif }; typedef int apr_os_file_t; /**< native file */ typedef DIR apr_os_dir_t; /**< native dir */ typedef int apr_os_sock_t; /**< native dir */ typedef struct apr_os_proc_mutex_t apr_os_proc_mutex_t; /**< native proces * mutex */ #if APR_HAS_THREADS && APR_HAVE_PTHREAD_H typedef pthread_t apr_os_thread_t; /**< native thread */ typedef pthread_key_t apr_os_threadkey_t; /**< native thread address * space */ #endif typedef pid_t apr_os_proc_t; /**< native pid */ typedef struct timeval apr_os_imp_time_t; /**< native timeval */ typedef struct tm apr_os_exp_time_t; /**< native tm */ /** @var apr_os_dso_handle_t * native dso types */ #if defined(HPUX) || defined(HPUX10) || defined(HPUX11) #include <dl.h> typedef shl_t apr_os_dso_handle_t; #elif defined(DARWIN) #include <mach-o/dyld.h> typedef NSModule apr_os_dso_handle_t; #else typedef void * apr_os_dso_handle_t; #endif typedef void* apr_os_shm_t; /**< native SHM */ #endif /** * @typedef apr_os_sock_info_t * @brief alias for local OS socket */ /** * everything APR needs to know about an active socket to construct * an APR socket from it; currently, this is platform-independent */ struct apr_os_sock_info_t { apr_os_sock_t *os_sock; /**< always required */ struct sockaddr *local; /**< NULL if not yet bound */ struct sockaddr *remote; /**< NULL if not connected */ int family; /**< always required (APR_INET, APR_INET6, etc.) */ int type; /**< always required (SOCK_STREAM, SOCK_DGRAM, etc.) */ int protocol; /**< 0 or actual protocol (APR_PROTO_SCTP, APR_PROTO_TCP, etc.) */ }; typedef struct apr_os_sock_info_t apr_os_sock_info_t; #if APR_PROC_MUTEX_IS_GLOBAL || defined(DOXYGEN) /** Opaque global mutex type */ #define apr_os_global_mutex_t apr_os_proc_mutex_t /** @return apr_os_global_mutex */ #define apr_os_global_mutex_get apr_os_proc_mutex_get #else /** Thread and process mutex for those platforms where process mutexes * are not held in threads. */ struct apr_os_global_mutex_t { apr_pool_t *pool; apr_proc_mutex_t *proc_mutex; #if APR_HAS_THREADS apr_thread_mutex_t *thread_mutex; #endif /* APR_HAS_THREADS */ }; typedef struct apr_os_global_mutex_t apr_os_global_mutex_t; APR_DECLARE(apr_status_t) apr_os_global_mutex_get(apr_os_global_mutex_t *ospmutex, apr_global_mutex_t *pmutex); #endif /** * convert the file from apr type to os specific type. * @param thefile The os specific file we are converting to * @param file The apr file to convert. * @remark On Unix, it is only possible to get a file descriptor from * an apr file type. */ APR_DECLARE(apr_status_t) apr_os_file_get(apr_os_file_t *thefile, apr_file_t *file); /** * convert the dir from apr type to os specific type. * @param thedir The os specific dir we are converting to * @param dir The apr dir to convert. */ APR_DECLARE(apr_status_t) apr_os_dir_get(apr_os_dir_t **thedir, apr_dir_t *dir); /** * Convert the socket from an apr type to an OS specific socket * @param thesock The socket to convert. * @param sock The os specifc equivelant of the apr socket.. */ APR_DECLARE(apr_status_t) apr_os_sock_get(apr_os_sock_t *thesock, apr_socket_t *sock); /** * Convert the proc mutex from os specific type to apr type * @param ospmutex The os specific proc mutex we are converting to. * @param pmutex The apr proc mutex to convert. */ APR_DECLARE(apr_status_t) apr_os_proc_mutex_get(apr_os_proc_mutex_t *ospmutex, apr_proc_mutex_t *pmutex); /** * Get the exploded time in the platforms native format. * @param ostime the native time format * @param aprtime the time to convert */ APR_DECLARE(apr_status_t) apr_os_exp_time_get(apr_os_exp_time_t **ostime, apr_time_exp_t *aprtime); /** * Get the imploded time in the platforms native format. * @param ostime the native time format * @param aprtime the time to convert */ APR_DECLARE(apr_status_t) apr_os_imp_time_get(apr_os_imp_time_t **ostime, apr_time_t *aprtime); /** * convert the shm from apr type to os specific type. * @param osshm The os specific shm representation * @param shm The apr shm to convert. */ APR_DECLARE(apr_status_t) apr_os_shm_get(apr_os_shm_t *osshm, apr_shm_t *shm); #if APR_HAS_THREADS || defined(DOXYGEN) /** * @defgroup apr_os_thread Thread portability Routines * @{ */ /** * convert the thread to os specific type from apr type. * @param thethd The apr thread to convert * @param thd The os specific thread we are converting to */ APR_DECLARE(apr_status_t) apr_os_thread_get(apr_os_thread_t **thethd, apr_thread_t *thd); /** * convert the thread private memory key to os specific type from an apr type. * @param thekey The apr handle we are converting from. * @param key The os specific handle we are converting to. */ APR_DECLARE(apr_status_t) apr_os_threadkey_get(apr_os_threadkey_t *thekey, apr_threadkey_t *key); /** * convert the thread from os specific type to apr type. * @param thd The apr thread we are converting to. * @param thethd The os specific thread to convert * @param cont The pool to use if it is needed. */ APR_DECLARE(apr_status_t) apr_os_thread_put(apr_thread_t **thd, apr_os_thread_t *thethd, apr_pool_t *cont); /** * convert the thread private memory key from os specific type to apr type. * @param key The apr handle we are converting to. * @param thekey The os specific handle to convert * @param cont The pool to use if it is needed. */ APR_DECLARE(apr_status_t) apr_os_threadkey_put(apr_threadkey_t **key, apr_os_threadkey_t *thekey, apr_pool_t *cont); /** * Get the thread ID */ APR_DECLARE(apr_os_thread_t) apr_os_thread_current(void); /** * Compare two thread id's * @param tid1 1st Thread ID to compare * @param tid2 2nd Thread ID to compare */ APR_DECLARE(int) apr_os_thread_equal(apr_os_thread_t tid1, apr_os_thread_t tid2); /** @} */ #endif /* APR_HAS_THREADS */ /** * convert the file from os specific type to apr type. * @param file The apr file we are converting to. * @param thefile The os specific file to convert * @param flags The flags that were used to open this file. * @param cont The pool to use if it is needed. * @remark On Unix, it is only possible to put a file descriptor into * an apr file type. */ 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 *cont); /** * convert the file from os specific type to apr type. * @param file The apr file we are converting to. * @param thefile The os specific pipe to convert * @param cont The pool to use if it is needed. * @remark On Unix, it is only possible to put a file descriptor into * an apr file type. */ APR_DECLARE(apr_status_t) apr_os_pipe_put(apr_file_t **file, apr_os_file_t *thefile, apr_pool_t *cont); /** * convert the file from os specific type to apr type. * @param file The apr file we are converting to. * @param thefile The os specific pipe to convert * @param register_cleanup A cleanup will be registered on the apr_file_t * to issue apr_file_close(). * @param cont The pool to use if it is needed. * @remark On Unix, it is only possible to put a file descriptor into * an apr file type. */ 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 *cont); /** * convert the dir from os specific type to apr type. * @param dir The apr dir we are converting to. * @param thedir The os specific dir to convert * @param cont The pool to use when creating to apr directory. */ APR_DECLARE(apr_status_t) apr_os_dir_put(apr_dir_t **dir, apr_os_dir_t *thedir, apr_pool_t *cont); /** * Convert a socket from the os specific type to the apr type * @param sock The pool to use. * @param thesock The socket to convert to. * @param cont The socket we are converting to an apr type. * @remark If it is a true socket, it is best to call apr_os_sock_make() * and provide APR with more information about the socket. */ APR_DECLARE(apr_status_t) apr_os_sock_put(apr_socket_t **sock, apr_os_sock_t *thesock, apr_pool_t *cont); /** * Create a socket from an existing descriptor and local and remote * socket addresses. * @param apr_sock The new socket that has been set up * @param os_sock_info The os representation of the socket handle and * other characteristics of the socket * @param cont The pool to use * @remark If you only know the descriptor/handle or if it isn't really * a true socket, use apr_os_sock_put() instead. */ APR_DECLARE(apr_status_t) apr_os_sock_make(apr_socket_t **apr_sock, apr_os_sock_info_t *os_sock_info, apr_pool_t *cont); /** * Convert the proc mutex from os specific type to apr type * @param pmutex The apr proc mutex we are converting to. * @param ospmutex The os specific proc mutex to convert. * @param cont The pool to use if it is needed. */ APR_DECLARE(apr_status_t) apr_os_proc_mutex_put(apr_proc_mutex_t **pmutex, apr_os_proc_mutex_t *ospmutex, apr_pool_t *cont); /** * Put the imploded time in the APR format. * @param aprtime the APR time format * @param ostime the time to convert * @param cont the pool to use if necessary */ APR_DECLARE(apr_status_t) apr_os_imp_time_put(apr_time_t *aprtime, apr_os_imp_time_t **ostime, apr_pool_t *cont); /** * Put the exploded time in the APR format. * @param aprtime the APR time format * @param ostime the time to convert * @param cont the pool to use if necessary */ APR_DECLARE(apr_status_t) apr_os_exp_time_put(apr_time_exp_t *aprtime, apr_os_exp_time_t **ostime, apr_pool_t *cont); /** * convert the shared memory from os specific type to apr type. * @param shm The apr shm representation of osshm * @param osshm The os specific shm identity * @param cont The pool to use if it is needed. * @remark On fork()ed architectures, this is typically nothing more than * the memory block mapped. On non-fork architectures, this is typically * some internal handle to pass the mapping from process to process. */ APR_DECLARE(apr_status_t) apr_os_shm_put(apr_shm_t **shm, apr_os_shm_t *osshm, apr_pool_t *cont); #if APR_HAS_DSO || defined(DOXYGEN) /** * @defgroup apr_os_dso DSO (Dynamic Loading) Portabiliity Routines * @{ */ /** * convert the dso handle from os specific to apr * @param dso The apr handle we are converting to * @param thedso the os specific handle to convert * @param pool the pool to use if it is needed */ APR_DECLARE(apr_status_t) apr_os_dso_handle_put(apr_dso_handle_t **dso, apr_os_dso_handle_t thedso, apr_pool_t *pool); /** * convert the apr dso handle into an os specific one * @param aprdso The apr dso handle to convert * @param dso The os specific dso to return */ APR_DECLARE(apr_status_t) apr_os_dso_handle_get(apr_os_dso_handle_t *dso, apr_dso_handle_t *aprdso); #if APR_HAS_OS_UUID /** * Private: apr-util's apr_uuid module when supported by the platform */ APR_DECLARE(apr_status_t) apr_os_uuid_get(unsigned char *uuid_data); #endif /** @} */ #endif /* APR_HAS_DSO */ /** * Get the name of the system default characer set. * @param pool the pool to allocate the name from, if needed */ APR_DECLARE(const char*) apr_os_default_encoding(apr_pool_t *pool); /** * Get the name of the current locale character set. * @param pool the pool to allocate the name from, if needed * @remark Defers to apr_os_default_encoding if the current locale's * data can't be retreved on this system. */ APR_DECLARE(const char*) apr_os_locale_encoding(apr_pool_t *pool); /** @} */ #ifdef __cplusplus } #endif #endif /* ! APR_PORTABLE_H */
001-log4cxx
trunk/src/apr/include/apr_portable.h
C
asf20
18,502
/* 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. */ #ifndef APR_PROC_MUTEX_H #define APR_PROC_MUTEX_H /** * @file apr_proc_mutex.h * @brief APR Process Locking Routines */ #include "apr.h" #include "apr_pools.h" #include "apr_errno.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** * @defgroup apr_proc_mutex Process Locking Routines * @ingroup APR * @{ */ /** * Enumerated potential types for APR process locking methods * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. */ typedef enum { APR_LOCK_FCNTL, /**< fcntl() */ APR_LOCK_FLOCK, /**< flock() */ APR_LOCK_SYSVSEM, /**< System V Semaphores */ APR_LOCK_PROC_PTHREAD, /**< POSIX pthread process-based locking */ APR_LOCK_POSIXSEM, /**< POSIX semaphore process-based locking */ APR_LOCK_DEFAULT /**< Use the default process lock */ } apr_lockmech_e; /** Opaque structure representing a process mutex. */ typedef struct apr_proc_mutex_t apr_proc_mutex_t; /* Function definitions */ /** * Create and initialize a mutex that can be used to synchronize processes. * @param mutex the memory address where the newly created mutex will be * stored. * @param fname A file name to use if the lock mechanism requires one. This * argument should always be provided. The lock code itself will * determine if it should be used. * @param mech The mechanism to use for the interprocess lock, if any; one of * <PRE> * APR_LOCK_FCNTL * APR_LOCK_FLOCK * APR_LOCK_SYSVSEM * APR_LOCK_POSIXSEM * APR_LOCK_PROC_PTHREAD * APR_LOCK_DEFAULT pick the default mechanism for the platform * </PRE> * @param pool the pool from which to allocate the mutex. * @see apr_lockmech_e * @warning Check APR_HAS_foo_SERIALIZE defines to see if the platform supports * APR_LOCK_foo. Only APR_LOCK_DEFAULT is portable. */ APR_DECLARE(apr_status_t) apr_proc_mutex_create(apr_proc_mutex_t **mutex, const char *fname, apr_lockmech_e mech, apr_pool_t *pool); /** * Re-open a mutex in a child process. * @param mutex The newly re-opened mutex structure. * @param fname A file name to use if the mutex mechanism requires one. This * argument should always be provided. The mutex code itself will * determine if it should be used. This filename should be the * same one that was passed to apr_proc_mutex_create(). * @param pool The pool to operate on. * @remark This function must be called to maintain portability, even * if the underlying lock mechanism does not require it. */ APR_DECLARE(apr_status_t) apr_proc_mutex_child_init(apr_proc_mutex_t **mutex, const char *fname, apr_pool_t *pool); /** * Acquire the lock for the given mutex. If the mutex is already locked, * the current thread will be put to sleep until the lock becomes available. * @param mutex the mutex on which to acquire the lock. */ APR_DECLARE(apr_status_t) apr_proc_mutex_lock(apr_proc_mutex_t *mutex); /** * Attempt to acquire the lock for the given mutex. If the mutex has already * been acquired, the call returns immediately with APR_EBUSY. Note: it * is important that the APR_STATUS_IS_EBUSY(s) macro be used to determine * if the return value was APR_EBUSY, for portability reasons. * @param mutex the mutex on which to attempt the lock acquiring. */ APR_DECLARE(apr_status_t) apr_proc_mutex_trylock(apr_proc_mutex_t *mutex); /** * Release the lock for the given mutex. * @param mutex the mutex from which to release the lock. */ APR_DECLARE(apr_status_t) apr_proc_mutex_unlock(apr_proc_mutex_t *mutex); /** * Destroy the mutex and free the memory associated with the lock. * @param mutex the mutex to destroy. */ APR_DECLARE(apr_status_t) apr_proc_mutex_destroy(apr_proc_mutex_t *mutex); /** * Destroy the mutex and free the memory associated with the lock. * @param mutex the mutex to destroy. * @note This function is generally used to kill a cleanup on an already * created mutex */ APR_DECLARE(apr_status_t) apr_proc_mutex_cleanup(void *mutex); /** * Return the name of the lockfile for the mutex, or NULL * if the mutex doesn't use a lock file */ APR_DECLARE(const char *) apr_proc_mutex_lockfile(apr_proc_mutex_t *mutex); /** * Display the name of the mutex, as it relates to the actual method used. * This matches the valid options for Apache's AcceptMutex directive * @param mutex the name of the mutex */ APR_DECLARE(const char *) apr_proc_mutex_name(apr_proc_mutex_t *mutex); /** * Display the name of the default mutex: APR_LOCK_DEFAULT */ APR_DECLARE(const char *) apr_proc_mutex_defname(void); /** * Get the pool used by this proc_mutex. * @return apr_pool_t the pool */ APR_POOL_DECLARE_ACCESSOR(proc_mutex); /** @} */ #ifdef __cplusplus } #endif #endif /* ! APR_PROC_MUTEX_H */
001-log4cxx
trunk/src/apr/include/apr_proc_mutex.h
C
asf20
6,002
#!/usr/bin/perl -w use strict; use ExtUtils::MakeMaker qw(prompt); use File::Find; my $just_check = @ARGV ? $ARGV[0] eq '-c' : 0; shift if $just_check; my $dir = shift || '.'; my %names; my $prefix = 'apr_'; while (<DATA>) { chomp; my($old, $new) = grep { s/^$prefix//o } split; next unless $old and $new; $names{$old} = $new; } my $pattern = join '|', keys %names; #print "replacement pattern=$pattern\n"; find sub { chomp; return unless /\.[ch]$/; my $file = "$File::Find::dir/$_"; print "looking in $file\n"; replace($_, !$just_check); }, $dir; sub replace { my($file, $replace) = @_; local *IN, *OUT; my @lines; my $found = 0; open IN, $file or die "open $file: $!"; while (<IN>) { for (m/[^_\"]*$prefix($pattern)\b/og) { $found++; print " $file:$. apr_$_ -> apr_$names{$_}\n"; } push @lines, $_ if $replace; } close IN; return unless $found and $replace; # my $ans = prompt("replace?", 'y'); # return unless $ans =~ /^y/i; open OUT, ">$file" or die "open $file: $!"; for (@lines) { unless (/^\#include/) { s/([^_\"]*$prefix)($pattern)\b/$1$names{$2}/og; } print OUT $_; } close OUT; } __DATA__ apr_time_t: apr_implode_gmt apr_time_exp_gmt_get apr_socket_t: apr_close_socket apr_socket_close apr_create_socket apr_socket_create apr_get_sockaddr apr_socket_addr_get apr_get_socketdata apr_socket_data_get apr_set_socketdata apr_socket_data_set apr_shutdown apr_socket_shutdown apr_bind apr_socket_bind apr_listen apr_socket_listen apr_accept apr_socket_accept apr_connect apr_socket_connect apr_send apr_socket_send apr_sendv apr_socket_sendv apr_sendto apr_socket_sendto apr_recvfrom apr_socket_recvfrom apr_sendfile apr_socket_sendfile apr_recv apr_socket_recv apr_filepath_*: apr_filename_of_pathname apr_filepath_name_get apr_gid_t: apr_get_groupid apr_gid_get apr_get_groupname apr_gid_name_get apr_group_name_get apr_gid_name_get apr_compare_groups apr_gid_compare apr_uid_t: apr_get_home_directory apr_uid_homepath_get apr_get_userid apr_uid_get apr_current_userid apr_uid_current apr_compare_users apr_uid_compare apr_get_username apr_uid_name_get apr_compare_users apr_uid_compare
001-log4cxx
trunk/src/apr/helpers/apr_rename.pl
Perl
asf20
2,673
#!/usr/bin/perl -w use strict; use ExtUtils::MakeMaker qw(prompt); use File::Find; my $just_check = @ARGV ? $ARGV[0] eq '-c' : 0; shift if $just_check; my $dir = shift || '.'; my %names; my $prefix = 'apr_'; while (<DATA>) { chomp; my($old, $new) = grep { s/^$prefix//o } split; next unless $old and $new; $names{$old} = $new; } my $pattern = join '|', keys %names; #print "replacement pattern=$pattern\n"; find sub { chomp; return unless /\.[ch]$/; my $file = "$File::Find::dir/$_"; print "looking in $file\n"; replace($_, !$just_check); }, $dir; sub replace { my($file, $replace) = @_; local *IN, *OUT; my @lines; my $found = 0; open IN, $file or die "open $file: $!"; while (<IN>) { for (m/[^_\"]*$prefix($pattern)\b/og) { $found++; print " $file:$. apr_$_ -> apr_$names{$_}\n"; } push @lines, $_ if $replace; } close IN; return unless $found and $replace; # my $ans = prompt("replace?", 'y'); # return unless $ans =~ /^y/i; open OUT, ">$file" or die "open $file: $!"; for (@lines) { unless (/^\#include/) { s/([^_\"]*$prefix)($pattern)\b/$1$names{$2}/og; } print OUT $_; } close OUT; } __DATA__ apr_time_t: apr_implode_gmt apr_time_exp_gmt_get apr_socket_t: apr_close_socket apr_socket_close apr_create_socket apr_socket_create apr_get_sockaddr apr_socket_addr_get apr_get_socketdata apr_socket_data_get apr_set_socketdata apr_socket_data_set apr_shutdown apr_socket_shutdown apr_bind apr_socket_bind apr_listen apr_socket_listen apr_accept apr_socket_accept apr_connect apr_socket_connect apr_send apr_socket_send apr_sendv apr_socket_sendv apr_sendto apr_socket_sendto apr_recvfrom apr_socket_recvfrom apr_sendfile apr_socket_sendfile apr_recv apr_socket_recv apr_filepath_*: apr_filename_of_pathname apr_filepath_name_get apr_gid_t: apr_get_groupid apr_gid_get apr_get_groupname apr_gid_name_get apr_group_name_get apr_gid_name_get apr_compare_groups apr_gid_compare apr_uid_t: apr_get_home_directory apr_uid_homepath_get apr_get_userid apr_uid_get apr_current_userid apr_uid_current apr_compare_users apr_uid_compare apr_get_username apr_uid_name_get apr_compare_users apr_uid_compare
001-log4cxx
trunk/src/apr/helpers/.svn/text-base/apr_rename.pl.svn-base
Perl
asf20
2,673
/* 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_atime.h" #include "apr_portable.h" #include "apr_strings.h" APR_DECLARE_DATA const char apr_month_snames[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; APR_DECLARE_DATA const char apr_day_snames[7][4] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; APR_DECLARE(apr_status_t) apr_rfc822_date(char *date_str, apr_time_t t) { apr_time_exp_t xt; const char *s; int real_year; apr_time_exp_gmt(&xt, t); /* example: "Sat, 08 Jan 2000 18:31:41 GMT" */ /* 12345678901234567890123456789 */ s = &apr_day_snames[xt.tm_wday][0]; *date_str++ = *s++; *date_str++ = *s++; *date_str++ = *s++; *date_str++ = ','; *date_str++ = ' '; *date_str++ = xt.tm_mday / 10 + '0'; *date_str++ = xt.tm_mday % 10 + '0'; *date_str++ = ' '; s = &apr_month_snames[xt.tm_mon][0]; *date_str++ = *s++; *date_str++ = *s++; *date_str++ = *s++; *date_str++ = ' '; real_year = 1900 + xt.tm_year; /* This routine isn't y10k ready. */ *date_str++ = real_year / 1000 + '0'; *date_str++ = real_year % 1000 / 100 + '0'; *date_str++ = real_year % 100 / 10 + '0'; *date_str++ = real_year % 10 + '0'; *date_str++ = ' '; *date_str++ = xt.tm_hour / 10 + '0'; *date_str++ = xt.tm_hour % 10 + '0'; *date_str++ = ':'; *date_str++ = xt.tm_min / 10 + '0'; *date_str++ = xt.tm_min % 10 + '0'; *date_str++ = ':'; *date_str++ = xt.tm_sec / 10 + '0'; *date_str++ = xt.tm_sec % 10 + '0'; *date_str++ = ' '; *date_str++ = 'G'; *date_str++ = 'M'; *date_str++ = 'T'; *date_str++ = 0; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_ctime(char *date_str, apr_time_t t) { apr_time_exp_t xt; const char *s; int real_year; /* example: "Wed Jun 30 21:49:08 1993" */ /* 123456789012345678901234 */ apr_time_exp_lt(&xt, t); s = &apr_day_snames[xt.tm_wday][0]; *date_str++ = *s++; *date_str++ = *s++; *date_str++ = *s++; *date_str++ = ' '; s = &apr_month_snames[xt.tm_mon][0]; *date_str++ = *s++; *date_str++ = *s++; *date_str++ = *s++; *date_str++ = ' '; *date_str++ = xt.tm_mday / 10 + '0'; *date_str++ = xt.tm_mday % 10 + '0'; *date_str++ = ' '; *date_str++ = xt.tm_hour / 10 + '0'; *date_str++ = xt.tm_hour % 10 + '0'; *date_str++ = ':'; *date_str++ = xt.tm_min / 10 + '0'; *date_str++ = xt.tm_min % 10 + '0'; *date_str++ = ':'; *date_str++ = xt.tm_sec / 10 + '0'; *date_str++ = xt.tm_sec % 10 + '0'; *date_str++ = ' '; real_year = 1900 + xt.tm_year; *date_str++ = real_year / 1000 + '0'; *date_str++ = real_year % 1000 / 100 + '0'; *date_str++ = real_year % 100 / 10 + '0'; *date_str++ = real_year % 10 + '0'; *date_str++ = 0; return APR_SUCCESS; } #ifndef _WIN32_WCE apr_size_t win32_strftime_extra(char *s, size_t max, const char *format, const struct tm *tm) { /* If the new format string is bigger than max, the result string won't fit * anyway. If format strings are added, made sure the padding below is * enough */ char *new_format = (char *) malloc(max + 11); size_t i, j, format_length = strlen(format); apr_size_t return_value; int length_written; for (i = 0, j = 0; (i < format_length && j < max);) { if (format[i] != '%') { new_format[j++] = format[i++]; continue; } switch (format[i+1]) { case 'C': length_written = apr_snprintf(new_format + j, max - j, "%2d", (tm->tm_year + 1970)/100); j = (length_written == -1) ? max : (j + length_written); i += 2; break; case 'D': /* Is this locale dependent? Shouldn't be... Also note the year 2000 exposure here */ memcpy(new_format + j, "%m/%d/%y", 8); i += 2; j += 8; break; case 'r': memcpy(new_format + j, "%I:%M:%S %p", 11); i += 2; j += 11; break; case 'R': memcpy(new_format + j, "%H:%M", 5); i += 2; j += 5; break; case 'T': memcpy(new_format + j, "%H:%M:%S", 8); i += 2; j += 8; break; case 'e': length_written = apr_snprintf(new_format + j, max - j, "%2d", tm->tm_mday); j = (length_written == -1) ? max : (j + length_written); i += 2; break; default: /* We know we can advance two characters forward here. Also * makes sure that %% is preserved. */ new_format[j++] = format[i++]; new_format[j++] = format[i++]; } } if (j >= max) { *s = '\0'; /* Defensive programming, okay since output is undefined*/ return_value = 0; } else { new_format[j] = '\0'; return_value = strftime(s, max, new_format, tm); } free(new_format); return return_value; } #endif APR_DECLARE(apr_status_t) apr_strftime(char *s, apr_size_t *retsize, apr_size_t max, const char *format, apr_time_exp_t *xt) { #ifdef _WIN32_WCE return APR_ENOTIMPL; #else struct tm tm; memset(&tm, 0, sizeof tm); tm.tm_sec = xt->tm_sec; tm.tm_min = xt->tm_min; tm.tm_hour = xt->tm_hour; tm.tm_mday = xt->tm_mday; tm.tm_mon = xt->tm_mon; tm.tm_year = xt->tm_year; tm.tm_wday = xt->tm_wday; tm.tm_yday = xt->tm_yday; tm.tm_isdst = xt->tm_isdst; (*retsize) = win32_strftime_extra(s, max, format, &tm); return APR_SUCCESS; #endif }
001-log4cxx
trunk/src/apr/time/win32/timestr.c
C
asf20
6,833
/* 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_atime.h" #include "apr_time.h" #include "apr_general.h" #include "apr_lib.h" apr_status_t apr_get_curtime(struct atime_t *time, apr_time_t *rv) { if (time) { (*rv) = time->currtime; return APR_SUCCESS; } return APR_ENOTIME; } apr_status_t apr_get_sec(struct atime_t *time, apr_int32_t *rv) { if (time) { (*rv) = time->explodedtime->wSecond; return APR_SUCCESS; } return APR_ENOTIME; } apr_status_t apr_get_min(struct atime_t *time, apr_int32_t *rv) { if (time) { (*rv) = time->explodedtime->wMinute; return APR_SUCCESS; } return APR_ENOTIME; } apr_status_t apr_get_hour(struct atime_t *time, apr_int32_t *rv) { if (time) { (*rv) = time->explodedtime->wHour; return APR_SUCCESS; } return APR_ENOTIME; } apr_status_t apr_get_mday(struct atime_t *time, apr_int32_t *rv) { if (time) { (*rv) = time->explodedtime->wDay; return APR_SUCCESS; } return APR_ENOTIME; } apr_status_t apr_get_mon(struct atime_t *time, apr_int32_t *rv) { if (time) { (*rv) = time->explodedtime->wMonth; return APR_SUCCESS; } return APR_ENOTIME; } apr_status_t apr_get_year(struct atime_t *time, apr_int32_t *rv) { if (time) { (*rv) = time->explodedtime->wYear; return APR_SUCCESS; } return APR_ENOTIME; } apr_status_t apr_get_wday(struct atime_t *time, apr_int32_t *rv) { if (time) { (*rv) = time->explodedtime->wDayOfWeek; return APR_SUCCESS; } return APR_ENOTIME; } apr_status_t apr_set_sec(struct atime_t *time, apr_int32_t value) { if (!time) { return APR_ENOTIME; } if (time->explodedtime == NULL) { time->explodedtime = (SYSTEMTIME *)apr_pcalloc(time->cntxt, sizeof(SYSTEMTIME)); } if (time->explodedtime == NULL) { return APR_ENOMEM; } time->explodedtime->wSecond = value; return APR_SUCCESS; } apr_status_t apr_set_min(struct atime_t *time, apr_int32_t value) { if (!time) { return APR_ENOTIME; } if (time->explodedtime == NULL) { time->explodedtime = (SYSTEMTIME *)apr_pcalloc(time->cntxt, sizeof(SYSTEMTIME)); } if (time->explodedtime == NULL) { return APR_ENOMEM; } time->explodedtime->wMinute = value; return APR_SUCCESS; } apr_status_t apr_set_hour(struct atime_t *time, apr_int32_t value) { if (!time) { return APR_ENOTIME; } if (time->explodedtime == NULL) { time->explodedtime = (SYSTEMTIME *)apr_pcalloc(time->cntxt, sizeof(SYSTEMTIME)); } if (time->explodedtime == NULL) { return APR_ENOMEM; } time->explodedtime->wHour = value; return APR_SUCCESS; } apr_status_t apr_set_mday(struct atime_t *time, apr_int32_t value) { if (!time) { return APR_ENOTIME; } if (time->explodedtime == NULL) { time->explodedtime = (SYSTEMTIME *)apr_pcalloc(time->cntxt, sizeof(SYSTEMTIME)); } if (time->explodedtime == NULL) { return APR_ENOMEM; } time->explodedtime->wDay = value; return APR_SUCCESS; } apr_status_t apr_set_mon(struct atime_t *time, apr_int32_t value) { if (!time) { return APR_ENOTIME; } if (time->explodedtime == NULL) { time->explodedtime = (SYSTEMTIME *)apr_pcalloc(time->cntxt, sizeof(SYSTEMTIME)); } if (time->explodedtime == NULL) { return APR_ENOMEM; } time->explodedtime->wMonth = value; return APR_SUCCESS; } apr_status_t apr_set_year(struct atime_t *time, apr_int32_t value) { if (!time) { return APR_ENOTIME; } if (time->explodedtime == NULL) { time->explodedtime = (SYSTEMTIME *)apr_pcalloc(time->cntxt, sizeof(SYSTEMTIME)); } if (time->explodedtime == NULL) { return APR_ENOMEM; } time->explodedtime->wYear = value; return APR_SUCCESS; } apr_status_t apr_set_wday(struct atime_t *time, apr_int32_t value) { if (!time) { return APR_ENOTIME; } if (time->explodedtime == NULL) { time->explodedtime = (SYSTEMTIME *)apr_pcalloc(time->cntxt, sizeof(SYSTEMTIME)); } if (time->explodedtime == NULL) { return APR_ENOMEM; } time->explodedtime->wDayOfWeek = value; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/time/win32/access.c
C
asf20
5,352
/* 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_atime.h" #include "apr_time.h" #include "apr_general.h" #include "apr_lib.h" #include "apr_portable.h" #if APR_HAVE_TIME_H #include <time.h> #endif #if APR_HAVE_ERRNO_H #include <errno.h> #endif #include <string.h> #include <winbase.h> #include "apr_arch_misc.h" /* Leap year is any year divisible by four, but not by 100 unless also * divisible by 400 */ #define IsLeapYear(y) ((!(y % 4)) ? (((!(y % 400)) && (y % 100)) ? 1 : 0) : 0) static DWORD get_local_timezone(TIME_ZONE_INFORMATION **tzresult) { static TIME_ZONE_INFORMATION tz; static DWORD result; static int init = 0; if (!init) { result = GetTimeZoneInformation(&tz); init = 1; } *tzresult = &tz; return result; } static void SystemTimeToAprExpTime(apr_time_exp_t *xt, SYSTEMTIME *tm) { static const int dayoffset[12] = {0, 31, 59, 90, 120, 151, 182, 212, 243, 273, 304, 334}; /* Note; the caller is responsible for filling in detailed tm_usec, * tm_gmtoff and tm_isdst data when applicable. */ xt->tm_usec = tm->wMilliseconds * 1000; xt->tm_sec = tm->wSecond; xt->tm_min = tm->wMinute; xt->tm_hour = tm->wHour; xt->tm_mday = tm->wDay; xt->tm_mon = tm->wMonth - 1; xt->tm_year = tm->wYear - 1900; xt->tm_wday = tm->wDayOfWeek; xt->tm_yday = dayoffset[xt->tm_mon] + (tm->wDay - 1); xt->tm_isdst = 0; xt->tm_gmtoff = 0; /* If this is a leap year, and we're past the 28th of Feb. (the * 58th day after Jan. 1), we'll increment our tm_yday by one. */ if (IsLeapYear(tm->wYear) && (xt->tm_yday > 58)) xt->tm_yday++; } APR_DECLARE(apr_status_t) apr_time_ansi_put(apr_time_t *result, time_t input) { *result = (apr_time_t) input * APR_USEC_PER_SEC; return APR_SUCCESS; } /* Return micro-seconds since the Unix epoch (jan. 1, 1970) UTC */ APR_DECLARE(apr_time_t) apr_time_now(void) { LONGLONG aprtime = 0; FILETIME time; #ifndef _WIN32_WCE GetSystemTimeAsFileTime(&time); #else SYSTEMTIME st; GetSystemTime(&st); SystemTimeToFileTime(&st, &time); #endif FileTimeToAprTime(&aprtime, &time); return aprtime; } APR_DECLARE(apr_status_t) apr_time_exp_gmt(apr_time_exp_t *result, apr_time_t input) { FILETIME ft; SYSTEMTIME st; AprTimeToFileTime(&ft, input); FileTimeToSystemTime(&ft, &st); /* The Platform SDK documents that SYSTEMTIME/FILETIME are * generally UTC, so no timezone info needed */ SystemTimeToAprExpTime(result, &st); result->tm_usec = (apr_int32_t) (input % APR_USEC_PER_SEC); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_time_exp_tz(apr_time_exp_t *result, apr_time_t input, apr_int32_t offs) { FILETIME ft; SYSTEMTIME st; AprTimeToFileTime(&ft, input + (offs * APR_USEC_PER_SEC)); FileTimeToSystemTime(&ft, &st); /* The Platform SDK documents that SYSTEMTIME/FILETIME are * generally UTC, so we will simply note the offs used. */ SystemTimeToAprExpTime(result, &st); result->tm_usec = (apr_int32_t) (input % APR_USEC_PER_SEC); result->tm_gmtoff = offs; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_time_exp_lt(apr_time_exp_t *result, apr_time_t input) { SYSTEMTIME st; FILETIME ft, localft; AprTimeToFileTime(&ft, input); #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { TIME_ZONE_INFORMATION *tz; SYSTEMTIME localst; apr_time_t localtime; get_local_timezone(&tz); FileTimeToSystemTime(&ft, &st); /* The Platform SDK documents that SYSTEMTIME/FILETIME are * generally UTC. We use SystemTimeToTzSpecificLocalTime * because FileTimeToLocalFileFime is documented that the * resulting time local file time would have DST relative * to the *present* date, not the date converted. */ SystemTimeToTzSpecificLocalTime(tz, &st, &localst); SystemTimeToAprExpTime(result, &localst); result->tm_usec = (apr_int32_t) (input % APR_USEC_PER_SEC); /* Recover the resulting time as an apr time and use the * delta for gmtoff in seconds (and ignore msec rounding) */ SystemTimeToFileTime(&localst, &localft); FileTimeToAprTime(&localtime, &localft); result->tm_gmtoff = (int)apr_time_sec(localtime) - (int)apr_time_sec(input); /* To compute the dst flag, we compare the expected * local (standard) timezone bias to the delta. * [Note, in war time or double daylight time the * resulting tm_isdst is, desireably, 2 hours] */ result->tm_isdst = (result->tm_gmtoff / 3600) - (-(tz->Bias + tz->StandardBias) / 60); } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { TIME_ZONE_INFORMATION tz; /* XXX: This code is simply *wrong*. The time converted will always * map to the *now current* status of daylight savings time. */ FileTimeToLocalFileTime(&ft, &localft); FileTimeToSystemTime(&localft, &st); SystemTimeToAprExpTime(result, &st); result->tm_usec = (apr_int32_t) (input % APR_USEC_PER_SEC); switch (GetTimeZoneInformation(&tz)) { case TIME_ZONE_ID_UNKNOWN: result->tm_isdst = 0; /* Bias = UTC - local time in minutes * tm_gmtoff is seconds east of UTC */ result->tm_gmtoff = tz.Bias * -60; break; case TIME_ZONE_ID_STANDARD: result->tm_isdst = 0; result->tm_gmtoff = (tz.Bias + tz.StandardBias) * -60; break; case TIME_ZONE_ID_DAYLIGHT: result->tm_isdst = 1; result->tm_gmtoff = (tz.Bias + tz.DaylightBias) * -60; break; default: /* noop */; } } #endif return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_time_exp_get(apr_time_t *t, apr_time_exp_t *xt) { apr_time_t year = xt->tm_year; apr_time_t days; static const int dayoffset[12] = {306, 337, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275}; /* shift new year to 1st March in order to make leap year calc easy */ if (xt->tm_mon < 2) year--; /* Find number of days since 1st March 1900 (in the Gregorian calendar). */ days = year * 365 + year / 4 - year / 100 + (year / 100 + 3) / 4; days += dayoffset[xt->tm_mon] + xt->tm_mday - 1; days -= 25508; /* 1 jan 1970 is 25508 days since 1 mar 1900 */ days = ((days * 24 + xt->tm_hour) * 60 + xt->tm_min) * 60 + xt->tm_sec; if (days < 0) { return APR_EBADDATE; } *t = days * APR_USEC_PER_SEC + xt->tm_usec; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_time_exp_gmt_get(apr_time_t *t, apr_time_exp_t *xt) { apr_status_t status = apr_time_exp_get(t, xt); if (status == APR_SUCCESS) *t -= (apr_time_t) xt->tm_gmtoff * APR_USEC_PER_SEC; return status; } APR_DECLARE(apr_status_t) apr_os_imp_time_get(apr_os_imp_time_t **ostime, apr_time_t *aprtime) { /* TODO: Consider not passing in pointer to apr_time_t (e.g., call by value) */ AprTimeToFileTime(*ostime, *aprtime); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_exp_time_get(apr_os_exp_time_t **ostime, apr_time_exp_t *aprexptime) { (*ostime)->wYear = aprexptime->tm_year + 1900; (*ostime)->wMonth = aprexptime->tm_mon + 1; (*ostime)->wDayOfWeek = aprexptime->tm_wday; (*ostime)->wDay = aprexptime->tm_mday; (*ostime)->wHour = aprexptime->tm_hour; (*ostime)->wMinute = aprexptime->tm_min; (*ostime)->wSecond = aprexptime->tm_sec; (*ostime)->wMilliseconds = aprexptime->tm_usec / 1000; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_imp_time_put(apr_time_t *aprtime, apr_os_imp_time_t **ostime, apr_pool_t *cont) { /* XXX: sanity failure, what is file time, gmt or local ? */ FileTimeToAprTime(aprtime, *ostime); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_exp_time_put(apr_time_exp_t *aprtime, apr_os_exp_time_t **ostime, apr_pool_t *cont) { /* The Platform SDK documents that SYSTEMTIME/FILETIME are * generally UTC, so no timezone info needed */ SystemTimeToAprExpTime(aprtime, *ostime); return APR_SUCCESS; } APR_DECLARE(void) apr_sleep(apr_interval_time_t t) { /* One of the few sane situations for a cast, Sleep * is in ms, not us, and passed as a DWORD value */ Sleep((DWORD)(t / 1000)); } static apr_status_t clock_restore(void *unsetres) { ULONG newRes; SetTimerResolution((ULONG)unsetres, FALSE, &newRes); return APR_SUCCESS; } APR_DECLARE(void) apr_time_clock_hires(apr_pool_t *p) { ULONG newRes; /* Timer resolution is stated in 100ns units. Note that TRUE requests the * new clock resolution, FALSE above releases the request. */ if (SetTimerResolution(10000, TRUE, &newRes) == 0 /* STATUS_SUCCESS */) { /* register the cleanup... */ apr_pool_cleanup_register(p, (void*)10000, clock_restore, apr_pool_cleanup_null); } }
001-log4cxx
trunk/src/apr/time/win32/time.c
C
asf20
10,649
/* 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_time.h" #include "apr_lib.h" #include "apr_private.h" /* System Headers required for time library */ #if APR_HAVE_SYS_TIME_H #include <sys/time.h> #endif #ifdef HAVE_TIME_H #include <time.h> #endif #if APR_HAVE_STRING_H #include <string.h> #endif /* End System Headers */ APR_DECLARE_DATA const char apr_month_snames[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; APR_DECLARE_DATA const char apr_day_snames[7][4] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; apr_status_t apr_rfc822_date(char *date_str, apr_time_t t) { apr_time_exp_t xt; const char *s; int real_year; apr_time_exp_gmt(&xt, t); /* example: "Sat, 08 Jan 2000 18:31:41 GMT" */ /* 12345678901234567890123456789 */ s = &apr_day_snames[xt.tm_wday][0]; *date_str++ = *s++; *date_str++ = *s++; *date_str++ = *s++; *date_str++ = ','; *date_str++ = ' '; *date_str++ = xt.tm_mday / 10 + '0'; *date_str++ = xt.tm_mday % 10 + '0'; *date_str++ = ' '; s = &apr_month_snames[xt.tm_mon][0]; *date_str++ = *s++; *date_str++ = *s++; *date_str++ = *s++; *date_str++ = ' '; real_year = 1900 + xt.tm_year; /* This routine isn't y10k ready. */ *date_str++ = real_year / 1000 + '0'; *date_str++ = real_year % 1000 / 100 + '0'; *date_str++ = real_year % 100 / 10 + '0'; *date_str++ = real_year % 10 + '0'; *date_str++ = ' '; *date_str++ = xt.tm_hour / 10 + '0'; *date_str++ = xt.tm_hour % 10 + '0'; *date_str++ = ':'; *date_str++ = xt.tm_min / 10 + '0'; *date_str++ = xt.tm_min % 10 + '0'; *date_str++ = ':'; *date_str++ = xt.tm_sec / 10 + '0'; *date_str++ = xt.tm_sec % 10 + '0'; *date_str++ = ' '; *date_str++ = 'G'; *date_str++ = 'M'; *date_str++ = 'T'; *date_str++ = 0; return APR_SUCCESS; } apr_status_t apr_ctime(char *date_str, apr_time_t t) { apr_time_exp_t xt; const char *s; int real_year; /* example: "Wed Jun 30 21:49:08 1993" */ /* 123456789012345678901234 */ apr_time_exp_lt(&xt, t); s = &apr_day_snames[xt.tm_wday][0]; *date_str++ = *s++; *date_str++ = *s++; *date_str++ = *s++; *date_str++ = ' '; s = &apr_month_snames[xt.tm_mon][0]; *date_str++ = *s++; *date_str++ = *s++; *date_str++ = *s++; *date_str++ = ' '; *date_str++ = xt.tm_mday / 10 + '0'; *date_str++ = xt.tm_mday % 10 + '0'; *date_str++ = ' '; *date_str++ = xt.tm_hour / 10 + '0'; *date_str++ = xt.tm_hour % 10 + '0'; *date_str++ = ':'; *date_str++ = xt.tm_min / 10 + '0'; *date_str++ = xt.tm_min % 10 + '0'; *date_str++ = ':'; *date_str++ = xt.tm_sec / 10 + '0'; *date_str++ = xt.tm_sec % 10 + '0'; *date_str++ = ' '; real_year = 1900 + xt.tm_year; *date_str++ = real_year / 1000 + '0'; *date_str++ = real_year % 1000 / 100 + '0'; *date_str++ = real_year % 100 / 10 + '0'; *date_str++ = real_year % 10 + '0'; *date_str++ = 0; return APR_SUCCESS; } apr_status_t apr_strftime(char *s, apr_size_t *retsize, apr_size_t max, const char *format, apr_time_exp_t *xt) { struct tm tm; memset(&tm, 0, sizeof tm); tm.tm_sec = xt->tm_sec; tm.tm_min = xt->tm_min; tm.tm_hour = xt->tm_hour; tm.tm_mday = xt->tm_mday; tm.tm_mon = xt->tm_mon; tm.tm_year = xt->tm_year; tm.tm_wday = xt->tm_wday; tm.tm_yday = xt->tm_yday; tm.tm_isdst = xt->tm_isdst; #if defined(HAVE_STRUCT_TM_TM_GMTOFF) tm.tm_gmtoff = xt->tm_gmtoff; #elif defined(HAVE_STRUCT_TM___TM_GMTOFF) tm.__tm_gmtoff = xt->tm_gmtoff; #endif (*retsize) = strftime(s, max, format, &tm); return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/time/unix/timestr.c
C
asf20
4,601
/* 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_time.h" #include "apr_lib.h" #include "apr_private.h" #include "apr_strings.h" /* private APR headers */ #include "apr_arch_internal_time.h" /* System Headers required for time library */ #if APR_HAVE_SYS_TIME_H #include <sys/time.h> #endif #if APR_HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_TIME_H #include <time.h> #endif /* End System Headers */ #if !defined(HAVE_STRUCT_TM_TM_GMTOFF) && !defined(HAVE_STRUCT_TM___TM_GMTOFF) static apr_int32_t server_gmt_offset; #define NO_GMTOFF_IN_STRUCT_TM #endif static apr_int32_t get_offset(struct tm *tm) { #if defined(HAVE_STRUCT_TM_TM_GMTOFF) return tm->tm_gmtoff; #elif defined(HAVE_STRUCT_TM___TM_GMTOFF) return tm->__tm_gmtoff; #else #ifdef NETWARE /* Need to adjust the global variable each time otherwise the web server would have to be restarted when daylight savings changes. */ if (daylightOnOff) { return server_gmt_offset + daylightOffset; } #else if (tm->tm_isdst) return server_gmt_offset + 3600; #endif return server_gmt_offset; #endif } APR_DECLARE(apr_status_t) apr_time_ansi_put(apr_time_t *result, time_t input) { *result = (apr_time_t)input * APR_USEC_PER_SEC; return APR_SUCCESS; } /* NB NB NB NB This returns GMT!!!!!!!!!! */ APR_DECLARE(apr_time_t) apr_time_now(void) { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * APR_USEC_PER_SEC + tv.tv_usec; } static void explode_time(apr_time_exp_t *xt, apr_time_t t, apr_int32_t offset, int use_localtime) { struct tm tm; time_t tt = (t / APR_USEC_PER_SEC) + offset; xt->tm_usec = t % APR_USEC_PER_SEC; #if APR_HAS_THREADS && defined (_POSIX_THREAD_SAFE_FUNCTIONS) if (use_localtime) localtime_r(&tt, &tm); else gmtime_r(&tt, &tm); #else if (use_localtime) tm = *localtime(&tt); else tm = *gmtime(&tt); #endif xt->tm_sec = tm.tm_sec; xt->tm_min = tm.tm_min; xt->tm_hour = tm.tm_hour; xt->tm_mday = tm.tm_mday; xt->tm_mon = tm.tm_mon; xt->tm_year = tm.tm_year; xt->tm_wday = tm.tm_wday; xt->tm_yday = tm.tm_yday; xt->tm_isdst = tm.tm_isdst; xt->tm_gmtoff = get_offset(&tm); } APR_DECLARE(apr_status_t) apr_time_exp_tz(apr_time_exp_t *result, apr_time_t input, apr_int32_t offs) { explode_time(result, input, offs, 0); result->tm_gmtoff = offs; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_time_exp_gmt(apr_time_exp_t *result, apr_time_t input) { return apr_time_exp_tz(result, input, 0); } APR_DECLARE(apr_status_t) apr_time_exp_lt(apr_time_exp_t *result, apr_time_t input) { #if defined(__EMX__) /* EMX gcc (OS/2) has a timezone global we can use */ return apr_time_exp_tz(result, input, -timezone); #else explode_time(result, input, 0, 1); return APR_SUCCESS; #endif /* __EMX__ */ } APR_DECLARE(apr_status_t) apr_time_exp_get(apr_time_t *t, apr_time_exp_t *xt) { apr_time_t year = xt->tm_year; apr_time_t days; static const int dayoffset[12] = {306, 337, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275}; /* shift new year to 1st March in order to make leap year calc easy */ if (xt->tm_mon < 2) year--; /* Find number of days since 1st March 1900 (in the Gregorian calendar). */ days = year * 365 + year / 4 - year / 100 + (year / 100 + 3) / 4; days += dayoffset[xt->tm_mon] + xt->tm_mday - 1; days -= 25508; /* 1 jan 1970 is 25508 days since 1 mar 1900 */ days = ((days * 24 + xt->tm_hour) * 60 + xt->tm_min) * 60 + xt->tm_sec; if (days < 0) { return APR_EBADDATE; } *t = days * APR_USEC_PER_SEC + xt->tm_usec; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_time_exp_gmt_get(apr_time_t *t, apr_time_exp_t *xt) { apr_status_t status = apr_time_exp_get(t, xt); if (status == APR_SUCCESS) *t -= (apr_time_t) xt->tm_gmtoff * APR_USEC_PER_SEC; return status; } APR_DECLARE(apr_status_t) apr_os_imp_time_get(apr_os_imp_time_t **ostime, apr_time_t *aprtime) { (*ostime)->tv_usec = *aprtime % APR_USEC_PER_SEC; (*ostime)->tv_sec = *aprtime / APR_USEC_PER_SEC; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_exp_time_get(apr_os_exp_time_t **ostime, apr_time_exp_t *aprtime) { (*ostime)->tm_sec = aprtime->tm_sec; (*ostime)->tm_min = aprtime->tm_min; (*ostime)->tm_hour = aprtime->tm_hour; (*ostime)->tm_mday = aprtime->tm_mday; (*ostime)->tm_mon = aprtime->tm_mon; (*ostime)->tm_year = aprtime->tm_year; (*ostime)->tm_wday = aprtime->tm_wday; (*ostime)->tm_yday = aprtime->tm_yday; (*ostime)->tm_isdst = aprtime->tm_isdst; #if defined(HAVE_STRUCT_TM_TM_GMTOFF) (*ostime)->tm_gmtoff = aprtime->tm_gmtoff; #elif defined(HAVE_STRUCT_TM___TM_GMTOFF) (*ostime)->__tm_gmtoff = aprtime->tm_gmtoff; #endif return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_imp_time_put(apr_time_t *aprtime, apr_os_imp_time_t **ostime, apr_pool_t *cont) { *aprtime = (*ostime)->tv_sec * APR_USEC_PER_SEC + (*ostime)->tv_usec; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_exp_time_put(apr_time_exp_t *aprtime, apr_os_exp_time_t **ostime, apr_pool_t *cont) { aprtime->tm_sec = (*ostime)->tm_sec; aprtime->tm_min = (*ostime)->tm_min; aprtime->tm_hour = (*ostime)->tm_hour; aprtime->tm_mday = (*ostime)->tm_mday; aprtime->tm_mon = (*ostime)->tm_mon; aprtime->tm_year = (*ostime)->tm_year; aprtime->tm_wday = (*ostime)->tm_wday; aprtime->tm_yday = (*ostime)->tm_yday; aprtime->tm_isdst = (*ostime)->tm_isdst; #if defined(HAVE_STRUCT_TM_TM_GMTOFF) aprtime->tm_gmtoff = (*ostime)->tm_gmtoff; #elif defined(HAVE_STRUCT_TM___TM_GMTOFF) aprtime->tm_gmtoff = (*ostime)->__tm_gmtoff; #endif return APR_SUCCESS; } APR_DECLARE(void) apr_sleep(apr_interval_time_t t) { #ifdef OS2 DosSleep(t/1000); #elif defined(BEOS) snooze(t); #elif defined(NETWARE) delay(t/1000); #else struct timeval tv; tv.tv_usec = t % APR_USEC_PER_SEC; tv.tv_sec = t / APR_USEC_PER_SEC; select(0, NULL, NULL, NULL, &tv); #endif } #ifdef OS2 APR_DECLARE(apr_status_t) apr_os2_time_to_apr_time(apr_time_t *result, FDATE os2date, FTIME os2time) { struct tm tmpdate; memset(&tmpdate, 0, sizeof(tmpdate)); tmpdate.tm_hour = os2time.hours; tmpdate.tm_min = os2time.minutes; tmpdate.tm_sec = os2time.twosecs * 2; tmpdate.tm_mday = os2date.day; tmpdate.tm_mon = os2date.month - 1; tmpdate.tm_year = os2date.year + 80; tmpdate.tm_isdst = -1; *result = mktime(&tmpdate) * APR_USEC_PER_SEC; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_apr_time_to_os2_time(FDATE *os2date, FTIME *os2time, apr_time_t aprtime) { time_t ansitime = aprtime / APR_USEC_PER_SEC; struct tm *lt; lt = localtime(&ansitime); os2time->hours = lt->tm_hour; os2time->minutes = lt->tm_min; os2time->twosecs = lt->tm_sec / 2; os2date->day = lt->tm_mday; os2date->month = lt->tm_mon + 1; os2date->year = lt->tm_year - 80; return APR_SUCCESS; } #endif #ifdef NETWARE APR_DECLARE(void) apr_netware_setup_time(void) { tzset(); server_gmt_offset = -TZONE; } #else APR_DECLARE(void) apr_unix_setup_time(void) { #ifdef NO_GMTOFF_IN_STRUCT_TM /* Precompute the offset from GMT on systems where it's not in struct tm. Note: This offset is normalized to be independent of daylight savings time; if the calculation happens to be done in a time/place where a daylight savings adjustment is in effect, the returned offset has the same value that it would have in the same location if daylight savings were not in effect. The reason for this is that the returned offset can be applied to a past or future timestamp in explode_time(), so the DST adjustment obtained from the current time won't necessarily be applicable. mktime() is the inverse of localtime(); so, presumably, passing in a struct tm made by gmtime() let's us calculate the true GMT offset. However, there's a catch: if daylight savings is in effect, gmtime()will set the tm_isdst field and confuse mktime() into returning a time that's offset by one hour. In that case, we must adjust the calculated GMT offset. */ struct timeval now; time_t t1, t2; struct tm t; gettimeofday(&now, NULL); t1 = now.tv_sec; t2 = 0; #if APR_HAS_THREADS && defined(_POSIX_THREAD_SAFE_FUNCTIONS) gmtime_r(&t1, &t); #else t = *gmtime(&t1); #endif t.tm_isdst = 0; /* we know this GMT time isn't daylight-savings */ t2 = mktime(&t); server_gmt_offset = (apr_int32_t) difftime(t1, t2); #endif /* NO_GMTOFF_IN_STRUCT_TM */ } #endif /* A noop on all known Unix implementations */ APR_DECLARE(void) apr_time_clock_hires(apr_pool_t *p) { return; }
001-log4cxx
trunk/src/apr/time/unix/time.c
C
asf20
10,501
/* 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_mmap.h" #include "apr_errno.h" #include "apr_arch_file_io.h" #include "apr_portable.h" #include "apr_strings.h" #if APR_HAS_MMAP static apr_status_t mmap_cleanup(void *themmap) { apr_mmap_t *mm = themmap; apr_mmap_t *next = APR_RING_NEXT(mm,link); apr_status_t rv = 0; /* we no longer refer to the mmaped region */ APR_RING_REMOVE(mm,link); APR_RING_NEXT(mm,link) = NULL; APR_RING_PREV(mm,link) = NULL; if (next != mm) { /* more references exist, so we're done */ return APR_SUCCESS; } if (mm->mv) { if (!UnmapViewOfFile(mm->mv)) { apr_status_t rv = apr_get_os_error(); CloseHandle(mm->mhandle); mm->mv = NULL; mm->mhandle = NULL; return rv; } mm->mv = NULL; } if (mm->mhandle) { if (!CloseHandle(mm->mhandle)) { apr_status_t rv = apr_get_os_error(); CloseHandle(mm->mhandle); mm->mhandle = NULL; return rv; } mm->mhandle = NULL; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_mmap_create(apr_mmap_t **new, apr_file_t *file, apr_off_t offset, apr_size_t size, apr_int32_t flag, apr_pool_t *cont) { static DWORD memblock = 0; DWORD fmaccess = 0; DWORD mvaccess = 0; DWORD offlo; DWORD offhi; if (size == 0) return APR_EINVAL; if (flag & APR_MMAP_WRITE) fmaccess |= PAGE_READWRITE; else if (flag & APR_MMAP_READ) fmaccess |= PAGE_READONLY; if (flag & APR_MMAP_READ) mvaccess |= FILE_MAP_READ; if (flag & APR_MMAP_WRITE) mvaccess |= FILE_MAP_WRITE; if (!file || !file->filehand || file->filehand == INVALID_HANDLE_VALUE || file->buffered) return APR_EBADF; if (!memblock) { SYSTEM_INFO si; GetSystemInfo(&si); memblock = si.dwAllocationGranularity; } *new = apr_pcalloc(cont, sizeof(apr_mmap_t)); (*new)->pstart = (offset / memblock) * memblock; (*new)->poffset = offset - (*new)->pstart; (*new)->psize = (apr_size_t)((*new)->poffset) + size; /* The size of the CreateFileMapping object is the current size * of the size of the mmap object (e.g. file size), not the size * of the mapped region! */ (*new)->mhandle = CreateFileMapping(file->filehand, NULL, fmaccess, 0, 0, NULL); if (!(*new)->mhandle || (*new)->mhandle == INVALID_HANDLE_VALUE) { *new = NULL; return apr_get_os_error(); } offlo = (DWORD)(*new)->pstart; offhi = (DWORD)((*new)->pstart >> 32); (*new)->mv = MapViewOfFile((*new)->mhandle, mvaccess, offhi, offlo, (*new)->psize); if (!(*new)->mv) { apr_status_t rv = apr_get_os_error(); CloseHandle((*new)->mhandle); *new = NULL; return rv; } (*new)->mm = (char*)((*new)->mv) + (*new)->poffset; (*new)->size = size; (*new)->cntxt = cont; APR_RING_ELEM_INIT(*new, link); /* register the cleanup... */ apr_pool_cleanup_register((*new)->cntxt, (void*)(*new), mmap_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_mmap_dup(apr_mmap_t **new_mmap, apr_mmap_t *old_mmap, apr_pool_t *p) { *new_mmap = (apr_mmap_t *)apr_pmemdup(p, old_mmap, sizeof(apr_mmap_t)); (*new_mmap)->cntxt = p; APR_RING_INSERT_AFTER(old_mmap, *new_mmap, link); apr_pool_cleanup_register(p, *new_mmap, mmap_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_mmap_delete(apr_mmap_t *mm) { return apr_pool_cleanup_run(mm->cntxt, mm, mmap_cleanup); } #endif
001-log4cxx
trunk/src/apr/mmap/win32/mmap.c
C
asf20
4,868
/* 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. */ /* common .c * This file has any function that is truly common and platform * neutral. Or at least that's the theory. * * The header files are a problem so there are a few #ifdef's to take * care of those. * */ #include "apr.h" #include "apr_private.h" #include "apr_mmap.h" #include "apr_errno.h" #if APR_HAS_MMAP || defined(BEOS) APR_DECLARE(apr_status_t) apr_mmap_offset(void **addr, apr_mmap_t *mmap, apr_off_t offset) { if (offset < 0 || offset > mmap->size) return APR_EINVAL; (*addr) = (char *) mmap->mm + offset; return APR_SUCCESS; } #endif
001-log4cxx
trunk/src/apr/mmap/unix/common.c
C
asf20
1,432
/* 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_strings.h" #include "apr_mmap.h" #include "apr_errno.h" #include "apr_arch_file_io.h" #include "apr_portable.h" /* System headers required for the mmap library */ #ifdef BEOS #include <kernel/OS.h> #endif #if APR_HAVE_STRING_H #include <string.h> #endif #if APR_HAVE_STDIO_H #include <stdio.h> #endif #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #ifdef HAVE_SYS_MMAN_H #include <sys/mman.h> #endif #if APR_HAS_MMAP || defined(BEOS) static apr_status_t mmap_cleanup(void *themmap) { apr_mmap_t *mm = themmap; apr_mmap_t *next = APR_RING_NEXT(mm,link); int rv = 0; /* we no longer refer to the mmaped region */ APR_RING_REMOVE(mm,link); APR_RING_NEXT(mm,link) = NULL; APR_RING_PREV(mm,link) = NULL; if (next != mm) { /* more references exist, so we're done */ return APR_SUCCESS; } #ifdef BEOS rv = delete_area(mm->area); #else rv = munmap(mm->mm, mm->size); #endif mm->mm = (void *)-1; if (rv == 0) { return APR_SUCCESS; } return errno; } APR_DECLARE(apr_status_t) apr_mmap_create(apr_mmap_t **new, apr_file_t *file, apr_off_t offset, apr_size_t size, apr_int32_t flag, apr_pool_t *cont) { void *mm; #ifdef BEOS area_id aid = -1; uint32 pages = 0; #else apr_int32_t native_flags = 0; #endif #if APR_HAS_LARGE_FILES && defined(HAVE_MMAP64) #define mmap mmap64 #elif APR_HAS_LARGE_FILES && SIZEOF_OFF_T == 4 /* LFS but no mmap64: check for overflow */ if ((apr_int64_t)offset + size > INT_MAX) return APR_EINVAL; #endif if (size == 0) return APR_EINVAL; if (file == NULL || file->filedes == -1 || file->buffered) return APR_EBADF; (*new) = (apr_mmap_t *)apr_pcalloc(cont, sizeof(apr_mmap_t)); #ifdef BEOS /* XXX: mmap shouldn't really change the seek offset */ apr_file_seek(file, APR_SET, &offset); /* There seems to be some strange interactions that mean our area must * be set as READ & WRITE or writev will fail! Go figure... * So we ignore the value in flags and always ask for both READ and WRITE */ pages = (size + B_PAGE_SIZE -1) / B_PAGE_SIZE; aid = create_area("apr_mmap", &mm , B_ANY_ADDRESS, pages * B_PAGE_SIZE, B_NO_LOCK, B_WRITE_AREA|B_READ_AREA); if (aid < B_NO_ERROR) { /* we failed to get an area we can use... */ *new = NULL; return APR_ENOMEM; } if (aid >= B_NO_ERROR) read(file->filedes, mm, size); (*new)->area = aid; #else if (flag & APR_MMAP_WRITE) { native_flags |= PROT_WRITE; } if (flag & APR_MMAP_READ) { native_flags |= PROT_READ; } mm = mmap(NULL, size, native_flags, MAP_SHARED, file->filedes, offset); if (mm == (void *)-1) { /* we failed to get an mmap'd file... */ *new = NULL; return errno; } #endif (*new)->mm = mm; (*new)->size = size; (*new)->cntxt = cont; APR_RING_ELEM_INIT(*new, link); /* register the cleanup... */ apr_pool_cleanup_register((*new)->cntxt, (void*)(*new), mmap_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_mmap_dup(apr_mmap_t **new_mmap, apr_mmap_t *old_mmap, apr_pool_t *p) { *new_mmap = (apr_mmap_t *)apr_pmemdup(p, old_mmap, sizeof(apr_mmap_t)); (*new_mmap)->cntxt = p; APR_RING_INSERT_AFTER(old_mmap, *new_mmap, link); apr_pool_cleanup_register(p, *new_mmap, mmap_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_mmap_delete(apr_mmap_t *mm) { return apr_pool_cleanup_run(mm->cntxt, mm, mmap_cleanup); } #endif
001-log4cxx
trunk/src/apr/mmap/unix/mmap.c
C
asf20
4,776
/* 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_atomic.h" #include "apr_portable.h" /* for get_os_proc */ #include "apr_strings.h" #include "apr_general.h" #include "apr_pools.h" #include "apr_allocator.h" #include "apr_lib.h" #include "apr_thread_mutex.h" #include "apr_hash.h" #include "apr_time.h" #define APR_WANT_MEMFUNC #include "apr_want.h" #include "apr_env.h" #if APR_HAVE_STDLIB_H #include <stdlib.h> /* for malloc, free and abort */ #endif #if APR_HAVE_UNISTD_H #include <unistd.h> /* for getpid */ #endif /* * Magic numbers */ #define MIN_ALLOC 8192 #define MAX_INDEX 20 #define BOUNDARY_INDEX 12 #define BOUNDARY_SIZE (1 << BOUNDARY_INDEX) /* * Timing constants for killing subprocesses * There is a total 3-second delay between sending a SIGINT * and sending of the final SIGKILL. * TIMEOUT_INTERVAL should be set to TIMEOUT_USECS / 64 * for the exponetial timeout alogrithm. */ #define TIMEOUT_USECS 3000000 #define TIMEOUT_INTERVAL 46875 /* * Allocator */ struct apr_allocator_t { apr_uint32_t max_index; apr_uint32_t max_free_index; apr_uint32_t current_free_index; #if APR_HAS_THREADS apr_thread_mutex_t *mutex; #endif /* APR_HAS_THREADS */ apr_pool_t *owner; apr_memnode_t *free[MAX_INDEX]; }; #define SIZEOF_ALLOCATOR_T APR_ALIGN_DEFAULT(sizeof(apr_allocator_t)) /* * Allocator */ APR_DECLARE(apr_status_t) apr_allocator_create(apr_allocator_t **allocator) { apr_allocator_t *new_allocator; *allocator = NULL; if ((new_allocator = malloc(SIZEOF_ALLOCATOR_T)) == NULL) return APR_ENOMEM; memset(new_allocator, 0, SIZEOF_ALLOCATOR_T); new_allocator->max_free_index = APR_ALLOCATOR_MAX_FREE_UNLIMITED; *allocator = new_allocator; return APR_SUCCESS; } APR_DECLARE(void) apr_allocator_destroy(apr_allocator_t *allocator) { apr_uint32_t index; apr_memnode_t *node, **ref; for (index = 0; index < MAX_INDEX; index++) { ref = &allocator->free[index]; while ((node = *ref) != NULL) { *ref = node->next; free(node); } } free(allocator); } #if APR_HAS_THREADS APR_DECLARE(void) apr_allocator_mutex_set(apr_allocator_t *allocator, apr_thread_mutex_t *mutex) { allocator->mutex = mutex; } APR_DECLARE(apr_thread_mutex_t *) apr_allocator_mutex_get( apr_allocator_t *allocator) { return allocator->mutex; } #endif /* APR_HAS_THREADS */ APR_DECLARE(void) apr_allocator_owner_set(apr_allocator_t *allocator, apr_pool_t *pool) { allocator->owner = pool; } APR_DECLARE(apr_pool_t *) apr_allocator_owner_get(apr_allocator_t *allocator) { return allocator->owner; } APR_DECLARE(void) apr_allocator_max_free_set(apr_allocator_t *allocator, apr_size_t in_size) { apr_uint32_t max_free_index; apr_uint32_t size = (APR_UINT32_TRUNC_CAST)in_size; #if APR_HAS_THREADS apr_thread_mutex_t *mutex; mutex = apr_allocator_mutex_get(allocator); if (mutex != NULL) apr_thread_mutex_lock(mutex); #endif /* APR_HAS_THREADS */ max_free_index = APR_ALIGN(size, BOUNDARY_SIZE) >> BOUNDARY_INDEX; allocator->current_free_index += max_free_index; allocator->current_free_index -= allocator->max_free_index; allocator->max_free_index = max_free_index; if (allocator->current_free_index > max_free_index) allocator->current_free_index = max_free_index; #if APR_HAS_THREADS if (mutex != NULL) apr_thread_mutex_unlock(mutex); #endif } static APR_INLINE apr_memnode_t *allocator_alloc(apr_allocator_t *allocator, apr_size_t size) { apr_memnode_t *node, **ref; apr_uint32_t max_index; apr_size_t i, index; /* Round up the block size to the next boundary, but always * allocate at least a certain size (MIN_ALLOC). */ size = APR_ALIGN(size + APR_MEMNODE_T_SIZE, BOUNDARY_SIZE); if (size < MIN_ALLOC) size = MIN_ALLOC; /* Find the index for this node size by * dividing its size by the boundary size */ index = (size >> BOUNDARY_INDEX) - 1; if (index > APR_UINT32_MAX) { return NULL; } /* First see if there are any nodes in the area we know * our node will fit into. */ if (index <= allocator->max_index) { #if APR_HAS_THREADS if (allocator->mutex) apr_thread_mutex_lock(allocator->mutex); #endif /* APR_HAS_THREADS */ /* Walk the free list to see if there are * any nodes on it of the requested size * * NOTE: an optimization would be to check * allocator->free[index] first and if no * node is present, directly use * allocator->free[max_index]. This seems * like overkill though and could cause * memory waste. */ max_index = allocator->max_index; ref = &allocator->free[index]; i = index; while (*ref == NULL && i < max_index) { ref++; i++; } if ((node = *ref) != NULL) { /* If we have found a node and it doesn't have any * nodes waiting in line behind it _and_ we are on * the highest available index, find the new highest * available index */ if ((*ref = node->next) == NULL && i >= max_index) { do { ref--; max_index--; } while (*ref == NULL && max_index > 0); allocator->max_index = max_index; } allocator->current_free_index += node->index; if (allocator->current_free_index > allocator->max_free_index) allocator->current_free_index = allocator->max_free_index; #if APR_HAS_THREADS if (allocator->mutex) apr_thread_mutex_unlock(allocator->mutex); #endif /* APR_HAS_THREADS */ node->next = NULL; node->first_avail = (char *)node + APR_MEMNODE_T_SIZE; return node; } #if APR_HAS_THREADS if (allocator->mutex) apr_thread_mutex_unlock(allocator->mutex); #endif /* APR_HAS_THREADS */ } /* If we found nothing, seek the sink (at index 0), if * it is not empty. */ else if (allocator->free[0]) { #if APR_HAS_THREADS if (allocator->mutex) apr_thread_mutex_lock(allocator->mutex); #endif /* APR_HAS_THREADS */ /* Walk the free list to see if there are * any nodes on it of the requested size */ ref = &allocator->free[0]; while ((node = *ref) != NULL && index > node->index) ref = &node->next; if (node) { *ref = node->next; allocator->current_free_index += node->index; if (allocator->current_free_index > allocator->max_free_index) allocator->current_free_index = allocator->max_free_index; #if APR_HAS_THREADS if (allocator->mutex) apr_thread_mutex_unlock(allocator->mutex); #endif /* APR_HAS_THREADS */ node->next = NULL; node->first_avail = (char *)node + APR_MEMNODE_T_SIZE; return node; } #if APR_HAS_THREADS if (allocator->mutex) apr_thread_mutex_unlock(allocator->mutex); #endif /* APR_HAS_THREADS */ } /* If we haven't got a suitable node, malloc a new one * and initialize it. */ if ((node = malloc(size)) == NULL) return NULL; node->next = NULL; node->index = (APR_UINT32_TRUNC_CAST)index; node->first_avail = (char *)node + APR_MEMNODE_T_SIZE; node->endp = (char *)node + size; return node; } static APR_INLINE void allocator_free(apr_allocator_t *allocator, apr_memnode_t *node) { apr_memnode_t *next, *freelist = NULL; apr_uint32_t index, max_index; apr_uint32_t max_free_index, current_free_index; #if APR_HAS_THREADS if (allocator->mutex) apr_thread_mutex_lock(allocator->mutex); #endif /* APR_HAS_THREADS */ max_index = allocator->max_index; max_free_index = allocator->max_free_index; current_free_index = allocator->current_free_index; /* Walk the list of submitted nodes and free them one by one, * shoving them in the right 'size' buckets as we go. */ do { next = node->next; index = node->index; if (max_free_index != APR_ALLOCATOR_MAX_FREE_UNLIMITED && index > current_free_index) { node->next = freelist; freelist = node; } else if (index < MAX_INDEX) { /* Add the node to the appropiate 'size' bucket. Adjust * the max_index when appropiate. */ if ((node->next = allocator->free[index]) == NULL && index > max_index) { max_index = index; } allocator->free[index] = node; current_free_index -= index; } else { /* This node is too large to keep in a specific size bucket, * just add it to the sink (at index 0). */ node->next = allocator->free[0]; allocator->free[0] = node; current_free_index -= index; } } while ((node = next) != NULL); allocator->max_index = max_index; allocator->current_free_index = current_free_index; #if APR_HAS_THREADS if (allocator->mutex) apr_thread_mutex_unlock(allocator->mutex); #endif /* APR_HAS_THREADS */ while (freelist != NULL) { node = freelist; freelist = node->next; free(node); } } APR_DECLARE(apr_memnode_t *) apr_allocator_alloc(apr_allocator_t *allocator, apr_size_t size) { return allocator_alloc(allocator, size); } APR_DECLARE(void) apr_allocator_free(apr_allocator_t *allocator, apr_memnode_t *node) { allocator_free(allocator, node); } /* * Debug level */ #define APR_POOL_DEBUG_GENERAL 0x01 #define APR_POOL_DEBUG_VERBOSE 0x02 #define APR_POOL_DEBUG_LIFETIME 0x04 #define APR_POOL_DEBUG_OWNER 0x08 #define APR_POOL_DEBUG_VERBOSE_ALLOC 0x10 #define APR_POOL_DEBUG_VERBOSE_ALL (APR_POOL_DEBUG_VERBOSE \ | APR_POOL_DEBUG_VERBOSE_ALLOC) /* * Structures */ typedef struct cleanup_t cleanup_t; /** A list of processes */ struct process_chain { /** The process ID */ apr_proc_t *proc; apr_kill_conditions_e kill_how; /** The next process in the list */ struct process_chain *next; }; #if APR_POOL_DEBUG typedef struct debug_node_t debug_node_t; struct debug_node_t { debug_node_t *next; apr_uint32_t index; void *beginp[64]; void *endp[64]; }; #define SIZEOF_DEBUG_NODE_T APR_ALIGN_DEFAULT(sizeof(debug_node_t)) #endif /* APR_POOL_DEBUG */ /* The ref field in the apr_pool_t struct holds a * pointer to the pointer referencing this pool. * It is used for parent, child, sibling management. * Look at apr_pool_create_ex() and apr_pool_destroy() * to see how it is used. */ struct apr_pool_t { apr_pool_t *parent; apr_pool_t *child; apr_pool_t *sibling; apr_pool_t **ref; cleanup_t *cleanups; cleanup_t *free_cleanups; apr_allocator_t *allocator; struct process_chain *subprocesses; apr_abortfunc_t abort_fn; apr_hash_t *user_data; const char *tag; #if !APR_POOL_DEBUG apr_memnode_t *active; apr_memnode_t *self; /* The node containing the pool itself */ char *self_first_avail; #else /* APR_POOL_DEBUG */ apr_pool_t *joined; /* the caller has guaranteed that this pool * will survive as long as ->joined */ debug_node_t *nodes; const char *file_line; apr_uint32_t creation_flags; unsigned int stat_alloc; unsigned int stat_total_alloc; unsigned int stat_clear; #if APR_HAS_THREADS apr_os_thread_t owner; apr_thread_mutex_t *mutex; #endif /* APR_HAS_THREADS */ #endif /* APR_POOL_DEBUG */ #ifdef NETWARE apr_os_proc_t owner_proc; #endif /* defined(NETWARE) */ }; #define SIZEOF_POOL_T APR_ALIGN_DEFAULT(sizeof(apr_pool_t)) /* * Variables */ static apr_byte_t apr_pools_initialized = 0; static apr_pool_t *global_pool = NULL; #if !APR_POOL_DEBUG static apr_allocator_t *global_allocator = NULL; #endif /* !APR_POOL_DEBUG */ #if (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALL) static apr_file_t *file_stderr = NULL; #endif /* (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALL) */ /* * Local functions */ static void run_cleanups(cleanup_t **c); static void run_child_cleanups(cleanup_t **c); static void free_proc_chain(struct process_chain *procs); #if APR_POOL_DEBUG static void pool_destroy_debug(apr_pool_t *pool, const char *file_line); #endif #if !APR_POOL_DEBUG /* * Initialization */ APR_DECLARE(apr_status_t) apr_pool_initialize(void) { apr_status_t rv; if (apr_pools_initialized++) return APR_SUCCESS; if ((rv = apr_allocator_create(&global_allocator)) != APR_SUCCESS) { apr_pools_initialized = 0; return rv; } if ((rv = apr_pool_create_ex(&global_pool, NULL, NULL, global_allocator)) != APR_SUCCESS) { apr_allocator_destroy(global_allocator); global_allocator = NULL; apr_pools_initialized = 0; return rv; } apr_pool_tag(global_pool, "apr_global_pool"); /* This has to happen here because mutexes might be backed by * atomics. It used to be snug and safe in apr_initialize(). */ if ((rv = apr_atomic_init(global_pool)) != APR_SUCCESS) { return rv; } #if APR_HAS_THREADS { apr_thread_mutex_t *mutex; if ((rv = apr_thread_mutex_create(&mutex, APR_THREAD_MUTEX_DEFAULT, global_pool)) != APR_SUCCESS) { return rv; } apr_allocator_mutex_set(global_allocator, mutex); } #endif /* APR_HAS_THREADS */ apr_allocator_owner_set(global_allocator, global_pool); return APR_SUCCESS; } APR_DECLARE(void) apr_pool_terminate(void) { if (!apr_pools_initialized) return; if (--apr_pools_initialized) return; apr_pool_destroy(global_pool); /* This will also destroy the mutex */ global_pool = NULL; global_allocator = NULL; } /* Node list management helper macros; list_insert() inserts 'node' * before 'point'. */ #define list_insert(node, point) do { \ node->ref = point->ref; \ *node->ref = node; \ node->next = point; \ point->ref = &node->next; \ } while (0) /* list_remove() removes 'node' from its list. */ #define list_remove(node) do { \ *node->ref = node->next; \ node->next->ref = node->ref; \ } while (0) /* * Memory allocation */ APR_DECLARE(void *) apr_palloc(apr_pool_t *pool, apr_size_t size) { apr_memnode_t *active, *node; void *mem; apr_size_t free_index; size = APR_ALIGN_DEFAULT(size); active = pool->active; /* If the active node has enough bytes left, use it. */ if (size < (apr_size_t)(active->endp - active->first_avail)) { mem = active->first_avail; active->first_avail += size; return mem; } node = active->next; if (size < (apr_size_t)(node->endp - node->first_avail)) { list_remove(node); } else { if ((node = allocator_alloc(pool->allocator, size)) == NULL) { if (pool->abort_fn) pool->abort_fn(APR_ENOMEM); return NULL; } } node->free_index = 0; mem = node->first_avail; node->first_avail += size; list_insert(node, active); pool->active = node; free_index = (APR_ALIGN(active->endp - active->first_avail + 1, BOUNDARY_SIZE) - BOUNDARY_SIZE) >> BOUNDARY_INDEX; active->free_index = (APR_UINT32_TRUNC_CAST)free_index; node = active->next; if (free_index >= node->free_index) return mem; do { node = node->next; } while (free_index < node->free_index); list_remove(active); list_insert(active, node); return mem; } /* Provide an implementation of apr_pcalloc for backward compatibility * with code built before apr_pcalloc was a macro */ #ifdef apr_pcalloc #undef apr_pcalloc #endif APR_DECLARE(void *) apr_pcalloc(apr_pool_t *pool, apr_size_t size); APR_DECLARE(void *) apr_pcalloc(apr_pool_t *pool, apr_size_t size) { void *mem; size = APR_ALIGN_DEFAULT(size); if ((mem = apr_palloc(pool, size)) != NULL) { memset(mem, 0, size); } return mem; } /* * Pool creation/destruction */ APR_DECLARE(void) apr_pool_clear(apr_pool_t *pool) { apr_memnode_t *active; /* Destroy the subpools. The subpools will detach themselves from * this pool thus this loop is safe and easy. */ while (pool->child) apr_pool_destroy(pool->child); /* Run cleanups */ run_cleanups(&pool->cleanups); pool->cleanups = NULL; pool->free_cleanups = NULL; /* Free subprocesses */ free_proc_chain(pool->subprocesses); pool->subprocesses = NULL; /* Clear the user data. */ pool->user_data = NULL; /* Find the node attached to the pool structure, reset it, make * it the active node and free the rest of the nodes. */ active = pool->active = pool->self; active->first_avail = pool->self_first_avail; if (active->next == active) return; *active->ref = NULL; allocator_free(pool->allocator, active->next); active->next = active; active->ref = &active->next; } APR_DECLARE(void) apr_pool_destroy(apr_pool_t *pool) { apr_memnode_t *active; apr_allocator_t *allocator; /* Destroy the subpools. The subpools will detach themselve from * this pool thus this loop is safe and easy. */ while (pool->child) apr_pool_destroy(pool->child); /* Run cleanups */ run_cleanups(&pool->cleanups); /* Free subprocesses */ free_proc_chain(pool->subprocesses); /* Remove the pool from the parents child list */ if (pool->parent) { #if APR_HAS_THREADS apr_thread_mutex_t *mutex; if ((mutex = apr_allocator_mutex_get(pool->parent->allocator)) != NULL) apr_thread_mutex_lock(mutex); #endif /* APR_HAS_THREADS */ if ((*pool->ref = pool->sibling) != NULL) pool->sibling->ref = pool->ref; #if APR_HAS_THREADS if (mutex) apr_thread_mutex_unlock(mutex); #endif /* APR_HAS_THREADS */ } /* Find the block attached to the pool structure. Save a copy of the * allocator pointer, because the pool struct soon will be no more. */ allocator = pool->allocator; active = pool->self; *active->ref = NULL; #if APR_HAS_THREADS if (apr_allocator_owner_get(allocator) == pool) { /* Make sure to remove the lock, since it is highly likely to * be invalid now. */ apr_allocator_mutex_set(allocator, NULL); } #endif /* APR_HAS_THREADS */ /* Free all the nodes in the pool (including the node holding the * pool struct), by giving them back to the allocator. */ allocator_free(allocator, active); /* If this pool happens to be the owner of the allocator, free * everything in the allocator (that includes the pool struct * and the allocator). Don't worry about destroying the optional mutex * in the allocator, it will have been destroyed by the cleanup function. */ if (apr_allocator_owner_get(allocator) == pool) { apr_allocator_destroy(allocator); } } APR_DECLARE(apr_status_t) apr_pool_create_ex(apr_pool_t **newpool, apr_pool_t *parent, apr_abortfunc_t abort_fn, apr_allocator_t *allocator) { apr_pool_t *pool; apr_memnode_t *node; *newpool = NULL; if (!parent) parent = global_pool; if (!abort_fn && parent) abort_fn = parent->abort_fn; if (allocator == NULL) allocator = parent->allocator; if ((node = allocator_alloc(allocator, MIN_ALLOC - APR_MEMNODE_T_SIZE)) == NULL) { if (abort_fn) abort_fn(APR_ENOMEM); return APR_ENOMEM; } node->next = node; node->ref = &node->next; pool = (apr_pool_t *)node->first_avail; node->first_avail = pool->self_first_avail = (char *)pool + SIZEOF_POOL_T; pool->allocator = allocator; pool->active = pool->self = node; pool->abort_fn = abort_fn; pool->child = NULL; pool->cleanups = NULL; pool->free_cleanups = NULL; pool->subprocesses = NULL; pool->user_data = NULL; pool->tag = NULL; #ifdef NETWARE pool->owner_proc = (apr_os_proc_t)getnlmhandle(); #endif /* defined(NETWARE) */ if ((pool->parent = parent) != NULL) { #if APR_HAS_THREADS apr_thread_mutex_t *mutex; if ((mutex = apr_allocator_mutex_get(parent->allocator)) != NULL) apr_thread_mutex_lock(mutex); #endif /* APR_HAS_THREADS */ if ((pool->sibling = parent->child) != NULL) pool->sibling->ref = &pool->sibling; parent->child = pool; pool->ref = &parent->child; #if APR_HAS_THREADS if (mutex) apr_thread_mutex_unlock(mutex); #endif /* APR_HAS_THREADS */ } else { pool->sibling = NULL; pool->ref = NULL; } *newpool = pool; return APR_SUCCESS; } /* * "Print" functions */ /* * apr_psprintf is implemented by writing directly into the current * block of the pool, starting right at first_avail. If there's * insufficient room, then a new block is allocated and the earlier * output is copied over. The new block isn't linked into the pool * until all the output is done. * * Note that this is completely safe because nothing else can * allocate in this apr_pool_t while apr_psprintf is running. alarms are * blocked, and the only thing outside of apr_pools.c that's invoked * is apr_vformatter -- which was purposefully written to be * self-contained with no callouts. */ struct psprintf_data { apr_vformatter_buff_t vbuff; apr_memnode_t *node; apr_pool_t *pool; apr_byte_t got_a_new_node; apr_memnode_t *free; }; #define APR_PSPRINTF_MIN_STRINGSIZE 32 static int psprintf_flush(apr_vformatter_buff_t *vbuff) { struct psprintf_data *ps = (struct psprintf_data *)vbuff; apr_memnode_t *node, *active; apr_size_t cur_len, size; char *strp; apr_pool_t *pool; apr_size_t free_index; pool = ps->pool; active = ps->node; strp = ps->vbuff.curpos; cur_len = strp - active->first_avail; size = cur_len << 1; /* Make sure that we don't try to use a block that has less * than APR_PSPRINTF_MIN_STRINGSIZE bytes left in it. This * also catches the case where size == 0, which would result * in reusing a block that can't even hold the NUL byte. */ if (size < APR_PSPRINTF_MIN_STRINGSIZE) size = APR_PSPRINTF_MIN_STRINGSIZE; node = active->next; if (!ps->got_a_new_node && size < (apr_size_t)(node->endp - node->first_avail)) { list_remove(node); list_insert(node, active); node->free_index = 0; pool->active = node; free_index = (APR_ALIGN(active->endp - active->first_avail + 1, BOUNDARY_SIZE) - BOUNDARY_SIZE) >> BOUNDARY_INDEX; active->free_index = (APR_UINT32_TRUNC_CAST)free_index; node = active->next; if (free_index < node->free_index) { do { node = node->next; } while (free_index < node->free_index); list_remove(active); list_insert(active, node); } node = pool->active; } else { if ((node = allocator_alloc(pool->allocator, size)) == NULL) return -1; if (ps->got_a_new_node) { active->next = ps->free; ps->free = active; } ps->got_a_new_node = 1; } memcpy(node->first_avail, active->first_avail, cur_len); ps->node = node; ps->vbuff.curpos = node->first_avail + cur_len; ps->vbuff.endpos = node->endp - 1; /* Save a byte for NUL terminator */ return 0; } APR_DECLARE(char *) apr_pvsprintf(apr_pool_t *pool, const char *fmt, va_list ap) { struct psprintf_data ps; char *strp; apr_size_t size; apr_memnode_t *active, *node; apr_size_t free_index; ps.node = active = pool->active; ps.pool = pool; ps.vbuff.curpos = ps.node->first_avail; /* Save a byte for the NUL terminator */ ps.vbuff.endpos = ps.node->endp - 1; ps.got_a_new_node = 0; ps.free = NULL; /* Make sure that the first node passed to apr_vformatter has at least * room to hold the NUL terminator. */ if (ps.node->first_avail == ps.node->endp) { if (psprintf_flush(&ps.vbuff) == -1) { if (pool->abort_fn) { pool->abort_fn(APR_ENOMEM); } return NULL; } } if (apr_vformatter(psprintf_flush, &ps.vbuff, fmt, ap) == -1) { if (pool->abort_fn) pool->abort_fn(APR_ENOMEM); return NULL; } strp = ps.vbuff.curpos; *strp++ = '\0'; size = strp - ps.node->first_avail; size = APR_ALIGN_DEFAULT(size); strp = ps.node->first_avail; ps.node->first_avail += size; if (ps.free) allocator_free(pool->allocator, ps.free); /* * Link the node in if it's a new one */ if (!ps.got_a_new_node) return strp; active = pool->active; node = ps.node; node->free_index = 0; list_insert(node, active); pool->active = node; free_index = (APR_ALIGN(active->endp - active->first_avail + 1, BOUNDARY_SIZE) - BOUNDARY_SIZE) >> BOUNDARY_INDEX; active->free_index = (APR_UINT32_TRUNC_CAST)free_index; node = active->next; if (free_index >= node->free_index) return strp; do { node = node->next; } while (free_index < node->free_index); list_remove(active); list_insert(active, node); return strp; } #else /* APR_POOL_DEBUG */ /* * Debug helper functions */ /* * Walk the pool tree rooted at pool, depth first. When fn returns * anything other than 0, abort the traversal and return the value * returned by fn. */ static int apr_pool_walk_tree(apr_pool_t *pool, int (*fn)(apr_pool_t *pool, void *data), void *data) { int rv; apr_pool_t *child; rv = fn(pool, data); if (rv) return rv; #if APR_HAS_THREADS if (pool->mutex) { apr_thread_mutex_lock(pool->mutex); } #endif /* APR_HAS_THREADS */ child = pool->child; while (child) { rv = apr_pool_walk_tree(child, fn, data); if (rv) break; child = child->sibling; } #if APR_HAS_THREADS if (pool->mutex) { apr_thread_mutex_unlock(pool->mutex); } #endif /* APR_HAS_THREADS */ return rv; } #if (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALL) static void apr_pool_log_event(apr_pool_t *pool, const char *event, const char *file_line, int deref) { if (file_stderr) { if (deref) { apr_file_printf(file_stderr, "POOL DEBUG: " "[%lu" #if APR_HAS_THREADS "/%lu" #endif /* APR_HAS_THREADS */ "] " "%7s " "(%10lu/%10lu/%10lu) " "0x%08X \"%s\" " "<%s> " "(%u/%u/%u) " "\n", (unsigned long)getpid(), #if APR_HAS_THREADS (unsigned long)apr_os_thread_current(), #endif /* APR_HAS_THREADS */ event, (unsigned long)apr_pool_num_bytes(pool, 0), (unsigned long)apr_pool_num_bytes(pool, 1), (unsigned long)apr_pool_num_bytes(global_pool, 1), (unsigned int)pool, pool->tag, file_line, pool->stat_alloc, pool->stat_total_alloc, pool->stat_clear); } else { apr_file_printf(file_stderr, "POOL DEBUG: " "[%lu" #if APR_HAS_THREADS "/%lu" #endif /* APR_HAS_THREADS */ "] " "%7s " " " "0x%08X " "<%s> " "\n", (unsigned long)getpid(), #if APR_HAS_THREADS (unsigned long)apr_os_thread_current(), #endif /* APR_HAS_THREADS */ event, (unsigned int)pool, file_line); } } } #endif /* (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALL) */ #if (APR_POOL_DEBUG & APR_POOL_DEBUG_LIFETIME) static int pool_is_child_of(apr_pool_t *parent, void *data) { apr_pool_t *pool = (apr_pool_t *)data; return (pool == parent); } static int apr_pool_is_child_of(apr_pool_t *pool, apr_pool_t *parent) { if (parent == NULL) return 0; return apr_pool_walk_tree(parent, pool_is_child_of, pool); } #endif /* (APR_POOL_DEBUG & APR_POOL_DEBUG_LIFETIME) */ static void apr_pool_check_integrity(apr_pool_t *pool) { /* Rule of thumb: use of the global pool is always * ok, since the only user is apr_pools.c. Unless * people have searched for the top level parent and * started to use that... */ if (pool == global_pool || global_pool == NULL) return; /* Lifetime * This basically checks to see if the pool being used is still * a relative to the global pool. If not it was previously * destroyed, in which case we abort(). */ #if (APR_POOL_DEBUG & APR_POOL_DEBUG_LIFETIME) if (!apr_pool_is_child_of(pool, global_pool)) { #if (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALL) apr_pool_log_event(pool, "LIFE", __FILE__ ":apr_pool_integrity check", 0); #endif /* (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALL) */ abort(); } #endif /* (APR_POOL_DEBUG & APR_POOL_DEBUG_LIFETIME) */ #if (APR_POOL_DEBUG & APR_POOL_DEBUG_OWNER) #if APR_HAS_THREADS if (!apr_os_thread_equal(pool->owner, apr_os_thread_current())) { #if (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALL) apr_pool_log_event(pool, "THREAD", __FILE__ ":apr_pool_integrity check", 0); #endif /* (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALL) */ abort(); } #endif /* APR_HAS_THREADS */ #endif /* (APR_POOL_DEBUG & APR_POOL_DEBUG_OWNER) */ } /* * Initialization (debug) */ APR_DECLARE(apr_status_t) apr_pool_initialize(void) { apr_status_t rv; #if (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALL) char *logpath; #endif if (apr_pools_initialized++) return APR_SUCCESS; /* Since the debug code works a bit differently then the * regular pools code, we ask for a lock here. The regular * pools code has got this lock embedded in the global * allocator, a concept unknown to debug mode. */ if ((rv = apr_pool_create_ex(&global_pool, NULL, NULL, NULL)) != APR_SUCCESS) { return rv; } apr_pool_tag(global_pool, "APR global pool"); apr_pools_initialized = 1; /* This has to happen here because mutexes might be backed by * atomics. It used to be snug and safe in apr_initialize(). */ if ((rv = apr_atomic_init(global_pool)) != APR_SUCCESS) { return rv; } #if (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALL) rv = apr_env_get(&logpath, "APR_POOL_DEBUG_LOG", global_pool); if (rv == APR_SUCCESS) { apr_file_open(&file_stderr, logpath, APR_APPEND|APR_WRITE|APR_CREATE, APR_OS_DEFAULT, global_pool); } else { apr_file_open_stderr(&file_stderr, global_pool); } if (file_stderr) { apr_file_printf(file_stderr, "POOL DEBUG: [PID" #if APR_HAS_THREADS "/TID" #endif /* APR_HAS_THREADS */ "] ACTION (SIZE /POOL SIZE /TOTAL SIZE) " "POOL \"TAG\" <__FILE__:__LINE__> (ALLOCS/TOTAL ALLOCS/CLEARS)\n"); apr_pool_log_event(global_pool, "GLOBAL", __FILE__ ":apr_pool_initialize", 0); } #endif /* (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALL) */ return APR_SUCCESS; } APR_DECLARE(void) apr_pool_terminate(void) { if (!apr_pools_initialized) return; apr_pools_initialized = 0; apr_pool_destroy(global_pool); /* This will also destroy the mutex */ global_pool = NULL; #if (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALL) file_stderr = NULL; #endif /* (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALL) */ } /* * Memory allocation (debug) */ static void *pool_alloc(apr_pool_t *pool, apr_size_t size) { debug_node_t *node; void *mem; if ((mem = malloc(size)) == NULL) { if (pool->abort_fn) pool->abort_fn(APR_ENOMEM); return NULL; } node = pool->nodes; if (node == NULL || node->index == 64) { if ((node = malloc(SIZEOF_DEBUG_NODE_T)) == NULL) { if (pool->abort_fn) pool->abort_fn(APR_ENOMEM); return NULL; } memset(node, 0, SIZEOF_DEBUG_NODE_T); node->next = pool->nodes; pool->nodes = node; node->index = 0; } node->beginp[node->index] = mem; node->endp[node->index] = (char *)mem + size; node->index++; pool->stat_alloc++; pool->stat_total_alloc++; return mem; } APR_DECLARE(void *) apr_palloc_debug(apr_pool_t *pool, apr_size_t size, const char *file_line) { void *mem; apr_pool_check_integrity(pool); mem = pool_alloc(pool, size); #if (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALLOC) apr_pool_log_event(pool, "PALLOC", file_line, 1); #endif /* (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALLOC) */ return mem; } APR_DECLARE(void *) apr_pcalloc_debug(apr_pool_t *pool, apr_size_t size, const char *file_line) { void *mem; apr_pool_check_integrity(pool); mem = pool_alloc(pool, size); memset(mem, 0, size); #if (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALLOC) apr_pool_log_event(pool, "PCALLOC", file_line, 1); #endif /* (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALLOC) */ return mem; } /* * Pool creation/destruction (debug) */ #define POOL_POISON_BYTE 'A' static void pool_clear_debug(apr_pool_t *pool, const char *file_line) { debug_node_t *node; apr_uint32_t index; /* Destroy the subpools. The subpools will detach themselves from * this pool thus this loop is safe and easy. */ while (pool->child) pool_destroy_debug(pool->child, file_line); /* Run cleanups */ run_cleanups(&pool->cleanups); pool->free_cleanups = NULL; pool->cleanups = NULL; /* If new child pools showed up, this is a reason to raise a flag */ if (pool->child) abort(); /* Free subprocesses */ free_proc_chain(pool->subprocesses); pool->subprocesses = NULL; /* Clear the user data. */ pool->user_data = NULL; /* Free the blocks, scribbling over them first to help highlight * use-after-free issues. */ while ((node = pool->nodes) != NULL) { pool->nodes = node->next; for (index = 0; index < node->index; index++) { memset(node->beginp[index], POOL_POISON_BYTE, node->endp[index] - node->beginp[index]); free(node->beginp[index]); } memset(node, POOL_POISON_BYTE, SIZEOF_DEBUG_NODE_T); free(node); } pool->stat_alloc = 0; pool->stat_clear++; } APR_DECLARE(void) apr_pool_clear_debug(apr_pool_t *pool, const char *file_line) { #if APR_HAS_THREADS apr_thread_mutex_t *mutex = NULL; #endif apr_pool_check_integrity(pool); #if (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE) apr_pool_log_event(pool, "CLEAR", file_line, 1); #endif /* (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE) */ #if APR_HAS_THREADS if (pool->parent != NULL) mutex = pool->parent->mutex; /* Lock the parent mutex before clearing so that if we have our * own mutex it won't be accessed by apr_pool_walk_tree after * it has been destroyed. */ if (mutex != NULL && mutex != pool->mutex) { apr_thread_mutex_lock(mutex); } #endif pool_clear_debug(pool, file_line); #if APR_HAS_THREADS /* If we had our own mutex, it will have been destroyed by * the registered cleanups. Recreate the mutex. Unlock * the mutex we obtained above. */ if (mutex != pool->mutex) { (void)apr_thread_mutex_create(&pool->mutex, APR_THREAD_MUTEX_NESTED, pool); if (mutex != NULL) (void)apr_thread_mutex_unlock(mutex); } #endif /* APR_HAS_THREADS */ } static void pool_destroy_debug(apr_pool_t *pool, const char *file_line) { apr_pool_check_integrity(pool); #if (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE) apr_pool_log_event(pool, "DESTROY", file_line, 1); #endif /* (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE) */ pool_clear_debug(pool, file_line); /* Remove the pool from the parents child list */ if (pool->parent) { #if APR_HAS_THREADS apr_thread_mutex_t *mutex; if ((mutex = pool->parent->mutex) != NULL) apr_thread_mutex_lock(mutex); #endif /* APR_HAS_THREADS */ if ((*pool->ref = pool->sibling) != NULL) pool->sibling->ref = pool->ref; #if APR_HAS_THREADS if (mutex) apr_thread_mutex_unlock(mutex); #endif /* APR_HAS_THREADS */ } if (pool->allocator != NULL && apr_allocator_owner_get(pool->allocator) == pool) { apr_allocator_destroy(pool->allocator); } /* Free the pool itself */ free(pool); } APR_DECLARE(void) apr_pool_destroy_debug(apr_pool_t *pool, const char *file_line) { if (pool->joined) { /* Joined pools must not be explicitly destroyed; the caller * has broken the guarantee. */ #if (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALL) apr_pool_log_event(pool, "LIFE", __FILE__ ":apr_pool_destroy abort on joined", 0); #endif /* (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE_ALL) */ abort(); } pool_destroy_debug(pool, file_line); } APR_DECLARE(apr_status_t) apr_pool_create_ex_debug(apr_pool_t **newpool, apr_pool_t *parent, apr_abortfunc_t abort_fn, apr_allocator_t *allocator, const char *file_line) { apr_pool_t *pool; *newpool = NULL; if (!parent) { parent = global_pool; } else { apr_pool_check_integrity(parent); if (!allocator) allocator = parent->allocator; } if (!abort_fn && parent) abort_fn = parent->abort_fn; if ((pool = malloc(SIZEOF_POOL_T)) == NULL) { if (abort_fn) abort_fn(APR_ENOMEM); return APR_ENOMEM; } memset(pool, 0, SIZEOF_POOL_T); pool->allocator = allocator; pool->abort_fn = abort_fn; pool->tag = file_line; pool->file_line = file_line; if ((pool->parent = parent) != NULL) { #if APR_HAS_THREADS if (parent->mutex) apr_thread_mutex_lock(parent->mutex); #endif /* APR_HAS_THREADS */ if ((pool->sibling = parent->child) != NULL) pool->sibling->ref = &pool->sibling; parent->child = pool; pool->ref = &parent->child; #if APR_HAS_THREADS if (parent->mutex) apr_thread_mutex_unlock(parent->mutex); #endif /* APR_HAS_THREADS */ } else { pool->sibling = NULL; pool->ref = NULL; } #if APR_HAS_THREADS pool->owner = apr_os_thread_current(); #endif /* APR_HAS_THREADS */ #ifdef NETWARE pool->owner_proc = (apr_os_proc_t)getnlmhandle(); #endif /* defined(NETWARE) */ if (parent == NULL || parent->allocator != allocator) { #if APR_HAS_THREADS apr_status_t rv; /* No matter what the creation flags say, always create * a lock. Without it integrity_check and apr_pool_num_bytes * blow up (because they traverse pools child lists that * possibly belong to another thread, in combination with * the pool having no lock). However, this might actually * hide problems like creating a child pool of a pool * belonging to another thread. */ if ((rv = apr_thread_mutex_create(&pool->mutex, APR_THREAD_MUTEX_NESTED, pool)) != APR_SUCCESS) { free(pool); return rv; } #endif /* APR_HAS_THREADS */ } else { #if APR_HAS_THREADS if (parent) pool->mutex = parent->mutex; #endif /* APR_HAS_THREADS */ } *newpool = pool; #if (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE) apr_pool_log_event(pool, "CREATE", file_line, 1); #endif /* (APR_POOL_DEBUG & APR_POOL_DEBUG_VERBOSE) */ return APR_SUCCESS; } /* * "Print" functions (debug) */ struct psprintf_data { apr_vformatter_buff_t vbuff; char *mem; apr_size_t size; }; static int psprintf_flush(apr_vformatter_buff_t *vbuff) { struct psprintf_data *ps = (struct psprintf_data *)vbuff; apr_size_t size; size = ps->vbuff.curpos - ps->mem; ps->size <<= 1; if ((ps->mem = realloc(ps->mem, ps->size)) == NULL) return -1; ps->vbuff.curpos = ps->mem + size; ps->vbuff.endpos = ps->mem + ps->size - 1; return 0; } APR_DECLARE(char *) apr_pvsprintf(apr_pool_t *pool, const char *fmt, va_list ap) { struct psprintf_data ps; debug_node_t *node; apr_pool_check_integrity(pool); ps.size = 64; ps.mem = malloc(ps.size); ps.vbuff.curpos = ps.mem; /* Save a byte for the NUL terminator */ ps.vbuff.endpos = ps.mem + ps.size - 1; if (apr_vformatter(psprintf_flush, &ps.vbuff, fmt, ap) == -1) { if (pool->abort_fn) pool->abort_fn(APR_ENOMEM); return NULL; } *ps.vbuff.curpos++ = '\0'; /* * Link the node in */ node = pool->nodes; if (node == NULL || node->index == 64) { if ((node = malloc(SIZEOF_DEBUG_NODE_T)) == NULL) { if (pool->abort_fn) pool->abort_fn(APR_ENOMEM); return NULL; } node->next = pool->nodes; pool->nodes = node; node->index = 0; } node->beginp[node->index] = ps.mem; node->endp[node->index] = ps.mem + ps.size; node->index++; return ps.mem; } /* * Debug functions */ APR_DECLARE(void) apr_pool_join(apr_pool_t *p, apr_pool_t *sub) { #if APR_POOL_DEBUG if (sub->parent != p) { abort(); } sub->joined = p; #endif } static int pool_find(apr_pool_t *pool, void *data) { void **pmem = (void **)data; debug_node_t *node; apr_uint32_t index; node = pool->nodes; while (node) { for (index = 0; index < node->index; index++) { if (node->beginp[index] <= *pmem && node->endp[index] > *pmem) { *pmem = pool; return 1; } } node = node->next; } return 0; } APR_DECLARE(apr_pool_t *) apr_pool_find(const void *mem) { void *pool = (void *)mem; if (apr_pool_walk_tree(global_pool, pool_find, &pool)) return pool; return NULL; } static int pool_num_bytes(apr_pool_t *pool, void *data) { apr_size_t *psize = (apr_size_t *)data; debug_node_t *node; apr_uint32_t index; node = pool->nodes; while (node) { for (index = 0; index < node->index; index++) { *psize += (char *)node->endp[index] - (char *)node->beginp[index]; } node = node->next; } return 0; } APR_DECLARE(apr_size_t) apr_pool_num_bytes(apr_pool_t *pool, int recurse) { apr_size_t size = 0; if (!recurse) { pool_num_bytes(pool, &size); return size; } apr_pool_walk_tree(pool, pool_num_bytes, &size); return size; } APR_DECLARE(void) apr_pool_lock(apr_pool_t *pool, int flag) { } #endif /* !APR_POOL_DEBUG */ #ifdef NETWARE void netware_pool_proc_cleanup () { apr_pool_t *pool = global_pool->child; apr_os_proc_t owner_proc = (apr_os_proc_t)getnlmhandle(); while (pool) { if (pool->owner_proc == owner_proc) { apr_pool_destroy (pool); pool = global_pool->child; } else { pool = pool->sibling; } } return; } #endif /* defined(NETWARE) */ /* * "Print" functions (common) */ APR_DECLARE_NONSTD(char *) apr_psprintf(apr_pool_t *p, const char *fmt, ...) { va_list ap; char *res; va_start(ap, fmt); res = apr_pvsprintf(p, fmt, ap); va_end(ap); return res; } /* * Pool Properties */ APR_DECLARE(void) apr_pool_abort_set(apr_abortfunc_t abort_fn, apr_pool_t *pool) { pool->abort_fn = abort_fn; } APR_DECLARE(apr_abortfunc_t) apr_pool_abort_get(apr_pool_t *pool) { return pool->abort_fn; } APR_DECLARE(apr_pool_t *) apr_pool_parent_get(apr_pool_t *pool) { #ifdef NETWARE /* On NetWare, don't return the global_pool, return the application pool as the top most pool */ if (pool->parent == global_pool) return NULL; else #endif return pool->parent; } APR_DECLARE(apr_allocator_t *) apr_pool_allocator_get(apr_pool_t *pool) { return pool->allocator; } /* return TRUE if a is an ancestor of b * NULL is considered an ancestor of all pools */ APR_DECLARE(int) apr_pool_is_ancestor(apr_pool_t *a, apr_pool_t *b) { if (a == NULL) return 1; #if APR_POOL_DEBUG /* Find the pool with the longest lifetime guaranteed by the * caller: */ while (a->joined) { a = a->joined; } #endif while (b) { if (a == b) return 1; b = b->parent; } return 0; } APR_DECLARE(void) apr_pool_tag(apr_pool_t *pool, const char *tag) { pool->tag = tag; } /* * User data management */ APR_DECLARE(apr_status_t) apr_pool_userdata_set(const void *data, const char *key, apr_status_t (*cleanup) (void *), apr_pool_t *pool) { #if APR_POOL_DEBUG apr_pool_check_integrity(pool); #endif /* APR_POOL_DEBUG */ if (pool->user_data == NULL) pool->user_data = apr_hash_make(pool); if (apr_hash_get(pool->user_data, key, APR_HASH_KEY_STRING) == NULL) { char *new_key = apr_pstrdup(pool, key); apr_hash_set(pool->user_data, new_key, APR_HASH_KEY_STRING, data); } else { apr_hash_set(pool->user_data, key, APR_HASH_KEY_STRING, data); } if (cleanup) apr_pool_cleanup_register(pool, data, cleanup, cleanup); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_pool_userdata_setn(const void *data, const char *key, apr_status_t (*cleanup)(void *), apr_pool_t *pool) { #if APR_POOL_DEBUG apr_pool_check_integrity(pool); #endif /* APR_POOL_DEBUG */ if (pool->user_data == NULL) pool->user_data = apr_hash_make(pool); apr_hash_set(pool->user_data, key, APR_HASH_KEY_STRING, data); if (cleanup) apr_pool_cleanup_register(pool, data, cleanup, cleanup); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_pool_userdata_get(void **data, const char *key, apr_pool_t *pool) { #if APR_POOL_DEBUG apr_pool_check_integrity(pool); #endif /* APR_POOL_DEBUG */ if (pool->user_data == NULL) { *data = NULL; } else { *data = apr_hash_get(pool->user_data, key, APR_HASH_KEY_STRING); } return APR_SUCCESS; } /* * Cleanup */ struct cleanup_t { struct cleanup_t *next; const void *data; apr_status_t (*plain_cleanup_fn)(void *data); apr_status_t (*child_cleanup_fn)(void *data); }; APR_DECLARE(void) apr_pool_cleanup_register(apr_pool_t *p, const void *data, apr_status_t (*plain_cleanup_fn)(void *data), apr_status_t (*child_cleanup_fn)(void *data)) { cleanup_t *c; #if APR_POOL_DEBUG apr_pool_check_integrity(p); #endif /* APR_POOL_DEBUG */ if (p != NULL) { if (p->free_cleanups) { /* reuse a cleanup structure */ c = p->free_cleanups; p->free_cleanups = c->next; } else { c = apr_palloc(p, sizeof(cleanup_t)); } c->data = data; c->plain_cleanup_fn = plain_cleanup_fn; c->child_cleanup_fn = child_cleanup_fn; c->next = p->cleanups; p->cleanups = c; } } APR_DECLARE(void) apr_pool_cleanup_kill(apr_pool_t *p, const void *data, apr_status_t (*cleanup_fn)(void *)) { cleanup_t *c, **lastp; #if APR_POOL_DEBUG apr_pool_check_integrity(p); #endif /* APR_POOL_DEBUG */ if (p == NULL) return; c = p->cleanups; lastp = &p->cleanups; while (c) { if (c->data == data && c->plain_cleanup_fn == cleanup_fn) { *lastp = c->next; /* move to freelist */ c->next = p->free_cleanups; p->free_cleanups = c; break; } lastp = &c->next; c = c->next; } } APR_DECLARE(void) apr_pool_child_cleanup_set(apr_pool_t *p, const void *data, apr_status_t (*plain_cleanup_fn)(void *), apr_status_t (*child_cleanup_fn)(void *)) { cleanup_t *c; #if APR_POOL_DEBUG apr_pool_check_integrity(p); #endif /* APR_POOL_DEBUG */ if (p == NULL) return; c = p->cleanups; while (c) { if (c->data == data && c->plain_cleanup_fn == plain_cleanup_fn) { c->child_cleanup_fn = child_cleanup_fn; break; } c = c->next; } } APR_DECLARE(apr_status_t) apr_pool_cleanup_run(apr_pool_t *p, void *data, apr_status_t (*cleanup_fn)(void *)) { apr_pool_cleanup_kill(p, data, cleanup_fn); return (*cleanup_fn)(data); } static void run_cleanups(cleanup_t **cref) { cleanup_t *c = *cref; while (c) { *cref = c->next; (*c->plain_cleanup_fn)((void *)c->data); c = *cref; } } static void run_child_cleanups(cleanup_t **cref) { cleanup_t *c = *cref; while (c) { *cref = c->next; (*c->child_cleanup_fn)((void *)c->data); c = *cref; } } static void cleanup_pool_for_exec(apr_pool_t *p) { run_child_cleanups(&p->cleanups); for (p = p->child; p; p = p->sibling) cleanup_pool_for_exec(p); } APR_DECLARE(void) apr_pool_cleanup_for_exec(void) { #if !defined(WIN32) && !defined(OS2) /* * Don't need to do anything on NT or OS/2, because I * am actually going to spawn the new process - not * exec it. All handles that are not inheritable, will * be automajically closed. The only problem is with * file handles that are open, but there isn't much * I can do about that (except if the child decides * to go out and close them */ cleanup_pool_for_exec(global_pool); #endif /* !defined(WIN32) && !defined(OS2) */ } APR_DECLARE_NONSTD(apr_status_t) apr_pool_cleanup_null(void *data) { /* do nothing cleanup routine */ return APR_SUCCESS; } /* Subprocesses don't use the generic cleanup interface because * we don't want multiple subprocesses to result in multiple * three-second pauses; the subprocesses have to be "freed" all * at once. If other resources are introduced with the same property, * we might want to fold support for that into the generic interface. * For now, it's a special case. */ APR_DECLARE(void) apr_pool_note_subprocess(apr_pool_t *pool, apr_proc_t *proc, apr_kill_conditions_e how) { struct process_chain *pc = apr_palloc(pool, sizeof(struct process_chain)); pc->proc = proc; pc->kill_how = how; pc->next = pool->subprocesses; pool->subprocesses = pc; } static void free_proc_chain(struct process_chain *procs) { /* Dispose of the subprocesses we've spawned off in the course of * whatever it was we're cleaning up now. This may involve killing * some of them off... */ struct process_chain *pc; int need_timeout = 0; apr_time_t timeout_interval; if (!procs) return; /* No work. Whew! */ /* First, check to see if we need to do the SIGTERM, sleep, SIGKILL * dance with any of the processes we're cleaning up. If we've got * any kill-on-sight subprocesses, ditch them now as well, so they * don't waste any more cycles doing whatever it is that they shouldn't * be doing anymore. */ #ifndef NEED_WAITPID /* Pick up all defunct processes */ for (pc = procs; pc; pc = pc->next) { if (apr_proc_wait(pc->proc, NULL, NULL, APR_NOWAIT) != APR_CHILD_NOTDONE) pc->kill_how = APR_KILL_NEVER; } #endif /* !defined(NEED_WAITPID) */ for (pc = procs; pc; pc = pc->next) { #ifndef WIN32 if ((pc->kill_how == APR_KILL_AFTER_TIMEOUT) || (pc->kill_how == APR_KILL_ONLY_ONCE)) { /* * Subprocess may be dead already. Only need the timeout if not. * Note: apr_proc_kill on Windows is TerminateProcess(), which is * similar to a SIGKILL, so always give the process a timeout * under Windows before killing it. */ if (apr_proc_kill(pc->proc, SIGTERM) == APR_SUCCESS) need_timeout = 1; } else if (pc->kill_how == APR_KILL_ALWAYS) { #else /* WIN32 knows only one fast, clean method of killing processes today */ if (pc->kill_how != APR_KILL_NEVER) { need_timeout = 1; pc->kill_how = APR_KILL_ALWAYS; #endif apr_proc_kill(pc->proc, SIGKILL); } } /* Sleep only if we have to. The sleep algorithm grows * by a factor of two on each iteration. TIMEOUT_INTERVAL * is equal to TIMEOUT_USECS / 64. */ if (need_timeout) { timeout_interval = TIMEOUT_INTERVAL; apr_sleep(timeout_interval); do { /* check the status of the subprocesses */ need_timeout = 0; for (pc = procs; pc; pc = pc->next) { if (pc->kill_how == APR_KILL_AFTER_TIMEOUT) { if (apr_proc_wait(pc->proc, NULL, NULL, APR_NOWAIT) == APR_CHILD_NOTDONE) need_timeout = 1; /* subprocess is still active */ else pc->kill_how = APR_KILL_NEVER; /* subprocess has exited */ } } if (need_timeout) { if (timeout_interval >= TIMEOUT_USECS) { break; } apr_sleep(timeout_interval); timeout_interval *= 2; } } while (need_timeout); } /* OK, the scripts we just timed out for have had a chance to clean up * --- now, just get rid of them, and also clean up the system accounting * goop... */ for (pc = procs; pc; pc = pc->next) { if (pc->kill_how == APR_KILL_AFTER_TIMEOUT) apr_proc_kill(pc->proc, SIGKILL); } /* Now wait for all the signaled processes to die */ for (pc = procs; pc; pc = pc->next) { if (pc->kill_how != APR_KILL_NEVER) (void)apr_proc_wait(pc->proc, NULL, NULL, APR_WAIT); } } /* * Pool creation/destruction stubs, for people who are running * mixed release/debug enviroments. */ #if !APR_POOL_DEBUG APR_DECLARE(void *) apr_palloc_debug(apr_pool_t *pool, apr_size_t size, const char *file_line) { return apr_palloc(pool, size); } APR_DECLARE(void *) apr_pcalloc_debug(apr_pool_t *pool, apr_size_t size, const char *file_line) { return apr_pcalloc(pool, size); } APR_DECLARE(void) apr_pool_clear_debug(apr_pool_t *pool, const char *file_line) { apr_pool_clear(pool); } APR_DECLARE(void) apr_pool_destroy_debug(apr_pool_t *pool, const char *file_line) { apr_pool_destroy(pool); } APR_DECLARE(apr_status_t) apr_pool_create_ex_debug(apr_pool_t **newpool, apr_pool_t *parent, apr_abortfunc_t abort_fn, apr_allocator_t *allocator, const char *file_line) { return apr_pool_create_ex(newpool, parent, abort_fn, allocator); } #else /* APR_POOL_DEBUG */ #undef apr_palloc APR_DECLARE(void *) apr_palloc(apr_pool_t *pool, apr_size_t size); APR_DECLARE(void *) apr_palloc(apr_pool_t *pool, apr_size_t size) { return apr_palloc_debug(pool, size, "undefined"); } #undef apr_pcalloc APR_DECLARE(void *) apr_pcalloc(apr_pool_t *pool, apr_size_t size); APR_DECLARE(void *) apr_pcalloc(apr_pool_t *pool, apr_size_t size) { return apr_pcalloc_debug(pool, size, "undefined"); } #undef apr_pool_clear APR_DECLARE(void) apr_pool_clear(apr_pool_t *pool); APR_DECLARE(void) apr_pool_clear(apr_pool_t *pool) { apr_pool_clear_debug(pool, "undefined"); } #undef apr_pool_destroy APR_DECLARE(void) apr_pool_destroy(apr_pool_t *pool); APR_DECLARE(void) apr_pool_destroy(apr_pool_t *pool) { apr_pool_destroy_debug(pool, "undefined"); } #undef apr_pool_create_ex APR_DECLARE(apr_status_t) apr_pool_create_ex(apr_pool_t **newpool, apr_pool_t *parent, apr_abortfunc_t abort_fn, apr_allocator_t *allocator); APR_DECLARE(apr_status_t) apr_pool_create_ex(apr_pool_t **newpool, apr_pool_t *parent, apr_abortfunc_t abort_fn, apr_allocator_t *allocator) { return apr_pool_create_ex_debug(newpool, parent, abort_fn, allocator, "undefined"); } #endif /* APR_POOL_DEBUG */
001-log4cxx
trunk/src/apr/memory/unix/apr_pools.c
C
asf20
60,681
/* 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_hash.h" #if APR_HAVE_STDLIB_H #include <stdlib.h> #endif #if APR_HAVE_STRING_H #include <string.h> #endif #if APR_POOL_DEBUG && APR_HAVE_STDIO_H #include <stdio.h> #endif /* * The internal form of a hash table. * * The table is an array indexed by the hash of the key; collisions * are resolved by hanging a linked list of hash entries off each * element of the array. Although this is a really simple design it * isn't too bad given that pools have a low allocation overhead. */ typedef struct apr_hash_entry_t apr_hash_entry_t; struct apr_hash_entry_t { apr_hash_entry_t *next; unsigned int hash; const void *key; apr_ssize_t klen; const void *val; }; /* * Data structure for iterating through a hash table. * * We keep a pointer to the next hash entry here to allow the current * hash entry to be freed or otherwise mangled between calls to * apr_hash_next(). */ struct apr_hash_index_t { apr_hash_t *ht; apr_hash_entry_t *this, *next; unsigned int index; }; /* * The size of the array is always a power of two. We use the maximum * index rather than the size so that we can use bitwise-AND for * modular arithmetic. * The count of hash entries may be greater depending on the chosen * collision rate. */ struct apr_hash_t { apr_pool_t *pool; apr_hash_entry_t **array; apr_hash_index_t iterator; /* For apr_hash_first(NULL, ...) */ unsigned int count, max; apr_hashfunc_t hash_func; apr_hash_entry_t *free; /* List of recycled entries */ }; #define INITIAL_MAX 15 /* tunable == 2^n - 1 */ /* * Hash creation functions. */ static apr_hash_entry_t **alloc_array(apr_hash_t *ht, unsigned int max) { return apr_pcalloc(ht->pool, sizeof(*ht->array) * (max + 1)); } APR_DECLARE(apr_hash_t *) apr_hash_make(apr_pool_t *pool) { apr_hash_t *ht; ht = apr_palloc(pool, sizeof(apr_hash_t)); ht->pool = pool; ht->free = NULL; ht->count = 0; ht->max = INITIAL_MAX; ht->array = alloc_array(ht, ht->max); ht->hash_func = apr_hashfunc_default; return ht; } APR_DECLARE(apr_hash_t *) apr_hash_make_custom(apr_pool_t *pool, apr_hashfunc_t hash_func) { apr_hash_t *ht = apr_hash_make(pool); ht->hash_func = hash_func; return ht; } /* * Hash iteration functions. */ APR_DECLARE(apr_hash_index_t *) apr_hash_next(apr_hash_index_t *hi) { hi->this = hi->next; while (!hi->this) { if (hi->index > hi->ht->max) return NULL; hi->this = hi->ht->array[hi->index++]; } hi->next = hi->this->next; return hi; } APR_DECLARE(apr_hash_index_t *) apr_hash_first(apr_pool_t *p, apr_hash_t *ht) { apr_hash_index_t *hi; if (p) hi = apr_palloc(p, sizeof(*hi)); else hi = &ht->iterator; hi->ht = ht; hi->index = 0; hi->this = NULL; hi->next = NULL; return apr_hash_next(hi); } APR_DECLARE(void) apr_hash_this(apr_hash_index_t *hi, const void **key, apr_ssize_t *klen, void **val) { if (key) *key = hi->this->key; if (klen) *klen = hi->this->klen; if (val) *val = (void *)hi->this->val; } /* * Expanding a hash table */ static void expand_array(apr_hash_t *ht) { apr_hash_index_t *hi; apr_hash_entry_t **new_array; unsigned int new_max; new_max = ht->max * 2 + 1; new_array = alloc_array(ht, new_max); for (hi = apr_hash_first(NULL, ht); hi; hi = apr_hash_next(hi)) { unsigned int i = hi->this->hash & new_max; hi->this->next = new_array[i]; new_array[i] = hi->this; } ht->array = new_array; ht->max = new_max; } APR_DECLARE_NONSTD(unsigned int) apr_hashfunc_default(const char *char_key, apr_ssize_t *klen) { unsigned int hash = 0; const unsigned char *key = (const unsigned char *)char_key; const unsigned char *p; apr_ssize_t i; /* * This is the popular `times 33' hash algorithm which is used by * perl and also appears in Berkeley DB. This is one of the best * known hash functions for strings because it is both computed * very fast and distributes very well. * * The originator may be Dan Bernstein but the code in Berkeley DB * cites Chris Torek as the source. The best citation I have found * is "Chris Torek, Hash function for text in C, Usenet message * <27038@mimsy.umd.edu> in comp.lang.c , October, 1990." in Rich * Salz's USENIX 1992 paper about INN which can be found at * <http://citeseer.nj.nec.com/salz92internetnews.html>. * * The magic of number 33, i.e. why it works better than many other * constants, prime or not, has never been adequately explained by * anyone. So I try an explanation: if one experimentally tests all * multipliers between 1 and 256 (as I did while writing a low-level * data structure library some time ago) one detects that even * numbers are not useable at all. The remaining 128 odd numbers * (except for the number 1) work more or less all equally well. * They all distribute in an acceptable way and this way fill a hash * table with an average percent of approx. 86%. * * If one compares the chi^2 values of the variants (see * Bob Jenkins ``Hashing Frequently Asked Questions'' at * http://burtleburtle.net/bob/hash/hashfaq.html for a description * of chi^2), the number 33 not even has the best value. But the * number 33 and a few other equally good numbers like 17, 31, 63, * 127 and 129 have nevertheless a great advantage to the remaining * numbers in the large set of possible multipliers: their multiply * operation can be replaced by a faster operation based on just one * shift plus either a single addition or subtraction operation. And * because a hash function has to both distribute good _and_ has to * be very fast to compute, those few numbers should be preferred. * * -- Ralf S. Engelschall <rse@engelschall.com> */ if (*klen == APR_HASH_KEY_STRING) { for (p = key; *p; p++) { hash = hash * 33 + *p; } *klen = p - key; } else { for (p = key, i = *klen; i; i--, p++) { hash = hash * 33 + *p; } } return hash; } /* * This is where we keep the details of the hash function and control * the maximum collision rate. * * If val is non-NULL it creates and initializes a new hash entry if * there isn't already one there; it returns an updatable pointer so * that hash entries can be removed. */ static apr_hash_entry_t **find_entry(apr_hash_t *ht, const void *key, apr_ssize_t klen, const void *val) { apr_hash_entry_t **hep, *he; unsigned int hash; hash = ht->hash_func(key, &klen); /* scan linked list */ for (hep = &ht->array[hash & ht->max], he = *hep; he; hep = &he->next, he = *hep) { if (he->hash == hash && he->klen == klen && memcmp(he->key, key, klen) == 0) break; } if (he || !val) return hep; /* add a new entry for non-NULL values */ if ((he = ht->free) != NULL) ht->free = he->next; else he = apr_palloc(ht->pool, sizeof(*he)); he->next = NULL; he->hash = hash; he->key = key; he->klen = klen; he->val = val; *hep = he; ht->count++; return hep; } APR_DECLARE(apr_hash_t *) apr_hash_copy(apr_pool_t *pool, const apr_hash_t *orig) { apr_hash_t *ht; apr_hash_entry_t *new_vals; unsigned int i, j; ht = apr_palloc(pool, sizeof(apr_hash_t) + sizeof(*ht->array) * (orig->max + 1) + sizeof(apr_hash_entry_t) * orig->count); ht->pool = pool; ht->free = NULL; ht->count = orig->count; ht->max = orig->max; ht->hash_func = orig->hash_func; ht->array = (apr_hash_entry_t **)((char *)ht + sizeof(apr_hash_t)); new_vals = (apr_hash_entry_t *)((char *)(ht) + sizeof(apr_hash_t) + sizeof(*ht->array) * (orig->max + 1)); j = 0; for (i = 0; i <= ht->max; i++) { apr_hash_entry_t **new_entry = &(ht->array[i]); apr_hash_entry_t *orig_entry = orig->array[i]; while (orig_entry) { *new_entry = &new_vals[j++]; (*new_entry)->hash = orig_entry->hash; (*new_entry)->key = orig_entry->key; (*new_entry)->klen = orig_entry->klen; (*new_entry)->val = orig_entry->val; new_entry = &((*new_entry)->next); orig_entry = orig_entry->next; } *new_entry = NULL; } return ht; } APR_DECLARE(void *) apr_hash_get(apr_hash_t *ht, const void *key, apr_ssize_t klen) { apr_hash_entry_t *he; he = *find_entry(ht, key, klen, NULL); if (he) return (void *)he->val; else return NULL; } APR_DECLARE(void) apr_hash_set(apr_hash_t *ht, const void *key, apr_ssize_t klen, const void *val) { apr_hash_entry_t **hep; hep = find_entry(ht, key, klen, val); if (*hep) { if (!val) { /* delete entry */ apr_hash_entry_t *old = *hep; *hep = (*hep)->next; old->next = ht->free; ht->free = old; --ht->count; } else { /* replace entry */ (*hep)->val = val; /* check that the collision rate isn't too high */ if (ht->count > ht->max) { expand_array(ht); } } } /* else key not present and val==NULL */ } APR_DECLARE(unsigned int) apr_hash_count(apr_hash_t *ht) { return ht->count; } APR_DECLARE(apr_hash_t*) apr_hash_overlay(apr_pool_t *p, const apr_hash_t *overlay, const apr_hash_t *base) { return apr_hash_merge(p, overlay, base, NULL, NULL); } APR_DECLARE(apr_hash_t *) apr_hash_merge(apr_pool_t *p, const apr_hash_t *overlay, const apr_hash_t *base, void * (*merger)(apr_pool_t *p, const void *key, apr_ssize_t klen, const void *h1_val, const void *h2_val, const void *data), const void *data) { apr_hash_t *res; apr_hash_entry_t *new_vals = NULL; apr_hash_entry_t *iter; apr_hash_entry_t *ent; unsigned int i,j,k; #if APR_POOL_DEBUG /* we don't copy keys and values, so it's necessary that * overlay->a.pool and base->a.pool have a life span at least * as long as p */ if (!apr_pool_is_ancestor(overlay->pool, p)) { fprintf(stderr, "apr_hash_merge: overlay's pool is not an ancestor of p\n"); abort(); } if (!apr_pool_is_ancestor(base->pool, p)) { fprintf(stderr, "apr_hash_merge: base's pool is not an ancestor of p\n"); abort(); } #endif res = apr_palloc(p, sizeof(apr_hash_t)); res->pool = p; res->free = NULL; res->hash_func = base->hash_func; res->count = base->count; res->max = (overlay->max > base->max) ? overlay->max : base->max; if (base->count + overlay->count > res->max) { res->max = res->max * 2 + 1; } res->array = alloc_array(res, res->max); if (base->count + overlay->count) { new_vals = apr_palloc(p, sizeof(apr_hash_entry_t) * (base->count + overlay->count)); } j = 0; for (k = 0; k <= base->max; k++) { for (iter = base->array[k]; iter; iter = iter->next) { i = iter->hash & res->max; new_vals[j].klen = iter->klen; new_vals[j].key = iter->key; new_vals[j].val = iter->val; new_vals[j].hash = iter->hash; new_vals[j].next = res->array[i]; res->array[i] = &new_vals[j]; j++; } } for (k = 0; k <= overlay->max; k++) { for (iter = overlay->array[k]; iter; iter = iter->next) { i = iter->hash & res->max; for (ent = res->array[i]; ent; ent = ent->next) { if ((ent->klen == iter->klen) && (memcmp(ent->key, iter->key, iter->klen) == 0)) { if (merger) { ent->val = (*merger)(p, iter->key, iter->klen, iter->val, ent->val, data); } else { ent->val = iter->val; } break; } } if (!ent) { new_vals[j].klen = iter->klen; new_vals[j].key = iter->key; new_vals[j].val = iter->val; new_vals[j].hash = iter->hash; new_vals[j].next = res->array[i]; res->array[i] = &new_vals[j]; res->count++; j++; } } } return res; } APR_POOL_IMPLEMENT_ACCESSOR(hash)
001-log4cxx
trunk/src/apr/tables/apr_hash.c
C
asf20
14,835
/* 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. */ /* * Resource allocation code... the code here is responsible for making * sure that nothing leaks. * * rst --- 4/95 --- 6/95 */ #include "apr_private.h" #include "apr_general.h" #include "apr_pools.h" #include "apr_tables.h" #include "apr_strings.h" #include "apr_lib.h" #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 APR_POOL_DEBUG && APR_HAVE_STDIO_H #include <stdio.h> #endif /***************************************************************** * This file contains array and apr_table_t functions only. */ /***************************************************************** * * The 'array' functions... */ static void make_array_core(apr_array_header_t *res, apr_pool_t *p, int nelts, int elt_size, int clear) { /* * Assure sanity if someone asks for * array of zero elts. */ if (nelts < 1) { nelts = 1; } if (clear) { res->elts = apr_pcalloc(p, nelts * elt_size); } else { res->elts = apr_palloc(p, nelts * elt_size); } res->pool = p; res->elt_size = elt_size; res->nelts = 0; /* No active elements yet... */ res->nalloc = nelts; /* ...but this many allocated */ } APR_DECLARE(int) apr_is_empty_array(const apr_array_header_t *a) { return ((a == NULL) || (a->nelts == 0)); } APR_DECLARE(apr_array_header_t *) apr_array_make(apr_pool_t *p, int nelts, int elt_size) { apr_array_header_t *res; res = (apr_array_header_t *) apr_palloc(p, sizeof(apr_array_header_t)); make_array_core(res, p, nelts, elt_size, 1); return res; } APR_DECLARE(void *) apr_array_pop(apr_array_header_t *arr) { if (apr_is_empty_array(arr)) { return NULL; } return arr->elts + (arr->elt_size * (--arr->nelts)); } APR_DECLARE(void *) apr_array_push(apr_array_header_t *arr) { if (arr->nelts == arr->nalloc) { int new_size = (arr->nalloc <= 0) ? 1 : arr->nalloc * 2; char *new_data; new_data = apr_palloc(arr->pool, arr->elt_size * new_size); memcpy(new_data, arr->elts, arr->nalloc * arr->elt_size); memset(new_data + arr->nalloc * arr->elt_size, 0, arr->elt_size * (new_size - arr->nalloc)); arr->elts = new_data; arr->nalloc = new_size; } ++arr->nelts; return arr->elts + (arr->elt_size * (arr->nelts - 1)); } static void *apr_array_push_noclear(apr_array_header_t *arr) { if (arr->nelts == arr->nalloc) { int new_size = (arr->nalloc <= 0) ? 1 : arr->nalloc * 2; char *new_data; new_data = apr_palloc(arr->pool, arr->elt_size * new_size); memcpy(new_data, arr->elts, arr->nalloc * arr->elt_size); arr->elts = new_data; arr->nalloc = new_size; } ++arr->nelts; return arr->elts + (arr->elt_size * (arr->nelts - 1)); } APR_DECLARE(void) apr_array_cat(apr_array_header_t *dst, const apr_array_header_t *src) { int elt_size = dst->elt_size; if (dst->nelts + src->nelts > dst->nalloc) { int new_size = (dst->nalloc <= 0) ? 1 : dst->nalloc * 2; char *new_data; while (dst->nelts + src->nelts > new_size) { new_size *= 2; } new_data = apr_pcalloc(dst->pool, elt_size * new_size); memcpy(new_data, dst->elts, dst->nalloc * elt_size); dst->elts = new_data; dst->nalloc = new_size; } memcpy(dst->elts + dst->nelts * elt_size, src->elts, elt_size * src->nelts); dst->nelts += src->nelts; } APR_DECLARE(apr_array_header_t *) apr_array_copy(apr_pool_t *p, const apr_array_header_t *arr) { apr_array_header_t *res = (apr_array_header_t *) apr_palloc(p, sizeof(apr_array_header_t)); make_array_core(res, p, arr->nalloc, arr->elt_size, 0); memcpy(res->elts, arr->elts, arr->elt_size * arr->nelts); res->nelts = arr->nelts; memset(res->elts + res->elt_size * res->nelts, 0, res->elt_size * (res->nalloc - res->nelts)); return res; } /* This cute function copies the array header *only*, but arranges * for the data section to be copied on the first push or arraycat. * It's useful when the elements of the array being copied are * read only, but new stuff *might* get added on the end; we have the * overhead of the full copy only where it is really needed. */ static APR_INLINE void copy_array_hdr_core(apr_array_header_t *res, const apr_array_header_t *arr) { res->elts = arr->elts; res->elt_size = arr->elt_size; res->nelts = arr->nelts; res->nalloc = arr->nelts; /* Force overflow on push */ } APR_DECLARE(apr_array_header_t *) apr_array_copy_hdr(apr_pool_t *p, const apr_array_header_t *arr) { apr_array_header_t *res; res = (apr_array_header_t *) apr_palloc(p, sizeof(apr_array_header_t)); res->pool = p; copy_array_hdr_core(res, arr); return res; } /* The above is used here to avoid consing multiple new array bodies... */ APR_DECLARE(apr_array_header_t *) apr_array_append(apr_pool_t *p, const apr_array_header_t *first, const apr_array_header_t *second) { apr_array_header_t *res = apr_array_copy_hdr(p, first); apr_array_cat(res, second); return res; } /* apr_array_pstrcat generates a new string from the apr_pool_t containing * the concatenated sequence of substrings referenced as elements within * the array. The string will be empty if all substrings are empty or null, * or if there are no elements in the array. * If sep is non-NUL, it will be inserted between elements as a separator. */ APR_DECLARE(char *) apr_array_pstrcat(apr_pool_t *p, const apr_array_header_t *arr, const char sep) { char *cp, *res, **strpp; apr_size_t len; int i; if (arr->nelts <= 0 || arr->elts == NULL) { /* Empty table? */ return (char *) apr_pcalloc(p, 1); } /* Pass one --- find length of required string */ len = 0; for (i = 0, strpp = (char **) arr->elts; ; ++strpp) { if (strpp && *strpp != NULL) { len += strlen(*strpp); } if (++i >= arr->nelts) { break; } if (sep) { ++len; } } /* Allocate the required string */ res = (char *) apr_palloc(p, len + 1); cp = res; /* Pass two --- copy the argument strings into the result space */ for (i = 0, strpp = (char **) arr->elts; ; ++strpp) { if (strpp && *strpp != NULL) { len = strlen(*strpp); memcpy(cp, *strpp, len); cp += len; } if (++i >= arr->nelts) { break; } if (sep) { *cp++ = sep; } } *cp = '\0'; /* Return the result string */ return res; } /***************************************************************** * * The "table" functions. */ #if APR_CHARSET_EBCDIC #define CASE_MASK 0xbfbfbfbf #else #define CASE_MASK 0xdfdfdfdf #endif #define TABLE_HASH_SIZE 32 #define TABLE_INDEX_MASK 0x1f #define TABLE_HASH(key) (TABLE_INDEX_MASK & *(unsigned char *)(key)) #define TABLE_INDEX_IS_INITIALIZED(t, i) ((t)->index_initialized & (1 << (i))) #define TABLE_SET_INDEX_INITIALIZED(t, i) ((t)->index_initialized |= (1 << (i))) /* Compute the "checksum" for a key, consisting of the first * 4 bytes, normalized for case-insensitivity and packed into * an int...this checksum allows us to do a single integer * comparison as a fast check to determine whether we can * skip a strcasecmp */ #define COMPUTE_KEY_CHECKSUM(key, checksum) \ { \ const char *k = (key); \ apr_uint32_t c = (apr_uint32_t)*k; \ (checksum) = c; \ (checksum) <<= 8; \ if (c) { \ c = (apr_uint32_t)*++k; \ checksum |= c; \ } \ (checksum) <<= 8; \ if (c) { \ c = (apr_uint32_t)*++k; \ checksum |= c; \ } \ (checksum) <<= 8; \ if (c) { \ c = (apr_uint32_t)*++k; \ checksum |= c; \ } \ checksum &= CASE_MASK; \ } /** The opaque string-content table type */ struct apr_table_t { /* This has to be first to promote backwards compatibility with * older modules which cast a apr_table_t * to an apr_array_header_t *... * they should use the apr_table_elts() function for most of the * cases they do this for. */ /** The underlying array for the table */ apr_array_header_t a; #ifdef MAKE_TABLE_PROFILE /** Who created the array. */ void *creator; #endif /* An index to speed up table lookups. The way this works is: * - Hash the key into the index: * - index_first[TABLE_HASH(key)] is the offset within * the table of the first entry with that key * - index_last[TABLE_HASH(key)] is the offset within * the table of the last entry with that key * - If (and only if) there is no entry in the table whose * key hashes to index element i, then the i'th bit * of index_initialized will be zero. (Check this before * trying to use index_first[i] or index_last[i]!) */ apr_uint32_t index_initialized; int index_first[TABLE_HASH_SIZE]; int index_last[TABLE_HASH_SIZE]; }; /* * NOTICE: if you tweak this you should look at is_empty_table() * and table_elts() in alloc.h */ #ifdef MAKE_TABLE_PROFILE static apr_table_entry_t *table_push(apr_table_t *t) { if (t->a.nelts == t->a.nalloc) { return NULL; } return (apr_table_entry_t *) apr_array_push_noclear(&t->a); } #else /* MAKE_TABLE_PROFILE */ #define table_push(t) ((apr_table_entry_t *) apr_array_push_noclear(&(t)->a)) #endif /* MAKE_TABLE_PROFILE */ APR_DECLARE(const apr_array_header_t *) apr_table_elts(const apr_table_t *t) { return (const apr_array_header_t *)t; } APR_DECLARE(int) apr_is_empty_table(const apr_table_t *t) { return ((t == NULL) || (t->a.nelts == 0)); } APR_DECLARE(apr_table_t *) apr_table_make(apr_pool_t *p, int nelts) { apr_table_t *t = apr_palloc(p, sizeof(apr_table_t)); make_array_core(&t->a, p, nelts, sizeof(apr_table_entry_t), 0); #ifdef MAKE_TABLE_PROFILE t->creator = __builtin_return_address(0); #endif t->index_initialized = 0; return t; } APR_DECLARE(apr_table_t *) apr_table_copy(apr_pool_t *p, const apr_table_t *t) { apr_table_t *new = apr_palloc(p, sizeof(apr_table_t)); #if APR_POOL_DEBUG /* we don't copy keys and values, so it's necessary that t->a.pool * have a life span at least as long as p */ if (!apr_pool_is_ancestor(t->a.pool, p)) { fprintf(stderr, "apr_table_copy: t's pool is not an ancestor of p\n"); abort(); } #endif make_array_core(&new->a, p, t->a.nalloc, sizeof(apr_table_entry_t), 0); memcpy(new->a.elts, t->a.elts, t->a.nelts * sizeof(apr_table_entry_t)); new->a.nelts = t->a.nelts; memcpy(new->index_first, t->index_first, sizeof(int) * TABLE_HASH_SIZE); memcpy(new->index_last, t->index_last, sizeof(int) * TABLE_HASH_SIZE); new->index_initialized = t->index_initialized; return new; } static void table_reindex(apr_table_t *t) { int i; int hash; apr_table_entry_t *next_elt = (apr_table_entry_t *) t->a.elts; t->index_initialized = 0; for (i = 0; i < t->a.nelts; i++, next_elt++) { hash = TABLE_HASH(next_elt->key); t->index_last[hash] = i; if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { t->index_first[hash] = i; TABLE_SET_INDEX_INITIALIZED(t, hash); } } } APR_DECLARE(void) apr_table_clear(apr_table_t *t) { t->a.nelts = 0; t->index_initialized = 0; } APR_DECLARE(const char *) apr_table_get(const apr_table_t *t, const char *key) { apr_table_entry_t *next_elt; apr_table_entry_t *end_elt; apr_uint32_t checksum; int hash; if (key == NULL) { return NULL; } hash = TABLE_HASH(key); if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { return NULL; } COMPUTE_KEY_CHECKSUM(key, checksum); next_elt = ((apr_table_entry_t *) t->a.elts) + t->index_first[hash];; end_elt = ((apr_table_entry_t *) t->a.elts) + t->index_last[hash]; for (; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { return next_elt->val; } } return NULL; } APR_DECLARE(void) apr_table_set(apr_table_t *t, const char *key, const char *val) { apr_table_entry_t *next_elt; apr_table_entry_t *end_elt; apr_table_entry_t *table_end; apr_uint32_t checksum; int hash; COMPUTE_KEY_CHECKSUM(key, checksum); hash = TABLE_HASH(key); if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { t->index_first[hash] = t->a.nelts; TABLE_SET_INDEX_INITIALIZED(t, hash); goto add_new_elt; } next_elt = ((apr_table_entry_t *) t->a.elts) + t->index_first[hash];; end_elt = ((apr_table_entry_t *) t->a.elts) + t->index_last[hash]; table_end =((apr_table_entry_t *) t->a.elts) + t->a.nelts; for (; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { /* Found an existing entry with the same key, so overwrite it */ int must_reindex = 0; apr_table_entry_t *dst_elt = NULL; next_elt->val = apr_pstrdup(t->a.pool, val); /* Remove any other instances of this key */ for (next_elt++; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { t->a.nelts--; if (!dst_elt) { dst_elt = next_elt; } } else if (dst_elt) { *dst_elt++ = *next_elt; must_reindex = 1; } } /* If we've removed anything, shift over the remainder * of the table (note that the previous loop didn't * run to the end of the table, just to the last match * for the index) */ if (dst_elt) { for (; next_elt < table_end; next_elt++) { *dst_elt++ = *next_elt; } must_reindex = 1; } if (must_reindex) { table_reindex(t); } return; } } add_new_elt: t->index_last[hash] = t->a.nelts; next_elt = (apr_table_entry_t *) table_push(t); next_elt->key = apr_pstrdup(t->a.pool, key); next_elt->val = apr_pstrdup(t->a.pool, val); next_elt->key_checksum = checksum; } APR_DECLARE(void) apr_table_setn(apr_table_t *t, const char *key, const char *val) { apr_table_entry_t *next_elt; apr_table_entry_t *end_elt; apr_table_entry_t *table_end; apr_uint32_t checksum; int hash; COMPUTE_KEY_CHECKSUM(key, checksum); hash = TABLE_HASH(key); if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { t->index_first[hash] = t->a.nelts; TABLE_SET_INDEX_INITIALIZED(t, hash); goto add_new_elt; } next_elt = ((apr_table_entry_t *) t->a.elts) + t->index_first[hash];; end_elt = ((apr_table_entry_t *) t->a.elts) + t->index_last[hash]; table_end =((apr_table_entry_t *) t->a.elts) + t->a.nelts; for (; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { /* Found an existing entry with the same key, so overwrite it */ int must_reindex = 0; apr_table_entry_t *dst_elt = NULL; next_elt->val = (char *)val; /* Remove any other instances of this key */ for (next_elt++; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { t->a.nelts--; if (!dst_elt) { dst_elt = next_elt; } } else if (dst_elt) { *dst_elt++ = *next_elt; must_reindex = 1; } } /* If we've removed anything, shift over the remainder * of the table (note that the previous loop didn't * run to the end of the table, just to the last match * for the index) */ if (dst_elt) { for (; next_elt < table_end; next_elt++) { *dst_elt++ = *next_elt; } must_reindex = 1; } if (must_reindex) { table_reindex(t); } return; } } add_new_elt: t->index_last[hash] = t->a.nelts; next_elt = (apr_table_entry_t *) table_push(t); next_elt->key = (char *)key; next_elt->val = (char *)val; next_elt->key_checksum = checksum; } APR_DECLARE(void) apr_table_unset(apr_table_t *t, const char *key) { apr_table_entry_t *next_elt; apr_table_entry_t *end_elt; apr_table_entry_t *dst_elt; apr_uint32_t checksum; int hash; int must_reindex; hash = TABLE_HASH(key); if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { return; } COMPUTE_KEY_CHECKSUM(key, checksum); next_elt = ((apr_table_entry_t *) t->a.elts) + t->index_first[hash]; end_elt = ((apr_table_entry_t *) t->a.elts) + t->index_last[hash]; must_reindex = 0; for (; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { /* Found a match: remove this entry, plus any additional * matches for the same key that might follow */ apr_table_entry_t *table_end = ((apr_table_entry_t *) t->a.elts) + t->a.nelts; t->a.nelts--; dst_elt = next_elt; for (next_elt++; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { t->a.nelts--; } else { *dst_elt++ = *next_elt; } } /* Shift over the remainder of the table (note that * the previous loop didn't run to the end of the table, * just to the last match for the index) */ for (; next_elt < table_end; next_elt++) { *dst_elt++ = *next_elt; } must_reindex = 1; break; } } if (must_reindex) { table_reindex(t); } } APR_DECLARE(void) apr_table_merge(apr_table_t *t, const char *key, const char *val) { apr_table_entry_t *next_elt; apr_table_entry_t *end_elt; apr_uint32_t checksum; int hash; COMPUTE_KEY_CHECKSUM(key, checksum); hash = TABLE_HASH(key); if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { t->index_first[hash] = t->a.nelts; TABLE_SET_INDEX_INITIALIZED(t, hash); goto add_new_elt; } next_elt = ((apr_table_entry_t *) t->a.elts) + t->index_first[hash]; end_elt = ((apr_table_entry_t *) t->a.elts) + t->index_last[hash]; for (; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { /* Found an existing entry with the same key, so merge with it */ next_elt->val = apr_pstrcat(t->a.pool, next_elt->val, ", ", val, NULL); return; } } add_new_elt: t->index_last[hash] = t->a.nelts; next_elt = (apr_table_entry_t *) table_push(t); next_elt->key = apr_pstrdup(t->a.pool, key); next_elt->val = apr_pstrdup(t->a.pool, val); next_elt->key_checksum = checksum; } APR_DECLARE(void) apr_table_mergen(apr_table_t *t, const char *key, const char *val) { apr_table_entry_t *next_elt; apr_table_entry_t *end_elt; apr_uint32_t checksum; int hash; #if APR_POOL_DEBUG { if (!apr_pool_is_ancestor(apr_pool_find(key), t->a.pool)) { fprintf(stderr, "apr_table_mergen: key not in ancestor pool of t\n"); abort(); } if (!apr_pool_is_ancestor(apr_pool_find(val), t->a.pool)) { fprintf(stderr, "apr_table_mergen: key not in ancestor pool of t\n"); abort(); } } #endif COMPUTE_KEY_CHECKSUM(key, checksum); hash = TABLE_HASH(key); if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { t->index_first[hash] = t->a.nelts; TABLE_SET_INDEX_INITIALIZED(t, hash); goto add_new_elt; } next_elt = ((apr_table_entry_t *) t->a.elts) + t->index_first[hash];; end_elt = ((apr_table_entry_t *) t->a.elts) + t->index_last[hash]; for (; next_elt <= end_elt; next_elt++) { if ((checksum == next_elt->key_checksum) && !strcasecmp(next_elt->key, key)) { /* Found an existing entry with the same key, so merge with it */ next_elt->val = apr_pstrcat(t->a.pool, next_elt->val, ", ", val, NULL); return; } } add_new_elt: t->index_last[hash] = t->a.nelts; next_elt = (apr_table_entry_t *) table_push(t); next_elt->key = (char *)key; next_elt->val = (char *)val; next_elt->key_checksum = checksum; } APR_DECLARE(void) apr_table_add(apr_table_t *t, const char *key, const char *val) { apr_table_entry_t *elts; apr_uint32_t checksum; int hash; hash = TABLE_HASH(key); t->index_last[hash] = t->a.nelts; if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { t->index_first[hash] = t->a.nelts; TABLE_SET_INDEX_INITIALIZED(t, hash); } COMPUTE_KEY_CHECKSUM(key, checksum); elts = (apr_table_entry_t *) table_push(t); elts->key = apr_pstrdup(t->a.pool, key); elts->val = apr_pstrdup(t->a.pool, val); elts->key_checksum = checksum; } APR_DECLARE(void) apr_table_addn(apr_table_t *t, const char *key, const char *val) { apr_table_entry_t *elts; apr_uint32_t checksum; int hash; #if APR_POOL_DEBUG { if (!apr_pool_is_ancestor(apr_pool_find(key), t->a.pool)) { fprintf(stderr, "apr_table_addn: key not in ancestor pool of t\n"); abort(); } if (!apr_pool_is_ancestor(apr_pool_find(val), t->a.pool)) { fprintf(stderr, "apr_table_addn: key not in ancestor pool of t\n"); abort(); } } #endif hash = TABLE_HASH(key); t->index_last[hash] = t->a.nelts; if (!TABLE_INDEX_IS_INITIALIZED(t, hash)) { t->index_first[hash] = t->a.nelts; TABLE_SET_INDEX_INITIALIZED(t, hash); } COMPUTE_KEY_CHECKSUM(key, checksum); elts = (apr_table_entry_t *) table_push(t); elts->key = (char *)key; elts->val = (char *)val; elts->key_checksum = checksum; } APR_DECLARE(apr_table_t *) apr_table_overlay(apr_pool_t *p, const apr_table_t *overlay, const apr_table_t *base) { apr_table_t *res; #if APR_POOL_DEBUG /* we don't copy keys and values, so it's necessary that * overlay->a.pool and base->a.pool have a life span at least * as long as p */ if (!apr_pool_is_ancestor(overlay->a.pool, p)) { fprintf(stderr, "apr_table_overlay: overlay's pool is not an ancestor of p\n"); abort(); } if (!apr_pool_is_ancestor(base->a.pool, p)) { fprintf(stderr, "apr_table_overlay: base's pool is not an ancestor of p\n"); abort(); } #endif res = apr_palloc(p, sizeof(apr_table_t)); /* behave like append_arrays */ res->a.pool = p; copy_array_hdr_core(&res->a, &overlay->a); apr_array_cat(&res->a, &base->a); table_reindex(res); return res; } /* And now for something completely abstract ... * For each key value given as a vararg: * run the function pointed to as * int comp(void *r, char *key, char *value); * on each valid key-value pair in the apr_table_t t that matches the vararg key, * or once for every valid key-value pair if the vararg list is empty, * until the function returns false (0) or we finish the table. * * Note that we restart the traversal for each vararg, which means that * duplicate varargs will result in multiple executions of the function * for each matching key. Note also that if the vararg list is empty, * only one traversal will be made and will cut short if comp returns 0. * * Note that the table_get and table_merge functions assume that each key in * the apr_table_t is unique (i.e., no multiple entries with the same key). This * function does not make that assumption, since it (unfortunately) isn't * true for some of Apache's tables. * * Note that rec is simply passed-on to the comp function, so that the * caller can pass additional info for the task. * * ADDENDUM for apr_table_vdo(): * * The caching api will allow a user to walk the header values: * * apr_status_t apr_cache_el_header_walk(apr_cache_el *el, * int (*comp)(void *, const char *, const char *), void *rec, ...); * * So it can be ..., however from there I use a callback that use a va_list: * * apr_status_t (*cache_el_header_walk)(apr_cache_el *el, * int (*comp)(void *, const char *, const char *), void *rec, va_list); * * To pass those ...'s on down to the actual module that will handle walking * their headers, in the file case this is actually just an apr_table - and * rather than reimplementing apr_table_do (which IMHO would be bad) I just * called it with the va_list. For mod_shmem_cache I don't need it since I * can't use apr_table's, but mod_file_cache should (though a good hash would * be better, but that's a different issue :). * * So to make mod_file_cache easier to maintain, it's a good thing */ APR_DECLARE_NONSTD(int) apr_table_do(apr_table_do_callback_fn_t *comp, void *rec, const apr_table_t *t, ...) { int rv; va_list vp; va_start(vp, t); rv = apr_table_vdo(comp, rec, t, vp); va_end(vp); return rv; } /* XXX: do the semantics of this routine make any sense? Right now, * if the caller passed in a non-empty va_list of keys to search for, * the "early termination" facility only terminates on *that* key; other * keys will continue to process. Note that this only has any effect * at all if there are multiple entries in the table with the same key, * otherwise the called function can never effectively early-terminate * this function, as the zero return value is effectively ignored. * * Note also that this behavior is at odds with the behavior seen if an * empty va_list is passed in -- in that case, a zero return value terminates * the entire apr_table_vdo (which is what I think should happen in * both cases). * * If nobody objects soon, I'm going to change the order of the nested * loops in this function so that any zero return value from the (*comp) * function will cause a full termination of apr_table_vdo. I'm hesitant * at the moment because these (funky) semantics have been around for a * very long time, and although Apache doesn't seem to use them at all, * some third-party vendor might. I can only think of one possible reason * the existing semantics would make any sense, and it's very Apache-centric, * which is this: if (*comp) is looking for matches of a particular * substring in request headers (let's say it's looking for a particular * cookie name in the Set-Cookie headers), then maybe it wants to be * able to stop searching early as soon as it finds that one and move * on to the next key. That's only an optimization of course, but changing * the behavior of this function would mean that any code that tried * to do that would stop working right. * * Sigh. --JCW, 06/28/02 */ APR_DECLARE(int) apr_table_vdo(apr_table_do_callback_fn_t *comp, void *rec, const apr_table_t *t, va_list vp) { char *argp; apr_table_entry_t *elts = (apr_table_entry_t *) t->a.elts; int vdorv = 1; argp = va_arg(vp, char *); do { int rv = 1, i; if (argp) { /* Scan for entries that match the next key */ int hash = TABLE_HASH(argp); if (TABLE_INDEX_IS_INITIALIZED(t, hash)) { apr_uint32_t checksum; COMPUTE_KEY_CHECKSUM(argp, checksum); for (i = t->index_first[hash]; rv && (i <= t->index_last[hash]); ++i) { if (elts[i].key && (checksum == elts[i].key_checksum) && !strcasecmp(elts[i].key, argp)) { rv = (*comp) (rec, elts[i].key, elts[i].val); } } } } else { /* Scan the entire table */ for (i = 0; rv && (i < t->a.nelts); ++i) { if (elts[i].key) { rv = (*comp) (rec, elts[i].key, elts[i].val); } } } if (rv == 0) { vdorv = 0; } } while (argp && ((argp = va_arg(vp, char *)) != NULL)); return vdorv; } static apr_table_entry_t **table_mergesort(apr_pool_t *pool, apr_table_entry_t **values, apr_size_t n) { /* Bottom-up mergesort, based on design in Sedgewick's "Algorithms * in C," chapter 8 */ apr_table_entry_t **values_tmp = (apr_table_entry_t **)apr_palloc(pool, n * sizeof(apr_table_entry_t*)); apr_size_t i; apr_size_t blocksize; /* First pass: sort pairs of elements (blocksize=1) */ for (i = 0; i + 1 < n; i += 2) { if (strcasecmp(values[i]->key, values[i + 1]->key) > 0) { apr_table_entry_t *swap = values[i]; values[i] = values[i + 1]; values[i + 1] = swap; } } /* Merge successively larger blocks */ blocksize = 2; while (blocksize < n) { apr_table_entry_t **dst = values_tmp; apr_size_t next_start; apr_table_entry_t **swap; /* Merge consecutive pairs blocks of the next blocksize. * Within a block, elements are in sorted order due to * the previous iteration. */ for (next_start = 0; next_start + blocksize < n; next_start += (blocksize + blocksize)) { apr_size_t block1_start = next_start; apr_size_t block2_start = block1_start + blocksize; apr_size_t block1_end = block2_start; apr_size_t block2_end = block2_start + blocksize; if (block2_end > n) { /* The last block may be smaller than blocksize */ block2_end = n; } for (;;) { /* Merge the next two blocks: * Pick the smaller of the next element from * block 1 and the next element from block 2. * Once either of the blocks is emptied, copy * over all the remaining elements from the * other block */ if (block1_start == block1_end) { for (; block2_start < block2_end; block2_start++) { *dst++ = values[block2_start]; } break; } else if (block2_start == block2_end) { for (; block1_start < block1_end; block1_start++) { *dst++ = values[block1_start]; } break; } if (strcasecmp(values[block1_start]->key, values[block2_start]->key) > 0) { *dst++ = values[block2_start++]; } else { *dst++ = values[block1_start++]; } } } /* If n is not a multiple of 2*blocksize, some elements * will be left over at the end of the array. */ for (i = dst - values_tmp; i < n; i++) { values_tmp[i] = values[i]; } /* The output array of this pass becomes the input * array of the next pass, and vice versa */ swap = values_tmp; values_tmp = values; values = swap; blocksize += blocksize; } return values; } APR_DECLARE(void) apr_table_compress(apr_table_t *t, unsigned flags) { apr_table_entry_t **sort_array; apr_table_entry_t **sort_next; apr_table_entry_t **sort_end; apr_table_entry_t *table_next; apr_table_entry_t **last; int i; int dups_found; if (t->a.nelts <= 1) { return; } /* Copy pointers to all the table elements into an * array and sort to allow for easy detection of * duplicate keys */ sort_array = (apr_table_entry_t **) apr_palloc(t->a.pool, t->a.nelts * sizeof(apr_table_entry_t*)); sort_next = sort_array; table_next = (apr_table_entry_t *)t->a.elts; i = t->a.nelts; do { *sort_next++ = table_next++; } while (--i); /* Note: the merge is done with mergesort instead of quicksort * because mergesort is a stable sort and runs in n*log(n) * time regardless of its inputs (quicksort is quadratic in * the worst case) */ sort_array = table_mergesort(t->a.pool, sort_array, t->a.nelts); /* Process any duplicate keys */ dups_found = 0; sort_next = sort_array; sort_end = sort_array + t->a.nelts; last = sort_next++; while (sort_next < sort_end) { if (((*sort_next)->key_checksum == (*last)->key_checksum) && !strcasecmp((*sort_next)->key, (*last)->key)) { apr_table_entry_t **dup_last = sort_next + 1; dups_found = 1; while ((dup_last < sort_end) && ((*dup_last)->key_checksum == (*last)->key_checksum) && !strcasecmp((*dup_last)->key, (*last)->key)) { dup_last++; } dup_last--; /* Elements from last through dup_last, inclusive, * all have the same key */ if (flags == APR_OVERLAP_TABLES_MERGE) { apr_size_t len = 0; apr_table_entry_t **next = last; char *new_val; char *val_dst; do { len += strlen((*next)->val); len += 2; /* for ", " or trailing null */ } while (++next <= dup_last); new_val = (char *)apr_palloc(t->a.pool, len); val_dst = new_val; next = last; for (;;) { strcpy(val_dst, (*next)->val); val_dst += strlen((*next)->val); next++; if (next > dup_last) { *val_dst = 0; break; } else { *val_dst++ = ','; *val_dst++ = ' '; } } (*last)->val = new_val; } else { /* overwrite */ (*last)->val = (*dup_last)->val; } do { (*sort_next)->key = NULL; } while (++sort_next <= dup_last); } else { last = sort_next++; } } /* Shift elements to the left to fill holes left by removing duplicates */ if (dups_found) { apr_table_entry_t *src = (apr_table_entry_t *)t->a.elts; apr_table_entry_t *dst = (apr_table_entry_t *)t->a.elts; apr_table_entry_t *last_elt = src + t->a.nelts; do { if (src->key) { *dst++ = *src; } } while (++src < last_elt); t->a.nelts -= (int)(last_elt - dst); } table_reindex(t); } static void apr_table_cat(apr_table_t *t, const apr_table_t *s) { const int n = t->a.nelts; register int idx; apr_array_cat(&t->a,&s->a); if (n == 0) { memcpy(t->index_first,s->index_first,sizeof(int) * TABLE_HASH_SIZE); memcpy(t->index_last, s->index_last, sizeof(int) * TABLE_HASH_SIZE); t->index_initialized = s->index_initialized; return; } for (idx = 0; idx < TABLE_HASH_SIZE; ++idx) { if (TABLE_INDEX_IS_INITIALIZED(s, idx)) { t->index_last[idx] = s->index_last[idx] + n; if (!TABLE_INDEX_IS_INITIALIZED(t, idx)) { t->index_first[idx] = s->index_first[idx] + n; } } } t->index_initialized |= s->index_initialized; } APR_DECLARE(void) apr_table_overlap(apr_table_t *a, const apr_table_t *b, unsigned flags) { if (a->a.nelts + b->a.nelts == 0) { return; } #if APR_POOL_DEBUG /* Since the keys and values are not copied, it's required that * b->a.pool has a lifetime at least as long as a->a.pool. */ if (!apr_pool_is_ancestor(b->a.pool, a->a.pool)) { fprintf(stderr, "apr_table_overlap: b's pool is not an ancestor of a's\n"); abort(); } #endif apr_table_cat(a, b); apr_table_compress(a, flags); }
001-log4cxx
trunk/src/apr/tables/apr_tables.c
C
asf20
38,828
#!/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/buildconf
Shell
asf20
3,281
/* 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_threadproc.h" #include "win32/apr_arch_file_io.h" #include "apr_thread_proc.h" #include "apr_file_io.h" #include "apr_general.h" #include "apr_strings.h" #include "apr_portable.h" #include "apr_lib.h" #include <stdlib.h> #if APR_HAVE_SIGNAL_H #include <signal.h> #endif #include <string.h> #if APR_HAVE_PROCESS_H #include <process.h> #endif #ifdef _WIN32_WCE #ifndef DETACHED_PROCESS #define DETACHED_PROCESS 0 #endif #ifndef CREATE_UNICODE_ENVIRONMENT #define CREATE_UNICODE_ENVIRONMENT 0 #endif #ifndef STARTF_USESHOWWINDOW #define STARTF_USESHOWWINDOW 0 #endif #ifndef SW_HIDE #define SW_HIDE 0 #endif #endif /* * some of the ideas expressed herein are based off of Microsoft * Knowledge Base article: Q190351 * */ APR_DECLARE(apr_status_t) apr_procattr_create(apr_procattr_t **new, apr_pool_t *pool) { (*new) = (apr_procattr_t *)apr_pcalloc(pool, sizeof(apr_procattr_t)); (*new)->pool = pool; (*new)->cmdtype = APR_PROGRAM; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_io_set(apr_procattr_t *attr, apr_int32_t in, apr_int32_t out, apr_int32_t err) { apr_status_t stat = APR_SUCCESS; if (in) { /* APR_CHILD_BLOCK maps to APR_WRITE_BLOCK, while * APR_PARENT_BLOCK maps to APR_READ_BLOCK, so we * must transpose the CHILD/PARENT blocking flags * only for the stdin pipe. stdout/stderr naturally * map to the correct mode. */ if (in == APR_CHILD_BLOCK) in = APR_READ_BLOCK; else if (in == APR_PARENT_BLOCK) in = APR_WRITE_BLOCK; stat = apr_create_nt_pipe(&attr->child_in, &attr->parent_in, in, attr->pool); if (stat == APR_SUCCESS) stat = apr_file_inherit_unset(attr->parent_in); } if (out && stat == APR_SUCCESS) { stat = apr_create_nt_pipe(&attr->parent_out, &attr->child_out, out, attr->pool); if (stat == APR_SUCCESS) stat = apr_file_inherit_unset(attr->parent_out); } if (err && stat == APR_SUCCESS) { stat = apr_create_nt_pipe(&attr->parent_err, &attr->child_err, err, attr->pool); if (stat == APR_SUCCESS) stat = apr_file_inherit_unset(attr->parent_err); } return stat; } APR_DECLARE(apr_status_t) apr_procattr_child_in_set(apr_procattr_t *attr, apr_file_t *child_in, apr_file_t *parent_in) { apr_status_t rv = APR_SUCCESS; if (child_in) { if (attr->child_in == NULL) rv = apr_file_dup(&attr->child_in, child_in, attr->pool); else rv = apr_file_dup2(attr->child_in, child_in, attr->pool); if (rv == APR_SUCCESS) rv = apr_file_inherit_set(attr->child_in); } if (parent_in && rv == APR_SUCCESS) { if (attr->parent_in == NULL) rv = apr_file_dup(&attr->parent_in, parent_in, attr->pool); else rv = apr_file_dup2(attr->parent_in, parent_in, attr->pool); } return rv; } APR_DECLARE(apr_status_t) apr_procattr_child_out_set(apr_procattr_t *attr, apr_file_t *child_out, apr_file_t *parent_out) { apr_status_t rv = APR_SUCCESS; if (child_out) { if (attr->child_out == NULL) rv = apr_file_dup(&attr->child_out, child_out, attr->pool); else rv = apr_file_dup2(attr->child_out, child_out, attr->pool); if (rv == APR_SUCCESS) rv = apr_file_inherit_set(attr->child_out); } if (parent_out && rv == APR_SUCCESS) { if (attr->parent_out == NULL) rv = apr_file_dup(&attr->parent_out, parent_out, attr->pool); else rv = apr_file_dup2(attr->parent_out, parent_out, attr->pool); } return rv; } APR_DECLARE(apr_status_t) apr_procattr_child_err_set(apr_procattr_t *attr, apr_file_t *child_err, apr_file_t *parent_err) { apr_status_t rv = APR_SUCCESS; if (child_err) { if (attr->child_err == NULL) rv = apr_file_dup(&attr->child_err, child_err, attr->pool); else rv = apr_file_dup2(attr->child_err, child_err, attr->pool); if (rv == APR_SUCCESS) rv = apr_file_inherit_set(attr->child_err); } if (parent_err && rv == APR_SUCCESS) { if (attr->parent_err == NULL) rv = apr_file_dup(&attr->parent_err, parent_err, attr->pool); else rv = apr_file_dup2(attr->parent_err, parent_err, attr->pool); } return rv; } APR_DECLARE(apr_status_t) apr_procattr_dir_set(apr_procattr_t *attr, const char *dir) { /* curr dir must be in native format, there are all sorts of bugs in * the NT library loading code that flunk the '/' parsing test. */ return apr_filepath_merge(&attr->currdir, NULL, dir, APR_FILEPATH_NATIVE, attr->pool); } APR_DECLARE(apr_status_t) apr_procattr_cmdtype_set(apr_procattr_t *attr, apr_cmdtype_e cmd) { attr->cmdtype = cmd; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_detach_set(apr_procattr_t *attr, apr_int32_t det) { attr->detached = det; return APR_SUCCESS; } static apr_status_t attr_cleanup(void *theattr) { apr_procattr_t *attr = (apr_procattr_t *)theattr; if (attr->user_token) CloseHandle(attr->user_token); attr->user_token = NULL; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_user_set(apr_procattr_t *attr, const char *username, const char *password) { #ifdef _WIN32_WCE return APR_ENOTIMPL; #else HANDLE user; apr_wchar_t *wusername = NULL; apr_wchar_t *wpassword = NULL; apr_status_t rv; apr_size_t len, wlen; if (apr_os_level >= APR_WIN_NT_4) { if (attr->user_token) { /* Cannot set that twice */ if (attr->errfn) { attr->errfn(attr->pool, 0, apr_pstrcat(attr->pool, "function called twice" " on username: ", username, NULL)); } return APR_EINVAL; } len = strlen(username) + 1; wlen = len; wusername = apr_palloc(attr->pool, wlen * sizeof(apr_wchar_t)); if ((rv = apr_conv_utf8_to_ucs2(username, &len, wusername, &wlen)) != APR_SUCCESS) { if (attr->errfn) { attr->errfn(attr->pool, rv, apr_pstrcat(attr->pool, "utf8 to ucs2 conversion failed" " on username: ", username, NULL)); } return rv; } if (password) { len = strlen(password) + 1; wlen = len; wpassword = apr_palloc(attr->pool, wlen * sizeof(apr_wchar_t)); if ((rv = apr_conv_utf8_to_ucs2(password, &len, wpassword, &wlen)) != APR_SUCCESS) { if (attr->errfn) { attr->errfn(attr->pool, rv, apr_pstrcat(attr->pool, "utf8 to ucs2 conversion failed" " on password: ", password, NULL)); } return rv; } } if (!LogonUserW(wusername, NULL, wpassword ? wpassword : L"", LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &user)) { /* Logon Failed */ return apr_get_os_error(); } if (wpassword) memset(wpassword, 0, wlen * sizeof(apr_wchar_t)); /* Get the primary token for user */ if (!DuplicateTokenEx(user, TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY, NULL, SecurityImpersonation, TokenPrimary, &(attr->user_token))) { /* Failed to duplicate the user token */ rv = apr_get_os_error(); CloseHandle(user); return rv; } CloseHandle(user); attr->sd = apr_pcalloc(attr->pool, SECURITY_DESCRIPTOR_MIN_LENGTH); InitializeSecurityDescriptor(attr->sd, SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl(attr->sd, -1, 0, 0); attr->sa = apr_palloc(attr->pool, sizeof(SECURITY_ATTRIBUTES)); attr->sa->nLength = sizeof (SECURITY_ATTRIBUTES); attr->sa->lpSecurityDescriptor = attr->sd; attr->sa->bInheritHandle = TRUE; /* register the cleanup */ apr_pool_cleanup_register(attr->pool, (void *)attr, attr_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } else return APR_ENOTIMPL; #endif } APR_DECLARE(apr_status_t) apr_procattr_group_set(apr_procattr_t *attr, const char *groupname) { /* Always return SUCCESS cause groups are irrelevant */ return APR_SUCCESS; } static const char* has_space(const char *str) { const char *ch; for (ch = str; *ch; ++ch) { if (apr_isspace(*ch)) { return ch; } } return NULL; } static char *apr_caret_escape_args(apr_pool_t *p, const char *str) { char *cmd; unsigned char *d; const unsigned char *s; cmd = apr_palloc(p, 2 * strlen(str) + 1); /* Be safe */ d = (unsigned char *)cmd; s = (const unsigned char *)str; for (; *s; ++s) { /* * Newlines to Win32/OS2 CreateProcess() are ill advised. * Convert them to spaces since they are effectively white * space to most applications */ if (*s == '\r' || *s == '\n') { *d++ = ' '; continue; } if (IS_SHCHAR(*s)) { *d++ = '^'; } *d++ = *s; } *d = '\0'; return cmd; } APR_DECLARE(apr_status_t) apr_procattr_child_errfn_set(apr_procattr_t *attr, apr_child_errfn_t *errfn) { attr->errfn = errfn; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_error_check_set(apr_procattr_t *attr, apr_int32_t chk) { attr->errchk = chk; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_addrspace_set(apr_procattr_t *attr, apr_int32_t addrspace) { /* won't ever be used on this platform, so don't save the flag */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_proc_create(apr_proc_t *new, const char *progname, const char * const *args, const char * const *env, apr_procattr_t *attr, apr_pool_t *pool) { apr_status_t rv; apr_size_t i; const char *argv0; char *cmdline; char *pEnvBlock; PROCESS_INFORMATION pi; DWORD dwCreationFlags = 0; new->in = attr->parent_in; new->out = attr->parent_out; new->err = attr->parent_err; if (attr->detached) { /* If we are creating ourselves detached, Then we should hide the * window we are starting in. And we had better redfine our * handles for STDIN, STDOUT, and STDERR. Do not set the * detached attribute for Win9x. We have found that Win9x does * not manage the stdio handles properly when running old 16 * bit executables if the detached attribute is set. */ if (apr_os_level >= APR_WIN_NT) { /* * XXX DETACHED_PROCESS won't on Win9x at all; on NT/W2K * 16 bit executables fail (MS KB: Q150956) */ dwCreationFlags |= DETACHED_PROCESS; } } /* progname must be unquoted, in native format, as there are all sorts * of bugs in the NT library loader code that fault when parsing '/'. * XXX progname must be NULL if this is a 16 bit app running in WOW */ if (progname[0] == '\"') { progname = apr_pstrndup(pool, progname + 1, strlen(progname) - 2); } if (attr->cmdtype == APR_PROGRAM || attr->cmdtype == APR_PROGRAM_ENV) { char *fullpath = NULL; if ((rv = apr_filepath_merge(&fullpath, attr->currdir, progname, APR_FILEPATH_NATIVE, pool)) != APR_SUCCESS) { if (attr->errfn) { attr->errfn(pool, rv, apr_pstrcat(pool, "filepath_merge failed.", " currdir: ", attr->currdir, " progname: ", progname, NULL)); } return rv; } progname = fullpath; } else { /* Do not fail if the path isn't parseable for APR_PROGRAM_PATH * or APR_SHELLCMD. We only invoke apr_filepath_merge (with no * left hand side expression) in order to correct the path slash * delimiters. But the filename doesn't need to be in the CWD, * nor does it need to be a filename at all (it could be a * built-in shell command.) */ char *fullpath = NULL; if ((rv = apr_filepath_merge(&fullpath, "", progname, APR_FILEPATH_NATIVE, pool)) == APR_SUCCESS) { progname = fullpath; } } if (has_space(progname)) { argv0 = apr_pstrcat(pool, "\"", progname, "\"", NULL); } else { argv0 = progname; } /* Handle the args, seperate from argv0 */ cmdline = ""; for (i = 1; args && args[i]; ++i) { if (has_space(args[i]) || !args[i][0]) { cmdline = apr_pstrcat(pool, cmdline, " \"", args[i], "\"", NULL); } else { cmdline = apr_pstrcat(pool, cmdline, " ", args[i], NULL); } } #ifndef _WIN32_WCE if (attr->cmdtype == APR_SHELLCMD || attr->cmdtype == APR_SHELLCMD_ENV) { char *shellcmd = getenv("COMSPEC"); if (!shellcmd) { if (attr->errfn) { attr->errfn(pool, APR_EINVAL, "COMSPEC envar is not set"); } return APR_EINVAL; } if (shellcmd[0] == '"') { progname = apr_pstrndup(pool, shellcmd + 1, strlen(shellcmd) - 2); } else { progname = shellcmd; if (has_space(shellcmd)) { shellcmd = apr_pstrcat(pool, "\"", shellcmd, "\"", NULL); } } /* Command.com does not support a quoted command, while cmd.exe demands one. */ i = strlen(progname); if (i >= 11 && strcasecmp(progname + i - 11, "command.com") == 0) { cmdline = apr_pstrcat(pool, shellcmd, " /C ", argv0, cmdline, NULL); } else { cmdline = apr_pstrcat(pool, shellcmd, " /C \"", argv0, cmdline, "\"", NULL); } } else #endif { /* Win32 is _different_ than unix. While unix will find the given * program since it's already chdir'ed, Win32 cannot since the parent * attempts to open the program with it's own path. * ###: This solution isn't much better - it may defeat path searching * when the path search was desired. Open to further discussion. */ i = strlen(progname); if (i >= 4 && (strcasecmp(progname + i - 4, ".bat") == 0 || strcasecmp(progname + i - 4, ".cmd") == 0)) { char *shellcmd = getenv("COMSPEC"); if (!shellcmd) { if (attr->errfn) { attr->errfn(pool, APR_EINVAL, "COMSPEC envar is not set"); } return APR_EINVAL; } if (shellcmd[0] == '"') { progname = apr_pstrndup(pool, shellcmd + 1, strlen(shellcmd) - 2); } else { progname = shellcmd; if (has_space(shellcmd)) { shellcmd = apr_pstrcat(pool, "\"", shellcmd, "\"", NULL); } } i = strlen(progname); if (i >= 11 && strcasecmp(progname + i - 11, "command.com") == 0) { /* XXX: Still insecure - need doubled-quotes on each individual * arg of cmdline. Suspect we need to postpone cmdline parsing * until this moment in all four code paths, with some flags * to toggle 'which flavor' is needed. */ cmdline = apr_pstrcat(pool, shellcmd, " /C ", argv0, cmdline, NULL); } else { /* We must protect the cmdline args from any interpolation - this * is not a shellcmd, and the source of argv[] is untrusted. * Notice we escape ALL the cmdline args, including the quotes * around the individual args themselves. No sense in allowing * the shift-state to be toggled, and the application will * not see the caret escapes. */ cmdline = apr_caret_escape_args(pool, cmdline); /* * Our app name must always be quoted so the quotes surrounding * the entire /c "command args" are unambigious. */ if (*argv0 != '"') { cmdline = apr_pstrcat(pool, shellcmd, " /C \"\"", argv0, "\"", cmdline, "\"", NULL); } else { cmdline = apr_pstrcat(pool, shellcmd, " /C \"", argv0, cmdline, "\"", NULL); } } } else { /* A simple command we are directly invoking. Do not pass * the first arg to CreateProc() for APR_PROGRAM_PATH * invocation, since it would need to be a literal and * complete file path. That is; "c:\bin\aprtest.exe" * would succeed, but "c:\bin\aprtest" or "aprtest.exe" * can fail. */ cmdline = apr_pstrcat(pool, argv0, cmdline, NULL); if (attr->cmdtype == APR_PROGRAM_PATH) { progname = NULL; } } } if (!env || attr->cmdtype == APR_PROGRAM_ENV || attr->cmdtype == APR_SHELLCMD_ENV) { pEnvBlock = NULL; } else { apr_size_t iEnvBlockLen; /* * Win32's CreateProcess call requires that the environment * be passed in an environment block, a null terminated block of * null terminated strings. */ i = 0; iEnvBlockLen = 1; while (env[i]) { iEnvBlockLen += strlen(env[i]) + 1; i++; } if (!i) ++iEnvBlockLen; #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { apr_wchar_t *pNext; pEnvBlock = (char *)apr_palloc(pool, iEnvBlockLen * 2); dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT; i = 0; pNext = (apr_wchar_t*)pEnvBlock; while (env[i]) { apr_size_t in = strlen(env[i]) + 1; if ((rv = apr_conv_utf8_to_ucs2(env[i], &in, pNext, &iEnvBlockLen)) != APR_SUCCESS) { if (attr->errfn) { attr->errfn(pool, rv, apr_pstrcat(pool, "utf8 to ucs2 conversion failed" " on this string: ", env[i], NULL)); } return rv; } pNext = wcschr(pNext, L'\0') + 1; i++; } if (!i) *(pNext++) = L'\0'; *pNext = L'\0'; } #endif /* APR_HAS_UNICODE_FS */ #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { char *pNext; pEnvBlock = (char *)apr_palloc(pool, iEnvBlockLen); i = 0; pNext = pEnvBlock; while (env[i]) { strcpy(pNext, env[i]); pNext = strchr(pNext, '\0') + 1; i++; } if (!i) *(pNext++) = '\0'; *pNext = '\0'; } #endif /* APR_HAS_ANSI_FS */ } new->invoked = cmdline; #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { STARTUPINFOW si; apr_wchar_t *wprg = NULL; apr_wchar_t *wcmd = NULL; apr_wchar_t *wcwd = NULL; if (progname) { apr_size_t nprg = strlen(progname) + 1; apr_size_t nwprg = nprg + 6; wprg = apr_palloc(pool, nwprg * sizeof(wprg[0])); if ((rv = apr_conv_utf8_to_ucs2(progname, &nprg, wprg, &nwprg)) != APR_SUCCESS) { if (attr->errfn) { attr->errfn(pool, rv, apr_pstrcat(pool, "utf8 to ucs2 conversion failed" " on progname: ", progname, NULL)); } return rv; } } if (cmdline) { apr_size_t ncmd = strlen(cmdline) + 1; apr_size_t nwcmd = ncmd; wcmd = apr_palloc(pool, nwcmd * sizeof(wcmd[0])); if ((rv = apr_conv_utf8_to_ucs2(cmdline, &ncmd, wcmd, &nwcmd)) != APR_SUCCESS) { if (attr->errfn) { attr->errfn(pool, rv, apr_pstrcat(pool, "utf8 to ucs2 conversion failed" " on cmdline: ", cmdline, NULL)); } return rv; } } if (attr->currdir) { apr_size_t ncwd = strlen(attr->currdir) + 1; apr_size_t nwcwd = ncwd; wcwd = apr_palloc(pool, ncwd * sizeof(wcwd[0])); if ((rv = apr_conv_utf8_to_ucs2(attr->currdir, &ncwd, wcwd, &nwcwd)) != APR_SUCCESS) { if (attr->errfn) { attr->errfn(pool, rv, apr_pstrcat(pool, "utf8 to ucs2 conversion failed" " on currdir: ", attr->currdir, NULL)); } return rv; } } memset(&si, 0, sizeof(si)); si.cb = sizeof(si); if (attr->detached) { si.dwFlags |= STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; } #ifndef _WIN32_WCE if ((attr->child_in && attr->child_in->filehand) || (attr->child_out && attr->child_out->filehand) || (attr->child_err && attr->child_err->filehand)) { si.dwFlags |= STARTF_USESTDHANDLES; si.hStdInput = (attr->child_in) ? attr->child_in->filehand : INVALID_HANDLE_VALUE; si.hStdOutput = (attr->child_out) ? attr->child_out->filehand : INVALID_HANDLE_VALUE; si.hStdError = (attr->child_err) ? attr->child_err->filehand : INVALID_HANDLE_VALUE; } if (attr->user_token) { si.lpDesktop = L"Winsta0\\Default"; if (!ImpersonateLoggedOnUser(attr->user_token)) { /* failed to impersonate the logged user */ rv = apr_get_os_error(); CloseHandle(attr->user_token); attr->user_token = NULL; return rv; } rv = CreateProcessAsUserW(attr->user_token, wprg, wcmd, attr->sa, NULL, TRUE, dwCreationFlags, pEnvBlock, wcwd, &si, &pi); RevertToSelf(); } else { rv = CreateProcessW(wprg, wcmd, /* Executable & Command line */ NULL, NULL, /* Proc & thread security attributes */ TRUE, /* Inherit handles */ dwCreationFlags, /* Creation flags */ pEnvBlock, /* Environment block */ wcwd, /* Current directory name */ &si, &pi); } #else rv = CreateProcessW(wprg, wcmd, /* Executable & Command line */ NULL, NULL, /* Proc & thread security attributes */ FALSE, /* must be 0 */ dwCreationFlags, /* Creation flags */ NULL, /* Environment block must be NULL */ NULL, /* Current directory name must be NULL*/ NULL, /* STARTUPINFO not supported */ &pi); #endif } #endif /* APR_HAS_UNICODE_FS */ #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { STARTUPINFOA si; memset(&si, 0, sizeof(si)); si.cb = sizeof(si); if (attr->detached) { si.dwFlags |= STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; } if ((attr->child_in && attr->child_in->filehand) || (attr->child_out && attr->child_out->filehand) || (attr->child_err && attr->child_err->filehand)) { si.dwFlags |= STARTF_USESTDHANDLES; si.hStdInput = (attr->child_in) ? attr->child_in->filehand : INVALID_HANDLE_VALUE; si.hStdOutput = (attr->child_out) ? attr->child_out->filehand : INVALID_HANDLE_VALUE; si.hStdError = (attr->child_err) ? attr->child_err->filehand : INVALID_HANDLE_VALUE; } rv = CreateProcessA(progname, cmdline, /* Command line */ NULL, NULL, /* Proc & thread security attributes */ TRUE, /* Inherit handles */ dwCreationFlags, /* Creation flags */ pEnvBlock, /* Environment block */ attr->currdir, /* Current directory name */ &si, &pi); } #endif /* APR_HAS_ANSI_FS */ /* Check CreateProcess result */ if (!rv) return apr_get_os_error(); /* XXX Orphaned handle warning - no fix due to broken apr_proc_t api. */ new->hproc = pi.hProcess; new->pid = pi.dwProcessId; if (attr->child_in) { apr_file_close(attr->child_in); } if (attr->child_out) { apr_file_close(attr->child_out); } if (attr->child_err) { apr_file_close(attr->child_err); } CloseHandle(pi.hThread); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_proc_wait_all_procs(apr_proc_t *proc, int *exitcode, apr_exit_why_e *exitwhy, apr_wait_how_e waithow, apr_pool_t *p) { /* Unix does apr_proc_wait(proc(-1), exitcode, exitwhy, waithow) * but Win32's apr_proc_wait won't work that way. We can either * register all APR created processes in some sort of AsyncWait * thread, or simply walk from the global process pool for all * apr_pool_note_subprocess()es registered with APR. */ return APR_ENOTIMPL; } static apr_exit_why_e why_from_exit_code(DWORD exit) { /* See WinNT.h STATUS_ACCESS_VIOLATION and family for how * this class of failures was determined */ if (((exit & 0xC0000000) == 0xC0000000) && !(exit & 0x3FFF0000)) return APR_PROC_SIGNAL; else return APR_PROC_EXIT; /* ### No way to tell if Dr Watson grabbed a core, AFAICT. */ } APR_DECLARE(apr_status_t) apr_proc_wait(apr_proc_t *proc, int *exitcode, apr_exit_why_e *exitwhy, apr_wait_how_e waithow) { DWORD stat; DWORD time; if (waithow == APR_WAIT) time = INFINITE; else time = 0; if ((stat = WaitForSingleObject(proc->hproc, time)) == WAIT_OBJECT_0) { if (GetExitCodeProcess(proc->hproc, &stat)) { if (exitcode) *exitcode = stat; if (exitwhy) *exitwhy = why_from_exit_code(stat); CloseHandle(proc->hproc); proc->hproc = NULL; return APR_CHILD_DONE; } } else if (stat == WAIT_TIMEOUT) { return APR_CHILD_NOTDONE; } return apr_get_os_error(); } APR_DECLARE(apr_status_t) apr_proc_detach(int daemonize) { return APR_ENOTIMPL; }
001-log4cxx
trunk/src/apr/threadproc/win32/proc.c
C
asf20
31,555
/* 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 "win32/apr_arch_threadproc.h" #include "apr_thread_proc.h" #include "apr_general.h" #include "apr_lib.h" #include "apr_portable.h" #if APR_HAVE_PROCESS_H #include <process.h> #endif #include "apr_arch_misc.h" /* Chosen for us by apr_initialize */ DWORD tls_apr_thread = 0; APR_DECLARE(apr_status_t) apr_threadattr_create(apr_threadattr_t **new, apr_pool_t *pool) { (*new) = (apr_threadattr_t *)apr_palloc(pool, sizeof(apr_threadattr_t)); if ((*new) == NULL) { return APR_ENOMEM; } (*new)->pool = pool; (*new)->detach = 0; (*new)->stacksize = 0; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_threadattr_detach_set(apr_threadattr_t *attr, apr_int32_t on) { attr->detach = on; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_threadattr_detach_get(apr_threadattr_t *attr) { if (attr->detach == 1) return APR_DETACH; return APR_NOTDETACH; } APR_DECLARE(apr_status_t) apr_threadattr_stacksize_set(apr_threadattr_t *attr, apr_size_t stacksize) { attr->stacksize = stacksize; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_threadattr_guardsize_set(apr_threadattr_t *attr, apr_size_t size) { return APR_ENOTIMPL; } static void *dummy_worker(void *opaque) { apr_thread_t *thd = (apr_thread_t *)opaque; TlsSetValue(tls_apr_thread, thd->td); return thd->func(thd, thd->data); } APR_DECLARE(apr_status_t) apr_thread_create(apr_thread_t **new, apr_threadattr_t *attr, apr_thread_start_t func, void *data, apr_pool_t *pool) { apr_status_t stat; unsigned temp; HANDLE handle; (*new) = (apr_thread_t *)apr_palloc(pool, sizeof(apr_thread_t)); if ((*new) == NULL) { return APR_ENOMEM; } (*new)->pool = pool; (*new)->data = data; (*new)->func = func; (*new)->td = NULL; stat = apr_pool_create(&(*new)->pool, pool); if (stat != APR_SUCCESS) { return stat; } /* Use 0 for Thread Stack Size, because that will default the stack to the * same size as the calling thread. */ #ifndef _WIN32_WCE if ((handle = (HANDLE)_beginthreadex(NULL, attr && attr->stacksize > 0 ? attr->stacksize : 0, (unsigned int (APR_THREAD_FUNC *)(void *))dummy_worker, (*new), 0, &temp)) == 0) { return APR_FROM_OS_ERROR(_doserrno); } #else if ((handle = CreateThread(NULL, attr && attr->stacksize > 0 ? attr->stacksize : 0, (unsigned int (APR_THREAD_FUNC *)(void *))dummy_worker, (*new), 0, &temp)) == 0) { return apr_get_os_error(); } #endif if (attr && attr->detach) { CloseHandle(handle); } else (*new)->td = handle; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_thread_exit(apr_thread_t *thd, apr_status_t retval) { thd->exitval = retval; apr_pool_destroy(thd->pool); thd->pool = NULL; #ifndef _WIN32_WCE _endthreadex(0); #else ExitThread(0); #endif return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_thread_join(apr_status_t *retval, apr_thread_t *thd) { apr_status_t rv = APR_SUCCESS; if (!thd->td) { /* Can not join on detached threads */ return APR_DETACH; } rv = WaitForSingleObject(thd->td, INFINITE); if ( rv == WAIT_OBJECT_0 || rv == WAIT_ABANDONED) { /* If the thread_exit has been called */ if (!thd->pool) *retval = thd->exitval; else rv = APR_INCOMPLETE; } else rv = apr_get_os_error(); CloseHandle(thd->td); thd->td = NULL; return rv; } APR_DECLARE(apr_status_t) apr_thread_detach(apr_thread_t *thd) { if (thd->td && CloseHandle(thd->td)) { thd->td = NULL; return APR_SUCCESS; } else { return apr_get_os_error(); } } APR_DECLARE(void) apr_thread_yield() { /* SwitchToThread is not supported on Win9x, but since it's * primarily a noop (entering time consuming code, therefore * providing more critical threads a bit larger timeslice) * we won't worry too much if it's not available. */ #ifndef _WIN32_WCE if (apr_os_level >= APR_WIN_NT) { SwitchToThread(); } #endif } APR_DECLARE(apr_status_t) apr_thread_data_get(void **data, const char *key, apr_thread_t *thread) { return apr_pool_userdata_get(data, key, thread->pool); } APR_DECLARE(apr_status_t) apr_thread_data_set(void *data, const char *key, apr_status_t (*cleanup) (void *), apr_thread_t *thread) { return apr_pool_userdata_set(data, key, cleanup, thread->pool); } APR_DECLARE(apr_os_thread_t) apr_os_thread_current(void) { HANDLE hthread = (HANDLE)TlsGetValue(tls_apr_thread); HANDLE hproc; if (hthread) { return hthread; } hproc = GetCurrentProcess(); hthread = GetCurrentThread(); if (!DuplicateHandle(hproc, hthread, hproc, &hthread, 0, FALSE, DUPLICATE_SAME_ACCESS)) { return NULL; } TlsSetValue(tls_apr_thread, hthread); return hthread; } APR_DECLARE(apr_status_t) apr_os_thread_get(apr_os_thread_t **thethd, apr_thread_t *thd) { if (thd == NULL) { return APR_ENOTHREAD; } *thethd = thd->td; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_thread_put(apr_thread_t **thd, apr_os_thread_t *thethd, apr_pool_t *pool) { if (pool == NULL) { return APR_ENOPOOL; } if ((*thd) == NULL) { (*thd) = (apr_thread_t *)apr_palloc(pool, sizeof(apr_thread_t)); (*thd)->pool = pool; } (*thd)->td = thethd; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_thread_once_init(apr_thread_once_t **control, apr_pool_t *p) { (*control) = apr_pcalloc(p, sizeof(**control)); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_thread_once(apr_thread_once_t *control, void (*func)(void)) { if (!InterlockedExchange(&control->value, 1)) { func(); } return APR_SUCCESS; } APR_DECLARE(int) apr_os_thread_equal(apr_os_thread_t tid1, apr_os_thread_t tid2) { /* Since the only tid's we support our are own, and * apr_os_thread_current returns the identical handle * to the one we created initially, the test is simple. */ return (tid1 == tid2); } APR_POOL_IMPLEMENT_ACCESSOR(thread)
001-log4cxx
trunk/src/apr/threadproc/win32/thread.c
C
asf20
8,055
/* 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_threadproc.h" #include "apr_thread_proc.h" #include "apr_general.h" #include "apr_lib.h" #include "apr_errno.h" #include "apr_portable.h" APR_DECLARE(apr_status_t) apr_threadkey_private_create(apr_threadkey_t **key, void (*dest)(void *), apr_pool_t *pool) { (*key) = (apr_threadkey_t *)apr_palloc(pool, sizeof(apr_threadkey_t)); if ((*key) == NULL) { return APR_ENOMEM; } (*key)->pool = pool; if (((*key)->key = TlsAlloc()) != 0xFFFFFFFF) { return APR_SUCCESS; } return apr_get_os_error(); } APR_DECLARE(apr_status_t) apr_threadkey_private_get(void **new, apr_threadkey_t *key) { if ((*new) = TlsGetValue(key->key)) { return APR_SUCCESS; } return apr_get_os_error(); } APR_DECLARE(apr_status_t) apr_threadkey_private_set(void *priv, apr_threadkey_t *key) { if (TlsSetValue(key->key, priv)) { return APR_SUCCESS; } return apr_get_os_error(); } APR_DECLARE(apr_status_t) apr_threadkey_private_delete(apr_threadkey_t *key) { if (TlsFree(key->key)) { return APR_SUCCESS; } return apr_get_os_error(); } APR_DECLARE(apr_status_t) apr_threadkey_data_get(void **data, const char *key, apr_threadkey_t *threadkey) { return apr_pool_userdata_get(data, key, threadkey->pool); } APR_DECLARE(apr_status_t) apr_threadkey_data_set(void *data, const char *key, apr_status_t (*cleanup)(void *), apr_threadkey_t *threadkey) { return apr_pool_userdata_set(data, key, cleanup, threadkey->pool); } APR_DECLARE(apr_status_t) apr_os_threadkey_get(apr_os_threadkey_t *thekey, apr_threadkey_t *key) { *thekey = key->key; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_threadkey_put(apr_threadkey_t **key, apr_os_threadkey_t *thekey, apr_pool_t *pool) { if (pool == NULL) { return APR_ENOPOOL; } if ((*key) == NULL) { (*key) = (apr_threadkey_t *)apr_palloc(pool, sizeof(apr_threadkey_t)); (*key)->pool = pool; } (*key)->key = *thekey; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/threadproc/win32/threadpriv.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 "win32/apr_arch_threadproc.h" #include "win32/apr_arch_file_io.h" #include "apr_thread_proc.h" #include "apr_file_io.h" #include "apr_general.h" #if APR_HAVE_SIGNAL_H #include <signal.h> #endif #include <string.h> #if APR_HAVE_SYS_WAIT #include <sys/wait.h> #endif /* Windows only really support killing process, but that will do for now. * * ### Actually, closing the input handle to the proc should also do fine * for most console apps. This definately needs improvement... */ APR_DECLARE(apr_status_t) apr_proc_kill(apr_proc_t *proc, int signal) { if (proc->hproc != NULL) { if (TerminateProcess(proc->hproc, signal) == 0) { return apr_get_os_error(); } /* On unix, SIGKILL leaves a apr_proc_wait()able pid lying around, * so we will leave hproc alone until the app calls apr_proc_wait(). */ return APR_SUCCESS; } return APR_EPROC_UNKNOWN; } void apr_signal_init(apr_pool_t *pglobal) { } const char *apr_signal_description_get(int signum) { return "unknown signal (not supported)"; } APR_DECLARE(apr_status_t) apr_signal_block(int signum) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_signal_unblock(int signum) { return APR_ENOTIMPL; }
001-log4cxx
trunk/src/apr/threadproc/win32/signals.c
C
asf20
2,057
/* 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_threadproc.h" #include "apr_strings.h" struct send_pipe { int in; int out; int err; }; APR_DECLARE(apr_status_t) apr_procattr_create(apr_procattr_t **new, apr_pool_t *pool) { (*new) = (apr_procattr_t *)apr_palloc(pool, sizeof(apr_procattr_t)); if ((*new) == NULL) { return APR_ENOMEM; } (*new)->pool = pool; (*new)->parent_in = NULL; (*new)->child_in = NULL; (*new)->parent_out = NULL; (*new)->child_out = NULL; (*new)->parent_err = NULL; (*new)->child_err = NULL; (*new)->currdir = NULL; (*new)->cmdtype = APR_PROGRAM; (*new)->detached = 0; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_io_set(apr_procattr_t *attr, apr_int32_t in, apr_int32_t out, apr_int32_t err) { apr_status_t status; if (in != 0) { if ((status = apr_file_pipe_create(&attr->child_in, &attr->parent_in, attr->pool)) != APR_SUCCESS) { return status; } switch (in) { case APR_FULL_BLOCK: apr_file_pipe_timeout_set(attr->child_in, -1); apr_file_pipe_timeout_set(attr->parent_in, -1); break; case APR_PARENT_BLOCK: apr_file_pipe_timeout_set(attr->child_in, -1); break; case APR_CHILD_BLOCK: apr_file_pipe_timeout_set(attr->parent_in, -1); break; default: break; } } if (out) { if ((status = apr_file_pipe_create(&attr->parent_out, &attr->child_out, attr->pool)) != APR_SUCCESS) { return status; } switch (out) { case APR_FULL_BLOCK: apr_file_pipe_timeout_set(attr->child_out, -1); apr_file_pipe_timeout_set(attr->parent_out, -1); break; case APR_PARENT_BLOCK: apr_file_pipe_timeout_set(attr->child_out, -1); break; case APR_CHILD_BLOCK: apr_file_pipe_timeout_set(attr->parent_out, -1); break; default: break; } } if (err) { if ((status = apr_file_pipe_create(&attr->parent_err, &attr->child_err, attr->pool)) != APR_SUCCESS) { return status; } switch (err) { case APR_FULL_BLOCK: apr_file_pipe_timeout_set(attr->child_err, -1); apr_file_pipe_timeout_set(attr->parent_err, -1); break; case APR_PARENT_BLOCK: apr_file_pipe_timeout_set(attr->child_err, -1); break; case APR_CHILD_BLOCK: apr_file_pipe_timeout_set(attr->parent_err, -1); break; default: break; } } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_dir_set(apr_procattr_t *attr, const char *dir) { char * cwd; if (dir[0] != '/') { cwd = (char*)malloc(sizeof(char) * PATH_MAX); getcwd(cwd, PATH_MAX); attr->currdir = (char *)apr_pstrcat(attr->pool, cwd, "/", dir, NULL); free(cwd); } else { attr->currdir = (char *)apr_pstrdup(attr->pool, dir); } if (attr->currdir) { return APR_SUCCESS; } return APR_ENOMEM; } APR_DECLARE(apr_status_t) apr_procattr_cmdtype_set(apr_procattr_t *attr, apr_cmdtype_e cmd) { attr->cmdtype = cmd; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_detach_set(apr_procattr_t *attr, apr_int32_t detach) { attr->detached = detach; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_proc_fork(apr_proc_t *proc, apr_pool_t *pool) { int pid; if ((pid = fork()) < 0) { return errno; } else if (pid == 0) { /* This is really ugly... * The semantics of BeOS's fork() are that areas (used for shared * memory) get COW'd :-( The only way we can make shared memory * work across fork() is therefore to find any areas that have * been created and then clone them into our address space. * Thankfully only COW'd areas have the lock variable set at * anything but 0, so we can use that to find the areas we need to * copy. Of course what makes it even worse is that the loop through * the area's will go into an infinite loop, eating memory and then * eventually segfault unless we know when we reach then end of the * "original" areas and stop. Why? Well, we delete the area and then * add another to the end of the list... */ area_info ai; int32 cookie = 0; area_id highest = 0; while (get_next_area_info(0, &cookie, &ai) == B_OK) if (ai.area > highest) highest = ai.area; cookie = 0; while (get_next_area_info(0, &cookie, &ai) == B_OK) { if (ai.area > highest) break; if (ai.lock > 0) { area_id original = find_area(ai.name); delete_area(ai.area); clone_area(ai.name, &ai.address, B_CLONE_ADDRESS, ai.protection, original); } } proc->pid = pid; proc->in = NULL; proc->out = NULL; proc->err = NULL; return APR_INCHILD; } proc->pid = pid; proc->in = NULL; proc->out = NULL; proc->err = NULL; return APR_INPARENT; } APR_DECLARE(apr_status_t) apr_procattr_child_errfn_set(apr_procattr_t *attr, apr_child_errfn_t *errfn) { /* won't ever be called on this platform, so don't save the function pointer */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_error_check_set(apr_procattr_t *attr, apr_int32_t chk) { /* won't ever be used on this platform, so don't save the flag */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_addrspace_set(apr_procattr_t *attr, apr_int32_t addrspace) { /* won't ever be used on this platform, so don't save the flag */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_proc_create(apr_proc_t *new, const char *progname, const char * const *args, const char * const *env, apr_procattr_t *attr, apr_pool_t *pool) { int i=0,nargs=0; char **newargs = NULL; thread_id newproc, sender; struct send_pipe *sp; char * dir = NULL; sp = (struct send_pipe *)apr_palloc(pool, sizeof(struct send_pipe)); new->in = attr->parent_in; new->err = attr->parent_err; new->out = attr->parent_out; sp->in = attr->child_in ? attr->child_in->filedes : -1; sp->out = attr->child_out ? attr->child_out->filedes : -1; sp->err = attr->child_err ? attr->child_err->filedes : -1; i = 0; while (args && args[i]) { i++; } newargs = (char**)malloc(sizeof(char *) * (i + 4)); newargs[0] = strdup("/boot/home/config/bin/apr_proc_stub"); if (attr->currdir == NULL) { /* we require the directory , so use a temp. variable */ dir = malloc(sizeof(char) * PATH_MAX); getcwd(dir, PATH_MAX); newargs[1] = strdup(dir); free(dir); } else { newargs[1] = strdup(attr->currdir); } newargs[2] = strdup(progname); i=0;nargs = 3; while (args && args[i]) { newargs[nargs] = strdup(args[i]); i++;nargs++; } newargs[nargs] = NULL; /* ### we should be looking at attr->cmdtype in here... */ newproc = load_image(nargs, (const char**)newargs, (const char**)env); /* load_image copies the data so now we can free it... */ while (--nargs >= 0) free (newargs[nargs]); free(newargs); if (newproc < B_NO_ERROR) { return errno; } resume_thread(newproc); if (attr->child_in) { apr_file_close(attr->child_in); } if (attr->child_out) { apr_file_close(attr->child_out); } if (attr->child_err) { apr_file_close(attr->child_err); } send_data(newproc, 0, (void*)sp, sizeof(struct send_pipe)); new->pid = newproc; /* before we go charging on we need the new process to get to a * certain point. When it gets there it'll let us know and we * can carry on. */ receive_data(&sender, (void*)NULL,0); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_proc_wait_all_procs(apr_proc_t *proc, int *exitcode, apr_exit_why_e *exitwhy, apr_wait_how_e waithow, apr_pool_t *p) { proc->pid = -1; return apr_proc_wait(proc, exitcode, exitwhy, waithow); } APR_DECLARE(apr_status_t) apr_proc_wait(apr_proc_t *proc, int *exitcode, apr_exit_why_e *exitwhy, apr_wait_how_e waithow) { pid_t pstatus; int waitpid_options = WUNTRACED; int exit_int; int ignore; apr_exit_why_e ignorewhy; if (exitcode == NULL) { exitcode = &ignore; } if (exitwhy == NULL) { exitwhy = &ignorewhy; } if (waithow != APR_WAIT) { waitpid_options |= WNOHANG; } if ((pstatus = waitpid(proc->pid, &exit_int, waitpid_options)) > 0) { proc->pid = pstatus; if (WIFEXITED(exit_int)) { *exitwhy = APR_PROC_EXIT; *exitcode = WEXITSTATUS(exit_int); } else if (WIFSIGNALED(exit_int)) { *exitwhy = APR_PROC_SIGNAL; *exitcode = WTERMSIG(exit_int); } else { /* unexpected condition */ return APR_EGENERAL; } return APR_CHILD_DONE; } else if (pstatus == 0) { return APR_CHILD_NOTDONE; } return errno; } APR_DECLARE(apr_status_t) apr_procattr_child_in_set(apr_procattr_t *attr, apr_file_t *child_in, apr_file_t *parent_in) { if (attr->child_in == NULL && attr->parent_in == NULL) apr_file_pipe_create(&attr->child_in, &attr->parent_in, attr->pool); if (child_in != NULL) apr_file_dup(&attr->child_in, child_in, attr->pool); if (parent_in != NULL) apr_file_dup(&attr->parent_in, parent_in, attr->pool); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_child_out_set(apr_procattr_t *attr, apr_file_t *child_out, apr_file_t *parent_out) { if (attr->child_out == NULL && attr->parent_out == NULL) apr_file_pipe_create(&attr->child_out, &attr->parent_out, attr->pool); if (child_out != NULL) apr_file_dup(&attr->child_out, child_out, attr->pool); if (parent_out != NULL) apr_file_dup(&attr->parent_out, parent_out, attr->pool); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_child_err_set(apr_procattr_t *attr, apr_file_t *child_err, apr_file_t *parent_err) { if (attr->child_err == NULL && attr->parent_err == NULL) apr_file_pipe_create(&attr->child_err, &attr->parent_err, attr->pool); if (child_err != NULL) apr_file_dup(&attr->child_err, child_err, attr->pool); if (parent_err != NULL) apr_file_dup(&attr->parent_err, parent_err, attr->pool); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_limit_set(apr_procattr_t *attr, apr_int32_t what, void *limit) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_procattr_user_set(apr_procattr_t *attr, const char *username, const char *password) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_procattr_group_set(apr_procattr_t *attr, const char *groupname) { return APR_ENOTIMPL; }
001-log4cxx
trunk/src/apr/threadproc/beos/proc.c
C
asf20
13,326
/* 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. */ /* As the signal code is identical, use the unix version to reduce code duplication */ #include "../unix/signals.c" #include "../unix/procsup.c"
001-log4cxx
trunk/src/apr/threadproc/beos/threadproc_common.c
C
asf20
952
/* 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 <kernel/OS.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> struct pipefd { int in; int out; int err; }; int main(int argc, char *argv[]) { /* we expect the following... * * argv[0] = this stub * argv[1] = directory to run in... * argv[2] = progname to execute * rest of arguments to be passed to program */ char *progname = argv[2]; char *directory = argv[1]; struct pipefd *pfd; thread_id sender; void *buffer; char ** newargs; int i = 0; newargs = (char**)malloc(sizeof(char*) * (argc - 1)); buffer = (void*)malloc(sizeof(struct pipefd)); /* this will block until we get the data */ receive_data(&sender, buffer, sizeof(struct pipefd)); pfd = (struct pipefd*)buffer; if (pfd->in > STDERR_FILENO) { if (dup2(pfd->in, STDIN_FILENO) != STDIN_FILENO) return (-1); close (pfd->in); } if (pfd->out > STDERR_FILENO) { if (dup2(pfd->out, STDOUT_FILENO) != STDOUT_FILENO) return (-1); close (pfd->out); } if (pfd->err > STDERR_FILENO) { if (dup2(pfd->err, STDERR_FILENO) != STDERR_FILENO) return (-1); close (pfd->err); } for (i=3;i<=argc;i++){ newargs[i-3] = argv[i]; } /* tell the caller we're OK to start */ send_data(sender,1,NULL,0); if (directory != NULL) chdir(directory); execve (progname, newargs, environ); return (-1); }
001-log4cxx
trunk/src/apr/threadproc/beos/apr_proc_stub.c
C
asf20
2,125
/* 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_threadproc.h" #include "apr_portable.h" APR_DECLARE(apr_status_t) apr_threadattr_create(apr_threadattr_t **new, apr_pool_t *pool) { (*new) = (apr_threadattr_t *)apr_palloc(pool, sizeof(apr_threadattr_t)); if ((*new) == NULL) { return APR_ENOMEM; } (*new)->pool = pool; (*new)->attr = (int32)B_NORMAL_PRIORITY; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_threadattr_detach_set(apr_threadattr_t *attr, apr_int32_t on) { if (on == 1){ attr->detached = 1; } else { attr->detached = 0; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_threadattr_detach_get(apr_threadattr_t *attr) { if (attr->detached == 1){ return APR_DETACH; } return APR_NOTDETACH; } APR_DECLARE(apr_status_t) apr_threadattr_stacksize_set(apr_threadattr_t *attr, apr_size_t stacksize) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_threadattr_guardsize_set(apr_threadattr_t *attr, apr_size_t size) { return APR_ENOTIMPL; } static void *dummy_worker(void *opaque) { apr_thread_t *thd = (apr_thread_t*)opaque; return thd->func(thd, thd->data); } APR_DECLARE(apr_status_t) apr_thread_create(apr_thread_t **new, apr_threadattr_t *attr, apr_thread_start_t func, void *data, apr_pool_t *pool) { int32 temp; apr_status_t stat; (*new) = (apr_thread_t *)apr_palloc(pool, sizeof(apr_thread_t)); if ((*new) == NULL) { return APR_ENOMEM; } (*new)->pool = pool; (*new)->data = data; (*new)->func = func; (*new)->exitval = -1; /* First we create the new thread...*/ if (attr) temp = attr->attr; else temp = B_NORMAL_PRIORITY; stat = apr_pool_create(&(*new)->pool, pool); if (stat != APR_SUCCESS) { return stat; } (*new)->td = spawn_thread((thread_func)dummy_worker, "apr thread", temp, (*new)); /* Now we try to run it...*/ if (resume_thread((*new)->td) == B_NO_ERROR) { return APR_SUCCESS; } else { return errno; } } APR_DECLARE(apr_os_thread_t) apr_os_thread_current(void) { return find_thread(NULL); } int apr_os_thread_equal(apr_os_thread_t tid1, apr_os_thread_t tid2) { return tid1 == tid2; } APR_DECLARE(apr_status_t) apr_thread_exit(apr_thread_t *thd, apr_status_t retval) { apr_pool_destroy(thd->pool); thd->exitval = retval; exit_thread ((status_t)(retval)); /* This will never be reached... */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_thread_join(apr_status_t *retval, apr_thread_t *thd) { status_t rv = 0, ret; ret = wait_for_thread(thd->td, &rv); if (ret == B_NO_ERROR) { *retval = rv; return APR_SUCCESS; } else { /* if we've missed the thread's death, did we set an exit value prior * to it's demise? If we did return that. */ if (thd->exitval != -1) { *retval = thd->exitval; return APR_SUCCESS; } else return ret; } } APR_DECLARE(apr_status_t) apr_thread_detach(apr_thread_t *thd) { if (suspend_thread(thd->td) == B_NO_ERROR){ return APR_SUCCESS; } else { return errno; } } void apr_thread_yield() { } APR_DECLARE(apr_status_t) apr_thread_data_get(void **data, const char *key, apr_thread_t *thread) { return apr_pool_userdata_get(data, key, thread->pool); } APR_DECLARE(apr_status_t) apr_thread_data_set(void *data, const char *key, apr_status_t (*cleanup) (void *), apr_thread_t *thread) { return apr_pool_userdata_set(data, key, cleanup, thread->pool); } APR_DECLARE(apr_status_t) apr_os_thread_get(apr_os_thread_t **thethd, apr_thread_t *thd) { *thethd = &thd->td; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_thread_put(apr_thread_t **thd, apr_os_thread_t *thethd, apr_pool_t *pool) { if (pool == NULL) { return APR_ENOPOOL; } if ((*thd) == NULL) { (*thd) = (apr_thread_t *)apr_pcalloc(pool, sizeof(apr_thread_t)); (*thd)->pool = pool; } (*thd)->td = *thethd; return APR_SUCCESS; } static apr_status_t thread_once_cleanup(void *vcontrol) { apr_thread_once_t *control = (apr_thread_once_t *)vcontrol; if (control->sem) { release_sem(control->sem); delete_sem(control->sem); } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_thread_once_init(apr_thread_once_t **control, apr_pool_t *p) { int rc; *control = (apr_thread_once_t *)apr_pcalloc(p, sizeof(apr_thread_once_t)); (*control)->hit = 0; /* we haven't done it yet... */ rc = ((*control)->sem = create_sem(1, "thread_once")); if (rc < 0) return rc; apr_pool_cleanup_register(p, control, thread_once_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_thread_once(apr_thread_once_t *control, void (*func)(void)) { if (!control->hit) { if (acquire_sem(control->sem) == B_OK) { control->hit = 1; func(); } } return APR_SUCCESS; } APR_POOL_IMPLEMENT_ACCESSOR(thread)
001-log4cxx
trunk/src/apr/threadproc/beos/thread.c
C
asf20
6,403
/* 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_threadproc.h" static struct beos_key key_table[BEOS_MAX_DATAKEYS]; static struct beos_private_data *beos_data[BEOS_MAX_DATAKEYS]; static sem_id lock; APR_DECLARE(apr_status_t) apr_threadkey_private_create(apr_threadkey_t **key, void (*dest)(void *), apr_pool_t *pool) { (*key) = (apr_threadkey_t *)apr_palloc(pool, sizeof(apr_threadkey_t)); if ((*key) == NULL) { return APR_ENOMEM; } (*key)->pool = pool; acquire_sem(lock); for ((*key)->key=0; (*key)->key < BEOS_MAX_DATAKEYS; (*key)->key++){ if (key_table[(*key)->key].assigned == 0){ key_table[(*key)->key].assigned = 1; key_table[(*key)->key].destructor = dest; release_sem(lock); return APR_SUCCESS; } } release_sem(lock); return APR_ENOMEM; } APR_DECLARE(apr_status_t) apr_threadkey_private_get(void **new, apr_threadkey_t *key) { thread_id tid; int i, index=0; tid = find_thread(NULL); for (i=0;i<BEOS_MAX_DATAKEYS;i++){ if (beos_data[i]->data){ /* it's been used */ if (beos_data[i]->td == tid){ index = i; } } } if (index == 0){ /* no storage for thread so we can't get anything... */ return APR_ENOMEM; } if ((key->key < BEOS_MAX_DATAKEYS) && (key_table)){ acquire_sem(key_table[key->key].lock); if (key_table[key->key].count){ (*new) = (void*)beos_data[index]->data[key->key]; } else { (*new) = NULL; } release_sem(key_table[key->key].lock); } else { (*new) = NULL; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_threadkey_private_set(void *priv, apr_threadkey_t *key) { thread_id tid; int i,index = 0, ret = 0; tid = find_thread(NULL); for (i=0; i < BEOS_MAX_DATAKEYS; i++){ if (beos_data[i]->data){ if (beos_data[i]->td == tid){index = i;} } } if (index==0){ /* not yet been allocated */ for (i=0; i< BEOS_MAX_DATAKEYS; i++){ if (! beos_data[i]->data){ /* we'll take this one... */ index = i; beos_data[i]->data = (const void **)malloc(sizeof(void *) * BEOS_MAX_DATAKEYS); memset((void *)beos_data[i]->data, 0, sizeof(void *) * BEOS_MAX_DATAKEYS); beos_data[i]->count = (int)malloc(sizeof(int)); beos_data[i]->td = (thread_id)malloc(sizeof(thread_id)); beos_data[i]->td = tid; } } } if (index == 0){ /* we're out of luck.. */ return APR_ENOMEM; } if ((key->key < BEOS_MAX_DATAKEYS) && (key_table)){ acquire_sem(key_table[key->key].lock); if (key_table[key->key].count){ if (beos_data[index]->data[key->key] == NULL){ if (priv != NULL){ beos_data[index]->count++; key_table[key->key].count++; } } else { if (priv == NULL){ beos_data[index]->count--; key_table[key->key].count--; } } beos_data[index]->data[key->key] = priv; ret = 1; } else { ret = 0; } release_sem(key_table[key->key].lock); } if (ret) return APR_SUCCESS; return APR_ENOMEM; } APR_DECLARE(apr_status_t) apr_threadkey_private_delete(apr_threadkey_t *key) { if (key->key < BEOS_MAX_DATAKEYS){ acquire_sem(key_table[key->key].lock); if (key_table[key->key].count == 1){ key_table[key->key].destructor = NULL; key_table[key->key].count = 0; } release_sem(key_table[key->key].lock); } else { return APR_ENOMEM; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_threadkey_data_get(void **data, const char *key, apr_threadkey_t *threadkey) { return apr_pool_userdata_get(data, key, threadkey->pool); } APR_DECLARE(apr_status_t) apr_threadkey_data_set(void *data, const char *key, apr_status_t (*cleanup) (void *), apr_threadkey_t *threadkey) { return apr_pool_userdata_set(data, key, cleanup, threadkey->pool); } APR_DECLARE(apr_status_t) apr_os_threadkey_get(apr_os_threadkey_t *thekey, apr_threadkey_t *key) { *thekey = key->key; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_threadkey_put(apr_threadkey_t **key, apr_os_threadkey_t *thekey, apr_pool_t *pool) { if (pool == NULL) { return APR_ENOPOOL; } if ((*key) == NULL) { (*key) = (apr_threadkey_t *)apr_pcalloc(pool, sizeof(apr_threadkey_t)); (*key)->pool = pool; } (*key)->key = *thekey; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/threadproc/beos/threadpriv.c
C
asf20
5,200
/* 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_threadproc.h" #include "apr_strings.h" #include "apr_portable.h" #include "apr_signal.h" #include "apr_random.h" APR_DECLARE(apr_status_t) apr_procattr_create(apr_procattr_t **new, apr_pool_t *pool) { (*new) = (apr_procattr_t *)apr_pcalloc(pool, sizeof(apr_procattr_t)); if ((*new) == NULL) { return APR_ENOMEM; } (*new)->pool = pool; (*new)->cmdtype = APR_PROGRAM; (*new)->uid = (*new)->gid = -1; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_io_set(apr_procattr_t *attr, apr_int32_t in, apr_int32_t out, apr_int32_t err) { apr_status_t status; if (in != 0) { if ((status = apr_file_pipe_create(&attr->child_in, &attr->parent_in, attr->pool)) != APR_SUCCESS) { return status; } switch (in) { case APR_FULL_BLOCK: break; case APR_PARENT_BLOCK: apr_file_pipe_timeout_set(attr->child_in, 0); break; case APR_CHILD_BLOCK: apr_file_pipe_timeout_set(attr->parent_in, 0); break; default: apr_file_pipe_timeout_set(attr->child_in, 0); apr_file_pipe_timeout_set(attr->parent_in, 0); } } if (out) { if ((status = apr_file_pipe_create(&attr->parent_out, &attr->child_out, attr->pool)) != APR_SUCCESS) { return status; } switch (out) { case APR_FULL_BLOCK: break; case APR_PARENT_BLOCK: apr_file_pipe_timeout_set(attr->child_out, 0); break; case APR_CHILD_BLOCK: apr_file_pipe_timeout_set(attr->parent_out, 0); break; default: apr_file_pipe_timeout_set(attr->child_out, 0); apr_file_pipe_timeout_set(attr->parent_out, 0); } } if (err) { if ((status = apr_file_pipe_create(&attr->parent_err, &attr->child_err, attr->pool)) != APR_SUCCESS) { return status; } switch (err) { case APR_FULL_BLOCK: break; case APR_PARENT_BLOCK: apr_file_pipe_timeout_set(attr->child_err, 0); break; case APR_CHILD_BLOCK: apr_file_pipe_timeout_set(attr->parent_err, 0); break; default: apr_file_pipe_timeout_set(attr->child_err, 0); apr_file_pipe_timeout_set(attr->parent_err, 0); } } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_child_in_set(apr_procattr_t *attr, apr_file_t *child_in, apr_file_t *parent_in) { apr_status_t rv = APR_SUCCESS; if (attr->child_in == NULL && attr->parent_in == NULL) rv = apr_file_pipe_create(&attr->child_in, &attr->parent_in, attr->pool); if (child_in != NULL && rv == APR_SUCCESS) rv = apr_file_dup2(attr->child_in, child_in, attr->pool); if (parent_in != NULL && rv == APR_SUCCESS) rv = apr_file_dup2(attr->parent_in, parent_in, attr->pool); return rv; } APR_DECLARE(apr_status_t) apr_procattr_child_out_set(apr_procattr_t *attr, apr_file_t *child_out, apr_file_t *parent_out) { apr_status_t rv = APR_SUCCESS; if (attr->child_out == NULL && attr->parent_out == NULL) rv = apr_file_pipe_create(&attr->child_out, &attr->parent_out, attr->pool); if (child_out != NULL && rv == APR_SUCCESS) rv = apr_file_dup2(attr->child_out, child_out, attr->pool); if (parent_out != NULL && rv == APR_SUCCESS) rv = apr_file_dup2(attr->parent_out, parent_out, attr->pool); return rv; } APR_DECLARE(apr_status_t) apr_procattr_child_err_set(apr_procattr_t *attr, apr_file_t *child_err, apr_file_t *parent_err) { apr_status_t rv = APR_SUCCESS; if (attr->child_err == NULL && attr->parent_err == NULL) rv = apr_file_pipe_create(&attr->child_err, &attr->parent_err, attr->pool); if (child_err != NULL && rv == APR_SUCCESS) rv = apr_file_dup2(attr->child_err, child_err, attr->pool); if (parent_err != NULL && rv == APR_SUCCESS) rv = apr_file_dup2(attr->parent_err, parent_err, attr->pool); return rv; } APR_DECLARE(apr_status_t) apr_procattr_dir_set(apr_procattr_t *attr, const char *dir) { attr->currdir = apr_pstrdup(attr->pool, dir); if (attr->currdir) { return APR_SUCCESS; } return APR_ENOMEM; } APR_DECLARE(apr_status_t) apr_procattr_cmdtype_set(apr_procattr_t *attr, apr_cmdtype_e cmd) { attr->cmdtype = cmd; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_detach_set(apr_procattr_t *attr, apr_int32_t detach) { attr->detached = detach; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_proc_fork(apr_proc_t *proc, apr_pool_t *pool) { int pid; if ((pid = fork()) < 0) { return errno; } else if (pid == 0) { proc->pid = pid; proc->in = NULL; proc->out = NULL; proc->err = NULL; apr_random_after_fork(proc); return APR_INCHILD; } proc->pid = pid; proc->in = NULL; proc->out = NULL; proc->err = NULL; return APR_INPARENT; } static apr_status_t limit_proc(apr_procattr_t *attr) { #if APR_HAVE_STRUCT_RLIMIT && APR_HAVE_SETRLIMIT #ifdef RLIMIT_CPU if (attr->limit_cpu != NULL) { if ((setrlimit(RLIMIT_CPU, attr->limit_cpu)) != 0) { return errno; } } #endif #ifdef RLIMIT_NPROC if (attr->limit_nproc != NULL) { if ((setrlimit(RLIMIT_NPROC, attr->limit_nproc)) != 0) { return errno; } } #endif #ifdef RLIMIT_NOFILE if (attr->limit_nofile != NULL) { if ((setrlimit(RLIMIT_NOFILE, attr->limit_nofile)) != 0) { return errno; } } #endif #if defined(RLIMIT_AS) if (attr->limit_mem != NULL) { if ((setrlimit(RLIMIT_AS, attr->limit_mem)) != 0) { return errno; } } #elif defined(RLIMIT_DATA) if (attr->limit_mem != NULL) { if ((setrlimit(RLIMIT_DATA, attr->limit_mem)) != 0) { return errno; } } #elif defined(RLIMIT_VMEM) if (attr->limit_mem != NULL) { if ((setrlimit(RLIMIT_VMEM, attr->limit_mem)) != 0) { return errno; } } #endif #else /* * Maybe make a note in error_log that setrlimit isn't supported?? */ #endif return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_child_errfn_set(apr_procattr_t *attr, apr_child_errfn_t *errfn) { attr->errfn = errfn; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_error_check_set(apr_procattr_t *attr, apr_int32_t chk) { attr->errchk = chk; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_addrspace_set(apr_procattr_t *attr, apr_int32_t addrspace) { /* won't ever be used on this platform, so don't save the flag */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_user_set(apr_procattr_t *attr, const char *username, const char *password) { apr_status_t rv; apr_gid_t gid; if ((rv = apr_uid_get(&attr->uid, &gid, username, attr->pool)) != APR_SUCCESS) { attr->uid = -1; return rv; } /* Use default user group if not already set */ if (attr->gid == -1) { attr->gid = gid; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_group_set(apr_procattr_t *attr, const char *groupname) { apr_status_t rv; if ((rv = apr_gid_get(&attr->gid, groupname, attr->pool)) != APR_SUCCESS) attr->gid = -1; return rv; } APR_DECLARE(apr_status_t) apr_proc_create(apr_proc_t *new, const char *progname, const char * const *args, const char * const *env, apr_procattr_t *attr, apr_pool_t *pool) { int i; const char * const empty_envp[] = {NULL}; if (!env) { /* Specs require an empty array instead of NULL; * Purify will trigger a failure, even if many * implementations don't. */ env = empty_envp; } new->in = attr->parent_in; new->err = attr->parent_err; new->out = attr->parent_out; if (attr->errchk) { if (attr->currdir) { if (access(attr->currdir, X_OK) == -1) { /* chdir() in child wouldn't have worked */ return errno; } } if (attr->cmdtype == APR_PROGRAM || attr->cmdtype == APR_PROGRAM_ENV || *progname == '/') { /* for both of these values of cmdtype, caller must pass * full path, so it is easy to check; * caller can choose to pass full path for other * values of cmdtype */ if (access(progname, R_OK|X_OK) == -1) { /* exec*() in child wouldn't have worked */ return errno; } } else { /* todo: search PATH for progname then try to access it */ } } if ((new->pid = fork()) < 0) { return errno; } else if (new->pid == 0) { int status; /* child process */ /* * If we do exec cleanup before the dup2() calls to set up pipes * on 0-2, we accidentally close the pipes used by programs like * mod_cgid. * * If we do exec cleanup after the dup2() calls, cleanup can accidentally * close our pipes which replaced any files which previously had * descriptors 0-2. * * The solution is to kill the cleanup for the pipes, then do * exec cleanup, then do the dup2() calls. */ if (attr->child_in) { apr_pool_cleanup_kill(apr_file_pool_get(attr->child_in), attr->child_in, apr_unix_file_cleanup); } if (attr->child_out) { apr_pool_cleanup_kill(apr_file_pool_get(attr->child_out), attr->child_out, apr_unix_file_cleanup); } if (attr->child_err) { apr_pool_cleanup_kill(apr_file_pool_get(attr->child_err), attr->child_err, apr_unix_file_cleanup); } apr_pool_cleanup_for_exec(); if (attr->child_in) { apr_file_close(attr->parent_in); dup2(attr->child_in->filedes, STDIN_FILENO); apr_file_close(attr->child_in); } if (attr->child_out) { apr_file_close(attr->parent_out); dup2(attr->child_out->filedes, STDOUT_FILENO); apr_file_close(attr->child_out); } if (attr->child_err) { apr_file_close(attr->parent_err); dup2(attr->child_err->filedes, STDERR_FILENO); apr_file_close(attr->child_err); } apr_signal(SIGCHLD, SIG_DFL); /* not sure if this is needed or not */ if (attr->currdir != NULL) { if (chdir(attr->currdir) == -1) { if (attr->errfn) { attr->errfn(pool, errno, "change of working directory failed"); } exit(-1); /* We have big problems, the child should exit. */ } } /* Only try to switch if we are running as root */ if (attr->gid != -1 && !geteuid()) { if ((status = setgid(attr->gid))) { if (attr->errfn) { attr->errfn(pool, errno, "setting of group failed"); } exit(-1); /* We have big problems, the child should exit. */ } } if (attr->uid != -1 && !geteuid()) { if ((status = setuid(attr->uid))) { if (attr->errfn) { attr->errfn(pool, errno, "setting of user failed"); } exit(-1); /* We have big problems, the child should exit. */ } } if ((status = limit_proc(attr)) != APR_SUCCESS) { if (attr->errfn) { attr->errfn(pool, errno, "setting of resource limits failed"); } exit(-1); /* We have big problems, the child should exit. */ } if (attr->cmdtype == APR_SHELLCMD || attr->cmdtype == APR_SHELLCMD_ENV) { int onearg_len = 0; const char *newargs[4]; newargs[0] = SHELL_PATH; newargs[1] = "-c"; i = 0; while (args[i]) { onearg_len += strlen(args[i]); onearg_len++; /* for space delimiter */ i++; } switch(i) { case 0: /* bad parameters; we're doomed */ break; case 1: /* no args, or caller already built a single string from * progname and args */ newargs[2] = args[0]; break; default: { char *ch, *onearg; ch = onearg = apr_palloc(pool, onearg_len); i = 0; while (args[i]) { size_t len = strlen(args[i]); memcpy(ch, args[i], len); ch += len; *ch = ' '; ++ch; ++i; } --ch; /* back up to trailing blank */ *ch = '\0'; newargs[2] = onearg; } } newargs[3] = NULL; if (attr->detached) { apr_proc_detach(APR_PROC_DETACH_DAEMONIZE); } if (attr->cmdtype == APR_SHELLCMD) { execve(SHELL_PATH, (char * const *) newargs, (char * const *)env); } else { execv(SHELL_PATH, (char * const *)newargs); } } else if (attr->cmdtype == APR_PROGRAM) { if (attr->detached) { apr_proc_detach(APR_PROC_DETACH_DAEMONIZE); } execve(progname, (char * const *)args, (char * const *)env); } else if (attr->cmdtype == APR_PROGRAM_ENV) { if (attr->detached) { apr_proc_detach(APR_PROC_DETACH_DAEMONIZE); } execv(progname, (char * const *)args); } else { /* APR_PROGRAM_PATH */ if (attr->detached) { apr_proc_detach(APR_PROC_DETACH_DAEMONIZE); } execvp(progname, (char * const *)args); } if (attr->errfn) { char *desc; desc = apr_psprintf(pool, "exec of '%s' failed", progname); attr->errfn(pool, errno, desc); } exit(-1); /* if we get here, there is a problem, so exit with an * error code. */ } /* Parent process */ if (attr->child_in) { apr_file_close(attr->child_in); } if (attr->child_out) { apr_file_close(attr->child_out); } if (attr->child_err) { apr_file_close(attr->child_err); } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_proc_wait_all_procs(apr_proc_t *proc, int *exitcode, apr_exit_why_e *exitwhy, apr_wait_how_e waithow, apr_pool_t *p) { proc->pid = -1; return apr_proc_wait(proc, exitcode, exitwhy, waithow); } APR_DECLARE(apr_status_t) apr_proc_wait(apr_proc_t *proc, int *exitcode, apr_exit_why_e *exitwhy, apr_wait_how_e waithow) { pid_t pstatus; int waitpid_options = WUNTRACED; int exit_int; int ignore; apr_exit_why_e ignorewhy; if (exitcode == NULL) { exitcode = &ignore; } if (exitwhy == NULL) { exitwhy = &ignorewhy; } if (waithow != APR_WAIT) { waitpid_options |= WNOHANG; } do { pstatus = waitpid(proc->pid, &exit_int, waitpid_options); } while (pstatus < 0 && errno == EINTR); if (pstatus > 0) { proc->pid = pstatus; if (WIFEXITED(exit_int)) { *exitwhy = APR_PROC_EXIT; *exitcode = WEXITSTATUS(exit_int); } else if (WIFSIGNALED(exit_int)) { *exitwhy = APR_PROC_SIGNAL; #ifdef WCOREDUMP if (WCOREDUMP(exit_int)) { *exitwhy |= APR_PROC_SIGNAL_CORE; } #endif *exitcode = WTERMSIG(exit_int); } else { /* unexpected condition */ return APR_EGENERAL; } return APR_CHILD_DONE; } else if (pstatus == 0) { return APR_CHILD_NOTDONE; } return errno; } APR_DECLARE(apr_status_t) apr_procattr_limit_set(apr_procattr_t *attr, apr_int32_t what, struct rlimit *limit) { switch(what) { case APR_LIMIT_CPU: #ifdef RLIMIT_CPU attr->limit_cpu = limit; break; #else return APR_ENOTIMPL; #endif case APR_LIMIT_MEM: #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS) attr->limit_mem = limit; break; #else return APR_ENOTIMPL; #endif case APR_LIMIT_NPROC: #ifdef RLIMIT_NPROC attr->limit_nproc = limit; break; #else return APR_ENOTIMPL; #endif case APR_LIMIT_NOFILE: #ifdef RLIMIT_NOFILE attr->limit_nofile = limit; break; #else return APR_ENOTIMPL; #endif } return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/threadproc/unix/proc.c
C
asf20
19,954
/* 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_portable.h" #include "apr_arch_threadproc.h" #if APR_HAS_THREADS #if APR_HAVE_PTHREAD_H /* Destroy the threadattr object */ static apr_status_t threadattr_cleanup(void *data) { apr_threadattr_t *attr = data; apr_status_t rv; rv = pthread_attr_destroy(&attr->attr); #ifdef PTHREAD_SETS_ERRNO if (rv) { rv = errno; } #endif return rv; } APR_DECLARE(apr_status_t) apr_threadattr_create(apr_threadattr_t **new, apr_pool_t *pool) { apr_status_t stat; (*new) = apr_palloc(pool, sizeof(apr_threadattr_t)); (*new)->pool = pool; stat = pthread_attr_init(&(*new)->attr); if (stat == 0) { apr_pool_cleanup_register(pool, *new, threadattr_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } #ifdef PTHREAD_SETS_ERRNO stat = errno; #endif return stat; } #define DETACH_ARG(v) ((v) ? PTHREAD_CREATE_DETACHED : PTHREAD_CREATE_JOINABLE) APR_DECLARE(apr_status_t) apr_threadattr_detach_set(apr_threadattr_t *attr, apr_int32_t on) { apr_status_t stat; #ifdef PTHREAD_ATTR_SETDETACHSTATE_ARG2_ADDR int arg = DETACH_ARG(v); if ((stat = pthread_attr_setdetachstate(&attr->attr, &arg)) == 0) { #else if ((stat = pthread_attr_setdetachstate(&attr->attr, DETACH_ARG(on))) == 0) { #endif return APR_SUCCESS; } else { #ifdef PTHREAD_SETS_ERRNO stat = errno; #endif return stat; } } APR_DECLARE(apr_status_t) apr_threadattr_detach_get(apr_threadattr_t *attr) { int state; #ifdef PTHREAD_ATTR_GETDETACHSTATE_TAKES_ONE_ARG state = pthread_attr_getdetachstate(&attr->attr); #else pthread_attr_getdetachstate(&attr->attr, &state); #endif if (state == 1) return APR_DETACH; return APR_NOTDETACH; } APR_DECLARE(apr_status_t) apr_threadattr_stacksize_set(apr_threadattr_t *attr, apr_size_t stacksize) { int stat; stat = pthread_attr_setstacksize(&attr->attr, stacksize); if (stat == 0) { return APR_SUCCESS; } #ifdef PTHREAD_SETS_ERRNO stat = errno; #endif return stat; } APR_DECLARE(apr_status_t) apr_threadattr_guardsize_set(apr_threadattr_t *attr, apr_size_t size) { #ifdef HAVE_PTHREAD_ATTR_SETGUARDSIZE apr_status_t rv; rv = pthread_attr_setguardsize(&attr->attr, size); if (rv == 0) { return APR_SUCCESS; } #ifdef PTHREAD_SETS_ERRNO rv = errno; #endif return rv; #else return APR_ENOTIMPL; #endif } static void *dummy_worker(void *opaque) { apr_thread_t *thread = (apr_thread_t*)opaque; return thread->func(thread, thread->data); } APR_DECLARE(apr_status_t) apr_thread_create(apr_thread_t **new, apr_threadattr_t *attr, apr_thread_start_t func, void *data, apr_pool_t *pool) { apr_status_t stat; pthread_attr_t *temp; (*new) = (apr_thread_t *)apr_pcalloc(pool, sizeof(apr_thread_t)); if ((*new) == NULL) { return APR_ENOMEM; } (*new)->td = (pthread_t *)apr_pcalloc(pool, sizeof(pthread_t)); if ((*new)->td == NULL) { return APR_ENOMEM; } (*new)->pool = pool; (*new)->data = data; (*new)->func = func; if (attr) temp = &attr->attr; else temp = NULL; stat = apr_pool_create(&(*new)->pool, pool); if (stat != APR_SUCCESS) { return stat; } if ((stat = pthread_create((*new)->td, temp, dummy_worker, (*new))) == 0) { return APR_SUCCESS; } else { #ifdef PTHREAD_SETS_ERRNO stat = errno; #endif return stat; } } APR_DECLARE(apr_os_thread_t) apr_os_thread_current(void) { return pthread_self(); } APR_DECLARE(int) apr_os_thread_equal(apr_os_thread_t tid1, apr_os_thread_t tid2) { return pthread_equal(tid1, tid2); } APR_DECLARE(apr_status_t) apr_thread_exit(apr_thread_t *thd, apr_status_t retval) { thd->exitval = retval; apr_pool_destroy(thd->pool); pthread_exit(NULL); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_thread_join(apr_status_t *retval, apr_thread_t *thd) { apr_status_t stat; apr_status_t *thread_stat; if ((stat = pthread_join(*thd->td,(void *)&thread_stat)) == 0) { *retval = thd->exitval; return APR_SUCCESS; } else { #ifdef PTHREAD_SETS_ERRNO stat = errno; #endif return stat; } } APR_DECLARE(apr_status_t) apr_thread_detach(apr_thread_t *thd) { apr_status_t stat; #ifdef PTHREAD_DETACH_ARG1_ADDR if ((stat = pthread_detach(thd->td)) == 0) { #else if ((stat = pthread_detach(*thd->td)) == 0) { #endif return APR_SUCCESS; } else { #ifdef PTHREAD_SETS_ERRNO stat = errno; #endif return stat; } } void apr_thread_yield() { } APR_DECLARE(apr_status_t) apr_thread_data_get(void **data, const char *key, apr_thread_t *thread) { return apr_pool_userdata_get(data, key, thread->pool); } APR_DECLARE(apr_status_t) apr_thread_data_set(void *data, const char *key, apr_status_t (*cleanup)(void *), apr_thread_t *thread) { return apr_pool_userdata_set(data, key, cleanup, thread->pool); } APR_DECLARE(apr_status_t) apr_os_thread_get(apr_os_thread_t **thethd, apr_thread_t *thd) { *thethd = thd->td; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_thread_put(apr_thread_t **thd, apr_os_thread_t *thethd, apr_pool_t *pool) { if (pool == NULL) { return APR_ENOPOOL; } if ((*thd) == NULL) { (*thd) = (apr_thread_t *)apr_pcalloc(pool, sizeof(apr_thread_t)); (*thd)->pool = pool; } (*thd)->td = thethd; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_thread_once_init(apr_thread_once_t **control, apr_pool_t *p) { static const pthread_once_t once_init = PTHREAD_ONCE_INIT; *control = apr_palloc(p, sizeof(**control)); (*control)->once = once_init; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_thread_once(apr_thread_once_t *control, void (*func)(void)) { return pthread_once(&control->once, func); } APR_POOL_IMPLEMENT_ACCESSOR(thread) #endif /* HAVE_PTHREAD_H */ #endif /* APR_HAS_THREADS */ #if !APR_HAS_THREADS /* avoid warning for no prototype */ APR_DECLARE(apr_status_t) apr_os_thread_get(void); APR_DECLARE(apr_status_t) apr_os_thread_get(void) { return APR_ENOTIMPL; } #endif
001-log4cxx
trunk/src/apr/threadproc/unix/thread.c
C
asf20
7,975
/* 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_portable.h" #include "apr_arch_threadproc.h" #if APR_HAS_THREADS #if APR_HAVE_PTHREAD_H APR_DECLARE(apr_status_t) apr_threadkey_private_create(apr_threadkey_t **key, void (*dest)(void *), apr_pool_t *pool) { (*key) = (apr_threadkey_t *)apr_pcalloc(pool, sizeof(apr_threadkey_t)); if ((*key) == NULL) { return APR_ENOMEM; } (*key)->pool = pool; return pthread_key_create(&(*key)->key, dest); } APR_DECLARE(apr_status_t) apr_threadkey_private_get(void **new, apr_threadkey_t *key) { #ifdef PTHREAD_GETSPECIFIC_TAKES_TWO_ARGS if (pthread_getspecific(key->key,new)) *new = NULL; #else (*new) = pthread_getspecific(key->key); #endif return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_threadkey_private_set(void *priv, apr_threadkey_t *key) { apr_status_t stat; if ((stat = pthread_setspecific(key->key, priv)) == 0) { return APR_SUCCESS; } else { return stat; } } APR_DECLARE(apr_status_t) apr_threadkey_private_delete(apr_threadkey_t *key) { #ifdef HAVE_PTHREAD_KEY_DELETE apr_status_t stat; if ((stat = pthread_key_delete(key->key)) == 0) { return APR_SUCCESS; } return stat; #else return APR_ENOTIMPL; #endif } APR_DECLARE(apr_status_t) apr_threadkey_data_get(void **data, const char *key, apr_threadkey_t *threadkey) { return apr_pool_userdata_get(data, key, threadkey->pool); } APR_DECLARE(apr_status_t) apr_threadkey_data_set(void *data, const char *key, apr_status_t (*cleanup)(void *), apr_threadkey_t *threadkey) { return apr_pool_userdata_set(data, key, cleanup, threadkey->pool); } APR_DECLARE(apr_status_t) apr_os_threadkey_get(apr_os_threadkey_t *thekey, apr_threadkey_t *key) { *thekey = key->key; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_threadkey_put(apr_threadkey_t **key, apr_os_threadkey_t *thekey, apr_pool_t *pool) { if (pool == NULL) { return APR_ENOPOOL; } if ((*key) == NULL) { (*key) = (apr_threadkey_t *)apr_pcalloc(pool, sizeof(apr_threadkey_t)); (*key)->pool = pool; } (*key)->key = *thekey; return APR_SUCCESS; } #endif /* APR_HAVE_PTHREAD_H */ #endif /* APR_HAS_THREADS */ #if !APR_HAS_THREADS /* avoid warning for no prototype */ APR_DECLARE(apr_status_t) apr_os_threadkey_get(void); APR_DECLARE(apr_status_t) apr_os_threadkey_get(void) { return APR_ENOTIMPL; } #endif
001-log4cxx
trunk/src/apr/threadproc/unix/threadpriv.c
C
asf20
3,706
/* 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_DOSEXCEPTIONS /* for OS2 */ #include "apr_arch_threadproc.h" #include "apr_private.h" #include "apr_pools.h" #include "apr_signal.h" #include "apr_strings.h" #include <assert.h> #if APR_HAS_THREADS && APR_HAVE_PTHREAD_H #include <pthread.h> #endif #ifdef SIGWAIT_TAKES_ONE_ARG #define apr_sigwait(a,b) ((*(b)=sigwait((a)))<0?-1:0) #else #define apr_sigwait(a,b) sigwait((a),(b)) #endif APR_DECLARE(apr_status_t) apr_proc_kill(apr_proc_t *proc, int signum) { #ifdef OS2 /* SIGTERM's don't work too well in OS/2 (only affects other EMX * programs). CGIs may not be, esp. REXX scripts, so use a native * call instead */ if (signum == SIGTERM) { return APR_OS2_STATUS(DosSendSignalException(proc->pid, XCPT_SIGNAL_BREAK)); } #endif /* OS2 */ if (kill(proc->pid, signum) == -1) { return errno; } return APR_SUCCESS; } #if APR_HAVE_SIGACTION #if defined(__NetBSD__) || defined(DARWIN) static void avoid_zombies(int signo) { int exit_status; while (waitpid(-1, &exit_status, WNOHANG) > 0) { /* do nothing */ } } #endif /* DARWIN */ /* * Replace standard signal() with the more reliable sigaction equivalent * from W. Richard Stevens' "Advanced Programming in the UNIX Environment" * (the version that does not automatically restart system calls). */ APR_DECLARE(apr_sigfunc_t *) apr_signal(int signo, apr_sigfunc_t * func) { struct sigaction act, oact; act.sa_handler = func; sigemptyset(&act.sa_mask); act.sa_flags = 0; #ifdef SA_INTERRUPT /* SunOS */ act.sa_flags |= SA_INTERRUPT; #endif #if defined(__osf__) && defined(__alpha) /* XXX jeff thinks this should be enabled whenever SA_NOCLDWAIT is defined */ /* this is required on Tru64 to cause child processes to * disappear gracefully - XPG4 compatible */ if ((signo == SIGCHLD) && (func == SIG_IGN)) { act.sa_flags |= SA_NOCLDWAIT; } #endif #if defined(__NetBSD__) || defined(DARWIN) /* ignoring SIGCHLD or leaving the default disposition doesn't avoid zombies, * and there is no SA_NOCLDWAIT flag, so catch the signal and reap status in * the handler to avoid zombies */ if ((signo == SIGCHLD) && (func == SIG_IGN)) { act.sa_handler = avoid_zombies; } #endif if (sigaction(signo, &act, &oact) < 0) return SIG_ERR; return oact.sa_handler; } #endif /* HAVE_SIGACTION */ /* AC_DECL_SYS_SIGLIST defines either of these symbols depending * on the version of autoconf used. */ #if defined(SYS_SIGLIST_DECLARED) || HAVE_DECL_SYS_SIGLIST void apr_signal_init(apr_pool_t *pglobal) { } const char *apr_signal_description_get(int signum) { return sys_siglist[signum]; } #else /* !(SYS_SIGLIST_DECLARED || HAVE_DECL_SYS_SIGLIST) */ /* we need to roll our own signal description stuff */ #if defined(NSIG) #define APR_NUMSIG NSIG #elif defined(_NSIG) #define APR_NUMSIG _NSIG #elif defined(__NSIG) #define APR_NUMSIG __NSIG #else #define APR_NUMSIG 33 /* breaks on OS/390 with < 33; 32 is o.k. for most */ #endif static const char *signal_description[APR_NUMSIG]; #define store_desc(index, string) \ do { \ if (index >= APR_NUMSIG) { \ assert(index < APR_NUMSIG); \ } \ else { \ signal_description[index] = string; \ } \ } while (0) void apr_signal_init(apr_pool_t *pglobal) { int sig; store_desc(0, "Signal 0"); #ifdef SIGHUP store_desc(SIGHUP, "Hangup"); #endif #ifdef SIGINT store_desc(SIGINT, "Interrupt"); #endif #ifdef SIGQUIT store_desc(SIGQUIT, "Quit"); #endif #ifdef SIGILL store_desc(SIGILL, "Illegal instruction"); #endif #ifdef SIGTRAP store_desc(SIGTRAP, "Trace/BPT trap"); #endif #ifdef SIGIOT store_desc(SIGIOT, "IOT instruction"); #endif #ifdef SIGABRT store_desc(SIGABRT, "Abort"); #endif #ifdef SIGEMT store_desc(SIGEMT, "Emulator trap"); #endif #ifdef SIGFPE store_desc(SIGFPE, "Arithmetic exception"); #endif #ifdef SIGKILL store_desc(SIGKILL, "Killed"); #endif #ifdef SIGBUS store_desc(SIGBUS, "Bus error"); #endif #ifdef SIGSEGV store_desc(SIGSEGV, "Segmentation fault"); #endif #ifdef SIGSYS store_desc(SIGSYS, "Bad system call"); #endif #ifdef SIGPIPE store_desc(SIGPIPE, "Broken pipe"); #endif #ifdef SIGALRM store_desc(SIGALRM, "Alarm clock"); #endif #ifdef SIGTERM store_desc(SIGTERM, "Terminated"); #endif #ifdef SIGUSR1 store_desc(SIGUSR1, "User defined signal 1"); #endif #ifdef SIGUSR2 store_desc(SIGUSR2, "User defined signal 2"); #endif #ifdef SIGCLD store_desc(SIGCLD, "Child status change"); #endif #ifdef SIGCHLD store_desc(SIGCHLD, "Child status change"); #endif #ifdef SIGPWR store_desc(SIGPWR, "Power-fail restart"); #endif #ifdef SIGWINCH store_desc(SIGWINCH, "Window changed"); #endif #ifdef SIGURG store_desc(SIGURG, "urgent socket condition"); #endif #ifdef SIGPOLL store_desc(SIGPOLL, "Pollable event occurred"); #endif #ifdef SIGIO store_desc(SIGIO, "socket I/O possible"); #endif #ifdef SIGSTOP store_desc(SIGSTOP, "Stopped (signal)"); #endif #ifdef SIGTSTP store_desc(SIGTSTP, "Stopped"); #endif #ifdef SIGCONT store_desc(SIGCONT, "Continued"); #endif #ifdef SIGTTIN store_desc(SIGTTIN, "Stopped (tty input)"); #endif #ifdef SIGTTOU store_desc(SIGTTOU, "Stopped (tty output)"); #endif #ifdef SIGVTALRM store_desc(SIGVTALRM, "virtual timer expired"); #endif #ifdef SIGPROF store_desc(SIGPROF, "profiling timer expired"); #endif #ifdef SIGXCPU store_desc(SIGXCPU, "exceeded cpu limit"); #endif #ifdef SIGXFSZ store_desc(SIGXFSZ, "exceeded file size limit"); #endif for (sig = 0; sig < APR_NUMSIG; ++sig) if (signal_description[sig] == NULL) signal_description[sig] = apr_psprintf(pglobal, "signal #%d", sig); } const char *apr_signal_description_get(int signum) { return signum < APR_NUMSIG ? signal_description[signum] : "unknown signal (number)"; } #endif /* SYS_SIGLIST_DECLARED || HAVE_DECL_SYS_SIGLIST */ #if APR_HAS_THREADS && (HAVE_SIGSUSPEND || APR_HAVE_SIGWAIT) && !defined(OS2) static void remove_sync_sigs(sigset_t *sig_mask) { #ifdef SIGABRT sigdelset(sig_mask, SIGABRT); #endif #ifdef SIGBUS sigdelset(sig_mask, SIGBUS); #endif #ifdef SIGEMT sigdelset(sig_mask, SIGEMT); #endif #ifdef SIGFPE sigdelset(sig_mask, SIGFPE); #endif #ifdef SIGILL sigdelset(sig_mask, SIGILL); #endif #ifdef SIGIOT sigdelset(sig_mask, SIGIOT); #endif #ifdef SIGPIPE sigdelset(sig_mask, SIGPIPE); #endif #ifdef SIGSEGV sigdelset(sig_mask, SIGSEGV); #endif #ifdef SIGSYS sigdelset(sig_mask, SIGSYS); #endif #ifdef SIGTRAP sigdelset(sig_mask, SIGTRAP); #endif /* the rest of the signals removed from the mask in this function * absolutely must be removed; you cannot block synchronous signals * (requirement of pthreads API) * * SIGUSR2 is being removed from the mask for the convenience of * Purify users (Solaris, HP-UX, SGI) since Purify uses SIGUSR2 */ #ifdef SIGUSR2 sigdelset(sig_mask, SIGUSR2); #endif } APR_DECLARE(apr_status_t) apr_signal_thread(int(*signal_handler)(int signum)) { sigset_t sig_mask; #if APR_HAVE_SIGWAIT int (*sig_func)(int signum) = (int (*)(int))signal_handler; #endif /* This thread will be the one responsible for handling signals */ sigfillset(&sig_mask); /* On certain platforms, sigwait() returns EINVAL if any of various * unblockable signals are included in the mask. This was first * observed on AIX and Tru64. */ #ifdef SIGKILL sigdelset(&sig_mask, SIGKILL); #endif #ifdef SIGSTOP sigdelset(&sig_mask, SIGSTOP); #endif #ifdef SIGCONT sigdelset(&sig_mask, SIGCONT); #endif #ifdef SIGWAITING sigdelset(&sig_mask, SIGWAITING); #endif /* no synchronous signals should be in the mask passed to sigwait() */ remove_sync_sigs(&sig_mask); /* On AIX (4.3.3, at least), sigwait() won't wake up if the high- * order bit of the second word of flags is turned on. sigdelset() * returns an error when trying to turn this off, so we'll turn it * off manually. * * Note that the private fields differ between 32-bit and 64-bit * and even between _ALL_SOURCE and !_ALL_SOURCE. Except that on * AIX 4.3 32-bit builds and 64-bit builds use the same definition. * * Applicable AIX fixes such that this is no longer needed: * * APAR IY23096 for AIX 51B, fix included in AIX 51C, and * APAR IY24162 for 43X. */ #if defined(_AIX) #if defined(__64BIT__) && defined(_AIXVERSION_510) #ifdef _ALL_SOURCE sig_mask.ss_set[3] &= 0x7FFFFFFF; #else /* not _ALL_SOURCE */ sig_mask.__ss_set[3] &= 0x7FFFFFFF; #endif #else /* not 64-bit build, or 64-bit build on 4.3 */ #ifdef _ALL_SOURCE sig_mask.hisigs &= 0x7FFFFFFF; #else /* not _ALL_SOURCE */ sig_mask.__hisigs &= 0x7FFFFFFF; #endif #endif #endif /* _AIX */ while (1) { #if APR_HAVE_SIGWAIT int signal_received; if (apr_sigwait(&sig_mask, &signal_received) != 0) { /* handle sigwait() error here */ } if (sig_func(signal_received) == 1) { return APR_SUCCESS; } #elif HAVE_SIGSUSPEND sigsuspend(&sig_mask); #else #error No apr_sigwait() and no sigsuspend() #endif } } APR_DECLARE(apr_status_t) apr_setup_signal_thread(void) { sigset_t sig_mask; int rv; /* All threads should mask out signals to be handled by * the thread doing sigwait(). * * No thread should ever block synchronous signals. * See the Solaris man page for pthread_sigmask() for * some information. Solaris chooses to knock out such * processes when a blocked synchronous signal is * delivered, skipping any registered signal handler. * AIX doesn't call a signal handler either. At least * one level of linux+glibc does call the handler even * when the synchronous signal is blocked. */ sigfillset(&sig_mask); remove_sync_sigs(&sig_mask); #if defined(SIGPROCMASK_SETS_THREAD_MASK) || ! APR_HAS_THREADS if ((rv = sigprocmask(SIG_SETMASK, &sig_mask, NULL)) != 0) { rv = errno; } #else if ((rv = pthread_sigmask(SIG_SETMASK, &sig_mask, NULL)) != 0) { #ifdef PTHREAD_SETS_ERRNO rv = errno; #endif } #endif return rv; } #endif /* APR_HAS_THREADS && ... */ APR_DECLARE(apr_status_t) apr_signal_block(int signum) { #if APR_HAVE_SIGACTION sigset_t sig_mask; int rv; sigemptyset(&sig_mask); sigaddset(&sig_mask, signum); #if defined(SIGPROCMASK_SETS_THREAD_MASK) || ! APR_HAS_THREADS if ((rv = sigprocmask(SIG_BLOCK, &sig_mask, NULL)) != 0) { rv = errno; } #else if ((rv = pthread_sigmask(SIG_BLOCK, &sig_mask, NULL)) != 0) { #ifdef PTHREAD_SETS_ERRNO rv = errno; #endif } #endif return rv; #else return APR_ENOTIMPL; #endif } APR_DECLARE(apr_status_t) apr_signal_unblock(int signum) { #if APR_HAVE_SIGACTION sigset_t sig_mask; int rv; sigemptyset(&sig_mask); sigaddset(&sig_mask, signum); #if defined(SIGPROCMASK_SETS_THREAD_MASK) || ! APR_HAS_THREADS if ((rv = sigprocmask(SIG_UNBLOCK, &sig_mask, NULL)) != 0) { rv = errno; } #else if ((rv = pthread_sigmask(SIG_UNBLOCK, &sig_mask, NULL)) != 0) { #ifdef PTHREAD_SETS_ERRNO rv = errno; #endif } #endif return rv; #else return APR_ENOTIMPL; #endif }
001-log4cxx
trunk/src/apr/threadproc/unix/signals.c
C
asf20
12,428
/* 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_threadproc.h" APR_DECLARE(apr_status_t) apr_proc_detach(int daemonize) { int x; if (chdir("/") == -1) { return errno; } #if !defined(MPE) && !defined(OS2) && !defined(TPF) && !defined(BEOS) /* Don't detach for MPE because child processes can't survive the death of * the parent. */ if (daemonize) { if ((x = fork()) > 0) { exit(0); } else if (x == -1) { perror("fork"); fprintf(stderr, "unable to fork new process\n"); exit(1); /* we can't do anything here, so just exit. */ } /* RAISE_SIGSTOP(DETACH); */ } #endif #ifdef HAVE_SETSID /* A setsid() failure is not fatal if we didn't just fork(). * The calling process may be the process group leader, in * which case setsid() will fail with EPERM. */ if (setsid() == -1 && daemonize) { return errno; } #elif defined(NEXT) || defined(NEWSOS) if (setpgrp(0, getpid()) == -1) { return errno; } #elif defined(OS2) || defined(TPF) || defined(MPE) /* do nothing */ #else if (setpgid(0, 0) == -1) { return errno; } #endif /* close out the standard file descriptors */ if (freopen("/dev/null", "r", stdin) == NULL) { return errno; /* continue anyhow -- note we can't close out descriptor 0 because we * have nothing to replace it with, and if we didn't have a descriptor * 0 the next file would be created with that value ... leading to * havoc. */ } if (freopen("/dev/null", "w", stdout) == NULL) { return errno; } /* We are going to reopen this again in a little while to the error * log file, but better to do it twice and suffer a small performance * hit for consistancy than not reopen it here. */ if (freopen("/dev/null", "w", stderr) == NULL) { return errno; } return APR_SUCCESS; } #if (!HAVE_WAITPID) /* From ikluft@amdahl.com * this is not ideal but it works for SVR3 variants * Modified by dwd@bell-labs.com to call wait3 instead of wait because * apache started to use the WNOHANG option. */ int waitpid(pid_t pid, int *statusp, int options) { int tmp_pid; if (kill(pid, 0) == -1) { errno = ECHILD; return -1; } while (((tmp_pid = wait3(statusp, options, 0)) != pid) && (tmp_pid != -1) && (tmp_pid != 0) && (pid != -1)) ; return tmp_pid; } #endif
001-log4cxx
trunk/src/apr/threadproc/unix/procsup.c
C
asf20
3,288
/* 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_threadproc.h" #include "apr_arch_file_io.h" #include "apr_strings.h" #include "apr_portable.h" #include <proc.h> apr_status_t apr_netware_proc_cleanup(void *theproc) { apr_proc_t *proc = theproc; int exit_int; int waitpid_options = WUNTRACED | WNOHANG; if (proc->pid > 0) { waitpid(proc->pid, &exit_int, waitpid_options); } /* NXVmDestroy(proc->pid); */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_create(apr_procattr_t **new,apr_pool_t *pool) { (*new) = (apr_procattr_t *)apr_pcalloc(pool, sizeof(apr_procattr_t)); if ((*new) == NULL) { return APR_ENOMEM; } (*new)->pool = pool; (*new)->cmdtype = APR_PROGRAM; /* Default to a current path since NetWare doesn't handle it very well */ apr_filepath_get(&((*new)->currdir), APR_FILEPATH_NATIVE, pool); (*new)->detached = 1; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_io_set(apr_procattr_t *attr, apr_int32_t in, apr_int32_t out, apr_int32_t err) { apr_status_t status; if (in != 0) { if ((status = apr_file_pipe_create(&attr->child_in, &attr->parent_in, attr->pool)) != APR_SUCCESS) { return status; } switch (in) { case APR_FULL_BLOCK: break; case APR_PARENT_BLOCK: apr_file_pipe_timeout_set(attr->child_in, 0); break; case APR_CHILD_BLOCK: apr_file_pipe_timeout_set(attr->parent_in, 0); break; default: apr_file_pipe_timeout_set(attr->child_in, 0); apr_file_pipe_timeout_set(attr->parent_in, 0); } } if (out) { if ((status = apr_file_pipe_create(&attr->parent_out, &attr->child_out, attr->pool)) != APR_SUCCESS) { return status; } switch (out) { case APR_FULL_BLOCK: break; case APR_PARENT_BLOCK: apr_file_pipe_timeout_set(attr->child_out, 0); break; case APR_CHILD_BLOCK: apr_file_pipe_timeout_set(attr->parent_out, 0); break; default: apr_file_pipe_timeout_set(attr->child_out, 0); apr_file_pipe_timeout_set(attr->parent_out, 0); } } if (err) { if ((status = apr_file_pipe_create(&attr->parent_err, &attr->child_err, attr->pool)) != APR_SUCCESS) { return status; } switch (err) { case APR_FULL_BLOCK: break; case APR_PARENT_BLOCK: apr_file_pipe_timeout_set(attr->child_err, 0); break; case APR_CHILD_BLOCK: apr_file_pipe_timeout_set(attr->parent_err, 0); break; default: apr_file_pipe_timeout_set(attr->child_err, 0); apr_file_pipe_timeout_set(attr->parent_err, 0); } } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_child_in_set(apr_procattr_t *attr, apr_file_t *child_in, apr_file_t *parent_in) { if (attr->child_in == NULL && attr->parent_in == NULL) apr_file_pipe_create(&attr->child_in, &attr->parent_in, attr->pool); if (child_in != NULL) apr_file_dup2(attr->child_in, child_in, attr->pool); if (parent_in != NULL) apr_file_dup2(attr->parent_in, parent_in, attr->pool); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_child_out_set(apr_procattr_t *attr, apr_file_t *child_out, apr_file_t *parent_out) { if (attr->child_out == NULL && attr->parent_out == NULL) apr_file_pipe_create(&attr->child_out, &attr->parent_out, attr->pool); if (child_out != NULL) apr_file_dup2(attr->child_out, child_out, attr->pool); if (parent_out != NULL) apr_file_dup2(attr->parent_out, parent_out, attr->pool); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_child_err_set(apr_procattr_t *attr, apr_file_t *child_err, apr_file_t *parent_err) { if (attr->child_err == NULL && attr->parent_err == NULL) apr_file_pipe_create(&attr->child_err, &attr->parent_err, attr->pool); if (child_err != NULL) apr_file_dup2(attr->child_err, child_err, attr->pool); if (parent_err != NULL) apr_file_dup2(attr->parent_err, parent_err, attr->pool); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_dir_set(apr_procattr_t *attr, const char *dir) { return apr_filepath_merge(&attr->currdir, NULL, dir, APR_FILEPATH_NATIVE, attr->pool); } APR_DECLARE(apr_status_t) apr_procattr_cmdtype_set(apr_procattr_t *attr, apr_cmdtype_e cmd) { /* won't ever be called on this platform, so don't save the function pointer */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_detach_set(apr_procattr_t *attr, apr_int32_t detach) { attr->detached = detach; return APR_SUCCESS; } #if APR_HAS_FORK APR_DECLARE(apr_status_t) apr_proc_fork(apr_proc_t *proc, apr_pool_t *pool) { int pid; if ((pid = fork()) < 0) { return errno; } else if (pid == 0) { proc->pid = pid; proc->in = NULL; proc->out = NULL; proc->err = NULL; return APR_INCHILD; } proc->pid = pid; proc->in = NULL; proc->out = NULL; proc->err = NULL; return APR_INPARENT; } #endif static apr_status_t limit_proc(apr_procattr_t *attr) { #if APR_HAVE_STRUCT_RLIMIT && APR_HAVE_SETRLIMIT #ifdef RLIMIT_CPU if (attr->limit_cpu != NULL) { if ((setrlimit(RLIMIT_CPU, attr->limit_cpu)) != 0) { return errno; } } #endif #ifdef RLIMIT_NPROC if (attr->limit_nproc != NULL) { if ((setrlimit(RLIMIT_NPROC, attr->limit_nproc)) != 0) { return errno; } } #endif #if defined(RLIMIT_AS) if (attr->limit_mem != NULL) { if ((setrlimit(RLIMIT_AS, attr->limit_mem)) != 0) { return errno; } } #elif defined(RLIMIT_DATA) if (attr->limit_mem != NULL) { if ((setrlimit(RLIMIT_DATA, attr->limit_mem)) != 0) { return errno; } } #elif defined(RLIMIT_VMEM) if (attr->limit_mem != NULL) { if ((setrlimit(RLIMIT_VMEM, attr->limit_mem)) != 0) { return errno; } } #endif #else /* * Maybe make a note in error_log that setrlimit isn't supported?? */ #endif return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_child_errfn_set(apr_procattr_t *attr, apr_child_errfn_t *errfn) { /* won't ever be called on this platform, so don't save the function pointer */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_error_check_set(apr_procattr_t *attr, apr_int32_t chk) { /* won't ever be used on this platform, so don't save the flag */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_addrspace_set(apr_procattr_t *attr, apr_int32_t addrspace) { attr->addrspace = addrspace; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_proc_create(apr_proc_t *newproc, const char *progname, const char * const *args, const char * const *env, apr_procattr_t *attr, apr_pool_t *pool) { wiring_t wire; int addr_space; wire.infd = attr->child_in ? attr->child_in->filedes : FD_UNUSED; wire.outfd = attr->child_out ? attr->child_out->filedes : FD_UNUSED; wire.errfd = attr->child_err ? attr->child_err->filedes : FD_UNUSED; newproc->in = attr->parent_in; newproc->out = attr->parent_out; newproc->err = attr->parent_err; /* attr->detached and PROC_DETACHED do not mean the same thing. attr->detached means * start the NLM in a separate address space. PROC_DETACHED means don't wait for the * NLM to unload by calling wait() or waitpid(), just clean up */ addr_space = PROC_LOAD_SILENT | (attr->addrspace ? 0 : PROC_CURRENT_SPACE); addr_space |= (attr->detached ? PROC_DETACHED : 0); if (attr->currdir) { char *fullpath = NULL; apr_status_t rv; if ((rv = apr_filepath_merge(&fullpath, attr->currdir, progname, APR_FILEPATH_NATIVE, pool)) != APR_SUCCESS) { return rv; } progname = fullpath; } if ((newproc->pid = procve(progname, addr_space, (const char**)env, &wire, NULL, NULL, 0, NULL, (const char **)args)) == -1) { return errno; } if (attr->child_in) { apr_pool_cleanup_kill(apr_file_pool_get(attr->child_in), attr->child_in, apr_unix_file_cleanup); apr_file_close(attr->child_in); } if (attr->child_out) { apr_pool_cleanup_kill(apr_file_pool_get(attr->child_out), attr->child_out, apr_unix_file_cleanup); apr_file_close(attr->child_out); } if (attr->child_err) { apr_pool_cleanup_kill(apr_file_pool_get(attr->child_err), attr->child_err, apr_unix_file_cleanup); apr_file_close(attr->child_err); } apr_pool_cleanup_register(pool, (void *)newproc, apr_netware_proc_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_proc_wait_all_procs(apr_proc_t *proc, int *exitcode, apr_exit_why_e *exitwhy, apr_wait_how_e waithow, apr_pool_t *p) { proc->pid = -1; return apr_proc_wait(proc, exitcode, exitwhy, waithow); } APR_DECLARE(apr_status_t) apr_proc_wait(apr_proc_t *proc, int *exitcode, apr_exit_why_e *exitwhy, apr_wait_how_e waithow) { pid_t pstatus; int waitpid_options = WUNTRACED; int exit_int; int ignore; apr_exit_why_e ignorewhy; if (exitcode == NULL) { exitcode = &ignore; } if (exitwhy == NULL) { exitwhy = &ignorewhy; } if (waithow != APR_WAIT) { waitpid_options |= WNOHANG; } /* If the pid is 0 then the process was started detached. There is no need to wait since there is nothing to wait for on a detached process. Starting a process as non-detached and then calling wait or waitpid could cause the thread to hang. The reason for this is because NetWare does not have a way to kill or even signal a process to be killed. Starting all processes as detached avoids the possibility of a thread hanging. */ if (proc->pid == 0) { *exitwhy = APR_PROC_EXIT; *exitcode = 0; return APR_CHILD_DONE; } if ((pstatus = waitpid(proc->pid, &exit_int, waitpid_options)) > 0) { proc->pid = pstatus; if (WIFEXITED(exit_int)) { *exitwhy = APR_PROC_EXIT; *exitcode = WEXITSTATUS(exit_int); } else if (WIFSIGNALED(exit_int)) { *exitwhy = APR_PROC_SIGNAL; *exitcode = WIFTERMSIG(exit_int); } else { /* unexpected condition */ return APR_EGENERAL; } return APR_CHILD_DONE; } else if (pstatus == 0) { return APR_CHILD_NOTDONE; } return errno; } APR_DECLARE(apr_status_t) apr_procattr_limit_set(apr_procattr_t *attr, apr_int32_t what, struct rlimit *limit) { switch(what) { case APR_LIMIT_CPU: #ifdef RLIMIT_CPU attr->limit_cpu = limit; break; #else return APR_ENOTIMPL; #endif case APR_LIMIT_MEM: #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS) attr->limit_mem = limit; break; #else return APR_ENOTIMPL; #endif case APR_LIMIT_NPROC: #ifdef RLIMIT_NPROC attr->limit_nproc = limit; break; #else return APR_ENOTIMPL; #endif } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_user_set(apr_procattr_t *attr, const char *username, const char *password) { /* Always return SUCCESS because NetWare threads don't run as a user */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_group_set(apr_procattr_t *attr, const char *groupname) { /* Always return SUCCESS because NetWare threads don't run within a group */ return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/threadproc/netware/proc.c
C
asf20
13,986
/* 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_portable.h" #include "apr_strings.h" #include "apr_arch_threadproc.h" static int thread_count = 0; apr_status_t apr_threadattr_create(apr_threadattr_t **new, apr_pool_t *pool) { (*new) = (apr_threadattr_t *)apr_palloc(pool, sizeof(apr_threadattr_t)); if ((*new) == NULL) { return APR_ENOMEM; } (*new)->pool = pool; (*new)->stack_size = APR_DEFAULT_STACK_SIZE; (*new)->detach = 0; (*new)->thread_name = NULL; return APR_SUCCESS; } apr_status_t apr_threadattr_detach_set(apr_threadattr_t *attr,apr_int32_t on) { attr->detach = on; return APR_SUCCESS; } apr_status_t apr_threadattr_detach_get(apr_threadattr_t *attr) { if (attr->detach == 1) return APR_DETACH; return APR_NOTDETACH; } APR_DECLARE(apr_status_t) apr_threadattr_stacksize_set(apr_threadattr_t *attr, apr_size_t stacksize) { attr->stack_size = stacksize; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_threadattr_guardsize_set(apr_threadattr_t *attr, apr_size_t size) { return APR_ENOTIMPL; } static void *dummy_worker(void *opaque) { apr_thread_t *thd = (apr_thread_t *)opaque; return thd->func(thd, thd->data); } apr_status_t apr_thread_create(apr_thread_t **new, apr_threadattr_t *attr, apr_thread_start_t func, void *data, apr_pool_t *pool) { apr_status_t stat; long flags = NX_THR_BIND_CONTEXT; char threadName[NX_MAX_OBJECT_NAME_LEN+1]; size_t stack_size = APR_DEFAULT_STACK_SIZE; if (attr && attr->thread_name) { strncpy (threadName, attr->thread_name, NX_MAX_OBJECT_NAME_LEN); } else { sprintf(threadName, "APR_thread %04ld", ++thread_count); } /* An original stack size of 0 will allow NXCreateThread() to * assign a default system stack size. An original stack * size of less than 0 will assign the APR default stack size. * anything else will be taken as is. */ if (attr && (attr->stack_size >= 0)) { stack_size = attr->stack_size; } (*new) = (apr_thread_t *)apr_palloc(pool, sizeof(apr_thread_t)); if ((*new) == NULL) { return APR_ENOMEM; } (*new)->pool = pool; (*new)->data = data; (*new)->func = func; (*new)->thread_name = (char*)apr_pstrdup(pool, threadName); stat = apr_pool_create(&(*new)->pool, pool); if (stat != APR_SUCCESS) { return stat; } if (attr && attr->detach) { flags |= NX_THR_DETACHED; } (*new)->ctx = NXContextAlloc( /* void(*start_routine)(void *arg)*/(void (*)(void *)) dummy_worker, /* void *arg */ (*new), /* int priority */ NX_PRIO_MED, /* NXSize_t stackSize */ stack_size, /* long flags */ NX_CTX_NORMAL, /* int *error */ &stat); stat = NXContextSetName( /* NXContext_t ctx */ (*new)->ctx, /* const char *name */ threadName); stat = NXThreadCreate( /* NXContext_t context */ (*new)->ctx, /* long flags */ flags, /* NXThreadId_t *thread_id */ &(*new)->td); if(stat==0) return APR_SUCCESS; return(stat);// if error } apr_os_thread_t apr_os_thread_current() { return NXThreadGetId(); } int apr_os_thread_equal(apr_os_thread_t tid1, apr_os_thread_t tid2) { return (tid1 == tid2); } void apr_thread_yield() { NXThreadYield(); } apr_status_t apr_thread_exit(apr_thread_t *thd, apr_status_t retval) { thd->exitval = retval; apr_pool_destroy(thd->pool); NXThreadExit(NULL); return APR_SUCCESS; } apr_status_t apr_thread_join(apr_status_t *retval, apr_thread_t *thd) { apr_status_t stat; NXThreadId_t dthr; if ((stat = NXThreadJoin(thd->td, &dthr, NULL)) == 0) { *retval = thd->exitval; return APR_SUCCESS; } else { return stat; } } apr_status_t apr_thread_detach(apr_thread_t *thd) { return APR_SUCCESS; } apr_status_t apr_thread_data_get(void **data, const char *key, apr_thread_t *thread) { if (thread != NULL) { return apr_pool_userdata_get(data, key, thread->pool); } else { data = NULL; return APR_ENOTHREAD; } } apr_status_t apr_thread_data_set(void *data, const char *key, apr_status_t (*cleanup) (void *), apr_thread_t *thread) { if (thread != NULL) { return apr_pool_userdata_set(data, key, cleanup, thread->pool); } else { data = NULL; return APR_ENOTHREAD; } } APR_DECLARE(apr_status_t) apr_os_thread_get(apr_os_thread_t **thethd, apr_thread_t *thd) { if (thd == NULL) { return APR_ENOTHREAD; } *thethd = &(thd->td); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_thread_put(apr_thread_t **thd, apr_os_thread_t *thethd, apr_pool_t *pool) { if (pool == NULL) { return APR_ENOPOOL; } if ((*thd) == NULL) { (*thd) = (apr_thread_t *)apr_palloc(pool, sizeof(apr_thread_t)); (*thd)->pool = pool; } (*thd)->td = *thethd; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_thread_once_init(apr_thread_once_t **control, apr_pool_t *p) { (*control) = apr_pcalloc(p, sizeof(**control)); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_thread_once(apr_thread_once_t *control, void (*func)(void)) { if (!atomic_xchg(&control->value, 1)) { func(); } return APR_SUCCESS; } APR_POOL_IMPLEMENT_ACCESSOR(thread)
001-log4cxx
trunk/src/apr/threadproc/netware/thread.c
C
asf20
6,994
/* 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_arch_threadproc.h" apr_status_t apr_threadkey_private_create(apr_threadkey_t **key, void (*dest)(void *), apr_pool_t *pool) { apr_status_t stat; (*key) = (apr_threadkey_t *)apr_palloc(pool, sizeof(apr_threadkey_t)); if ((*key) == NULL) { return APR_ENOMEM; } (*key)->pool = pool; if ((stat = NXKeyCreate(NULL, dest, &(*key)->key)) == 0) { return stat; } return stat; } apr_status_t apr_threadkey_private_get(void **new, apr_threadkey_t *key) { apr_status_t stat; if ((stat = NXKeyGetValue(key->key, new)) == 0) { return APR_SUCCESS; } else { return stat; } } apr_status_t apr_threadkey_private_set(void *priv, apr_threadkey_t *key) { apr_status_t stat; if ((stat = NXKeySetValue(key->key, priv)) == 0) { return APR_SUCCESS; } else { return stat; } } apr_status_t apr_threadkey_private_delete(apr_threadkey_t *key) { apr_status_t stat; if ((stat = NXKeyDelete(key->key)) == 0) { return APR_SUCCESS; } return stat; } apr_status_t apr_threadkey_data_get(void **data, const char *key, apr_threadkey_t *threadkey) { return apr_pool_userdata_get(data, key, threadkey->pool); } apr_status_t apr_threadkey_data_set(void *data, const char *key, apr_status_t (*cleanup) (void *), apr_threadkey_t *threadkey) { return apr_pool_userdata_set(data, key, cleanup, threadkey->pool); } apr_status_t apr_os_threadkey_get(apr_os_threadkey_t *thekey, apr_threadkey_t *key) { thekey = &(key->key); return APR_SUCCESS; } apr_status_t apr_os_threadkey_put(apr_threadkey_t **key, apr_os_threadkey_t *thekey, apr_pool_t *pool) { if (pool == NULL) { return APR_ENOPOOL; } if ((*key) == NULL) { (*key) = (apr_threadkey_t *)apr_palloc(pool, sizeof(apr_threadkey_t)); (*key)->pool = pool; } (*key)->key = *thekey; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/threadproc/netware/threadpriv.c
C
asf20
2,977
/* 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_threadproc.h" #include <nks/thread.h> #include "apr_private.h" #include "apr_pools.h" #include "apr_signal.h" #include "apr_strings.h" #include <assert.h> #if APR_HAS_THREADS && APR_HAVE_PTHREAD_H #include <pthread.h> #endif APR_DECLARE(apr_status_t) apr_proc_kill(apr_proc_t *proc, int signum) { return APR_ENOTIMPL; } void apr_signal_init(apr_pool_t *pglobal) { } const char *apr_signal_description_get(int signum) { switch (signum) { case SIGABRT: return "Abort"; case SIGFPE: return "Arithmetic exception"; case SIGILL: return "Illegal instruction"; case SIGINT: return "Interrupt"; case SIGSEGV: return "Segmentation fault"; case SIGTERM: return "Terminated"; case SIGPOLL: return "Pollable event occurred"; default: return "unknown signal (not supported)"; } } static void *signal_thread_func(void *signal_handler) { return NULL; } APR_DECLARE(apr_status_t) apr_setup_signal_thread(void) { int rv = 0; return rv; } APR_DECLARE(apr_status_t) apr_signal_block(int signum) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_signal_unblock(int signum) { return APR_ENOTIMPL; }
001-log4cxx
trunk/src/apr/threadproc/netware/signals.c
C
asf20
2,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_arch_threadproc.h" apr_status_t apr_proc_detach(int daemonize) { #if 0 int x; pid_t pgrp; chdir("/"); #if !defined(MPE) && !defined(OS2) && !defined(TPF) && !defined(BEOS) /* Don't detach for MPE because child processes can't survive the death of the parent. */ if ((x = fork()) > 0) exit(0); else if (x == -1) { perror("fork"); fprintf(stderr, "unable to fork new process\n"); exit(1); /* we can't do anything here, so just exit. */ } /* RAISE_SIGSTOP(DETACH);*/ #endif #if APR_HAVE_SETSID if ((pgrp = setsid()) == -1) { return errno; } #elif defined(NEXT) || defined(NEWSOS) if (setpgrp(0, getpid()) == -1 || (pgrp = getpgrp(0)) == -1) { return errno; } #elif defined(OS2) || defined(TPF) /* OS/2 don't support process group IDs */ pgrp = getpid(); #elif defined(MPE) /* MPE uses negative pid for process group */ pgrp = -getpid(); #else if ((pgrp = setpgid(0, 0)) == -1) { return errno; } #endif /* close out the standard file descriptors */ if (freopen("/dev/null", "r", stdin) == NULL) { return errno; /* continue anyhow -- note we can't close out descriptor 0 because we * have nothing to replace it with, and if we didn't have a descriptor * 0 the next file would be created with that value ... leading to * havoc. */ } if (freopen("/dev/null", "w", stdout) == NULL) { return errno; } /* We are going to reopen this again in a little while to the error * log file, but better to do it twice and suffer a small performance * hit for consistancy than not reopen it here. */ if (freopen("/dev/null", "w", stderr) == NULL) { return errno; } #endif return APR_SUCCESS; } #if 0 #if (!HAVE_WAITPID) /* From ikluft@amdahl.com * this is not ideal but it works for SVR3 variants * Modified by dwd@bell-labs.com to call wait3 instead of wait because * apache started to use the WNOHANG option. */ int waitpid(pid_t pid, int *statusp, int options) { int tmp_pid; if (kill(pid, 0) == -1) { errno = ECHILD; return -1; } while (((tmp_pid = wait3(statusp, options, 0)) != pid) && (tmp_pid != -1) && (tmp_pid != 0) && (pid != -1)) ; return tmp_pid; } #endif #endif
001-log4cxx
trunk/src/apr/threadproc/netware/procsup.c
C
asf20
3,190
/* 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_threadproc.h" #include "apr_arch_file_io.h" #include "apr_private.h" #include "apr_thread_proc.h" #include "apr_file_io.h" #include "apr_general.h" #include "apr_lib.h" #include "apr_portable.h" #include "apr_strings.h" #include "apr_signal.h" #include <signal.h> #include <string.h> #include <sys/wait.h> #include <unistd.h> #include <process.h> #include <stdlib.h> APR_DECLARE(apr_status_t) apr_procattr_create(apr_procattr_t **new, apr_pool_t *pool) { (*new) = (apr_procattr_t *)apr_palloc(pool, sizeof(apr_procattr_t)); if ((*new) == NULL) { return APR_ENOMEM; } (*new)->pool = pool; (*new)->parent_in = NULL; (*new)->child_in = NULL; (*new)->parent_out = NULL; (*new)->child_out = NULL; (*new)->parent_err = NULL; (*new)->child_err = NULL; (*new)->currdir = NULL; (*new)->cmdtype = APR_PROGRAM; (*new)->detached = FALSE; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_io_set(apr_procattr_t *attr, apr_int32_t in, apr_int32_t out, apr_int32_t err) { apr_status_t stat; if (in) { if ((stat = apr_file_pipe_create(&attr->child_in, &attr->parent_in, attr->pool)) != APR_SUCCESS) { return stat; } switch (in) { case APR_FULL_BLOCK: break; case APR_PARENT_BLOCK: apr_file_pipe_timeout_set(attr->child_in, 0); break; case APR_CHILD_BLOCK: apr_file_pipe_timeout_set(attr->parent_in, 0); break; default: apr_file_pipe_timeout_set(attr->child_in, 0); apr_file_pipe_timeout_set(attr->parent_in, 0); } } if (out) { if ((stat = apr_file_pipe_create(&attr->parent_out, &attr->child_out, attr->pool)) != APR_SUCCESS) { return stat; } switch (out) { case APR_FULL_BLOCK: break; case APR_PARENT_BLOCK: apr_file_pipe_timeout_set(attr->child_out, 0); break; case APR_CHILD_BLOCK: apr_file_pipe_timeout_set(attr->parent_out, 0); break; default: apr_file_pipe_timeout_set(attr->child_out, 0); apr_file_pipe_timeout_set(attr->parent_out, 0); } } if (err) { if ((stat = apr_file_pipe_create(&attr->parent_err, &attr->child_err, attr->pool)) != APR_SUCCESS) { return stat; } switch (err) { case APR_FULL_BLOCK: break; case APR_PARENT_BLOCK: apr_file_pipe_timeout_set(attr->child_err, 0); break; case APR_CHILD_BLOCK: apr_file_pipe_timeout_set(attr->parent_err, 0); break; default: apr_file_pipe_timeout_set(attr->child_err, 0); apr_file_pipe_timeout_set(attr->parent_err, 0); } } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_child_in_set(apr_procattr_t *attr, apr_file_t *child_in, apr_file_t *parent_in) { if (attr->child_in == NULL && attr->parent_in == NULL) apr_file_pipe_create(&attr->child_in, &attr->parent_in, attr->pool); if (child_in != NULL) apr_file_dup(&attr->child_in, child_in, attr->pool); if (parent_in != NULL) apr_file_dup(&attr->parent_in, parent_in, attr->pool); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_child_out_set(apr_procattr_t *attr, apr_file_t *child_out, apr_file_t *parent_out) { if (attr->child_out == NULL && attr->parent_out == NULL) apr_file_pipe_create(&attr->child_out, &attr->parent_out, attr->pool); if (child_out != NULL) apr_file_dup(&attr->child_out, child_out, attr->pool); if (parent_out != NULL) apr_file_dup(&attr->parent_out, parent_out, attr->pool); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_child_err_set(apr_procattr_t *attr, apr_file_t *child_err, apr_file_t *parent_err) { if (attr->child_err == NULL && attr->parent_err == NULL) apr_file_pipe_create(&attr->child_err, &attr->parent_err, attr->pool); if (child_err != NULL) apr_file_dup(&attr->child_err, child_err, attr->pool); if (parent_err != NULL) apr_file_dup(&attr->parent_err, parent_err, attr->pool); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_dir_set(apr_procattr_t *attr, const char *dir) { attr->currdir = apr_pstrdup(attr->pool, dir); if (attr->currdir) { return APR_SUCCESS; } return APR_ENOMEM; } APR_DECLARE(apr_status_t) apr_procattr_cmdtype_set(apr_procattr_t *attr, apr_cmdtype_e cmd) { attr->cmdtype = cmd; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_detach_set(apr_procattr_t *attr, apr_int32_t detach) { attr->detached = detach; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_proc_fork(apr_proc_t *proc, apr_pool_t *pool) { int pid; if ((pid = fork()) < 0) { return errno; } else if (pid == 0) { proc->pid = pid; proc->in = NULL; proc->out = NULL; proc->err = NULL; return APR_INCHILD; } proc->pid = pid; proc->in = NULL; proc->out = NULL; proc->err = NULL; return APR_INPARENT; } /* quotes in the string are doubled up. * Used to escape quotes in args passed to OS/2's cmd.exe */ static char *double_quotes(apr_pool_t *pool, const char *str) { int num_quotes = 0; int len = 0; char *quote_doubled_str, *dest; while (str[len]) { num_quotes += str[len++] == '\"'; } quote_doubled_str = apr_palloc(pool, len + num_quotes + 1); dest = quote_doubled_str; while (*str) { if (*str == '\"') *(dest++) = '\"'; *(dest++) = *(str++); } *dest = 0; return quote_doubled_str; } APR_DECLARE(apr_status_t) apr_procattr_child_errfn_set(apr_procattr_t *attr, apr_child_errfn_t *errfn) { /* won't ever be called on this platform, so don't save the function pointer */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_error_check_set(apr_procattr_t *attr, apr_int32_t chk) { /* won't ever be used on this platform, so don't save the flag */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_procattr_addrspace_set(apr_procattr_t *attr, apr_int32_t addrspace) { /* won't ever be used on this platform, so don't save the flag */ return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_proc_create(apr_proc_t *proc, const char *progname, const char * const *args, const char * const *env, apr_procattr_t *attr, apr_pool_t *pool) { int i, arg, numargs, cmdlen; apr_status_t status; const char **newargs; char savedir[300]; HFILE save_in, save_out, save_err, dup; int criticalsection = FALSE; char *extension, *newprogname, *extra_arg = NULL, *cmdline, *cmdline_pos; char interpreter[1024]; char error_object[260]; apr_file_t *progfile; int env_len, e; char *env_block, *env_block_pos; RESULTCODES rescodes; /* Prevent other threads from running while these process-wide resources are modified */ if (attr->child_in || attr->child_out || attr->child_err || attr->currdir) { criticalsection = TRUE; DosEnterCritSec(); } if (attr->child_in) { save_in = -1; DosDupHandle(STDIN_FILENO, &save_in); dup = STDIN_FILENO; DosDupHandle(attr->child_in->filedes, &dup); DosSetFHState(attr->parent_in->filedes, OPEN_FLAGS_NOINHERIT); } if (attr->child_out) { save_out = -1; DosDupHandle(STDOUT_FILENO, &save_out); dup = STDOUT_FILENO; DosDupHandle(attr->child_out->filedes, &dup); DosSetFHState(attr->parent_out->filedes, OPEN_FLAGS_NOINHERIT); } if (attr->child_err) { save_err = -1; DosDupHandle(STDERR_FILENO, &save_err); dup = STDERR_FILENO; DosDupHandle(attr->child_err->filedes, &dup); DosSetFHState(attr->parent_err->filedes, OPEN_FLAGS_NOINHERIT); } apr_signal(SIGCHLD, SIG_DFL); /*not sure if this is needed or not */ if (attr->currdir != NULL) { _getcwd2(savedir, sizeof(savedir)); if (_chdir2(attr->currdir) < 0) { if (criticalsection) DosExitCritSec(); return errno; } } interpreter[0] = 0; extension = strrchr(progname, '.'); if (extension == NULL || strchr(extension, '/') || strchr(extension, '\\')) extension = ""; /* ### how to handle APR_PROGRAM_ENV and APR_PROGRAM_PATH? */ if (attr->cmdtype == APR_SHELLCMD || attr->cmdtype == APR_SHELLCMD_ENV || strcasecmp(extension, ".cmd") == 0) { strcpy(interpreter, "#!" SHELL_PATH); extra_arg = "/C"; } else if (stricmp(extension, ".exe") != 0) { status = apr_file_open(&progfile, progname, APR_READ|APR_BUFFERED, 0, pool); if (status != APR_SUCCESS && APR_STATUS_IS_ENOENT(status)) { progname = apr_pstrcat(pool, progname, ".exe", NULL); } if (status == APR_SUCCESS) { status = apr_file_gets(interpreter, sizeof(interpreter), progfile); if (status == APR_SUCCESS) { if (interpreter[0] == '#' && interpreter[1] == '!') { /* delete CR/LF & any other whitespace off the end */ int end = strlen(interpreter) - 1; while (end >= 0 && apr_isspace(interpreter[end])) { interpreter[end] = '\0'; end--; } if (interpreter[2] != '/' && interpreter[2] != '\\' && interpreter[3] != ':') { char buffer[300]; if (DosSearchPath(SEARCH_ENVIRONMENT, "PATH", interpreter+2, buffer, sizeof(buffer)) == 0) { strcpy(interpreter+2, buffer); } else { strcat(interpreter, ".exe"); if (DosSearchPath(SEARCH_ENVIRONMENT, "PATH", interpreter+2, buffer, sizeof(buffer)) == 0) { strcpy(interpreter+2, buffer); } } } } else { interpreter[0] = 0; } } apr_file_close(progfile); } } i = 0; while (args && args[i]) { i++; } newargs = (const char **)apr_palloc(pool, sizeof (char *) * (i + 4)); numargs = 0; if (interpreter[0]) newargs[numargs++] = interpreter + 2; if (extra_arg) newargs[numargs++] = "/c"; newargs[numargs++] = newprogname = apr_pstrdup(pool, progname); arg = 1; while (args && args[arg]) { newargs[numargs++] = args[arg++]; } newargs[numargs] = NULL; for (i=0; newprogname[i]; i++) if (newprogname[i] == '/') newprogname[i] = '\\'; cmdlen = 0; for (i=0; i<numargs; i++) cmdlen += strlen(newargs[i]) + 3; cmdline = apr_palloc(pool, cmdlen + 2); cmdline_pos = cmdline; for (i=0; i<numargs; i++) { const char *a = newargs[i]; if (strpbrk(a, "&|<>\" ")) a = apr_pstrcat(pool, "\"", double_quotes(pool, a), "\"", NULL); if (i) *(cmdline_pos++) = ' '; strcpy(cmdline_pos, a); cmdline_pos += strlen(cmdline_pos); } *(++cmdline_pos) = 0; /* Add required second terminator */ cmdline_pos = strchr(cmdline, ' '); if (cmdline_pos) { *cmdline_pos = 0; cmdline_pos++; } /* Create environment block from list of envariables */ if (env) { for (env_len=1, e=0; env[e]; e++) env_len += strlen(env[e]) + 1; env_block = apr_palloc(pool, env_len); env_block_pos = env_block; for (e=0; env[e]; e++) { strcpy(env_block_pos, env[e]); env_block_pos += strlen(env_block_pos) + 1; } *env_block_pos = 0; /* environment block is terminated by a double null */ } else env_block = NULL; status = DosExecPgm(error_object, sizeof(error_object), attr->detached ? EXEC_BACKGROUND : EXEC_ASYNCRESULT, cmdline, env_block, &rescodes, cmdline); proc->pid = rescodes.codeTerminate; if (attr->currdir != NULL) { chdir(savedir); } if (attr->child_in) { apr_file_close(attr->child_in); dup = STDIN_FILENO; DosDupHandle(save_in, &dup); DosClose(save_in); } if (attr->child_out) { apr_file_close(attr->child_out); dup = STDOUT_FILENO; DosDupHandle(save_out, &dup); DosClose(save_out); } if (attr->child_err) { apr_file_close(attr->child_err); dup = STDERR_FILENO; DosDupHandle(save_err, &dup); DosClose(save_err); } if (criticalsection) DosExitCritSec(); proc->in = attr->parent_in; proc->err = attr->parent_err; proc->out = attr->parent_out; return status; } static void proces_result_codes(RESULTCODES codes, int *exitcode, apr_exit_why_e *exitwhy) { int result = 0; apr_exit_why_e why = APR_PROC_EXIT; switch (codes.codeTerminate) { case TC_EXIT: /* Normal exit */ why = APR_PROC_EXIT; result = codes.codeResult; break; case TC_HARDERROR: /* Hard error halt */ why = APR_PROC_SIGNAL; result = SIGSYS; break; case TC_KILLPROCESS: /* Was killed by a DosKillProcess() */ why = APR_PROC_SIGNAL; result = SIGKILL; break; case TC_TRAP: /* TRAP in 16 bit code */ case TC_EXCEPTION: /* Threw an exception (32 bit code) */ why = APR_PROC_SIGNAL; switch (codes.codeResult | XCPT_FATAL_EXCEPTION) { case XCPT_ACCESS_VIOLATION: result = SIGSEGV; break; case XCPT_ILLEGAL_INSTRUCTION: result = SIGILL; break; case XCPT_FLOAT_DIVIDE_BY_ZERO: case XCPT_INTEGER_DIVIDE_BY_ZERO: result = SIGFPE; break; default: result = codes.codeResult; break; } } if (exitcode) { *exitcode = result; } if (exitwhy) { *exitwhy = why; } } APR_DECLARE(apr_status_t) apr_proc_wait_all_procs(apr_proc_t *proc, int *exitcode, apr_exit_why_e *exitwhy, apr_wait_how_e waithow, apr_pool_t *p) { RESULTCODES codes; ULONG rc; PID pid; rc = DosWaitChild(DCWA_PROCESSTREE, waithow == APR_WAIT ? DCWW_WAIT : DCWW_NOWAIT, &codes, &pid, 0); if (rc == 0) { proc->pid = pid; proces_result_codes(codes, exitcode, exitwhy); return APR_CHILD_DONE; } else if (rc == ERROR_CHILD_NOT_COMPLETE) { return APR_CHILD_NOTDONE; } return APR_OS2_STATUS(rc); } APR_DECLARE(apr_status_t) apr_proc_wait(apr_proc_t *proc, int *exitcode, apr_exit_why_e *exitwhy, apr_wait_how_e waithow) { RESULTCODES codes; ULONG rc; PID pid; rc = DosWaitChild(DCWA_PROCESS, waithow == APR_WAIT ? DCWW_WAIT : DCWW_NOWAIT, &codes, &pid, proc->pid); if (rc == 0) { proces_result_codes(codes, exitcode, exitwhy); return APR_CHILD_DONE; } else if (rc == ERROR_CHILD_NOT_COMPLETE) { return APR_CHILD_NOTDONE; } return APR_OS2_STATUS(rc); } APR_DECLARE(apr_status_t) apr_proc_detach(int daemonize) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_procattr_user_set(apr_procattr_t *attr, const char *username, const char *password) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_procattr_group_set(apr_procattr_t *attr, const char *groupname) { return APR_ENOTIMPL; }
001-log4cxx
trunk/src/apr/threadproc/os2/proc.c
C
asf20
17,953
/* 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 #define INCL_DOS #include "apr_arch_threadproc.h" #include "apr_thread_proc.h" #include "apr_general.h" #include "apr_lib.h" #include "apr_portable.h" #include "apr_arch_file_io.h" #include <stdlib.h> APR_DECLARE(apr_status_t) apr_threadattr_create(apr_threadattr_t **new, apr_pool_t *pool) { (*new) = (apr_threadattr_t *)apr_palloc(pool, sizeof(apr_threadattr_t)); if ((*new) == NULL) { return APR_ENOMEM; } (*new)->pool = pool; (*new)->attr = 0; (*new)->stacksize = 0; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_threadattr_detach_set(apr_threadattr_t *attr, apr_int32_t on) { attr->attr |= APR_THREADATTR_DETACHED; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_threadattr_detach_get(apr_threadattr_t *attr) { return (attr->attr & APR_THREADATTR_DETACHED) ? APR_DETACH : APR_NOTDETACH; } APR_DECLARE(apr_status_t) apr_threadattr_stacksize_set(apr_threadattr_t *attr, apr_size_t stacksize) { attr->stacksize = stacksize; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_threadattr_guardsize_set(apr_threadattr_t *attr, apr_size_t size) { return APR_ENOTIMPL; } static void apr_thread_begin(void *arg) { apr_thread_t *thread = (apr_thread_t *)arg; thread->exitval = thread->func(thread, thread->data); } APR_DECLARE(apr_status_t) apr_thread_create(apr_thread_t **new, apr_threadattr_t *attr, apr_thread_start_t func, void *data, apr_pool_t *pool) { apr_status_t stat; apr_thread_t *thread; thread = (apr_thread_t *)apr_palloc(pool, sizeof(apr_thread_t)); *new = thread; if (thread == NULL) { return APR_ENOMEM; } thread->pool = pool; thread->attr = attr; thread->func = func; thread->data = data; stat = apr_pool_create(&thread->pool, pool); if (stat != APR_SUCCESS) { return stat; } if (attr == NULL) { stat = apr_threadattr_create(&thread->attr, thread->pool); if (stat != APR_SUCCESS) { return stat; } } thread->tid = _beginthread(apr_thread_begin, NULL, thread->attr->stacksize > 0 ? thread->attr->stacksize : APR_THREAD_STACKSIZE, thread); if (thread->tid < 0) { return errno; } return APR_SUCCESS; } APR_DECLARE(apr_os_thread_t) apr_os_thread_current() { PIB *ppib; TIB *ptib; DosGetInfoBlocks(&ptib, &ppib); return ptib->tib_ptib2->tib2_ultid; } APR_DECLARE(apr_status_t) apr_thread_exit(apr_thread_t *thd, apr_status_t retval) { thd->exitval = retval; _endthread(); return -1; /* If we get here something's wrong */ } APR_DECLARE(apr_status_t) apr_thread_join(apr_status_t *retval, apr_thread_t *thd) { ULONG rc; TID waittid = thd->tid; if (thd->attr->attr & APR_THREADATTR_DETACHED) return APR_EINVAL; rc = DosWaitThread(&waittid, DCWW_WAIT); if (rc == ERROR_INVALID_THREADID) rc = 0; /* Thread had already terminated */ *retval = thd->exitval; return APR_OS2_STATUS(rc); } APR_DECLARE(apr_status_t) apr_thread_detach(apr_thread_t *thd) { thd->attr->attr |= APR_THREADATTR_DETACHED; return APR_SUCCESS; } void apr_thread_yield() { DosSleep(0); } APR_DECLARE(apr_status_t) apr_os_thread_get(apr_os_thread_t **thethd, apr_thread_t *thd) { *thethd = &thd->tid; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_thread_put(apr_thread_t **thd, apr_os_thread_t *thethd, apr_pool_t *pool) { if ((*thd) == NULL) { (*thd) = (apr_thread_t *)apr_pcalloc(pool, sizeof(apr_thread_t)); (*thd)->pool = pool; } (*thd)->tid = *thethd; return APR_SUCCESS; } int apr_os_thread_equal(apr_os_thread_t tid1, apr_os_thread_t tid2) { return tid1 == tid2; } APR_DECLARE(apr_status_t) apr_thread_data_get(void **data, const char *key, apr_thread_t *thread) { return apr_pool_userdata_get(data, key, thread->pool); } APR_DECLARE(apr_status_t) apr_thread_data_set(void *data, const char *key, apr_status_t (*cleanup) (void *), apr_thread_t *thread) { return apr_pool_userdata_set(data, key, cleanup, thread->pool); } APR_POOL_IMPLEMENT_ACCESSOR(thread) static apr_status_t thread_once_cleanup(void *vcontrol) { apr_thread_once_t *control = (apr_thread_once_t *)vcontrol; if (control->sem) { DosCloseEventSem(control->sem); } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_thread_once_init(apr_thread_once_t **control, apr_pool_t *p) { ULONG rc; *control = (apr_thread_once_t *)apr_pcalloc(p, sizeof(apr_thread_once_t)); rc = DosCreateEventSem(NULL, &(*control)->sem, 0, TRUE); apr_pool_cleanup_register(p, control, thread_once_cleanup, apr_pool_cleanup_null); return APR_FROM_OS_ERROR(rc); } APR_DECLARE(apr_status_t) apr_thread_once(apr_thread_once_t *control, void (*func)(void)) { if (!control->hit) { ULONG count, rc; rc = DosResetEventSem(control->sem, &count); if (rc == 0 && count) { control->hit = 1; func(); } } return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/threadproc/os2/thread.c
C
asf20
6,436
/* 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_threadproc.h" #include "apr_thread_proc.h" #include "apr_portable.h" #include "apr_general.h" #include "apr_errno.h" #include "apr_lib.h" #include "apr_arch_file_io.h" APR_DECLARE(apr_status_t) apr_threadkey_private_create(apr_threadkey_t **key, void (*dest)(void *), apr_pool_t *pool) { (*key) = (apr_threadkey_t *)apr_palloc(pool, sizeof(apr_threadkey_t)); if ((*key) == NULL) { return APR_ENOMEM; } (*key)->pool = pool; return APR_OS2_STATUS(DosAllocThreadLocalMemory(1, &((*key)->key))); } APR_DECLARE(apr_status_t) apr_threadkey_private_get(void **new, apr_threadkey_t *key) { (*new) = (void *)*(key->key); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_threadkey_private_set(void *priv, apr_threadkey_t *key) { *(key->key) = (ULONG)priv; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_threadkey_private_delete(apr_threadkey_t *key) { return APR_OS2_STATUS(DosFreeThreadLocalMemory(key->key)); } APR_DECLARE(apr_status_t) apr_threadkey_data_get(void **data, const char *key, apr_threadkey_t *threadkey) { return apr_pool_userdata_get(data, key, threadkey->pool); } APR_DECLARE(apr_status_t) apr_threadkey_data_set(void *data, const char *key, apr_status_t (*cleanup) (void *), apr_threadkey_t *threadkey) { return apr_pool_userdata_set(data, key, cleanup, threadkey->pool); } APR_DECLARE(apr_status_t) apr_os_threadkey_get(apr_os_threadkey_t *thekey, apr_threadkey_t *key) { *thekey = key->key; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_threadkey_put(apr_threadkey_t **key, apr_os_threadkey_t *thekey, apr_pool_t *pool) { if (pool == NULL) { return APR_ENOPOOL; } if ((*key) == NULL) { (*key) = (apr_threadkey_t *)apr_pcalloc(pool, sizeof(apr_threadkey_t)); (*key)->pool = pool; } (*key)->key = *thekey; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/threadproc/os2/threadpriv.c
C
asf20
3,060
#include "../unix/signals.c"
001-log4cxx
trunk/src/apr/threadproc/os2/signals.c
C
asf20
29
#include <apr.h> #include <apr_random.h> #include <apr_pools.h> #include "sha2.h" static void sha256_init(apr_crypto_hash_t *h) { apr__SHA256_Init(h->data); } static void sha256_add(apr_crypto_hash_t *h,const void *data, apr_size_t bytes) { apr__SHA256_Update(h->data,data,bytes); } static void sha256_finish(apr_crypto_hash_t *h,unsigned char *result) { apr__SHA256_Final(result,h->data); } APR_DECLARE(apr_crypto_hash_t *) apr_crypto_sha256_new(apr_pool_t *p) { apr_crypto_hash_t *h=apr_palloc(p,sizeof *h); h->data=apr_palloc(p,sizeof(SHA256_CTX)); h->init=sha256_init; h->add=sha256_add; h->finish=sha256_finish; h->size=256/8; return h; }
001-log4cxx
trunk/src/apr/random/unix/sha2_glue.c
C
asf20
727
/* 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. */ /* * FILE: sha2.h * AUTHOR: Aaron D. Gifford <me@aarongifford.com> * * A licence was granted to the ASF by Aaron on 4 November 2003. */ #ifndef __SHA2_H__ #define __SHA2_H__ #ifdef __cplusplus extern "C" { #endif #include "apr.h" /*** SHA-256/384/512 Various Length Definitions ***********************/ #define SHA256_BLOCK_LENGTH 64 #define SHA256_DIGEST_LENGTH 32 #define SHA256_DIGEST_STRING_LENGTH (SHA256_DIGEST_LENGTH * 2 + 1) #define SHA384_BLOCK_LENGTH 128 #define SHA384_DIGEST_LENGTH 48 #define SHA384_DIGEST_STRING_LENGTH (SHA384_DIGEST_LENGTH * 2 + 1) #define SHA512_BLOCK_LENGTH 128 #define SHA512_DIGEST_LENGTH 64 #define SHA512_DIGEST_STRING_LENGTH (SHA512_DIGEST_LENGTH * 2 + 1) /*** SHA-256/384/512 Context Structures *******************************/ typedef struct _SHA256_CTX { apr_uint32_t state[8]; apr_uint64_t bitcount; apr_byte_t buffer[SHA256_BLOCK_LENGTH]; } SHA256_CTX; typedef struct _SHA512_CTX { apr_uint64_t state[8]; apr_uint64_t bitcount[2]; apr_byte_t buffer[SHA512_BLOCK_LENGTH]; } SHA512_CTX; typedef SHA512_CTX SHA384_CTX; /*** SHA-256/384/512 Function Prototypes ******************************/ void apr__SHA256_Init(SHA256_CTX *); void apr__SHA256_Update(SHA256_CTX *, const apr_byte_t *, size_t); void apr__SHA256_Final(apr_byte_t [SHA256_DIGEST_LENGTH], SHA256_CTX *); char* apr__SHA256_End(SHA256_CTX *, char [SHA256_DIGEST_STRING_LENGTH]); char* apr__SHA256_Data(const apr_byte_t *, size_t, char [SHA256_DIGEST_STRING_LENGTH]); void apr__SHA384_Init(SHA384_CTX *); void apr__SHA384_Update(SHA384_CTX *, const apr_byte_t *, size_t); void apr__SHA384_Final(apr_byte_t [SHA384_DIGEST_LENGTH], SHA384_CTX *); char* apr__SHA384_End(SHA384_CTX *, char [SHA384_DIGEST_STRING_LENGTH]); char* apr__SHA384_Data(const apr_byte_t *, size_t, char [SHA384_DIGEST_STRING_LENGTH]); void apr__SHA512_Init(SHA512_CTX *); void apr__SHA512_Update(SHA512_CTX *, const apr_byte_t *, size_t); void apr__SHA512_Final(apr_byte_t [SHA512_DIGEST_LENGTH], SHA512_CTX *); char* apr__SHA512_End(SHA512_CTX *, char [SHA512_DIGEST_STRING_LENGTH]); char* apr__SHA512_Data(const apr_byte_t *, size_t, char [SHA512_DIGEST_STRING_LENGTH]); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __SHA2_H__ */
001-log4cxx
trunk/src/apr/random/unix/sha2.h
C
asf20
3,254
/* 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. */ /* * FILE: sha2.c * AUTHOR: Aaron D. Gifford <me@aarongifford.com> * * A licence was granted to the ASF by Aaron on 4 November 2003. */ #include <string.h> /* memcpy()/memset() or bcopy()/bzero() */ #include <assert.h> /* assert() */ #include "sha2.h" /* * ASSERT NOTE: * Some sanity checking code is included using assert(). On my FreeBSD * system, this additional code can be removed by compiling with NDEBUG * defined. Check your own systems manpage on assert() to see how to * compile WITHOUT the sanity checking code on your system. * * UNROLLED TRANSFORM LOOP NOTE: * You can define SHA2_UNROLL_TRANSFORM to use the unrolled transform * loop version for the hash transform rounds (defined using macros * later in this file). Either define on the command line, for example: * * cc -DSHA2_UNROLL_TRANSFORM -o sha2 sha2.c sha2prog.c * * or define below: * * #define SHA2_UNROLL_TRANSFORM * */ /*** SHA-256/384/512 Machine Architecture Definitions *****************/ typedef apr_byte_t sha2_byte; /* Exactly 1 byte */ typedef apr_uint32_t sha2_word32; /* Exactly 4 bytes */ typedef apr_uint64_t sha2_word64; /* Exactly 8 bytes */ /*** SHA-256/384/512 Various Length Definitions ***********************/ /* NOTE: Most of these are in sha2.h */ #define SHA256_SHORT_BLOCK_LENGTH (SHA256_BLOCK_LENGTH - 8) #define SHA384_SHORT_BLOCK_LENGTH (SHA384_BLOCK_LENGTH - 16) #define SHA512_SHORT_BLOCK_LENGTH (SHA512_BLOCK_LENGTH - 16) /*** ENDIAN REVERSAL MACROS *******************************************/ #if !APR_IS_BIGENDIAN #define REVERSE32(w,x) { \ sha2_word32 tmp = (w); \ tmp = (tmp >> 16) | (tmp << 16); \ (x) = ((tmp & 0xff00ff00UL) >> 8) | ((tmp & 0x00ff00ffUL) << 8); \ } #define REVERSE64(w,x) { \ sha2_word64 tmp = (w); \ tmp = (tmp >> 32) | (tmp << 32); \ tmp = ((tmp & APR_UINT64_C(0xff00ff00ff00ff00)) >> 8) | \ ((tmp & APR_UINT64_C(0x00ff00ff00ff00ff)) << 8); \ (x) = ((tmp & APR_UINT64_C(0xffff0000ffff0000)) >> 16) | \ ((tmp & APR_UINT64_C(0x0000ffff0000ffff)) << 16); \ } #endif /* !APR_IS_BIGENDIAN */ /* * Macro for incrementally adding the unsigned 64-bit integer n to the * unsigned 128-bit integer (represented using a two-element array of * 64-bit words): */ #define ADDINC128(w,n) { \ (w)[0] += (sha2_word64)(n); \ if ((w)[0] < (n)) { \ (w)[1]++; \ } \ } /* * Macros for copying blocks of memory and for zeroing out ranges * of memory. Using these macros makes it easy to switch from * using memset()/memcpy() and using bzero()/bcopy(). * * Please define either SHA2_USE_MEMSET_MEMCPY or define * SHA2_USE_BZERO_BCOPY depending on which function set you * choose to use: */ #if !defined(SHA2_USE_MEMSET_MEMCPY) && !defined(SHA2_USE_BZERO_BCOPY) /* Default to memset()/memcpy() if no option is specified */ #define SHA2_USE_MEMSET_MEMCPY 1 #endif #if defined(SHA2_USE_MEMSET_MEMCPY) && defined(SHA2_USE_BZERO_BCOPY) /* Abort with an error if BOTH options are defined */ #error Define either SHA2_USE_MEMSET_MEMCPY or SHA2_USE_BZERO_BCOPY, not both! #endif #ifdef SHA2_USE_MEMSET_MEMCPY #define MEMSET_BZERO(p,l) memset((p), 0, (l)) #define MEMCPY_BCOPY(d,s,l) memcpy((d), (s), (l)) #endif #ifdef SHA2_USE_BZERO_BCOPY #define MEMSET_BZERO(p,l) bzero((p), (l)) #define MEMCPY_BCOPY(d,s,l) bcopy((s), (d), (l)) #endif /*** THE SIX LOGICAL FUNCTIONS ****************************************/ /* * Bit shifting and rotation (used by the six SHA-XYZ logical functions: * * NOTE: The naming of R and S appears backwards here (R is a SHIFT and * S is a ROTATION) because the SHA-256/384/512 description document * (see http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf) uses this * same "backwards" definition. */ /* Shift-right (used in SHA-256, SHA-384, and SHA-512): */ #define R(b,x) ((x) >> (b)) /* 32-bit Rotate-right (used in SHA-256): */ #define S32(b,x) (((x) >> (b)) | ((x) << (32 - (b)))) /* 64-bit Rotate-right (used in SHA-384 and SHA-512): */ #define S64(b,x) (((x) >> (b)) | ((x) << (64 - (b)))) /* Two of six logical functions used in SHA-256, SHA-384, and SHA-512: */ #define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z))) #define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) /* Four of six logical functions used in SHA-256: */ #define Sigma0_256(x) (S32(2, (x)) ^ S32(13, (x)) ^ S32(22, (x))) #define Sigma1_256(x) (S32(6, (x)) ^ S32(11, (x)) ^ S32(25, (x))) #define sigma0_256(x) (S32(7, (x)) ^ S32(18, (x)) ^ R(3 , (x))) #define sigma1_256(x) (S32(17, (x)) ^ S32(19, (x)) ^ R(10, (x))) /* Four of six logical functions used in SHA-384 and SHA-512: */ #define Sigma0_512(x) (S64(28, (x)) ^ S64(34, (x)) ^ S64(39, (x))) #define Sigma1_512(x) (S64(14, (x)) ^ S64(18, (x)) ^ S64(41, (x))) #define sigma0_512(x) (S64( 1, (x)) ^ S64( 8, (x)) ^ R( 7, (x))) #define sigma1_512(x) (S64(19, (x)) ^ S64(61, (x)) ^ R( 6, (x))) /*** INTERNAL FUNCTION PROTOTYPES *************************************/ /* NOTE: These should not be accessed directly from outside this * library -- they are intended for private internal visibility/use * only. */ void apr__SHA512_Last(SHA512_CTX*); void apr__SHA256_Transform(SHA256_CTX*, const sha2_word32*); void apr__SHA512_Transform(SHA512_CTX*, const sha2_word64*); /*** SHA-XYZ INITIAL HASH VALUES AND CONSTANTS ************************/ /* Hash constant words K for SHA-256: */ const static sha2_word32 K256[64] = { 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL }; /* Initial hash value H for SHA-256: */ const static sha2_word32 sha256_initial_hash_value[8] = { 0x6a09e667UL, 0xbb67ae85UL, 0x3c6ef372UL, 0xa54ff53aUL, 0x510e527fUL, 0x9b05688cUL, 0x1f83d9abUL, 0x5be0cd19UL }; /* Hash constant words K for SHA-384 and SHA-512: */ const static sha2_word64 K512[80] = { APR_UINT64_C(0x428a2f98d728ae22), APR_UINT64_C(0x7137449123ef65cd), APR_UINT64_C(0xb5c0fbcfec4d3b2f), APR_UINT64_C(0xe9b5dba58189dbbc), APR_UINT64_C(0x3956c25bf348b538), APR_UINT64_C(0x59f111f1b605d019), APR_UINT64_C(0x923f82a4af194f9b), APR_UINT64_C(0xab1c5ed5da6d8118), APR_UINT64_C(0xd807aa98a3030242), APR_UINT64_C(0x12835b0145706fbe), APR_UINT64_C(0x243185be4ee4b28c), APR_UINT64_C(0x550c7dc3d5ffb4e2), APR_UINT64_C(0x72be5d74f27b896f), APR_UINT64_C(0x80deb1fe3b1696b1), APR_UINT64_C(0x9bdc06a725c71235), APR_UINT64_C(0xc19bf174cf692694), APR_UINT64_C(0xe49b69c19ef14ad2), APR_UINT64_C(0xefbe4786384f25e3), APR_UINT64_C(0x0fc19dc68b8cd5b5), APR_UINT64_C(0x240ca1cc77ac9c65), APR_UINT64_C(0x2de92c6f592b0275), APR_UINT64_C(0x4a7484aa6ea6e483), APR_UINT64_C(0x5cb0a9dcbd41fbd4), APR_UINT64_C(0x76f988da831153b5), APR_UINT64_C(0x983e5152ee66dfab), APR_UINT64_C(0xa831c66d2db43210), APR_UINT64_C(0xb00327c898fb213f), APR_UINT64_C(0xbf597fc7beef0ee4), APR_UINT64_C(0xc6e00bf33da88fc2), APR_UINT64_C(0xd5a79147930aa725), APR_UINT64_C(0x06ca6351e003826f), APR_UINT64_C(0x142929670a0e6e70), APR_UINT64_C(0x27b70a8546d22ffc), APR_UINT64_C(0x2e1b21385c26c926), APR_UINT64_C(0x4d2c6dfc5ac42aed), APR_UINT64_C(0x53380d139d95b3df), APR_UINT64_C(0x650a73548baf63de), APR_UINT64_C(0x766a0abb3c77b2a8), APR_UINT64_C(0x81c2c92e47edaee6), APR_UINT64_C(0x92722c851482353b), APR_UINT64_C(0xa2bfe8a14cf10364), APR_UINT64_C(0xa81a664bbc423001), APR_UINT64_C(0xc24b8b70d0f89791), APR_UINT64_C(0xc76c51a30654be30), APR_UINT64_C(0xd192e819d6ef5218), APR_UINT64_C(0xd69906245565a910), APR_UINT64_C(0xf40e35855771202a), APR_UINT64_C(0x106aa07032bbd1b8), APR_UINT64_C(0x19a4c116b8d2d0c8), APR_UINT64_C(0x1e376c085141ab53), APR_UINT64_C(0x2748774cdf8eeb99), APR_UINT64_C(0x34b0bcb5e19b48a8), APR_UINT64_C(0x391c0cb3c5c95a63), APR_UINT64_C(0x4ed8aa4ae3418acb), APR_UINT64_C(0x5b9cca4f7763e373), APR_UINT64_C(0x682e6ff3d6b2b8a3), APR_UINT64_C(0x748f82ee5defb2fc), APR_UINT64_C(0x78a5636f43172f60), APR_UINT64_C(0x84c87814a1f0ab72), APR_UINT64_C(0x8cc702081a6439ec), APR_UINT64_C(0x90befffa23631e28), APR_UINT64_C(0xa4506cebde82bde9), APR_UINT64_C(0xbef9a3f7b2c67915), APR_UINT64_C(0xc67178f2e372532b), APR_UINT64_C(0xca273eceea26619c), APR_UINT64_C(0xd186b8c721c0c207), APR_UINT64_C(0xeada7dd6cde0eb1e), APR_UINT64_C(0xf57d4f7fee6ed178), APR_UINT64_C(0x06f067aa72176fba), APR_UINT64_C(0x0a637dc5a2c898a6), APR_UINT64_C(0x113f9804bef90dae), APR_UINT64_C(0x1b710b35131c471b), APR_UINT64_C(0x28db77f523047d84), APR_UINT64_C(0x32caab7b40c72493), APR_UINT64_C(0x3c9ebe0a15c9bebc), APR_UINT64_C(0x431d67c49c100d4c), APR_UINT64_C(0x4cc5d4becb3e42b6), APR_UINT64_C(0x597f299cfc657e2a), APR_UINT64_C(0x5fcb6fab3ad6faec), APR_UINT64_C(0x6c44198c4a475817) }; /* Initial hash value H for SHA-384 */ const static sha2_word64 sha384_initial_hash_value[8] = { APR_UINT64_C(0xcbbb9d5dc1059ed8), APR_UINT64_C(0x629a292a367cd507), APR_UINT64_C(0x9159015a3070dd17), APR_UINT64_C(0x152fecd8f70e5939), APR_UINT64_C(0x67332667ffc00b31), APR_UINT64_C(0x8eb44a8768581511), APR_UINT64_C(0xdb0c2e0d64f98fa7), APR_UINT64_C(0x47b5481dbefa4fa4) }; /* Initial hash value H for SHA-512 */ const static sha2_word64 sha512_initial_hash_value[8] = { APR_UINT64_C(0x6a09e667f3bcc908), APR_UINT64_C(0xbb67ae8584caa73b), APR_UINT64_C(0x3c6ef372fe94f82b), APR_UINT64_C(0xa54ff53a5f1d36f1), APR_UINT64_C(0x510e527fade682d1), APR_UINT64_C(0x9b05688c2b3e6c1f), APR_UINT64_C(0x1f83d9abfb41bd6b), APR_UINT64_C(0x5be0cd19137e2179) }; /* * Constant used by SHA256/384/512_End() functions for converting the * digest to a readable hexadecimal character string: */ static const char *sha2_hex_digits = "0123456789abcdef"; /*** SHA-256: *********************************************************/ void apr__SHA256_Init(SHA256_CTX* context) { if (context == (SHA256_CTX*)0) { return; } MEMCPY_BCOPY(context->state, sha256_initial_hash_value, SHA256_DIGEST_LENGTH); MEMSET_BZERO(context->buffer, SHA256_BLOCK_LENGTH); context->bitcount = 0; } #ifdef SHA2_UNROLL_TRANSFORM /* Unrolled SHA-256 round macros: */ #if !APR_IS_BIGENDIAN #define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \ REVERSE32(*data++, W256[j]); \ T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \ K256[j] + W256[j]; \ (d) += T1; \ (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ j++ #else /* APR_IS_BIGENDIAN */ #define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \ T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \ K256[j] + (W256[j] = *data++); \ (d) += T1; \ (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ j++ #endif /* APR_IS_BIGENDIAN */ #define ROUND256(a,b,c,d,e,f,g,h) \ s0 = W256[(j+1)&0x0f]; \ s0 = sigma0_256(s0); \ s1 = W256[(j+14)&0x0f]; \ s1 = sigma1_256(s1); \ T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] + \ (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); \ (d) += T1; \ (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ j++ void apr__SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) { sha2_word32 a, b, c, d, e, f, g, h, s0, s1; sha2_word32 T1, *W256; int j; W256 = (sha2_word32*)context->buffer; /* Initialize registers with the prev. intermediate value */ a = context->state[0]; b = context->state[1]; c = context->state[2]; d = context->state[3]; e = context->state[4]; f = context->state[5]; g = context->state[6]; h = context->state[7]; j = 0; do { /* Rounds 0 to 15 (unrolled): */ ROUND256_0_TO_15(a,b,c,d,e,f,g,h); ROUND256_0_TO_15(h,a,b,c,d,e,f,g); ROUND256_0_TO_15(g,h,a,b,c,d,e,f); ROUND256_0_TO_15(f,g,h,a,b,c,d,e); ROUND256_0_TO_15(e,f,g,h,a,b,c,d); ROUND256_0_TO_15(d,e,f,g,h,a,b,c); ROUND256_0_TO_15(c,d,e,f,g,h,a,b); ROUND256_0_TO_15(b,c,d,e,f,g,h,a); } while (j < 16); /* Now for the remaining rounds to 64: */ do { ROUND256(a,b,c,d,e,f,g,h); ROUND256(h,a,b,c,d,e,f,g); ROUND256(g,h,a,b,c,d,e,f); ROUND256(f,g,h,a,b,c,d,e); ROUND256(e,f,g,h,a,b,c,d); ROUND256(d,e,f,g,h,a,b,c); ROUND256(c,d,e,f,g,h,a,b); ROUND256(b,c,d,e,f,g,h,a); } while (j < 64); /* Compute the current intermediate hash value */ context->state[0] += a; context->state[1] += b; context->state[2] += c; context->state[3] += d; context->state[4] += e; context->state[5] += f; context->state[6] += g; context->state[7] += h; /* Clean up */ a = b = c = d = e = f = g = h = T1 = 0; } #else /* SHA2_UNROLL_TRANSFORM */ void apr__SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) { sha2_word32 a, b, c, d, e, f, g, h, s0, s1; sha2_word32 T1, T2, *W256; int j; W256 = (sha2_word32*)context->buffer; /* Initialize registers with the prev. intermediate value */ a = context->state[0]; b = context->state[1]; c = context->state[2]; d = context->state[3]; e = context->state[4]; f = context->state[5]; g = context->state[6]; h = context->state[7]; j = 0; do { #if !APR_IS_BIGENDIAN /* Copy data while converting to host byte order */ REVERSE32(*data++,W256[j]); /* Apply the SHA-256 compression function to update a..h */ T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j]; #else /* APR_IS_BIGENDIAN */ /* Apply the SHA-256 compression function to update a..h with copy */ T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j] = *data++); #endif /* APR_IS_BIGENDIAN */ T2 = Sigma0_256(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; j++; } while (j < 16); do { /* Part of the message block expansion: */ s0 = W256[(j+1)&0x0f]; s0 = sigma0_256(s0); s1 = W256[(j+14)&0x0f]; s1 = sigma1_256(s1); /* Apply the SHA-256 compression function to update a..h */ T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); T2 = Sigma0_256(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; j++; } while (j < 64); /* Compute the current intermediate hash value */ context->state[0] += a; context->state[1] += b; context->state[2] += c; context->state[3] += d; context->state[4] += e; context->state[5] += f; context->state[6] += g; context->state[7] += h; /* Clean up */ a = b = c = d = e = f = g = h = T1 = T2 = 0; } #endif /* SHA2_UNROLL_TRANSFORM */ void apr__SHA256_Update(SHA256_CTX* context, const sha2_byte *data, size_t len) { unsigned int freespace, usedspace; if (len == 0) { /* Calling with no data is valid - we do nothing */ return; } /* Sanity check: */ assert(context != (SHA256_CTX*)0 && data != (sha2_byte*)0); usedspace = (unsigned int)((context->bitcount >> 3) % SHA256_BLOCK_LENGTH); if (usedspace > 0) { /* Calculate how much free space is available in the buffer */ freespace = SHA256_BLOCK_LENGTH - usedspace; if (len >= freespace) { /* Fill the buffer completely and process it */ MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace); context->bitcount += freespace << 3; len -= freespace; data += freespace; apr__SHA256_Transform(context, (sha2_word32*)context->buffer); } else { /* The buffer is not yet full */ MEMCPY_BCOPY(&context->buffer[usedspace], data, len); context->bitcount += len << 3; /* Clean up: */ usedspace = freespace = 0; return; } } while (len >= SHA256_BLOCK_LENGTH) { /* Process as many complete blocks as we can */ apr__SHA256_Transform(context, (sha2_word32*)data); context->bitcount += SHA256_BLOCK_LENGTH << 3; len -= SHA256_BLOCK_LENGTH; data += SHA256_BLOCK_LENGTH; } if (len > 0) { /* There's left-overs, so save 'em */ MEMCPY_BCOPY(context->buffer, data, len); context->bitcount += len << 3; } /* Clean up: */ usedspace = freespace = 0; } void apr__SHA256_Final(sha2_byte digest[], SHA256_CTX* context) { sha2_word32 *d = (sha2_word32*)digest; unsigned int usedspace; /* Sanity check: */ assert(context != (SHA256_CTX*)0); /* If no digest buffer is passed, we don't bother doing this: */ if (digest != (sha2_byte*)0) { usedspace = (unsigned int)((context->bitcount >> 3) % SHA256_BLOCK_LENGTH); #if !APR_IS_BIGENDIAN /* Convert FROM host byte order */ REVERSE64(context->bitcount,context->bitcount); #endif if (usedspace > 0) { /* Begin padding with a 1 bit: */ context->buffer[usedspace++] = 0x80; if (usedspace <= SHA256_SHORT_BLOCK_LENGTH) { /* Set-up for the last transform: */ MEMSET_BZERO(&context->buffer[usedspace], SHA256_SHORT_BLOCK_LENGTH - usedspace); } else { if (usedspace < SHA256_BLOCK_LENGTH) { MEMSET_BZERO(&context->buffer[usedspace], SHA256_BLOCK_LENGTH - usedspace); } /* Do second-to-last transform: */ apr__SHA256_Transform(context, (sha2_word32*)context->buffer); /* And set-up for the last transform: */ MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH); } } else { /* Set-up for the last transform: */ MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH); /* Begin padding with a 1 bit: */ *context->buffer = 0x80; } /* Set the bit count: */ *(sha2_word64*)&context->buffer[SHA256_SHORT_BLOCK_LENGTH] = context->bitcount; /* Final transform: */ apr__SHA256_Transform(context, (sha2_word32*)context->buffer); #if !APR_IS_BIGENDIAN { /* Convert TO host byte order */ int j; for (j = 0; j < 8; j++) { REVERSE32(context->state[j],context->state[j]); *d++ = context->state[j]; } } #else MEMCPY_BCOPY(d, context->state, SHA256_DIGEST_LENGTH); #endif } /* Clean up state data: */ MEMSET_BZERO(context, sizeof(context)); usedspace = 0; } char *apr__SHA256_End(SHA256_CTX* context, char buffer[]) { sha2_byte digest[SHA256_DIGEST_LENGTH], *d = digest; int i; /* Sanity check: */ assert(context != (SHA256_CTX*)0); if (buffer != (char*)0) { apr__SHA256_Final(digest, context); for (i = 0; i < SHA256_DIGEST_LENGTH; i++) { *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; *buffer++ = sha2_hex_digits[*d & 0x0f]; d++; } *buffer = (char)0; } else { MEMSET_BZERO(context, sizeof(context)); } MEMSET_BZERO(digest, SHA256_DIGEST_LENGTH); return buffer; } char* apr__SHA256_Data(const sha2_byte* data, size_t len, char digest[SHA256_DIGEST_STRING_LENGTH]) { SHA256_CTX context; apr__SHA256_Init(&context); apr__SHA256_Update(&context, data, len); return apr__SHA256_End(&context, digest); } /*** SHA-512: *********************************************************/ void apr__SHA512_Init(SHA512_CTX* context) { if (context == (SHA512_CTX*)0) { return; } MEMCPY_BCOPY(context->state, sha512_initial_hash_value, SHA512_DIGEST_LENGTH); MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH); context->bitcount[0] = context->bitcount[1] = 0; } #ifdef SHA2_UNROLL_TRANSFORM /* Unrolled SHA-512 round macros: */ #if !APR_IS_BIGENDIAN #define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \ REVERSE64(*data++, W512[j]); \ T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \ K512[j] + W512[j]; \ (d) += T1, \ (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)), \ j++ #else /* APR_IS_BIGENDIAN */ #define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \ T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \ K512[j] + (W512[j] = *data++); \ (d) += T1; \ (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \ j++ #endif /* APR_IS_BIGENDIAN */ #define ROUND512(a,b,c,d,e,f,g,h) \ s0 = W512[(j+1)&0x0f]; \ s0 = sigma0_512(s0); \ s1 = W512[(j+14)&0x0f]; \ s1 = sigma1_512(s1); \ T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] + \ (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); \ (d) += T1; \ (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \ j++ void apr__SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) { sha2_word64 a, b, c, d, e, f, g, h, s0, s1; sha2_word64 T1, *W512 = (sha2_word64*)context->buffer; int j; /* Initialize registers with the prev. intermediate value */ a = context->state[0]; b = context->state[1]; c = context->state[2]; d = context->state[3]; e = context->state[4]; f = context->state[5]; g = context->state[6]; h = context->state[7]; j = 0; do { ROUND512_0_TO_15(a,b,c,d,e,f,g,h); ROUND512_0_TO_15(h,a,b,c,d,e,f,g); ROUND512_0_TO_15(g,h,a,b,c,d,e,f); ROUND512_0_TO_15(f,g,h,a,b,c,d,e); ROUND512_0_TO_15(e,f,g,h,a,b,c,d); ROUND512_0_TO_15(d,e,f,g,h,a,b,c); ROUND512_0_TO_15(c,d,e,f,g,h,a,b); ROUND512_0_TO_15(b,c,d,e,f,g,h,a); } while (j < 16); /* Now for the remaining rounds up to 79: */ do { ROUND512(a,b,c,d,e,f,g,h); ROUND512(h,a,b,c,d,e,f,g); ROUND512(g,h,a,b,c,d,e,f); ROUND512(f,g,h,a,b,c,d,e); ROUND512(e,f,g,h,a,b,c,d); ROUND512(d,e,f,g,h,a,b,c); ROUND512(c,d,e,f,g,h,a,b); ROUND512(b,c,d,e,f,g,h,a); } while (j < 80); /* Compute the current intermediate hash value */ context->state[0] += a; context->state[1] += b; context->state[2] += c; context->state[3] += d; context->state[4] += e; context->state[5] += f; context->state[6] += g; context->state[7] += h; /* Clean up */ a = b = c = d = e = f = g = h = T1 = 0; } #else /* SHA2_UNROLL_TRANSFORM */ void apr__SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) { sha2_word64 a, b, c, d, e, f, g, h, s0, s1; sha2_word64 T1, T2, *W512 = (sha2_word64*)context->buffer; int j; /* Initialize registers with the prev. intermediate value */ a = context->state[0]; b = context->state[1]; c = context->state[2]; d = context->state[3]; e = context->state[4]; f = context->state[5]; g = context->state[6]; h = context->state[7]; j = 0; do { #if !APR_IS_BIGENDIAN /* Convert TO host byte order */ REVERSE64(*data++, W512[j]); /* Apply the SHA-512 compression function to update a..h */ T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + W512[j]; #else /* APR_IS_BIGENDIAN */ /* Apply the SHA-512 compression function to update a..h with copy */ T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j] = *data++); #endif /* APR_IS_BIGENDIAN */ T2 = Sigma0_512(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; j++; } while (j < 16); do { /* Part of the message block expansion: */ s0 = W512[(j+1)&0x0f]; s0 = sigma0_512(s0); s1 = W512[(j+14)&0x0f]; s1 = sigma1_512(s1); /* Apply the SHA-512 compression function to update a..h */ T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); T2 = Sigma0_512(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; j++; } while (j < 80); /* Compute the current intermediate hash value */ context->state[0] += a; context->state[1] += b; context->state[2] += c; context->state[3] += d; context->state[4] += e; context->state[5] += f; context->state[6] += g; context->state[7] += h; /* Clean up */ a = b = c = d = e = f = g = h = T1 = T2 = 0; } #endif /* SHA2_UNROLL_TRANSFORM */ void apr__SHA512_Update(SHA512_CTX* context, const sha2_byte *data, size_t len) { unsigned int freespace, usedspace; if (len == 0) { /* Calling with no data is valid - we do nothing */ return; } /* Sanity check: */ assert(context != (SHA512_CTX*)0 && data != (sha2_byte*)0); usedspace = (unsigned int)((context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH); if (usedspace > 0) { /* Calculate how much free space is available in the buffer */ freespace = SHA512_BLOCK_LENGTH - usedspace; if (len >= freespace) { /* Fill the buffer completely and process it */ MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace); ADDINC128(context->bitcount, freespace << 3); len -= freespace; data += freespace; apr__SHA512_Transform(context, (sha2_word64*)context->buffer); } else { /* The buffer is not yet full */ MEMCPY_BCOPY(&context->buffer[usedspace], data, len); ADDINC128(context->bitcount, len << 3); /* Clean up: */ usedspace = freespace = 0; return; } } while (len >= SHA512_BLOCK_LENGTH) { /* Process as many complete blocks as we can */ apr__SHA512_Transform(context, (sha2_word64*)data); ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3); len -= SHA512_BLOCK_LENGTH; data += SHA512_BLOCK_LENGTH; } if (len > 0) { /* There's left-overs, so save 'em */ MEMCPY_BCOPY(context->buffer, data, len); ADDINC128(context->bitcount, len << 3); } /* Clean up: */ usedspace = freespace = 0; } void apr__SHA512_Last(SHA512_CTX* context) { unsigned int usedspace; usedspace = (unsigned int)((context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH); #if !APR_IS_BIGENDIAN /* Convert FROM host byte order */ REVERSE64(context->bitcount[0],context->bitcount[0]); REVERSE64(context->bitcount[1],context->bitcount[1]); #endif if (usedspace > 0) { /* Begin padding with a 1 bit: */ context->buffer[usedspace++] = 0x80; if (usedspace <= SHA512_SHORT_BLOCK_LENGTH) { /* Set-up for the last transform: */ MEMSET_BZERO(&context->buffer[usedspace], SHA512_SHORT_BLOCK_LENGTH - usedspace); } else { if (usedspace < SHA512_BLOCK_LENGTH) { MEMSET_BZERO(&context->buffer[usedspace], SHA512_BLOCK_LENGTH - usedspace); } /* Do second-to-last transform: */ apr__SHA512_Transform(context, (sha2_word64*)context->buffer); /* And set-up for the last transform: */ MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH - 2); } } else { /* Prepare for final transform: */ MEMSET_BZERO(context->buffer, SHA512_SHORT_BLOCK_LENGTH); /* Begin padding with a 1 bit: */ *context->buffer = 0x80; } /* Store the length of input data (in bits): */ *(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH] = context->bitcount[1]; *(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH+8] = context->bitcount[0]; /* Final transform: */ apr__SHA512_Transform(context, (sha2_word64*)context->buffer); } void apr__SHA512_Final(sha2_byte digest[], SHA512_CTX* context) { sha2_word64 *d = (sha2_word64*)digest; /* Sanity check: */ assert(context != (SHA512_CTX*)0); /* If no digest buffer is passed, we don't bother doing this: */ if (digest != (sha2_byte*)0) { apr__SHA512_Last(context); /* Save the hash data for output: */ #if !APR_IS_BIGENDIAN { /* Convert TO host byte order */ int j; for (j = 0; j < 8; j++) { REVERSE64(context->state[j],context->state[j]); *d++ = context->state[j]; } } #else /* APR_IS_BIGENDIAN */ MEMCPY_BCOPY(d, context->state, SHA512_DIGEST_LENGTH); #endif /* APR_IS_BIGENDIAN */ } /* Zero out state data */ MEMSET_BZERO(context, sizeof(context)); } char *apr__SHA512_End(SHA512_CTX* context, char buffer[]) { sha2_byte digest[SHA512_DIGEST_LENGTH], *d = digest; int i; /* Sanity check: */ assert(context != (SHA512_CTX*)0); if (buffer != (char*)0) { apr__SHA512_Final(digest, context); for (i = 0; i < SHA512_DIGEST_LENGTH; i++) { *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; *buffer++ = sha2_hex_digits[*d & 0x0f]; d++; } *buffer = (char)0; } else { MEMSET_BZERO(context, sizeof(context)); } MEMSET_BZERO(digest, SHA512_DIGEST_LENGTH); return buffer; } char* apr__SHA512_Data(const sha2_byte* data, size_t len, char digest[SHA512_DIGEST_STRING_LENGTH]) { SHA512_CTX context; apr__SHA512_Init(&context); apr__SHA512_Update(&context, data, len); return apr__SHA512_End(&context, digest); } /*** SHA-384: *********************************************************/ void apr__SHA384_Init(SHA384_CTX* context) { if (context == (SHA384_CTX*)0) { return; } MEMCPY_BCOPY(context->state, sha384_initial_hash_value, SHA512_DIGEST_LENGTH); MEMSET_BZERO(context->buffer, SHA384_BLOCK_LENGTH); context->bitcount[0] = context->bitcount[1] = 0; } void apr__SHA384_Update(SHA384_CTX* context, const sha2_byte* data, size_t len) { apr__SHA512_Update((SHA512_CTX*)context, data, len); } void apr__SHA384_Final(sha2_byte digest[], SHA384_CTX* context) { sha2_word64 *d = (sha2_word64*)digest; /* Sanity check: */ assert(context != (SHA384_CTX*)0); /* If no digest buffer is passed, we don't bother doing this: */ if (digest != (sha2_byte*)0) { apr__SHA512_Last((SHA512_CTX*)context); /* Save the hash data for output: */ #if !APR_IS_BIGENDIAN { /* Convert TO host byte order */ int j; for (j = 0; j < 6; j++) { REVERSE64(context->state[j],context->state[j]); *d++ = context->state[j]; } } #else /* APR_IS_BIGENDIAN */ MEMCPY_BCOPY(d, context->state, SHA384_DIGEST_LENGTH); #endif /* APR_IS_BIGENDIAN */ } /* Zero out state data */ MEMSET_BZERO(context, sizeof(context)); } char *apr__SHA384_End(SHA384_CTX* context, char buffer[]) { sha2_byte digest[SHA384_DIGEST_LENGTH], *d = digest; int i; /* Sanity check: */ assert(context != (SHA384_CTX*)0); if (buffer != (char*)0) { apr__SHA384_Final(digest, context); for (i = 0; i < SHA384_DIGEST_LENGTH; i++) { *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; *buffer++ = sha2_hex_digits[*d & 0x0f]; d++; } *buffer = (char)0; } else { MEMSET_BZERO(context, sizeof(context)); } MEMSET_BZERO(digest, SHA384_DIGEST_LENGTH); return buffer; } char* apr__SHA384_Data(const sha2_byte* data, size_t len, char digest[SHA384_DIGEST_STRING_LENGTH]) { SHA384_CTX context; apr__SHA384_Init(&context); apr__SHA384_Update(&context, data, len); return apr__SHA384_End(&context, digest); }
001-log4cxx
trunk/src/apr/random/unix/sha2.c
C
asf20
37,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. */ /* * See the paper "???" by Ben Laurie for an explanation of this PRNG. */ #include "apr.h" #include "apr_pools.h" #include "apr_random.h" #include "apr_thread_proc.h" #include <assert.h> #ifdef min #undef min #endif #define min(a,b) ((a) < (b) ? (a) : (b)) #define APR_RANDOM_DEFAULT_POOLS 32 #define APR_RANDOM_DEFAULT_REHASH_SIZE 1024 #define APR_RANDOM_DEFAULT_RESEED_SIZE 32 #define APR_RANDOM_DEFAULT_HASH_SECRET_SIZE 32 #define APR_RANDOM_DEFAULT_G_FOR_INSECURE 32 #define APR_RANDOM_DEFAULT_G_FOR_SECURE 320 typedef struct apr_random_pool_t { unsigned char *pool; unsigned int bytes; unsigned int pool_size; } apr_random_pool_t; #define hash_init(h) (h)->init(h) #define hash_add(h,b,n) (h)->add(h,b,n) #define hash_finish(h,r) (h)->finish(h,r) #define hash(h,r,b,n) hash_init(h),hash_add(h,b,n),hash_finish(h,r) #define crypt_setkey(c,k) (c)->set_key((c)->data,k) #define crypt_crypt(c,out,in) (c)->crypt((c)->date,out,in) struct apr_random_t { apr_pool_t *apr_pool; apr_crypto_hash_t *pool_hash; unsigned int npools; apr_random_pool_t *pools; unsigned int next_pool; unsigned int generation; apr_size_t rehash_size; apr_size_t reseed_size; apr_crypto_hash_t *key_hash; #define K_size(g) ((g)->key_hash->size) apr_crypto_hash_t *prng_hash; #define B_size(g) ((g)->prng_hash->size) unsigned char *H; unsigned char *H_waiting; #define H_size(g) (B_size(g)+K_size(g)) #define H_current(g) (((g)->insecure_started && !(g)->secure_started) \ ? (g)->H_waiting : (g)->H) unsigned char *randomness; apr_size_t random_bytes; unsigned int g_for_insecure; unsigned int g_for_secure; unsigned int secure_base; unsigned int insecure_started:1; unsigned int secure_started:1; apr_random_t *next; }; static apr_random_t *all_random; APR_DECLARE(void) apr_random_init(apr_random_t *g,apr_pool_t *p, apr_crypto_hash_t *pool_hash, apr_crypto_hash_t *key_hash, apr_crypto_hash_t *prng_hash) { unsigned int n; g->apr_pool = p; g->pool_hash = pool_hash; g->key_hash = key_hash; g->prng_hash = prng_hash; g->npools = APR_RANDOM_DEFAULT_POOLS; g->pools = apr_palloc(p,g->npools*sizeof *g->pools); for (n = 0; n < g->npools; ++n) { g->pools[n].bytes = g->pools[n].pool_size = 0; g->pools[n].pool = NULL; } g->next_pool = 0; g->generation = 0; g->rehash_size = APR_RANDOM_DEFAULT_REHASH_SIZE; /* Ensure that the rehash size is twice the size of the pool hasher */ g->rehash_size = ((g->rehash_size+2*g->pool_hash->size-1)/g->pool_hash->size /2)*g->pool_hash->size*2; g->reseed_size = APR_RANDOM_DEFAULT_RESEED_SIZE; g->H = apr_pcalloc(p,H_size(g)); g->H_waiting = apr_pcalloc(p,H_size(g)); g->randomness = apr_palloc(p,B_size(g)); g->random_bytes = 0; g->g_for_insecure = APR_RANDOM_DEFAULT_G_FOR_INSECURE; g->secure_base = 0; g->g_for_secure = APR_RANDOM_DEFAULT_G_FOR_SECURE; g->secure_started = g->insecure_started = 0; g->next = all_random; all_random = g; } static void mix_pid(apr_random_t *g,unsigned char *H,pid_t pid) { hash_init(g->key_hash); hash_add(g->key_hash,H,H_size(g)); hash_add(g->key_hash,&pid,sizeof pid); hash_finish(g->key_hash,H); } static void mixer(apr_random_t *g,pid_t pid) { unsigned char *H = H_current(g); /* mix the PID into the current H */ mix_pid(g,H,pid); /* if we are in waiting, then also mix into main H */ if (H != g->H) mix_pid(g,g->H,pid); /* change order of pool mixing for good measure - note that going backwards is much better than going forwards */ --g->generation; /* blow away any lingering randomness */ g->random_bytes = 0; } APR_DECLARE(void) apr_random_after_fork(apr_proc_t *proc) { apr_random_t *r; for (r = all_random; r; r = r->next) mixer(r,proc->pid); } APR_DECLARE(apr_random_t *) apr_random_standard_new(apr_pool_t *p) { apr_random_t *r = apr_palloc(p,sizeof *r); apr_random_init(r,p,apr_crypto_sha256_new(p),apr_crypto_sha256_new(p), apr_crypto_sha256_new(p)); return r; } static void rekey(apr_random_t *g) { unsigned int n; unsigned char *H = H_current(g); hash_init(g->key_hash); hash_add(g->key_hash,H,H_size(g)); for (n = 0 ; n < g->npools && (n == 0 || g->generation&(1 << (n-1))) ; ++n) { hash_add(g->key_hash,g->pools[n].pool,g->pools[n].bytes); g->pools[n].bytes = 0; } hash_finish(g->key_hash,H+B_size(g)); ++g->generation; if (!g->insecure_started && g->generation > g->g_for_insecure) { g->insecure_started = 1; if (!g->secure_started) { memcpy(g->H_waiting,g->H,H_size(g)); g->secure_base = g->generation; } } if (!g->secure_started && g->generation > g->secure_base+g->g_for_secure) { g->secure_started = 1; memcpy(g->H,g->H_waiting,H_size(g)); } } APR_DECLARE(void) apr_random_add_entropy(apr_random_t *g,const void *entropy_, apr_size_t bytes) { unsigned int n; const unsigned char *entropy = entropy_; for (n = 0; n < bytes; ++n) { apr_random_pool_t *p = &g->pools[g->next_pool]; if (++g->next_pool == g->npools) g->next_pool = 0; if (p->pool_size < p->bytes+1) { unsigned char *np = apr_palloc(g->apr_pool,(p->bytes+1)*2); memcpy(np,p->pool,p->bytes); p->pool = np; p->pool_size = (p->bytes+1)*2; } p->pool[p->bytes++] = entropy[n]; if (p->bytes == g->rehash_size) { unsigned int r; for (r = 0; r < p->bytes/2; r+=g->pool_hash->size) hash(g->pool_hash,p->pool+r,p->pool+r*2,g->pool_hash->size*2); p->bytes/=2; } assert(p->bytes < g->rehash_size); } if (g->pools[0].bytes >= g->reseed_size) rekey(g); } /* This will give g->B_size bytes of randomness */ static void apr_random_block(apr_random_t *g,unsigned char *random) { /* FIXME: in principle, these are different hashes */ hash(g->prng_hash,g->H,g->H,H_size(g)); hash(g->prng_hash,random,g->H,B_size(g)); } static void apr_random_bytes(apr_random_t *g,unsigned char *random, apr_size_t bytes) { apr_size_t n; for (n = 0; n < bytes; ) { int l; if (g->random_bytes == 0) { apr_random_block(g,g->randomness); g->random_bytes = B_size(g); } l = min(bytes-n,g->random_bytes); memcpy(&random[n],g->randomness+B_size(g)-g->random_bytes,l); g->random_bytes-=l; n+=l; } } APR_DECLARE(apr_status_t) apr_random_secure_bytes(apr_random_t *g, void *random, apr_size_t bytes) { if (!g->secure_started) return APR_ENOTENOUGHENTROPY; apr_random_bytes(g,random,bytes); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_random_insecure_bytes(apr_random_t *g, void *random, apr_size_t bytes) { if (!g->insecure_started) return APR_ENOTENOUGHENTROPY; apr_random_bytes(g,random,bytes); return APR_SUCCESS; } APR_DECLARE(void) apr_random_barrier(apr_random_t *g) { g->secure_started = 0; g->secure_base = g->generation; } APR_DECLARE(apr_status_t) apr_random_secure_ready(apr_random_t *r) { if (!r->secure_started) return APR_ENOTENOUGHENTROPY; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_random_insecure_ready(apr_random_t *r) { if (!r->insecure_started) return APR_ENOTENOUGHENTROPY; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/random/unix/apr_random.c
C
asf20
8,882
/* 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_general.h" #include "apr_errno.h" #include "apr_file_io.h" #include "apr_shm.h" #include "apr_arch_file_io.h" #include "limits.h" typedef struct memblock_t { apr_size_t size; apr_size_t length; } memblock_t; struct apr_shm_t { apr_pool_t *pool; memblock_t *memblk; void *usrmem; apr_size_t size; apr_size_t length; HANDLE hMap; }; static apr_status_t shm_cleanup(void* shm) { apr_status_t rv = APR_SUCCESS; apr_shm_t *m = shm; if (UnmapViewOfFile(m->memblk)) { rv = apr_get_os_error(); } if (CloseHandle(m->hMap)) { return (rv != APR_SUCCESS) ? rv : apr_get_os_error(); } /* ### Do we want to make a point of unlinking m->file here? * Need to add the fname to the apr_shm_t, in that case. */ return rv; } APR_DECLARE(apr_status_t) apr_shm_create(apr_shm_t **m, apr_size_t reqsize, const char *file, apr_pool_t *pool) { static apr_size_t memblock = 0; HANDLE hMap, hFile; apr_status_t rv; apr_size_t size; apr_file_t *f; void *base; void *mapkey; DWORD err, sizelo, sizehi; reqsize += sizeof(memblock_t); if (!memblock) { SYSTEM_INFO si; GetSystemInfo(&si); memblock = si.dwAllocationGranularity; } /* Compute the granualar multiple of the pagesize */ size = memblock * (1 + (reqsize - 1) / memblock); sizelo = (DWORD)size; #ifdef WIN64 sizehi = (DWORD)(size >> 32); #else sizehi = 0; #endif if (!file) { /* Do Anonymous, which must be passed as a duplicated handle */ #ifndef _WIN32_WCE hFile = INVALID_HANDLE_VALUE; #endif mapkey = NULL; } else { /* Do file backed, which is not an inherited handle * While we could open APR_EXCL, it doesn't seem that Unix * ever did. Ignore that error here, but fail later when * we discover we aren't the creator of the file map object. */ rv = apr_file_open(&f, file, APR_READ | APR_WRITE | APR_BINARY | APR_CREATE, APR_UREAD | APR_UWRITE, pool); if ((rv != APR_SUCCESS) || ((rv = apr_os_file_get(&hFile, f)) != APR_SUCCESS)) { return rv; } rv = apr_file_trunc(f, size); /* res_name_from_filename turns file into a pseudo-name * without slashes or backslashes, and prepends the \global * prefix on Win2K and later */ mapkey = res_name_from_filename(file, 1, pool); } #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { hMap = CreateFileMappingW(hFile, NULL, PAGE_READWRITE, sizehi, sizelo, mapkey); } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { hMap = CreateFileMappingA(hFile, NULL, PAGE_READWRITE, sizehi, sizelo, mapkey); } #endif err = apr_get_os_error(); if (file) { apr_file_close(f); } if (hMap && err == ERROR_ALREADY_EXISTS) { CloseHandle(hMap); return APR_EEXIST; } if (!hMap) { return err; } base = MapViewOfFile(hMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, size); if (!base) { CloseHandle(hMap); return apr_get_os_error(); } *m = (apr_shm_t *) apr_palloc(pool, sizeof(apr_shm_t)); (*m)->pool = pool; (*m)->hMap = hMap; (*m)->memblk = base; (*m)->size = size; (*m)->usrmem = (char*)base + sizeof(memblock_t); (*m)->length = reqsize - sizeof(memblock_t);; (*m)->memblk->length = (*m)->length; (*m)->memblk->size = (*m)->size; apr_pool_cleanup_register((*m)->pool, *m, shm_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_shm_destroy(apr_shm_t *m) { apr_status_t rv = shm_cleanup(m); apr_pool_cleanup_kill(m->pool, m, shm_cleanup); return rv; } APR_DECLARE(apr_status_t) apr_shm_remove(const char *filename, apr_pool_t *pool) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_shm_attach(apr_shm_t **m, const char *file, apr_pool_t *pool) { HANDLE hMap; void *mapkey; void *base; if (!file) { return APR_EINVAL; } else { /* res_name_from_filename turns file into a pseudo-name * without slashes or backslashes, and prepends the \global * prefix on Win2K and later */ mapkey = res_name_from_filename(file, 1, pool); } #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { #ifndef _WIN32_WCE hMap = OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, mapkey); #else /* The WCE 3.0 lacks OpenFileMapping. So we emulate one with * opening the existing shmem and reading its size from the header */ hMap = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(apr_shm_t), mapkey); #endif } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { hMap = OpenFileMappingA(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, mapkey); } #endif if (!hMap) { return apr_get_os_error(); } base = MapViewOfFile(hMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0); if (!base) { CloseHandle(hMap); return apr_get_os_error(); } *m = (apr_shm_t *) apr_palloc(pool, sizeof(apr_shm_t)); (*m)->pool = pool; (*m)->memblk = base; /* Real (*m)->mem->size could be recovered with VirtualQuery */ (*m)->size = (*m)->memblk->size; #if _WIN32_WCE /* Reopen with real size */ UnmapViewOfFile(base); CloseHandle(hMap); hMap = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, (*m)->size, mapkey); if (!hMap) { return apr_get_os_error(); } base = MapViewOfFile(hMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0); if (!base) { CloseHandle(hMap); return apr_get_os_error(); } #endif (*m)->hMap = hMap; (*m)->length = (*m)->memblk->length; (*m)->usrmem = (char*)base + sizeof(memblock_t); apr_pool_cleanup_register((*m)->pool, *m, shm_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_shm_detach(apr_shm_t *m) { apr_status_t rv = shm_cleanup(m); apr_pool_cleanup_kill(m->pool, m, shm_cleanup); return rv; } APR_DECLARE(void *) apr_shm_baseaddr_get(const apr_shm_t *m) { return m->usrmem; } APR_DECLARE(apr_size_t) apr_shm_size_get(const apr_shm_t *m) { return m->length; } APR_POOL_IMPLEMENT_ACCESSOR(shm) APR_DECLARE(apr_status_t) apr_os_shm_get(apr_os_shm_t *osshm, apr_shm_t *shm) { *osshm = shm->hMap; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_shm_put(apr_shm_t **m, apr_os_shm_t *osshm, apr_pool_t *pool) { void* base; base = MapViewOfFile(*osshm, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0); if (!base) { return apr_get_os_error(); } *m = (apr_shm_t *) apr_palloc(pool, sizeof(apr_shm_t)); (*m)->pool = pool; (*m)->hMap = *osshm; (*m)->memblk = base; (*m)->usrmem = (char*)base + sizeof(memblock_t); /* Real (*m)->mem->size could be recovered with VirtualQuery */ (*m)->size = (*m)->memblk->size; (*m)->length = (*m)->memblk->length; apr_pool_cleanup_register((*m)->pool, *m, shm_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/shmem/win32/shm.c
C
asf20
8,771
/* 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_general.h" #include "apr_shm.h" #include "apr_errno.h" #include "apr_lib.h" #include "apr_strings.h" #include <stdio.h> #include <stdlib.h> #include <kernel/OS.h> #include "apr_portable.h" struct apr_shm_t { apr_pool_t *pool; void *memblock; void *ptr; apr_size_t reqsize; apr_size_t avail; area_id aid; }; APR_DECLARE(apr_status_t) apr_shm_create(apr_shm_t **m, apr_size_t reqsize, const char *filename, apr_pool_t *p) { apr_size_t pagesize; area_id newid; char *addr; char shname[B_OS_NAME_LENGTH]; (*m) = (apr_shm_t *)apr_pcalloc(p, sizeof(apr_shm_t)); /* we MUST allocate in pages, so calculate how big an area we need... */ pagesize = ((reqsize + B_PAGE_SIZE - 1) / B_PAGE_SIZE) * B_PAGE_SIZE; if (!filename) { int num = 0; snprintf(shname, B_OS_NAME_LENGTH, "apr_shmem_%ld", find_thread(NULL)); while (find_area(shname) >= 0) snprintf(shname, B_OS_NAME_LENGTH, "apr_shmem_%ld_%d", find_thread(NULL), num++); } newid = create_area(filename ? filename : shname, (void*)&addr, B_ANY_ADDRESS, pagesize, B_LAZY_LOCK, B_READ_AREA|B_WRITE_AREA); if (newid < 0) return errno; (*m)->pool = p; (*m)->aid = newid; (*m)->memblock = addr; (*m)->ptr = (void*)addr; (*m)->avail = pagesize; /* record how big an area we actually created... */ (*m)->reqsize = reqsize; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_shm_destroy(apr_shm_t *m) { delete_area(m->aid); m->avail = 0; m->memblock = NULL; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_shm_remove(const char *filename, apr_pool_t *pool) { area_id deleteme = find_area(filename); if (deleteme == B_NAME_NOT_FOUND) return APR_EINVAL; delete_area(deleteme); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_shm_attach(apr_shm_t **m, const char *filename, apr_pool_t *pool) { area_info ai; thread_info ti; apr_shm_t *new_m; area_id deleteme = find_area(filename); if (deleteme == B_NAME_NOT_FOUND) return APR_EINVAL; new_m = (apr_shm_t*)apr_palloc(pool, sizeof(apr_shm_t*)); if (new_m == NULL) return APR_ENOMEM; new_m->pool = pool; get_area_info(deleteme, &ai); get_thread_info(find_thread(NULL), &ti); if (ti.team != ai.team) { area_id narea; narea = clone_area(ai.name, &(ai.address), B_CLONE_ADDRESS, B_READ_AREA|B_WRITE_AREA, ai.area); if (narea < B_OK) return narea; get_area_info(narea, &ai); new_m->aid = narea; new_m->memblock = ai.address; new_m->ptr = (void*)ai.address; new_m->avail = ai.size; new_m->reqsize = ai.size; } (*m) = new_m; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_shm_detach(apr_shm_t *m) { delete_area(m->aid); return APR_SUCCESS; } APR_DECLARE(void *) apr_shm_baseaddr_get(const apr_shm_t *m) { return m->memblock; } APR_DECLARE(apr_size_t) apr_shm_size_get(const apr_shm_t *m) { return m->reqsize; } APR_POOL_IMPLEMENT_ACCESSOR(shm) APR_DECLARE(apr_status_t) apr_os_shm_get(apr_os_shm_t *osshm, apr_shm_t *shm) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_os_shm_put(apr_shm_t **m, apr_os_shm_t *osshm, apr_pool_t *pool) { return APR_ENOTIMPL; }
001-log4cxx
trunk/src/apr/shmem/beos/shm.c
C
asf20
4,665
/* 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_shm.h" #include "apr_general.h" #include "apr_errno.h" #include "apr_user.h" #include "apr_strings.h" static apr_status_t shm_cleanup_owner(void *m_) { apr_shm_t *m = (apr_shm_t *)m_; /* anonymous shared memory */ if (m->filename == NULL) { #if APR_USE_SHMEM_MMAP_ZERO || APR_USE_SHMEM_MMAP_ANON if (munmap(m->base, m->realsize) == -1) { return errno; } return APR_SUCCESS; #endif #if APR_USE_SHMEM_SHMGET_ANON if (shmdt(m->base) == -1) { return errno; } /* This segment will automatically remove itself after all * references have detached. */ return APR_SUCCESS; #endif } /* name-based shared memory */ else { #if APR_USE_SHMEM_MMAP_TMP if (munmap(m->base, m->realsize) == -1) { return errno; } return apr_file_remove(m->filename, m->pool); #endif #if APR_USE_SHMEM_MMAP_SHM if (munmap(m->base, m->realsize) == -1) { return errno; } if (shm_unlink(m->filename) == -1) { return errno; } return APR_SUCCESS; #endif #if APR_USE_SHMEM_SHMGET /* Indicate that the segment is to be destroyed as soon * as all processes have detached. This also disallows any * new attachments to the segment. */ if (shmctl(m->shmid, IPC_RMID, NULL) == -1) { return errno; } if (shmdt(m->base) == -1) { return errno; } return apr_file_remove(m->filename, m->pool); #endif } return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_shm_create(apr_shm_t **m, apr_size_t reqsize, const char *filename, apr_pool_t *pool) { apr_shm_t *new_m; apr_status_t status; #if APR_USE_SHMEM_SHMGET || APR_USE_SHMEM_SHMGET_ANON struct shmid_ds shmbuf; apr_uid_t uid; apr_gid_t gid; #endif #if APR_USE_SHMEM_MMAP_TMP || APR_USE_SHMEM_MMAP_SHM || \ APR_USE_SHMEM_MMAP_ZERO int tmpfd; #endif #if APR_USE_SHMEM_SHMGET apr_size_t nbytes; key_t shmkey; #endif #if APR_USE_SHMEM_MMAP_ZERO || APR_USE_SHMEM_SHMGET || \ APR_USE_SHMEM_MMAP_TMP || APR_USE_SHMEM_MMAP_SHM apr_file_t *file; /* file where metadata is stored */ #endif /* Check if they want anonymous or name-based shared memory */ if (filename == NULL) { #if APR_USE_SHMEM_MMAP_ZERO || APR_USE_SHMEM_MMAP_ANON new_m = apr_palloc(pool, sizeof(apr_shm_t)); new_m->pool = pool; new_m->reqsize = reqsize; new_m->realsize = reqsize + APR_ALIGN_DEFAULT(sizeof(apr_size_t)); /* room for metadata */ new_m->filename = NULL; #if APR_USE_SHMEM_MMAP_ZERO status = apr_file_open(&file, "/dev/zero", APR_READ | APR_WRITE, APR_OS_DEFAULT, pool); if (status != APR_SUCCESS) { return status; } status = apr_os_file_get(&tmpfd, file); if (status != APR_SUCCESS) { return status; } new_m->base = mmap(NULL, new_m->realsize, PROT_READ|PROT_WRITE, MAP_SHARED, tmpfd, 0); if (new_m->base == (void *)MAP_FAILED) { return errno; } status = apr_file_close(file); if (status != APR_SUCCESS) { return status; } /* store the real size in the metadata */ *(apr_size_t*)(new_m->base) = new_m->realsize; /* metadata isn't usable */ new_m->usable = (char *)new_m->base + APR_ALIGN_DEFAULT(sizeof(apr_size_t)); apr_pool_cleanup_register(new_m->pool, new_m, shm_cleanup_owner, apr_pool_cleanup_null); *m = new_m; return APR_SUCCESS; #elif APR_USE_SHMEM_MMAP_ANON new_m->base = mmap(NULL, new_m->realsize, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED, -1, 0); if (new_m->base == (void *)MAP_FAILED) { return errno; } /* store the real size in the metadata */ *(apr_size_t*)(new_m->base) = new_m->realsize; /* metadata isn't usable */ new_m->usable = (char *)new_m->base + APR_ALIGN_DEFAULT(sizeof(apr_size_t)); apr_pool_cleanup_register(new_m->pool, new_m, shm_cleanup_owner, apr_pool_cleanup_null); *m = new_m; return APR_SUCCESS; #endif /* APR_USE_SHMEM_MMAP_ZERO */ #endif /* APR_USE_SHMEM_MMAP_ZERO || APR_USE_SHMEM_MMAP_ANON */ #if APR_USE_SHMEM_SHMGET_ANON new_m = apr_palloc(pool, sizeof(apr_shm_t)); new_m->pool = pool; new_m->reqsize = reqsize; new_m->realsize = reqsize; new_m->filename = NULL; if ((new_m->shmid = shmget(IPC_PRIVATE, new_m->realsize, SHM_R | SHM_W | IPC_CREAT)) < 0) { return errno; } if ((new_m->base = shmat(new_m->shmid, NULL, 0)) == (void *)-1) { return errno; } new_m->usable = new_m->base; if (shmctl(new_m->shmid, IPC_STAT, &shmbuf) == -1) { return errno; } apr_uid_current(&uid, &gid, pool); shmbuf.shm_perm.uid = uid; shmbuf.shm_perm.gid = gid; if (shmctl(new_m->shmid, IPC_SET, &shmbuf) == -1) { return errno; } /* Remove the segment once use count hits zero. * We will not attach to this segment again, since it is * anonymous memory, so it is ok to mark it for deletion. */ if (shmctl(new_m->shmid, IPC_RMID, NULL) == -1) { return errno; } apr_pool_cleanup_register(new_m->pool, new_m, shm_cleanup_owner, apr_pool_cleanup_null); *m = new_m; return APR_SUCCESS; #endif /* APR_USE_SHMEM_SHMGET_ANON */ /* It is an error if they want anonymous memory but we don't have it. */ return APR_ENOTIMPL; /* requested anonymous but we don't have it */ } /* Name-based shared memory */ else { new_m = apr_palloc(pool, sizeof(apr_shm_t)); new_m->pool = pool; new_m->reqsize = reqsize; new_m->filename = apr_pstrdup(pool, filename); #if APR_USE_SHMEM_MMAP_TMP || APR_USE_SHMEM_MMAP_SHM new_m->realsize = reqsize + APR_ALIGN_DEFAULT(sizeof(apr_size_t)); /* room for metadata */ /* FIXME: Ignore error for now. * * status = apr_file_remove(file, pool);*/ status = APR_SUCCESS; #if APR_USE_SHMEM_MMAP_TMP /* FIXME: Is APR_OS_DEFAULT sufficient? */ status = apr_file_open(&file, filename, APR_READ | APR_WRITE | APR_CREATE | APR_EXCL, APR_OS_DEFAULT, pool); if (status != APR_SUCCESS) { return status; } status = apr_os_file_get(&tmpfd, file); if (status != APR_SUCCESS) { apr_file_close(file); /* ignore errors, we're failing */ apr_file_remove(new_m->filename, new_m->pool); return status; } status = apr_file_trunc(file, new_m->realsize); if (status != APR_SUCCESS) { apr_file_close(file); /* ignore errors, we're failing */ apr_file_remove(new_m->filename, new_m->pool); return status; } new_m->base = mmap(NULL, new_m->realsize, PROT_READ | PROT_WRITE, MAP_SHARED, tmpfd, 0); /* FIXME: check for errors */ status = apr_file_close(file); if (status != APR_SUCCESS) { return status; } #endif /* APR_USE_SHMEM_MMAP_TMP */ #if APR_USE_SHMEM_MMAP_SHM tmpfd = shm_open(filename, O_RDWR | O_CREAT | O_EXCL, 0644); if (tmpfd == -1) { return errno; } status = apr_os_file_put(&file, &tmpfd, APR_READ | APR_WRITE | APR_CREATE | APR_EXCL, pool); if (status != APR_SUCCESS) { return status; } status = apr_file_trunc(file, new_m->realsize); if (status != APR_SUCCESS) { shm_unlink(filename); /* we're failing, remove the object */ return status; } new_m->base = mmap(NULL, reqsize, PROT_READ | PROT_WRITE, MAP_SHARED, tmpfd, 0); /* FIXME: check for errors */ status = apr_file_close(file); if (status != APR_SUCCESS) { return status; } #endif /* APR_USE_SHMEM_MMAP_SHM */ /* store the real size in the metadata */ *(apr_size_t*)(new_m->base) = new_m->realsize; /* metadata isn't usable */ new_m->usable = (char *)new_m->base + APR_ALIGN_DEFAULT(sizeof(apr_size_t)); apr_pool_cleanup_register(new_m->pool, new_m, shm_cleanup_owner, apr_pool_cleanup_null); *m = new_m; return APR_SUCCESS; #endif /* APR_USE_SHMEM_MMAP_TMP || APR_USE_SHMEM_MMAP_SHM */ #if APR_USE_SHMEM_SHMGET new_m->realsize = reqsize; /* FIXME: APR_OS_DEFAULT is too permissive, switch to 600 I think. */ status = apr_file_open(&file, filename, APR_WRITE | APR_CREATE | APR_EXCL, APR_OS_DEFAULT, pool); if (status != APR_SUCCESS) { return status; } /* ftok() (on solaris at least) requires that the file actually * exist before calling ftok(). */ shmkey = ftok(filename, 1); if (shmkey == (key_t)-1) { return errno; } if ((new_m->shmid = shmget(shmkey, new_m->realsize, SHM_R | SHM_W | IPC_CREAT | IPC_EXCL)) < 0) { return errno; } if ((new_m->base = shmat(new_m->shmid, NULL, 0)) == (void *)-1) { return errno; } new_m->usable = new_m->base; if (shmctl(new_m->shmid, IPC_STAT, &shmbuf) == -1) { return errno; } apr_uid_current(&uid, &gid, pool); shmbuf.shm_perm.uid = uid; shmbuf.shm_perm.gid = gid; if (shmctl(new_m->shmid, IPC_SET, &shmbuf) == -1) { return errno; } nbytes = sizeof(reqsize); status = apr_file_write(file, (const void *)&reqsize, &nbytes); if (status != APR_SUCCESS) { return status; } status = apr_file_close(file); if (status != APR_SUCCESS) { return status; } apr_pool_cleanup_register(new_m->pool, new_m, shm_cleanup_owner, apr_pool_cleanup_null); *m = new_m; return APR_SUCCESS; #endif /* APR_USE_SHMEM_SHMGET */ } return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_shm_remove(const char *filename, apr_pool_t *pool) { #if APR_USE_SHMEM_SHMGET apr_status_t status; apr_file_t *file; key_t shmkey; int shmid; #endif #if APR_USE_SHMEM_MMAP_TMP return apr_file_remove(filename, pool); #endif #if APR_USE_SHMEM_MMAP_SHM if (shm_unlink(filename) == -1) { return errno; } return APR_SUCCESS; #endif #if APR_USE_SHMEM_SHMGET /* Presume that the file already exists; just open for writing */ status = apr_file_open(&file, filename, APR_WRITE, APR_OS_DEFAULT, pool); if (status) { return status; } /* ftok() (on solaris at least) requires that the file actually * exist before calling ftok(). */ shmkey = ftok(filename, 1); if (shmkey == (key_t)-1) { goto shm_remove_failed; } apr_file_close(file); if ((shmid = shmget(shmkey, 0, SHM_R | SHM_W)) < 0) { goto shm_remove_failed; } /* Indicate that the segment is to be destroyed as soon * as all processes have detached. This also disallows any * new attachments to the segment. */ if (shmctl(shmid, IPC_RMID, NULL) == -1) { goto shm_remove_failed; } return apr_file_remove(filename, pool); shm_remove_failed: status = errno; /* ensure the file has been removed anyway. */ apr_file_remove(filename, pool); return status; #endif /* No support for anonymous shm */ return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_shm_destroy(apr_shm_t *m) { return apr_pool_cleanup_run(m->pool, m, shm_cleanup_owner); } static apr_status_t shm_cleanup_attach(void *m_) { apr_shm_t *m = (apr_shm_t *)m_; if (m->filename == NULL) { /* It doesn't make sense to detach from an anonymous memory segment. */ return APR_EINVAL; } else { #if APR_USE_SHMEM_MMAP_TMP || APR_USE_SHMEM_MMAP_SHM if (munmap(m->base, m->realsize) == -1) { return errno; } return APR_SUCCESS; #endif /* APR_USE_SHMEM_MMAP_TMP || APR_USE_SHMEM_MMAP_SHM */ #if APR_USE_SHMEM_SHMGET if (shmdt(m->base) == -1) { return errno; } return APR_SUCCESS; #endif } return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_shm_attach(apr_shm_t **m, const char *filename, apr_pool_t *pool) { if (filename == NULL) { /* It doesn't make sense to attach to a segment if you don't know * the filename. */ return APR_EINVAL; } else { #if APR_USE_SHMEM_MMAP_TMP || APR_USE_SHMEM_MMAP_SHM apr_shm_t *new_m; apr_status_t status; int tmpfd; apr_file_t *file; /* file where metadata is stored */ apr_size_t nbytes; new_m = apr_palloc(pool, sizeof(apr_shm_t)); new_m->pool = pool; new_m->filename = apr_pstrdup(pool, filename); status = apr_file_open(&file, filename, APR_READ | APR_WRITE, APR_OS_DEFAULT, pool); if (status != APR_SUCCESS) { return status; } status = apr_os_file_get(&tmpfd, file); if (status != APR_SUCCESS) { return status; } nbytes = sizeof(new_m->realsize); status = apr_file_read(file, (void *)&(new_m->realsize), &nbytes); if (status != APR_SUCCESS) { return status; } status = apr_os_file_get(&tmpfd, file); if (status != APR_SUCCESS) { apr_file_close(file); /* ignore errors, we're failing */ apr_file_remove(new_m->filename, new_m->pool); return status; } new_m->reqsize = new_m->realsize - sizeof(apr_size_t); new_m->base = mmap(NULL, new_m->realsize, PROT_READ | PROT_WRITE, MAP_SHARED, tmpfd, 0); /* FIXME: check for errors */ status = apr_file_close(file); if (status != APR_SUCCESS) { return status; } /* metadata isn't part of the usable segment */ new_m->usable = (char *)new_m->base + APR_ALIGN_DEFAULT(sizeof(apr_size_t)); apr_pool_cleanup_register(new_m->pool, new_m, shm_cleanup_attach, apr_pool_cleanup_null); *m = new_m; return APR_SUCCESS; #endif /* APR_USE_SHMEM_MMAP_TMP || APR_USE_SHMEM_MMAP_SHM */ #if APR_USE_SHMEM_SHMGET apr_shm_t *new_m; apr_status_t status; apr_file_t *file; /* file where metadata is stored */ apr_size_t nbytes; key_t shmkey; new_m = apr_palloc(pool, sizeof(apr_shm_t)); status = apr_file_open(&file, filename, APR_READ, APR_OS_DEFAULT, pool); if (status != APR_SUCCESS) { return status; } nbytes = sizeof(new_m->reqsize); status = apr_file_read(file, (void *)&(new_m->reqsize), &nbytes); if (status != APR_SUCCESS) { return status; } status = apr_file_close(file); if (status != APR_SUCCESS) { return status; } new_m->filename = apr_pstrdup(pool, filename); new_m->pool = pool; shmkey = ftok(filename, 1); if (shmkey == (key_t)-1) { return errno; } if ((new_m->shmid = shmget(shmkey, 0, SHM_R | SHM_W)) == -1) { return errno; } if ((new_m->base = shmat(new_m->shmid, NULL, 0)) == (void *)-1) { return errno; } new_m->usable = new_m->base; new_m->realsize = new_m->reqsize; apr_pool_cleanup_register(new_m->pool, new_m, shm_cleanup_attach, apr_pool_cleanup_null); *m = new_m; return APR_SUCCESS; #endif /* APR_USE_SHMEM_SHMGET */ } return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_shm_detach(apr_shm_t *m) { apr_status_t rv = shm_cleanup_attach(m); apr_pool_cleanup_kill(m->pool, m, shm_cleanup_attach); return rv; } APR_DECLARE(void *) apr_shm_baseaddr_get(const apr_shm_t *m) { return m->usable; } APR_DECLARE(apr_size_t) apr_shm_size_get(const apr_shm_t *m) { return m->reqsize; } APR_POOL_IMPLEMENT_ACCESSOR(shm) APR_DECLARE(apr_status_t) apr_os_shm_get(apr_os_shm_t *osshm, apr_shm_t *shm) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_os_shm_put(apr_shm_t **m, apr_os_shm_t *osshm, apr_pool_t *pool) { return APR_ENOTIMPL; }
001-log4cxx
trunk/src/apr/shmem/unix/shm.c
C
asf20
18,648
/* 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_general.h" #include "apr_shm.h" #include "apr_errno.h" #include "apr_lib.h" #include "apr_strings.h" #include "apr_portable.h" struct apr_shm_t { apr_pool_t *pool; void *memblock; }; APR_DECLARE(apr_status_t) apr_shm_create(apr_shm_t **m, apr_size_t reqsize, const char *filename, apr_pool_t *pool) { int rc; apr_shm_t *newm = (apr_shm_t *)apr_palloc(pool, sizeof(apr_shm_t)); char *name = NULL; ULONG flags = PAG_COMMIT|PAG_READ|PAG_WRITE; newm->pool = pool; if (filename) { name = apr_pstrcat(pool, "\\SHAREMEM\\", filename, NULL); } if (name == NULL) { flags |= OBJ_GETTABLE; } rc = DosAllocSharedMem(&(newm->memblock), name, reqsize, flags); if (rc) { return APR_OS2_STATUS(rc); } *m = newm; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_shm_destroy(apr_shm_t *m) { DosFreeMem(m->memblock); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_shm_remove(const char *filename, apr_pool_t *pool) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_shm_attach(apr_shm_t **m, const char *filename, apr_pool_t *pool) { int rc; apr_shm_t *newm = (apr_shm_t *)apr_palloc(pool, sizeof(apr_shm_t)); char *name = NULL; ULONG flags = PAG_READ|PAG_WRITE; newm->pool = pool; name = apr_pstrcat(pool, "\\SHAREMEM\\", filename, NULL); rc = DosGetNamedSharedMem(&(newm->memblock), name, flags); if (rc) { return APR_FROM_OS_ERROR(rc); } *m = newm; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_shm_detach(apr_shm_t *m) { int rc = 0; if (m->memblock) { rc = DosFreeMem(m->memblock); } return APR_FROM_OS_ERROR(rc); } APR_DECLARE(void *) apr_shm_baseaddr_get(const apr_shm_t *m) { return m->memblock; } APR_DECLARE(apr_size_t) apr_shm_size_get(const apr_shm_t *m) { ULONG flags, size = 0x1000000; DosQueryMem(m->memblock, &size, &flags); return size; } APR_POOL_IMPLEMENT_ACCESSOR(shm) APR_DECLARE(apr_status_t) apr_os_shm_get(apr_os_shm_t *osshm, apr_shm_t *shm) { *osshm = shm->memblock; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_shm_put(apr_shm_t **m, apr_os_shm_t *osshm, apr_pool_t *pool) { int rc; apr_shm_t *newm = (apr_shm_t *)apr_palloc(pool, sizeof(apr_shm_t)); ULONG flags = PAG_COMMIT|PAG_READ|PAG_WRITE; newm->pool = pool; rc = DosGetSharedMem(&(newm->memblock), flags); if (rc) { return APR_FROM_OS_ERROR(rc); } *m = newm; return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/shmem/os2/shm.c
C
asf20
3,732
/* 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_general.h" #include "apr_lib.h" #include "apr_portable.h" #include "apr_strings.h" #include <string.h> #include "apr_arch_inherit.h" #include "apr_arch_misc.h" static char generic_inaddr_any[16] = {0}; /* big enough for IPv4 or IPv6 */ static apr_status_t socket_cleanup(void *sock) { apr_socket_t *thesocket = sock; if (thesocket->socketdes != INVALID_SOCKET) { if (closesocket(thesocket->socketdes) == SOCKET_ERROR) { return apr_get_netos_error(); } thesocket->socketdes = INVALID_SOCKET; } #if APR_HAS_SENDFILE if (thesocket->overlapped) { CloseHandle(thesocket->overlapped->hEvent); thesocket->overlapped = NULL; } #endif return APR_SUCCESS; } static void set_socket_vars(apr_socket_t *sock, int family, int type, int protocol) { sock->type = type; sock->protocol = protocol; apr_sockaddr_vars_set(sock->local_addr, family, 0); apr_sockaddr_vars_set(sock->remote_addr, family, 0); } static void alloc_socket(apr_socket_t **new, apr_pool_t *p) { *new = (apr_socket_t *)apr_pcalloc(p, sizeof(apr_socket_t)); (*new)->pool = p; (*new)->local_addr = (apr_sockaddr_t *)apr_pcalloc((*new)->pool, sizeof(apr_sockaddr_t)); (*new)->local_addr->pool = p; (*new)->remote_addr = (apr_sockaddr_t *)apr_pcalloc((*new)->pool, sizeof(apr_sockaddr_t)); (*new)->remote_addr->pool = p; (*new)->remote_addr_unknown = 1; /* Create a pollset with room for one descriptor. */ /* ### check return codes */ (void) apr_pollset_create(&(*new)->pollset, 1, p, 0); } APR_DECLARE(apr_status_t) apr_socket_protocol_get(apr_socket_t *sock, int *protocol) { *protocol = sock->protocol; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_create(apr_socket_t **new, int family, int type, int protocol, apr_pool_t *cont) { int downgrade = (family == AF_UNSPEC); if (family == AF_UNSPEC) { #if APR_HAVE_IPV6 family = AF_INET6; #else family = AF_INET; #endif } alloc_socket(new, cont); /* For right now, we are not using socket groups. We may later. * No flags to use when creating a socket, so use 0 for that parameter as well. */ (*new)->socketdes = socket(family, type, protocol); #if APR_HAVE_IPV6 if ((*new)->socketdes == INVALID_SOCKET && downgrade) { family = AF_INET; (*new)->socketdes = socket(family, type, protocol); } #endif if ((*new)->socketdes == INVALID_SOCKET) { return apr_get_netos_error(); } #ifdef WIN32 /* Socket handles are never truly inheritable, there are too many * bugs associated. WSADuplicateSocket will copy them, but for our * purposes, always transform the socket() created as a non-inherited * handle */ #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { /* A different approach. Many users report errors such as * (32538)An operation was attempted on something that is not * a socket. : Parent: WSADuplicateSocket failed... * * This appears that the duplicated handle is no longer recognized * as a socket handle. SetHandleInformation should overcome that * problem by not altering the handle identifier. But this won't * work on 9x - it's unsupported. */ SetHandleInformation((HANDLE) (*new)->socketdes, HANDLE_FLAG_INHERIT, 0); } #endif #if APR_HAS_ANSI_FS ELSE_WIN_OS_IS_ANSI { HANDLE hProcess = GetCurrentProcess(); HANDLE dup; if (DuplicateHandle(hProcess, (HANDLE) (*new)->socketdes, hProcess, &dup, 0, FALSE, DUPLICATE_SAME_ACCESS)) { closesocket((*new)->socketdes); (*new)->socketdes = (SOCKET) dup; } } #endif #endif /* def WIN32 */ set_socket_vars(*new, family, type, protocol); (*new)->timeout = -1; (*new)->disconnected = 0; apr_pool_cleanup_register((*new)->pool, (void *)(*new), socket_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_shutdown(apr_socket_t *thesocket, apr_shutdown_how_e how) { int winhow = 0; #ifdef SD_RECEIVE switch (how) { case APR_SHUTDOWN_READ: { winhow = SD_RECEIVE; break; } case APR_SHUTDOWN_WRITE: { winhow = SD_SEND; break; } case APR_SHUTDOWN_READWRITE: { winhow = SD_BOTH; break; } default: return APR_BADARG; } #endif if (shutdown(thesocket->socketdes, winhow) == 0) { return APR_SUCCESS; } else { return apr_get_netos_error(); } } APR_DECLARE(apr_status_t) apr_socket_close(apr_socket_t *thesocket) { apr_pool_cleanup_kill(thesocket->pool, thesocket, socket_cleanup); return socket_cleanup(thesocket); } APR_DECLARE(apr_status_t) apr_socket_bind(apr_socket_t *sock, apr_sockaddr_t *sa) { if (bind(sock->socketdes, (struct sockaddr *)&sa->sa, sa->salen) == -1) { return apr_get_netos_error(); } else { sock->local_addr = sa; if (sock->local_addr->sa.sin.sin_port == 0) { sock->local_port_unknown = 1; /* ephemeral port */ } return APR_SUCCESS; } } APR_DECLARE(apr_status_t) apr_socket_listen(apr_socket_t *sock, apr_int32_t backlog) { if (listen(sock->socketdes, backlog) == SOCKET_ERROR) return apr_get_netos_error(); else return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_accept(apr_socket_t **new, apr_socket_t *sock, apr_pool_t *p) { SOCKET s; #if APR_HAVE_IPV6 struct sockaddr_storage sa; #else struct sockaddr sa; #endif int salen = sizeof(sock->remote_addr->sa); /* Don't allocate the memory until after we call accept. This allows us to work with nonblocking sockets. */ s = accept(sock->socketdes, (struct sockaddr *)&sa, &salen); if (s == INVALID_SOCKET) { return apr_get_netos_error(); } alloc_socket(new, p); set_socket_vars(*new, sock->local_addr->sa.sin.sin_family, SOCK_STREAM, sock->protocol); (*new)->timeout = -1; (*new)->disconnected = 0; (*new)->socketdes = s; /* XXX next line looks bogus w.r.t. AF_INET6 support */ (*new)->remote_addr->salen = sizeof((*new)->remote_addr->sa); memcpy (&(*new)->remote_addr->sa, &sa, salen); *(*new)->local_addr = *sock->local_addr; /* The above assignment just overwrote the pool entry. Setting the local_addr pool for the accepted socket back to what it should be. Otherwise all allocations for this socket will come from a server pool that is not freed until the process goes down.*/ (*new)->local_addr->pool = p; /* fix up any pointers which are no longer valid */ if (sock->local_addr->sa.sin.sin_family == AF_INET) { (*new)->local_addr->ipaddr_ptr = &(*new)->local_addr->sa.sin.sin_addr; } #if APR_HAVE_IPV6 else if (sock->local_addr->sa.sin.sin_family == AF_INET6) { (*new)->local_addr->ipaddr_ptr = &(*new)->local_addr->sa.sin6.sin6_addr; } #endif (*new)->remote_addr->port = ntohs((*new)->remote_addr->sa.sin.sin_port); if (sock->local_port_unknown) { /* not likely for a listening socket, but theoretically possible :) */ (*new)->local_port_unknown = 1; } #if APR_TCP_NODELAY_INHERITED if (apr_is_option_set(sock, APR_TCP_NODELAY) == 1) { apr_set_option(*new, APR_TCP_NODELAY, 1); } #endif /* TCP_NODELAY_INHERITED */ #if APR_O_NONBLOCK_INHERITED if (apr_is_option_set(sock, APR_SO_NONBLOCK) == 1) { apr_set_option(*new, APR_SO_NONBLOCK, 1); } #endif /* APR_O_NONBLOCK_INHERITED */ if (sock->local_interface_unknown || !memcmp(sock->local_addr->ipaddr_ptr, generic_inaddr_any, sock->local_addr->ipaddr_len)) { /* If the interface address inside the listening socket's local_addr wasn't * up-to-date, we don't know local interface of the connected socket either. * * If the listening socket was not bound to a specific interface, we * don't know the local_addr of the connected socket. */ (*new)->local_interface_unknown = 1; } apr_pool_cleanup_register((*new)->pool, (void *)(*new), socket_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_connect(apr_socket_t *sock, apr_sockaddr_t *sa) { apr_status_t rv; if ((sock->socketdes == INVALID_SOCKET) || (!sock->local_addr)) { return APR_ENOTSOCK; } if (connect(sock->socketdes, (const struct sockaddr *)&sa->sa.sin, sa->salen) == SOCKET_ERROR) { int rc; struct timeval tv, *tvptr; fd_set wfdset, efdset; rv = apr_get_netos_error(); if (rv != APR_FROM_OS_ERROR(WSAEWOULDBLOCK)) { return rv; } if (sock->timeout == 0) { /* Tell the app that the connect is in progress... * Gotta play some games here. connect on Unix will return * EINPROGRESS under the same circumstances that Windows * returns WSAEWOULDBLOCK. Do some adhoc canonicalization... */ return APR_FROM_OS_ERROR(WSAEINPROGRESS); } /* wait for the connect to complete or timeout */ FD_ZERO(&wfdset); FD_SET(sock->socketdes, &wfdset); FD_ZERO(&efdset); FD_SET(sock->socketdes, &efdset); if (sock->timeout < 0) { tvptr = NULL; } else { /* casts for winsock/timeval definition */ tv.tv_sec = (long)apr_time_sec(sock->timeout); tv.tv_usec = (int)apr_time_usec(sock->timeout); tvptr = &tv; } rc = select(FD_SETSIZE+1, NULL, &wfdset, &efdset, tvptr); if (rc == SOCKET_ERROR) { return apr_get_netos_error(); } else if (!rc) { return APR_FROM_OS_ERROR(WSAETIMEDOUT); } /* Evaluate the efdset */ if (FD_ISSET(sock->socketdes, &efdset)) { /* The connect failed. */ int rclen = sizeof(rc); if (getsockopt(sock->socketdes, SOL_SOCKET, SO_ERROR, (char*) &rc, &rclen)) { return apr_get_netos_error(); } return APR_FROM_OS_ERROR(rc); } } /* connect was OK .. amazing */ sock->remote_addr = sa; if (sock->local_addr->sa.sin.sin_port == 0) { sock->local_port_unknown = 1; } if (!memcmp(sock->local_addr->ipaddr_ptr, generic_inaddr_any, sock->local_addr->ipaddr_len)) { /* not bound to specific local interface; connect() had to assign * one for the socket */ sock->local_interface_unknown = 1; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_type_get(apr_socket_t *sock, int *type) { *type = sock->type; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_data_get(void **data, const char *key, apr_socket_t *sock) { sock_userdata_t *cur = sock->userdata; *data = NULL; while (cur) { if (!strcmp(cur->key, key)) { *data = cur->data; break; } cur = cur->next; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_data_set(apr_socket_t *sock, void *data, const char *key, apr_status_t (*cleanup)(void *)) { sock_userdata_t *new = apr_palloc(sock->pool, sizeof(sock_userdata_t)); new->key = apr_pstrdup(sock->pool, key); new->data = data; new->next = sock->userdata; sock->userdata = new; if (cleanup) { apr_pool_cleanup_register(sock->pool, data, cleanup, cleanup); } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_sock_get(apr_os_sock_t *thesock, apr_socket_t *sock) { *thesock = sock->socketdes; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_sock_make(apr_socket_t **apr_sock, apr_os_sock_info_t *os_sock_info, apr_pool_t *cont) { alloc_socket(apr_sock, cont); set_socket_vars(*apr_sock, os_sock_info->family, os_sock_info->type, os_sock_info->protocol); (*apr_sock)->timeout = -1; (*apr_sock)->disconnected = 0; (*apr_sock)->socketdes = *os_sock_info->os_sock; if (os_sock_info->local) { memcpy(&(*apr_sock)->local_addr->sa.sin, os_sock_info->local, (*apr_sock)->local_addr->salen); (*apr_sock)->local_addr->pool = cont; /* XXX IPv6 - this assumes sin_port and sin6_port at same offset */ (*apr_sock)->local_addr->port = ntohs((*apr_sock)->local_addr->sa.sin.sin_port); } else { (*apr_sock)->local_port_unknown = (*apr_sock)->local_interface_unknown = 1; } if (os_sock_info->remote) { memcpy(&(*apr_sock)->remote_addr->sa.sin, os_sock_info->remote, (*apr_sock)->remote_addr->salen); (*apr_sock)->remote_addr->pool = cont; /* XXX IPv6 - this assumes sin_port and sin6_port at same offset */ (*apr_sock)->remote_addr->port = ntohs((*apr_sock)->remote_addr->sa.sin.sin_port); } else { (*apr_sock)->remote_addr_unknown = 1; } apr_pool_cleanup_register((*apr_sock)->pool, (void *)(*apr_sock), socket_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_sock_put(apr_socket_t **sock, apr_os_sock_t *thesock, apr_pool_t *cont) { if ((*sock) == NULL) { alloc_socket(sock, cont); /* XXX figure out the actual socket type here */ /* *or* just decide that apr_os_sock_put() has to be told the family and type */ set_socket_vars(*sock, AF_INET, SOCK_STREAM, 0); (*sock)->timeout = -1; (*sock)->disconnected = 0; } (*sock)->local_port_unknown = (*sock)->local_interface_unknown = 1; (*sock)->remote_addr_unknown = 1; (*sock)->socketdes = *thesock; return APR_SUCCESS; } /* Sockets cannot be inherited through the standard sockets * inheritence. WSADuplicateSocket must be used. * This is not trivial to implement. */ APR_DECLARE(apr_status_t) apr_socket_inherit_set(apr_socket_t *socket) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_socket_inherit_unset(apr_socket_t *socket) { return APR_ENOTIMPL; } APR_POOL_IMPLEMENT_ACCESSOR(socket);
001-log4cxx
trunk/src/apr/network_io/win32/sockets.c
C
asf20
16,447
/* 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_general.h" #include "apr_strings.h" #include <string.h> apr_status_t soblock(SOCKET sd) { u_long zero = 0; if (ioctlsocket(sd, FIONBIO, &zero) == SOCKET_ERROR) { return apr_get_netos_error(); } return APR_SUCCESS; } apr_status_t sononblock(SOCKET sd) { u_long one = 1; if (ioctlsocket(sd, FIONBIO, &one) == SOCKET_ERROR) { return apr_get_netos_error(); } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_timeout_set(apr_socket_t *sock, apr_interval_time_t t) { apr_status_t stat; if (t == 0) { /* Set the socket non-blocking if it was previously blocking */ if (sock->timeout != 0) { if ((stat = sononblock(sock->socketdes)) != APR_SUCCESS) return stat; } } else if (t > 0) { /* Set the socket to blocking if it was previously non-blocking */ if (sock->timeout == 0) { if ((stat = soblock(sock->socketdes)) != APR_SUCCESS) return stat; } /* Reset socket timeouts if the new timeout differs from the old timeout */ if (sock->timeout != t) { /* Win32 timeouts are in msec, represented as int */ sock->timeout_ms = (int)apr_time_as_msec(t); setsockopt(sock->socketdes, SOL_SOCKET, SO_RCVTIMEO, (char *) &sock->timeout_ms, sizeof(sock->timeout_ms)); setsockopt(sock->socketdes, SOL_SOCKET, SO_SNDTIMEO, (char *) &sock->timeout_ms, sizeof(sock->timeout_ms)); } } else if (t < 0) { int zero = 0; /* Set the socket to blocking with infinite timeouts */ if ((stat = soblock(sock->socketdes)) != APR_SUCCESS) return stat; setsockopt(sock->socketdes, SOL_SOCKET, SO_RCVTIMEO, (char *) &zero, sizeof(zero)); setsockopt(sock->socketdes, SOL_SOCKET, SO_SNDTIMEO, (char *) &zero, sizeof(zero)); } sock->timeout = t; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_opt_set(apr_socket_t *sock, apr_int32_t opt, apr_int32_t on) { int one; apr_status_t stat; one = on ? 1 : 0; switch (opt) { case APR_SO_KEEPALIVE: if (on != apr_is_option_set(sock, APR_SO_KEEPALIVE)) { if (setsockopt(sock->socketdes, SOL_SOCKET, SO_KEEPALIVE, (void *)&one, sizeof(int)) == -1) { return apr_get_netos_error(); } apr_set_option(sock, APR_SO_KEEPALIVE, on); } break; case APR_SO_DEBUG: if (on != apr_is_option_set(sock, APR_SO_DEBUG)) { if (setsockopt(sock->socketdes, SOL_SOCKET, SO_DEBUG, (void *)&one, sizeof(int)) == -1) { return apr_get_netos_error(); } apr_set_option(sock, APR_SO_DEBUG, on); } break; case APR_SO_SNDBUF: if (setsockopt(sock->socketdes, SOL_SOCKET, SO_SNDBUF, (void *)&on, sizeof(int)) == -1) { return apr_get_netos_error(); } break; case APR_SO_RCVBUF: if (setsockopt(sock->socketdes, SOL_SOCKET, SO_RCVBUF, (void *)&on, sizeof(int)) == -1) { return apr_get_netos_error(); } break; case APR_SO_REUSEADDR: if (on != apr_is_option_set(sock, APR_SO_REUSEADDR)) { if (setsockopt(sock->socketdes, SOL_SOCKET, SO_REUSEADDR, (void *)&one, sizeof(int)) == -1) { return apr_get_netos_error(); } apr_set_option(sock, APR_SO_REUSEADDR, on); } break; case APR_SO_NONBLOCK: if (apr_is_option_set(sock, APR_SO_NONBLOCK) != on) { if (on) { if ((stat = sononblock(sock->socketdes)) != APR_SUCCESS) return stat; } else { if ((stat = soblock(sock->socketdes)) != APR_SUCCESS) return stat; } apr_set_option(sock, APR_SO_NONBLOCK, on); } break; case APR_SO_LINGER: { if (apr_is_option_set(sock, APR_SO_LINGER) != on) { struct linger li; li.l_onoff = on; li.l_linger = APR_MAX_SECS_TO_LINGER; if (setsockopt(sock->socketdes, SOL_SOCKET, SO_LINGER, (char *) &li, sizeof(struct linger)) == -1) { return apr_get_netos_error(); } apr_set_option(sock, APR_SO_LINGER, on); } break; } case APR_TCP_DEFER_ACCEPT: #if defined(TCP_DEFER_ACCEPT) if (apr_is_option_set(sock, APR_TCP_DEFER_ACCEPT) != on) { int optlevel = IPPROTO_TCP; int optname = TCP_DEFER_ACCEPT; if (setsockopt(sock->socketdes, optlevel, optname, (void *)&on, sizeof(int)) == -1) { return errno; } apr_set_option(sock, APR_TCP_DEFER_ACCEPT, on); } #else return APR_ENOTIMPL; #endif case APR_TCP_NODELAY: if (apr_is_option_set(sock, APR_TCP_NODELAY) != on) { int optlevel = IPPROTO_TCP; int optname = TCP_NODELAY; #if APR_HAVE_SCTP if (sock->protocol == IPPROTO_SCTP) { optlevel = IPPROTO_SCTP; optname = SCTP_NODELAY; } #endif if (setsockopt(sock->socketdes, optlevel, optname, (void *)&on, sizeof(int)) == -1) { return apr_get_netos_error(); } apr_set_option(sock, APR_TCP_NODELAY, on); } break; case APR_IPV6_V6ONLY: #if APR_HAVE_IPV6 && defined(IPV6_V6ONLY) /* we don't know the initial setting of this option, * so don't check sock->options since that optimization * won't work */ if (setsockopt(sock->socketdes, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&on, sizeof(int)) == -1) { return apr_get_netos_error(); } apr_set_option(sock, APR_IPV6_V6ONLY, on); #else return APR_ENOTIMPL; #endif break; default: return APR_EINVAL; break; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_timeout_get(apr_socket_t *sock, apr_interval_time_t *t) { *t = sock->timeout; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_opt_get(apr_socket_t *sock, apr_int32_t opt, apr_int32_t *on) { switch (opt) { case APR_SO_DISCONNECTED: *on = sock->disconnected; break; case APR_SO_KEEPALIVE: case APR_SO_DEBUG: case APR_SO_REUSEADDR: case APR_SO_NONBLOCK: case APR_SO_LINGER: default: *on = apr_is_option_set(sock, opt); break; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_atmark(apr_socket_t *sock, int *atmark) { u_long oobmark; if (ioctlsocket(sock->socketdes, SIOCATMARK, (void*) &oobmark) < 0) return apr_get_netos_error(); *atmark = (oobmark != 0); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_gethostname(char *buf, int len, apr_pool_t *cont) { if (gethostname(buf, len) == -1) { buf[0] = '\0'; return apr_get_netos_error(); } else if (!memchr(buf, '\0', len)) { /* buffer too small */ buf[0] = '\0'; return APR_ENAMETOOLONG; } return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/network_io/win32/sockopt.c
C
asf20
8,607
/* 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 "apr_arch_file_io.h" #if APR_HAVE_TIME_H #include <time.h> #endif /* MAX_SEGMENT_SIZE is the maximum amount of data that will be sent to a client * in one call of TransmitFile. This number must be small enough to give the * slowest client time to receive the data before the socket timeout triggers. * The same problem can exist with apr_socket_send(). In that case, we rely on * the application to adjust socket timeouts and max send segment * sizes appropriately. * For example, Apache will in most cases call apr_socket_send() with less * than 8193 bytes. */ #define MAX_SEGMENT_SIZE 65536 #define WSABUF_ON_STACK 50 APR_DECLARE(apr_status_t) apr_socket_send(apr_socket_t *sock, const char *buf, apr_size_t *len) { apr_ssize_t rv; WSABUF wsaData; int lasterror; DWORD dwBytes = 0; wsaData.len = (u_long)*len; wsaData.buf = (char*) buf; #ifndef _WIN32_WCE rv = WSASend(sock->socketdes, &wsaData, 1, &dwBytes, 0, NULL, NULL); #else rv = send(sock->socketdes, wsaData.buf, wsaData.len, 0); dwBytes = rv; #endif if (rv == SOCKET_ERROR) { lasterror = apr_get_netos_error(); *len = 0; return lasterror; } *len = dwBytes; 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; WSABUF wsaData; int lasterror; DWORD dwBytes = 0; DWORD flags = 0; wsaData.len = (u_long)*len; wsaData.buf = (char*) buf; #ifndef _WIN32_WCE rv = WSARecv(sock->socketdes, &wsaData, 1, &dwBytes, &flags, NULL, NULL); #else rv = recv(sock->socketdes, wsaData.buf, wsaData.len, 0); dwBytes = rv; #endif if (rv == SOCKET_ERROR) { lasterror = apr_get_netos_error(); *len = 0; return lasterror; } *len = dwBytes; return dwBytes == 0 ? APR_EOF : APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_sendv(apr_socket_t *sock, const struct iovec *vec, apr_int32_t in_vec, apr_size_t *nbytes) { apr_status_t rc = APR_SUCCESS; apr_ssize_t rv; apr_size_t cur_len; apr_int32_t nvec = 0; int i, j = 0; DWORD dwBytes = 0; WSABUF *pWsaBuf; for (i = 0; i < in_vec; i++) { cur_len = vec[i].iov_len; nvec++; while (cur_len > APR_DWORD_MAX) { nvec++; cur_len -= APR_DWORD_MAX; } } pWsaBuf = (nvec <= WSABUF_ON_STACK) ? _alloca(sizeof(WSABUF) * (nvec)) : malloc(sizeof(WSABUF) * (nvec)); if (!pWsaBuf) return APR_ENOMEM; for (i = 0; i < in_vec; i++) { char * base = vec[i].iov_base; cur_len = vec[i].iov_len; do { if (cur_len > APR_DWORD_MAX) { pWsaBuf[j].buf = base; pWsaBuf[j].len = APR_DWORD_MAX; cur_len -= APR_DWORD_MAX; base += APR_DWORD_MAX; } else { pWsaBuf[j].buf = base; pWsaBuf[j].len = (DWORD)cur_len; cur_len = 0; } j++; } while (cur_len > 0); } #ifndef _WIN32_WCE rv = WSASend(sock->socketdes, pWsaBuf, nvec, &dwBytes, 0, NULL, NULL); if (rv == SOCKET_ERROR) { rc = apr_get_netos_error(); } #else for (i = 0; i < nvec; i++) { rv = send(sock->socketdes, pWsaBuf[i].buf, pWsaBuf[i].len, 0); if (rv == SOCKET_ERROR) { rc = apr_get_netos_error(); break; } dwBytes += rv; } #endif if (nvec > WSABUF_ON_STACK) free(pWsaBuf); *nbytes = dwBytes; return rc; } 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; rv = sendto(sock->socketdes, buf, (int)*len, flags, (const struct sockaddr*)&where->sa, where->salen); if (rv == SOCKET_ERROR) { *len = 0; return apr_get_netos_error(); } *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; rv = recvfrom(sock->socketdes, buf, (int)*len, flags, (struct sockaddr*)&from->sa, &from->salen); if (rv == SOCKET_ERROR) { (*len) = 0; return apr_get_netos_error(); } (*len) = rv; if (rv == 0 && sock->type == SOCK_STREAM) return APR_EOF; return APR_SUCCESS; } static apr_status_t collapse_iovec(char **off, apr_size_t *len, struct iovec *iovec, int numvec, char *buf, apr_size_t buflen) { if (numvec == 1) { *off = iovec[0].iov_base; *len = iovec[0].iov_len; } else { int i; for (i = 0; i < numvec; i++) { *len += iovec[i].iov_len; } if (*len > buflen) { *len = 0; return APR_INCOMPLETE; } *off = buf; for (i = 0; i < numvec; i++) { memcpy(buf, iovec[i].iov_base, iovec[i].iov_len); buf += iovec[i].iov_len; } } return APR_SUCCESS; } #if APR_HAS_SENDFILE /* * apr_status_t apr_socket_sendfile(apr_socket_t *, apr_file_t *, apr_hdtr_t *, * apr_off_t *, apr_size_t *, apr_int32_t flags) * Send a file from an open file descriptor to a socket, along with * optional headers and trailers * arg 1) The socket to which we're writing * arg 2) The open file from which to read * arg 3) A structure containing the headers and trailers to send * arg 4) Offset into the file where we should begin writing * arg 5) Number of bytes to send out of the file * arg 6) APR flags that are mapped to OS specific flags */ APR_DECLARE(apr_status_t) apr_socket_sendfile(apr_socket_t *sock, apr_file_t *file, apr_hdtr_t *hdtr, apr_off_t *offset, apr_size_t *len, apr_int32_t flags) { apr_status_t status = APR_SUCCESS; apr_status_t rv; apr_off_t curoff = *offset; DWORD dwFlags = 0; apr_size_t nbytes; TRANSMIT_FILE_BUFFERS tfb, *ptfb = NULL; int ptr = 0; apr_size_t bytes_to_send; /* Bytes to send out of the file (not including headers) */ int disconnected = 0; int sendv_trailers = 0; char hdtrbuf[4096]; if (apr_os_level < APR_WIN_NT) { return APR_ENOTIMPL; } /* Use len to keep track of number of total bytes sent (including headers) */ bytes_to_send = *len; *len = 0; /* Handle the goofy case of sending headers/trailers and a zero byte file */ if (!bytes_to_send && hdtr) { if (hdtr->numheaders) { rv = apr_socket_sendv(sock, hdtr->headers, hdtr->numheaders, &nbytes); if (rv != APR_SUCCESS) return rv; *len += nbytes; } if (hdtr->numtrailers) { rv = apr_socket_sendv(sock, hdtr->trailers, hdtr->numtrailers, &nbytes); if (rv != APR_SUCCESS) return rv; *len += nbytes; } return APR_SUCCESS; } memset(&tfb, '\0', sizeof (tfb)); /* Collapse the headers into a single buffer */ if (hdtr && hdtr->numheaders) { apr_size_t head_length = tfb.HeadLength; ptfb = &tfb; nbytes = 0; rv = collapse_iovec((char **)&ptfb->Head, &head_length, hdtr->headers, hdtr->numheaders, hdtrbuf, sizeof(hdtrbuf)); tfb.HeadLength = (DWORD)head_length; /* If not enough buffer, punt to sendv */ if (rv == APR_INCOMPLETE) { rv = apr_socket_sendv(sock, hdtr->headers, hdtr->numheaders, &nbytes); if (rv != APR_SUCCESS) return rv; *len += nbytes; ptfb = NULL; } } /* Initialize the overlapped structure used on TransmitFile */ if (!sock->overlapped) { sock->overlapped = apr_pcalloc(sock->pool, sizeof(OVERLAPPED)); sock->overlapped->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); } while (bytes_to_send) { DWORD xmitbytes; if (bytes_to_send > MAX_SEGMENT_SIZE) { xmitbytes = MAX_SEGMENT_SIZE; } else { /* Last call to TransmitFile() */ xmitbytes = (DWORD)bytes_to_send; /* Collapse the trailers into a single buffer */ if (hdtr && hdtr->numtrailers) { apr_size_t tail_length = tfb.TailLength; ptfb = &tfb; rv = collapse_iovec((char**) &ptfb->Tail, &tail_length, hdtr->trailers, hdtr->numtrailers, hdtrbuf + ptfb->HeadLength, sizeof(hdtrbuf) - ptfb->HeadLength); tfb.TailLength = (DWORD)tail_length; if (rv == APR_INCOMPLETE) { /* If not enough buffer, punt to sendv, later */ sendv_trailers = 1; } } /* Disconnect the socket after last send */ if ((flags & APR_SENDFILE_DISCONNECT_SOCKET) && !sendv_trailers) { dwFlags |= TF_REUSE_SOCKET; dwFlags |= TF_DISCONNECT; disconnected = 1; } } sock->overlapped->Offset = (DWORD)(curoff); #if APR_HAS_LARGE_FILES sock->overlapped->OffsetHigh = (DWORD)(curoff >> 32); #endif /* XXX BoundsChecker claims dwFlags must not be zero. */ rv = TransmitFile(sock->socketdes, /* socket */ file->filehand, /* open file descriptor of the file to be sent */ xmitbytes, /* number of bytes to send. 0=send all */ 0, /* Number of bytes per send. 0=use default */ sock->overlapped, /* OVERLAPPED structure */ ptfb, /* header and trailer buffers */ dwFlags); /* flags to control various aspects of TransmitFile */ if (!rv) { status = apr_get_netos_error(); if ((status == APR_FROM_OS_ERROR(ERROR_IO_PENDING)) || (status == APR_FROM_OS_ERROR(WSA_IO_PENDING))) { rv = WaitForSingleObject(sock->overlapped->hEvent, (DWORD)(sock->timeout >= 0 ? sock->timeout_ms : INFINITE)); if (rv == WAIT_OBJECT_0) { status = APR_SUCCESS; if (!disconnected) { if (!WSAGetOverlappedResult(sock->socketdes, sock->overlapped, &xmitbytes, FALSE, &dwFlags)) { status = apr_get_netos_error(); } /* Ugly code alert: WSAGetOverlappedResult returns * a count of all bytes sent. This loop only * tracks bytes sent out of the file. */ else if (ptfb) { xmitbytes -= (ptfb->HeadLength + ptfb->TailLength); } } } else if (rv == WAIT_TIMEOUT) { status = APR_FROM_OS_ERROR(WAIT_TIMEOUT); } else if (rv == WAIT_ABANDONED) { /* Hummm... WAIT_ABANDONDED is not an error code. It is * a return specific to the Win32 WAIT functions that * indicates that a thread exited while holding a * mutex. Should consider triggering an assert * to detect the condition... */ status = APR_FROM_OS_ERROR(WAIT_TIMEOUT); } else status = apr_get_os_error(); } } if (status != APR_SUCCESS) break; bytes_to_send -= xmitbytes; curoff += xmitbytes; *len += xmitbytes; /* Adjust len for any headers/trailers sent */ if (ptfb) { *len += (ptfb->HeadLength + ptfb->TailLength); memset(&tfb, '\0', sizeof (tfb)); ptfb = NULL; } } if (status == APR_SUCCESS) { if (sendv_trailers) { rv = apr_socket_sendv(sock, hdtr->trailers, hdtr->numtrailers, &nbytes); if (rv != APR_SUCCESS) return rv; *len += nbytes; } /* Mark the socket as disconnected, but do not close it. * Note: The application must have stored the socket prior to making * the call to apr_socket_sendfile in order to either reuse it * or close it. */ if (disconnected) { sock->disconnected = 1; sock->socketdes = INVALID_SOCKET; } } return status; } #endif
001-log4cxx
trunk/src/apr/network_io/win32/sendrecv.c
C
asf20
15,083
#include "../unix/inet_ntop.c" #include "../unix/inet_pton.c" #include "../unix/sockets.c" #include "../unix/sockaddr.c" #include "../unix/sockopt.c"
001-log4cxx
trunk/src/apr/network_io/beos/socketcommon.c
C
asf20
150
/* 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" #if BEOS_BONE /* BONE uses the unix code - woohoo */ #include "../unix/sendrecv.c" #else #include "apr_arch_networkio.h" #include "apr_time.h" static apr_status_t wait_for_io_or_timeout(apr_socket_t *sock, int for_read) { struct timeval tv, *tvptr; fd_set fdset; int srv; do { FD_ZERO(&fdset); FD_SET(sock->socketdes, &fdset); if (sock->timeout < 0) { tvptr = NULL; } else { tv.tv_sec = sock->timeout / APR_USEC_PER_SEC; tv.tv_usec = sock->timeout % APR_USEC_PER_SEC; tvptr = &tv; } srv = select(sock->socketdes + 1, for_read ? &fdset : NULL, for_read ? NULL : &fdset, NULL, tvptr); /* TODO - timeout should be smaller on repeats of this loop */ } while (srv == -1 && errno == EINTR); if (srv == 0) { return APR_TIMEUP; } else if (srv < 0) { return errno; } return APR_SUCCESS; } #define SEND_WAIT APR_USEC_PER_SEC / 10 APR_DECLARE(apr_status_t) apr_socket_send(apr_socket_t *sock, const char *buf, apr_size_t *len) { apr_ssize_t rv; do { rv = send(sock->socketdes, buf, (*len), 0); } while (rv == -1 && errno == EINTR); if (rv == -1 && errno == EWOULDBLOCK && sock->timeout > 0) { apr_int32_t snooze_val = SEND_WAIT; apr_int32_t zzz = 0; do { rv = send(sock->socketdes, buf, (*len), 0); if (rv == -1 && errno == EWOULDBLOCK){ apr_sleep (snooze_val); zzz += snooze_val; snooze_val += SEND_WAIT; /* have we passed our timeout value */ if (zzz > (sock->timeout * APR_USEC_PER_SEC)) break; } } while (rv == -1 && (errno == EINTR || errno == EWOULDBLOCK)); } if (rv == -1) { *len = 0; return errno; } (*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; do { rv = recv(sock->socketdes, buf, (*len), 0); } while (rv == -1 && errno == EINTR); if (rv == -1 && errno == EWOULDBLOCK && sock->timeout > 0) { apr_status_t arv = wait_for_io_or_timeout(sock, 1); if (arv != APR_SUCCESS) { *len = 0; return arv; } else { do { rv = recv(sock->socketdes, buf, (*len), 0); } while (rv == -1 && errno == EINTR); } } if (rv == -1) { (*len) = 0; return errno; } (*len) = rv; if (rv == 0) return APR_EOF; return APR_SUCCESS; } /* BeOS doesn't have writev for sockets so we use the following instead... */ APR_DECLARE(apr_status_t) apr_socket_sendv(apr_socket_t * sock, const struct iovec *vec, apr_int32_t nvec, apr_size_t *len) { *len = vec[0].iov_len; return apr_socket_send(sock, vec[0].iov_base, len); } 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; do { rv = sendto(sock->socketdes, buf, (*len), flags, (const struct sockaddr*)&where->sa, where->salen); } while (rv == -1 && errno == EINTR); if (rv == -1 && (errno == EAGAIN || errno == EWOULDBLOCK) && sock->timeout != 0) { apr_status_t arv = wait_for_io_or_timeout(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 && errno == EINTR); } } if (rv == -1) { *len = 0; return errno; } *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; if (from == NULL){ return APR_ENOMEM; /* Not sure if this is correct. Maybe we should just allocate the memory?? */ } do { rv = recvfrom(sock->socketdes, buf, (*len), flags, (struct sockaddr*)&from->sa, &from->salen); } while (rv == -1 && errno == EINTR); if (rv == -1 && (errno == EAGAIN || errno == EWOULDBLOCK) && sock->timeout != 0) { apr_status_t arv = wait_for_io_or_timeout(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 && errno == EINTR); } } if (rv == -1) { (*len) = 0; return errno; } (*len) = rv; if (rv == 0) return APR_EOF; return APR_SUCCESS; } #endif /* ! BEOS_BONE */
001-log4cxx
trunk/src/apr/network_io/beos/sendrecv.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. */ #include "apr_arch_networkio.h" #include "apr_network_io.h" #include "apr_strings.h" #include "apr_support.h" #include "apr_portable.h" #include "apr_arch_inherit.h" #ifdef BEOS_R5 #undef close #define close closesocket #endif /* BEOS_R5 */ static char generic_inaddr_any[16] = {0}; /* big enough for IPv4 or IPv6 */ static apr_status_t socket_cleanup(void *sock) { apr_socket_t *thesocket = sock; if (close(thesocket->socketdes) == 0) { thesocket->socketdes = -1; return APR_SUCCESS; } else { return errno; } } static void set_socket_vars(apr_socket_t *sock, int family, int type, int protocol) { sock->type = type; sock->protocol = protocol; apr_sockaddr_vars_set(sock->local_addr, family, 0); apr_sockaddr_vars_set(sock->remote_addr, family, 0); sock->options = 0; #if defined(BEOS) && !defined(BEOS_BONE) /* BeOS pre-BONE has TCP_NODELAY on by default and it can't be * switched off! */ sock->options |= APR_TCP_NODELAY; #endif } static void alloc_socket(apr_socket_t **new, apr_pool_t *p) { *new = (apr_socket_t *)apr_pcalloc(p, sizeof(apr_socket_t)); (*new)->pool = p; (*new)->local_addr = (apr_sockaddr_t *)apr_pcalloc((*new)->pool, sizeof(apr_sockaddr_t)); (*new)->local_addr->pool = p; (*new)->remote_addr = (apr_sockaddr_t *)apr_pcalloc((*new)->pool, sizeof(apr_sockaddr_t)); (*new)->remote_addr->pool = p; (*new)->remote_addr_unknown = 1; #ifndef WAITIO_USES_POLL /* Create a pollset with room for one descriptor. */ /* ### check return codes */ (void) apr_pollset_create(&(*new)->pollset, 1, p, 0); #endif } apr_status_t apr_socket_protocol_get(apr_socket_t *sock, int *protocol) { *protocol = sock->protocol; return APR_SUCCESS; } apr_status_t apr_socket_create(apr_socket_t **new, int ofamily, int type, int protocol, apr_pool_t *cont) { int family = ofamily; if (family == APR_UNSPEC) { #if APR_HAVE_IPV6 family = APR_INET6; #else family = APR_INET; #endif } alloc_socket(new, cont); #ifndef BEOS_R5 (*new)->socketdes = socket(family, type, protocol); #else /* For some reason BeOS R5 has an unconventional protocol numbering, * so we need to translate here. */ switch (protocol) { case 0: (*new)->socketdes = socket(family, type, 0); break; case APR_PROTO_TCP: (*new)->socketdes = socket(family, type, IPPROTO_TCP); break; case APR_PROTO_UDP: (*new)->socketdes = socket(family, type, IPPROTO_UDP); break; case APR_PROTO_SCTP: default: errno = EPROTONOSUPPORT; (*new)->socketdes = -1; break; } #endif /* BEOS_R5 */ #if APR_HAVE_IPV6 if ((*new)->socketdes < 0 && ofamily == APR_UNSPEC) { family = APR_INET; (*new)->socketdes = socket(family, type, protocol); } #endif if ((*new)->socketdes < 0) { return errno; } set_socket_vars(*new, family, type, protocol); (*new)->timeout = -1; (*new)->inherit = 0; apr_pool_cleanup_register((*new)->pool, (void *)(*new), socket_cleanup, socket_cleanup); return APR_SUCCESS; } apr_status_t apr_socket_shutdown(apr_socket_t *thesocket, apr_shutdown_how_e how) { return (shutdown(thesocket->socketdes, how) == -1) ? errno : APR_SUCCESS; } apr_status_t apr_socket_close(apr_socket_t *thesocket) { return apr_pool_cleanup_run(thesocket->pool, thesocket, socket_cleanup); } apr_status_t apr_socket_bind(apr_socket_t *sock, apr_sockaddr_t *sa) { if (bind(sock->socketdes, (struct sockaddr *)&sa->sa, sa->salen) == -1) { return errno; } else { sock->local_addr = sa; /* XXX IPv6 - this assumes sin_port and sin6_port at same offset */ if (sock->local_addr->sa.sin.sin_port == 0) { /* no need for ntohs() when comparing w/ 0 */ sock->local_port_unknown = 1; /* kernel got us an ephemeral port */ } return APR_SUCCESS; } } apr_status_t apr_socket_listen(apr_socket_t *sock, apr_int32_t backlog) { if (listen(sock->socketdes, backlog) == -1) return errno; else return APR_SUCCESS; } apr_status_t apr_socket_accept(apr_socket_t **new, apr_socket_t *sock, apr_pool_t *connection_context) { alloc_socket(new, connection_context); set_socket_vars(*new, sock->local_addr->sa.sin.sin_family, SOCK_STREAM, sock->protocol); #ifndef HAVE_POLL (*new)->connected = 1; #endif (*new)->timeout = -1; (*new)->socketdes = accept(sock->socketdes, (struct sockaddr *)&(*new)->remote_addr->sa, &(*new)->remote_addr->salen); if ((*new)->socketdes < 0) { return errno; } #ifdef TPF if ((*new)->socketdes == 0) { /* 0 is an invalid socket for TPF */ return APR_EINTR; } #endif (*new)->remote_addr_unknown = 0; *(*new)->local_addr = *sock->local_addr; /* The above assignment just overwrote the pool entry. Setting the local_addr pool for the accepted socket back to what it should be. Otherwise all allocations for this socket will come from a server pool that is not freed until the process goes down.*/ (*new)->local_addr->pool = connection_context; /* fix up any pointers which are no longer valid */ if (sock->local_addr->sa.sin.sin_family == AF_INET) { (*new)->local_addr->ipaddr_ptr = &(*new)->local_addr->sa.sin.sin_addr; } #if APR_HAVE_IPV6 else if (sock->local_addr->sa.sin.sin_family == AF_INET6) { (*new)->local_addr->ipaddr_ptr = &(*new)->local_addr->sa.sin6.sin6_addr; } #endif (*new)->remote_addr->port = ntohs((*new)->remote_addr->sa.sin.sin_port); if (sock->local_port_unknown) { /* not likely for a listening socket, but theoretically possible :) */ (*new)->local_port_unknown = 1; } #if APR_TCP_NODELAY_INHERITED if (apr_is_option_set(sock, APR_TCP_NODELAY) == 1) { apr_set_option(*new, APR_TCP_NODELAY, 1); } #endif /* TCP_NODELAY_INHERITED */ #if APR_O_NONBLOCK_INHERITED if (apr_is_option_set(sock, APR_SO_NONBLOCK) == 1) { apr_set_option(*new, APR_SO_NONBLOCK, 1); } #endif /* APR_O_NONBLOCK_INHERITED */ if (sock->local_interface_unknown || !memcmp(sock->local_addr->ipaddr_ptr, generic_inaddr_any, sock->local_addr->ipaddr_len)) { /* If the interface address inside the listening socket's local_addr wasn't * up-to-date, we don't know local interface of the connected socket either. * * If the listening socket was not bound to a specific interface, we * don't know the local_addr of the connected socket. */ (*new)->local_interface_unknown = 1; } (*new)->inherit = 0; apr_pool_cleanup_register((*new)->pool, (void *)(*new), socket_cleanup, socket_cleanup); return APR_SUCCESS; } apr_status_t apr_socket_connect(apr_socket_t *sock, apr_sockaddr_t *sa) { int rc; do { rc = connect(sock->socketdes, (const struct sockaddr *)&sa->sa.sin, sa->salen); } while (rc == -1 && errno == EINTR); /* we can see EINPROGRESS the first time connect is called on a non-blocking * socket; if called again, we can see EALREADY */ if ((rc == -1) && (errno == EINPROGRESS || errno == EALREADY) && (sock->timeout > 0)) { rc = apr_wait_for_io_or_timeout(NULL, sock, 0); if (rc != APR_SUCCESS) { return rc; } #ifdef SO_ERROR { int error; apr_socklen_t len = sizeof(error); if ((rc = getsockopt(sock->socketdes, SOL_SOCKET, SO_ERROR, (char *)&error, &len)) < 0) { return errno; } if (error) { return error; } } #endif /* SO_ERROR */ } if (rc == -1 && errno != EISCONN) { return errno; } if (memcmp(sa->ipaddr_ptr, generic_inaddr_any, sa->ipaddr_len)) { /* A real remote address was passed in. If the unspecified * address was used, the actual remote addr will have to be * determined using getpeername() if required. */ /* ### this should probably be a structure copy + fixup as per * _accept()'s handling of local_addr */ sock->remote_addr = sa; sock->remote_addr_unknown = 0; } if (sock->local_addr->port == 0) { /* connect() got us an ephemeral port */ sock->local_port_unknown = 1; } if (!memcmp(sock->local_addr->ipaddr_ptr, generic_inaddr_any, sock->local_addr->ipaddr_len)) { /* not bound to specific local interface; connect() had to assign * one for the socket */ sock->local_interface_unknown = 1; } #ifndef HAVE_POLL sock->connected=1; #endif return APR_SUCCESS; } apr_status_t apr_socket_type_get(apr_socket_t *sock, int *type) { *type = sock->type; return APR_SUCCESS; } apr_status_t apr_socket_data_get(void **data, const char *key, apr_socket_t *sock) { sock_userdata_t *cur = sock->userdata; *data = NULL; while (cur) { if (!strcmp(cur->key, key)) { *data = cur->data; break; } cur = cur->next; } return APR_SUCCESS; } apr_status_t apr_socket_data_set(apr_socket_t *sock, void *data, const char *key, apr_status_t (*cleanup) (void *)) { sock_userdata_t *new = apr_palloc(sock->pool, sizeof(sock_userdata_t)); new->key = apr_pstrdup(sock->pool, key); new->data = data; new->next = sock->userdata; sock->userdata = new; if (cleanup) { apr_pool_cleanup_register(sock->pool, data, cleanup, cleanup); } return APR_SUCCESS; } apr_status_t apr_os_sock_get(apr_os_sock_t *thesock, apr_socket_t *sock) { *thesock = sock->socketdes; return APR_SUCCESS; } apr_status_t apr_os_sock_make(apr_socket_t **apr_sock, apr_os_sock_info_t *os_sock_info, apr_pool_t *cont) { alloc_socket(apr_sock, cont); set_socket_vars(*apr_sock, os_sock_info->family, os_sock_info->type, os_sock_info->protocol); (*apr_sock)->timeout = -1; (*apr_sock)->socketdes = *os_sock_info->os_sock; if (os_sock_info->local) { memcpy(&(*apr_sock)->local_addr->sa.sin, os_sock_info->local, (*apr_sock)->local_addr->salen); /* XXX IPv6 - this assumes sin_port and sin6_port at same offset */ (*apr_sock)->local_addr->port = ntohs((*apr_sock)->local_addr->sa.sin.sin_port); } else { (*apr_sock)->local_port_unknown = (*apr_sock)->local_interface_unknown = 1; } if (os_sock_info->remote) { #ifndef HAVE_POLL (*apr_sock)->connected = 1; #endif memcpy(&(*apr_sock)->remote_addr->sa.sin, os_sock_info->remote, (*apr_sock)->remote_addr->salen); /* XXX IPv6 - this assumes sin_port and sin6_port at same offset */ (*apr_sock)->remote_addr->port = ntohs((*apr_sock)->remote_addr->sa.sin.sin_port); } else { (*apr_sock)->remote_addr_unknown = 1; } (*apr_sock)->inherit = 0; apr_pool_cleanup_register((*apr_sock)->pool, (void *)(*apr_sock), socket_cleanup, socket_cleanup); return APR_SUCCESS; } apr_status_t apr_os_sock_put(apr_socket_t **sock, apr_os_sock_t *thesock, apr_pool_t *cont) { /* XXX Bogus assumption that *sock points at anything legit */ if ((*sock) == NULL) { alloc_socket(sock, cont); /* XXX IPv6 figure out the family here! */ /* XXX figure out the actual socket type here */ /* *or* just decide that apr_os_sock_put() has to be told the family and type */ set_socket_vars(*sock, APR_INET, SOCK_STREAM, 0); (*sock)->timeout = -1; } (*sock)->local_port_unknown = (*sock)->local_interface_unknown = 1; (*sock)->remote_addr_unknown = 1; (*sock)->socketdes = *thesock; return APR_SUCCESS; } APR_POOL_IMPLEMENT_ACCESSOR(socket) APR_IMPLEMENT_INHERIT_SET(socket, inherit, pool, socket_cleanup) APR_IMPLEMENT_INHERIT_UNSET(socket, inherit, pool, socket_cleanup)
001-log4cxx
trunk/src/apr/network_io/unix/sockets.c
C
asf20
13,562
/* Copyright (c) 1996 by Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ #include "apr_private.h" #include "apr_arch_networkio.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_NETINET_IN_H #include <netinet/in.h> #endif #if APR_HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #include <string.h> #if APR_HAVE_ERRNO_H #include <errno.h> #endif #ifndef IN6ADDRSZ #define IN6ADDRSZ 16 #endif #ifndef INT16SZ #define INT16SZ sizeof(apr_int16_t) #endif #ifndef INADDRSZ #define INADDRSZ 4 #endif #ifndef __P #define __P(x) x #endif #if !defined(EAFNOSUPPORT) && defined(WSAEAFNOSUPPORT) #define EAFNOSUPPORT WSAEAFNOSUPPORT #endif /* * WARNING: Don't even consider trying to compile this on a system where * sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX. */ static int inet_pton4 __P((const char *src, unsigned char *dst)); #if APR_HAVE_IPV6 static int inet_pton6 __P((const char *src, unsigned char *dst)); #endif /* int * inet_pton(af, src, dst) * convert from presentation format (which usually means ASCII printable) * to network format (which is usually some kind of binary format). * return: * 1 if the address was valid for the specified address family * 0 if the address wasn't valid (`dst' is untouched in this case) * -1 if some other error occurred (`dst' is untouched in this case, too) * author: * Paul Vixie, 1996. */ int apr_inet_pton(int af, const char *src, void *dst) { switch (af) { case AF_INET: return (inet_pton4(src, dst)); #if APR_HAVE_IPV6 case AF_INET6: return (inet_pton6(src, dst)); #endif default: errno = EAFNOSUPPORT; return (-1); } /* NOTREACHED */ } /* int * inet_pton4(src, dst) * like inet_aton() but without all the hexadecimal and shorthand. * return: * 1 if `src' is a valid dotted quad, else 0. * notice: * does not touch `dst' unless it's returning 1. * author: * Paul Vixie, 1996. */ static int inet_pton4(const char *src, unsigned char *dst) { static const char digits[] = "0123456789"; int saw_digit, octets, ch; unsigned char tmp[INADDRSZ], *tp; saw_digit = 0; octets = 0; *(tp = tmp) = 0; while ((ch = *src++) != '\0') { const char *pch; if ((pch = strchr(digits, ch)) != NULL) { unsigned int new = *tp * 10 + (unsigned int)(pch - digits); if (new > 255) return (0); *tp = new; if (! saw_digit) { if (++octets > 4) return (0); saw_digit = 1; } } else if (ch == '.' && saw_digit) { if (octets == 4) return (0); *++tp = 0; saw_digit = 0; } else return (0); } if (octets < 4) return (0); memcpy(dst, tmp, INADDRSZ); return (1); } #if APR_HAVE_IPV6 /* int * inet_pton6(src, dst) * convert presentation level address to network order binary form. * return: * 1 if `src' is a valid [RFC1884 2.2] address, else 0. * notice: * (1) does not touch `dst' unless it's returning 1. * (2) :: in a full address is silently ignored. * credit: * inspired by Mark Andrews. * author: * Paul Vixie, 1996. */ static int inet_pton6(const char *src, unsigned char *dst) { static const char xdigits_l[] = "0123456789abcdef", xdigits_u[] = "0123456789ABCDEF"; unsigned char tmp[IN6ADDRSZ], *tp, *endp, *colonp; const char *xdigits, *curtok; int ch, saw_xdigit; unsigned int val; memset((tp = tmp), '\0', IN6ADDRSZ); endp = tp + IN6ADDRSZ; colonp = NULL; /* Leading :: requires some special handling. */ if (*src == ':') if (*++src != ':') return (0); curtok = src; saw_xdigit = 0; val = 0; while ((ch = *src++) != '\0') { const char *pch; if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL) pch = strchr((xdigits = xdigits_u), ch); if (pch != NULL) { val <<= 4; val |= (pch - xdigits); if (val > 0xffff) return (0); saw_xdigit = 1; continue; } if (ch == ':') { curtok = src; if (!saw_xdigit) { if (colonp) return (0); colonp = tp; continue; } if (tp + INT16SZ > endp) return (0); *tp++ = (unsigned char) (val >> 8) & 0xff; *tp++ = (unsigned char) val & 0xff; saw_xdigit = 0; val = 0; continue; } if (ch == '.' && ((tp + INADDRSZ) <= endp) && inet_pton4(curtok, tp) > 0) { tp += INADDRSZ; saw_xdigit = 0; break; /* '\0' was seen by inet_pton4(). */ } return (0); } if (saw_xdigit) { if (tp + INT16SZ > endp) return (0); *tp++ = (unsigned char) (val >> 8) & 0xff; *tp++ = (unsigned char) val & 0xff; } if (colonp != NULL) { /* * Since some memmove()'s erroneously fail to handle * overlapping regions, we'll do the shift by hand. */ const int n = tp - colonp; int i; for (i = 1; i <= n; i++) { endp[- i] = colonp[n - i]; colonp[n - i] = 0; } tp = endp; } if (tp != endp) return (0); memcpy(dst, tmp, IN6ADDRSZ); return (1); } #endif
001-log4cxx
trunk/src/apr/network_io/unix/inet_pton.c
C
asf20
5,654
/* 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_strings.h" static apr_status_t soblock(int sd) { /* BeOS uses setsockopt at present for non blocking... */ #ifndef BEOS int fd_flags; fd_flags = fcntl(sd, F_GETFL, 0); #if defined(O_NONBLOCK) fd_flags &= ~O_NONBLOCK; #elif defined(O_NDELAY) fd_flags &= ~O_NDELAY; #elif defined(FNDELAY) fd_flags &= ~FNDELAY; #else #error Please teach APR how to make sockets blocking on your platform. #endif if (fcntl(sd, F_SETFL, fd_flags) == -1) { return errno; } #else int on = 0; if (setsockopt(sd, SOL_SOCKET, SO_NONBLOCK, &on, sizeof(int)) < 0) return errno; #endif /* BEOS */ return APR_SUCCESS; } static apr_status_t sononblock(int sd) { #ifndef BEOS int fd_flags; fd_flags = fcntl(sd, F_GETFL, 0); #if defined(O_NONBLOCK) fd_flags |= O_NONBLOCK; #elif defined(O_NDELAY) fd_flags |= O_NDELAY; #elif defined(FNDELAY) fd_flags |= FNDELAY; #else #error Please teach APR how to make sockets non-blocking on your platform. #endif if (fcntl(sd, F_SETFL, fd_flags) == -1) { return errno; } #else int on = 1; if (setsockopt(sd, SOL_SOCKET, SO_NONBLOCK, &on, sizeof(int)) < 0) return errno; #endif /* BEOS */ return APR_SUCCESS; } apr_status_t apr_socket_timeout_set(apr_socket_t *sock, apr_interval_time_t t) { apr_status_t stat; /* If our new timeout is non-negative and our old timeout was * negative, then we need to ensure that we are non-blocking. * Conversely, if our new timeout is negative and we had * non-negative timeout, we must make sure our socket is blocking. * We want to avoid calling fcntl more than necessary on the * socket. */ if (t >= 0 && sock->timeout < 0) { if (apr_is_option_set(sock, APR_SO_NONBLOCK) != 1) { if ((stat = sononblock(sock->socketdes)) != APR_SUCCESS) { return stat; } apr_set_option(sock, APR_SO_NONBLOCK, 1); } } else if (t < 0 && sock->timeout >= 0) { if (apr_is_option_set(sock, APR_SO_NONBLOCK) != 0) { if ((stat = soblock(sock->socketdes)) != APR_SUCCESS) { return stat; } apr_set_option(sock, APR_SO_NONBLOCK, 0); } } /* must disable the incomplete read support if we disable * a timeout */ if (t <= 0) { sock->options &= ~APR_INCOMPLETE_READ; } sock->timeout = t; return APR_SUCCESS; } apr_status_t apr_socket_opt_set(apr_socket_t *sock, apr_int32_t opt, apr_int32_t on) { int one; apr_status_t rv; if (on) one = 1; else one = 0; switch(opt) { case APR_SO_KEEPALIVE: #ifdef SO_KEEPALIVE if (on != apr_is_option_set(sock, APR_SO_KEEPALIVE)) { if (setsockopt(sock->socketdes, SOL_SOCKET, SO_KEEPALIVE, (void *)&one, sizeof(int)) == -1) { return errno; } apr_set_option(sock, APR_SO_KEEPALIVE, on); } #else return APR_ENOTIMPL; #endif break; case APR_SO_DEBUG: if (on != apr_is_option_set(sock, APR_SO_DEBUG)) { if (setsockopt(sock->socketdes, SOL_SOCKET, SO_DEBUG, (void *)&one, sizeof(int)) == -1) { return errno; } apr_set_option(sock, APR_SO_DEBUG, on); } break; case APR_SO_REUSEADDR: if (on != apr_is_option_set(sock, APR_SO_REUSEADDR)) { if (setsockopt(sock->socketdes, SOL_SOCKET, SO_REUSEADDR, (void *)&one, sizeof(int)) == -1) { return errno; } apr_set_option(sock, APR_SO_REUSEADDR, on); } break; case APR_SO_SNDBUF: #ifdef SO_SNDBUF if (setsockopt(sock->socketdes, SOL_SOCKET, SO_SNDBUF, (void *)&on, sizeof(int)) == -1) { return errno; } #else return APR_ENOTIMPL; #endif break; case APR_SO_RCVBUF: #ifdef SO_RCVBUF if (setsockopt(sock->socketdes, SOL_SOCKET, SO_RCVBUF, (void *)&on, sizeof(int)) == -1) { return errno; } #else return APR_ENOTIMPL; #endif break; case APR_SO_NONBLOCK: if (apr_is_option_set(sock, APR_SO_NONBLOCK) != on) { if (on) { if ((rv = sononblock(sock->socketdes)) != APR_SUCCESS) return rv; } else { if ((rv = soblock(sock->socketdes)) != APR_SUCCESS) return rv; } apr_set_option(sock, APR_SO_NONBLOCK, on); } break; case APR_SO_LINGER: #ifdef SO_LINGER if (apr_is_option_set(sock, APR_SO_LINGER) != on) { struct linger li; li.l_onoff = on; li.l_linger = APR_MAX_SECS_TO_LINGER; if (setsockopt(sock->socketdes, SOL_SOCKET, SO_LINGER, (char *) &li, sizeof(struct linger)) == -1) { return errno; } apr_set_option(sock, APR_SO_LINGER, on); } #else return APR_ENOTIMPL; #endif break; case APR_TCP_DEFER_ACCEPT: #if defined(TCP_DEFER_ACCEPT) if (apr_is_option_set(sock, APR_TCP_DEFER_ACCEPT) != on) { int optlevel = IPPROTO_TCP; int optname = TCP_DEFER_ACCEPT; if (setsockopt(sock->socketdes, optlevel, optname, (void *)&on, sizeof(int)) == -1) { return errno; } apr_set_option(sock, APR_TCP_DEFER_ACCEPT, on); } #else return APR_ENOTIMPL; #endif break; case APR_TCP_NODELAY: #if defined(TCP_NODELAY) if (apr_is_option_set(sock, APR_TCP_NODELAY) != on) { int optlevel = IPPROTO_TCP; int optname = TCP_NODELAY; #if APR_HAVE_SCTP if (sock->protocol == IPPROTO_SCTP) { optlevel = IPPROTO_SCTP; optname = SCTP_NODELAY; } #endif if (setsockopt(sock->socketdes, optlevel, optname, (void *)&on, sizeof(int)) == -1) { return errno; } apr_set_option(sock, APR_TCP_NODELAY, on); } #else /* BeOS pre-BONE has TCP_NODELAY set by default. * As it can't be turned off we might as well check if they're asking * for it to be turned on! */ #ifdef BEOS if (on == 1) return APR_SUCCESS; else #endif return APR_ENOTIMPL; #endif break; case APR_TCP_NOPUSH: #if APR_TCP_NOPUSH_FLAG /* TCP_NODELAY and TCP_CORK are mutually exclusive on Linux * kernels < 2.6; on newer kernels they can be used together * and TCP_CORK takes preference, which is the desired * behaviour. On older kernels, TCP_NODELAY must be toggled * to "off" whilst TCP_CORK is in effect. */ if (apr_is_option_set(sock, APR_TCP_NOPUSH) != on) { #ifndef HAVE_TCP_NODELAY_WITH_CORK int optlevel = IPPROTO_TCP; int optname = TCP_NODELAY; #if APR_HAVE_SCTP if (sock->protocol == IPPROTO_SCTP) { optlevel = IPPROTO_SCTP; optname = SCTP_NODELAY; } #endif /* OK we're going to change some settings here... */ if (apr_is_option_set(sock, APR_TCP_NODELAY) == 1 && on) { /* Now toggle TCP_NODELAY to off, if TCP_CORK is being * turned on: */ int tmpflag = 0; if (setsockopt(sock->socketdes, optlevel, optname, (void*)&tmpflag, sizeof(int)) == -1) { return errno; } apr_set_option(sock, APR_RESET_NODELAY, 1); apr_set_option(sock, APR_TCP_NODELAY, 0); } else if (on) { apr_set_option(sock, APR_RESET_NODELAY, 0); } #endif /* HAVE_TCP_NODELAY_WITH_CORK */ /* OK, now we can just set the TCP_NOPUSH flag accordingly...*/ if (setsockopt(sock->socketdes, IPPROTO_TCP, APR_TCP_NOPUSH_FLAG, (void*)&on, sizeof(int)) == -1) { return errno; } apr_set_option(sock, APR_TCP_NOPUSH, on); #ifndef HAVE_TCP_NODELAY_WITH_CORK if (!on && apr_is_option_set(sock, APR_RESET_NODELAY)) { /* Now, if TCP_CORK was just turned off, turn * TCP_NODELAY back on again if it was earlier toggled * to off: */ int tmpflag = 1; if (setsockopt(sock->socketdes, optlevel, optname, (void*)&tmpflag, sizeof(int)) == -1) { return errno; } apr_set_option(sock, APR_RESET_NODELAY,0); apr_set_option(sock, APR_TCP_NODELAY, 1); } #endif /* HAVE_TCP_NODELAY_WITH_CORK */ } #else return APR_ENOTIMPL; #endif break; case APR_INCOMPLETE_READ: apr_set_option(sock, APR_INCOMPLETE_READ, on); break; case APR_IPV6_V6ONLY: #if APR_HAVE_IPV6 && defined(IPV6_V6ONLY) /* we don't know the initial setting of this option, * so don't check sock->options since that optimization * won't work */ if (setsockopt(sock->socketdes, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&on, sizeof(int)) == -1) { return errno; } apr_set_option(sock, APR_IPV6_V6ONLY, on); #else return APR_ENOTIMPL; #endif break; default: return APR_EINVAL; } return APR_SUCCESS; } apr_status_t apr_socket_timeout_get(apr_socket_t *sock, apr_interval_time_t *t) { *t = sock->timeout; return APR_SUCCESS; } apr_status_t apr_socket_opt_get(apr_socket_t *sock, apr_int32_t opt, apr_int32_t *on) { switch(opt) { default: *on = apr_is_option_set(sock, opt); } return APR_SUCCESS; } apr_status_t apr_socket_atmark(apr_socket_t *sock, int *atmark) { #ifndef BEOS_R5 int oobmark; if (ioctl(sock->socketdes, SIOCATMARK, (void*) &oobmark) < 0) return apr_get_netos_error(); *atmark = (oobmark != 0); return APR_SUCCESS; #else /* BEOS_R5 */ return APR_ENOTIMPL; #endif } apr_status_t apr_gethostname(char *buf, apr_int32_t len, apr_pool_t *cont) { #ifdef BEOS_R5 if (gethostname(buf, len) == 0) { #else if (gethostname(buf, len) != 0) { #endif buf[0] = '\0'; return errno; } else if (!memchr(buf, '\0', len)) { /* buffer too small */ /* note... most platforms just truncate in this condition * linux+glibc return an error */ buf[0] = '\0'; return APR_ENAMETOOLONG; } return APR_SUCCESS; } #if APR_HAS_SO_ACCEPTFILTER apr_status_t apr_socket_accept_filter(apr_socket_t *sock, char *name, char *args) { struct accept_filter_arg af; strncpy(af.af_name, name, 16); strncpy(af.af_arg, args, 256 - 16); if ((setsockopt(sock->socketdes, SOL_SOCKET, SO_ACCEPTFILTER, &af, sizeof(af))) < 0) { return errno; } return APR_SUCCESS; } #endif
001-log4cxx
trunk/src/apr/network_io/unix/sockopt.c
C
asf20
12,134
/* 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_strings.h" #include "apr.h" #include "apr_lib.h" #include "apr_strings.h" #include "apr_private.h" #if APR_HAVE_STDLIB_H #include <stdlib.h> #endif #define APR_WANT_STRFUNC #include "apr_want.h" struct apr_ipsubnet_t { int family; #if APR_HAVE_IPV6 apr_uint32_t sub[4]; /* big enough for IPv4 and IPv6 addresses */ apr_uint32_t mask[4]; #else apr_uint32_t sub[1]; apr_uint32_t mask[1]; #endif }; #if !defined(NETWARE) && !defined(WIN32) #ifdef HAVE_SET_H_ERRNO #define SET_H_ERRNO(newval) set_h_errno(newval) #else #define SET_H_ERRNO(newval) h_errno = (newval) #endif #else #define SET_H_ERRNO(newval) #endif #if APR_HAS_THREADS && !defined(GETHOSTBYNAME_IS_THREAD_SAFE) && \ defined(HAVE_GETHOSTBYNAME_R) /* This is the maximum size that may be returned from the reentrant * gethostbyname_r function. If the system tries to use more, it * should return ERANGE. */ #define GETHOSTBYNAME_BUFLEN 512 #endif #ifdef _WIN32_WCE /* XXX: BS solution. Need an HAVE_GETSERVBYNAME and actually * do something here, to provide the obvious proto mappings. */ static void *getservbyname(const char *name, const char *proto) { return NULL; } #endif static apr_status_t get_local_addr(apr_socket_t *sock) { sock->local_addr->salen = sizeof(sock->local_addr->sa); if (getsockname(sock->socketdes, (struct sockaddr *)&sock->local_addr->sa, &sock->local_addr->salen) < 0) { return apr_get_netos_error(); } else { sock->local_port_unknown = sock->local_interface_unknown = 0; /* XXX assumes sin_port and sin6_port at same offset */ sock->local_addr->port = ntohs(sock->local_addr->sa.sin.sin_port); return APR_SUCCESS; } } static apr_status_t get_remote_addr(apr_socket_t *sock) { sock->remote_addr->salen = sizeof(sock->remote_addr->sa); if (getpeername(sock->socketdes, (struct sockaddr *)&sock->remote_addr->sa, &sock->remote_addr->salen) < 0) { return apr_get_netos_error(); } else { sock->remote_addr_unknown = 0; /* XXX assumes sin_port and sin6_port at same offset */ sock->remote_addr->port = ntohs(sock->remote_addr->sa.sin.sin_port); return APR_SUCCESS; } } APR_DECLARE(apr_status_t) apr_sockaddr_ip_get(char **addr, apr_sockaddr_t *sockaddr) { *addr = apr_palloc(sockaddr->pool, sockaddr->addr_str_len); apr_inet_ntop(sockaddr->family, sockaddr->ipaddr_ptr, *addr, sockaddr->addr_str_len); #if APR_HAVE_IPV6 if (sockaddr->family == AF_INET6 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)sockaddr->ipaddr_ptr)) { /* This is an IPv4-mapped IPv6 address; drop the leading * part of the address string so we're left with the familiar * IPv4 format. */ *addr += strlen("::ffff:"); } #endif return APR_SUCCESS; } void apr_sockaddr_vars_set(apr_sockaddr_t *addr, int family, apr_port_t port) { addr->family = family; addr->sa.sin.sin_family = family; if (port) { /* XXX IPv6: assumes sin_port and sin6_port at same offset */ addr->sa.sin.sin_port = htons(port); addr->port = port; } if (family == APR_INET) { addr->salen = sizeof(struct sockaddr_in); addr->addr_str_len = 16; addr->ipaddr_ptr = &(addr->sa.sin.sin_addr); addr->ipaddr_len = sizeof(struct in_addr); } #if APR_HAVE_IPV6 else if (family == APR_INET6) { addr->salen = sizeof(struct sockaddr_in6); addr->addr_str_len = 46; addr->ipaddr_ptr = &(addr->sa.sin6.sin6_addr); addr->ipaddr_len = sizeof(struct in6_addr); } #endif } APR_DECLARE(apr_status_t) apr_socket_addr_get(apr_sockaddr_t **sa, apr_interface_e which, apr_socket_t *sock) { if (which == APR_LOCAL) { if (sock->local_interface_unknown || sock->local_port_unknown) { apr_status_t rv = get_local_addr(sock); if (rv != APR_SUCCESS) { return rv; } } *sa = sock->local_addr; } else if (which == APR_REMOTE) { if (sock->remote_addr_unknown) { apr_status_t rv = get_remote_addr(sock); if (rv != APR_SUCCESS) { return rv; } } *sa = sock->remote_addr; } else { *sa = NULL; return APR_EINVAL; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_parse_addr_port(char **addr, char **scope_id, apr_port_t *port, const char *str, apr_pool_t *p) { const char *ch, *lastchar; int big_port; apr_size_t addrlen; *addr = NULL; /* assume not specified */ *scope_id = NULL; /* assume not specified */ *port = 0; /* assume not specified */ /* First handle the optional port number. That may be all that * is specified in the string. */ ch = lastchar = str + strlen(str) - 1; while (ch >= str && apr_isdigit(*ch)) { --ch; } if (ch < str) { /* Entire string is the port. */ big_port = atoi(str); if (big_port < 1 || big_port > 65535) { return APR_EINVAL; } *port = big_port; return APR_SUCCESS; } if (*ch == ':' && ch < lastchar) { /* host and port number specified */ if (ch == str) { /* string starts with ':' -- bad */ return APR_EINVAL; } big_port = atoi(ch + 1); if (big_port < 1 || big_port > 65535) { return APR_EINVAL; } *port = big_port; lastchar = ch - 1; } /* now handle the hostname */ addrlen = lastchar - str + 1; /* XXX we don't really have to require APR_HAVE_IPV6 for this; * just pass char[] for ipaddr (so we don't depend on struct in6_addr) * and always define APR_INET6 */ #if APR_HAVE_IPV6 if (*str == '[') { const char *end_bracket = memchr(str, ']', addrlen); struct in6_addr ipaddr; const char *scope_delim; if (!end_bracket || end_bracket != lastchar) { *port = 0; return APR_EINVAL; } /* handle scope id; this is the only context where it is allowed */ scope_delim = memchr(str, '%', addrlen); if (scope_delim) { if (scope_delim == end_bracket - 1) { /* '%' without scope id */ *port = 0; return APR_EINVAL; } addrlen = scope_delim - str - 1; *scope_id = apr_palloc(p, end_bracket - scope_delim); memcpy(*scope_id, scope_delim + 1, end_bracket - scope_delim - 1); (*scope_id)[end_bracket - scope_delim - 1] = '\0'; } else { addrlen = addrlen - 2; /* minus 2 for '[' and ']' */ } *addr = apr_palloc(p, addrlen + 1); memcpy(*addr, str + 1, addrlen); (*addr)[addrlen] = '\0'; if (apr_inet_pton(AF_INET6, *addr, &ipaddr) != 1) { *addr = NULL; *scope_id = NULL; *port = 0; return APR_EINVAL; } } else #endif { /* XXX If '%' is not a valid char in a DNS name, we *could* check * for bogus scope ids first. */ *addr = apr_palloc(p, addrlen + 1); memcpy(*addr, str, addrlen); (*addr)[addrlen] = '\0'; } return APR_SUCCESS; } #if defined(HAVE_GETADDRINFO) static apr_status_t call_resolver(apr_sockaddr_t **sa, const char *hostname, apr_int32_t family, apr_port_t port, apr_int32_t flags, apr_pool_t *p) { struct addrinfo hints, *ai, *ai_list; apr_sockaddr_t *prev_sa; int error; char *servname = NULL; memset(&hints, 0, sizeof(hints)); hints.ai_family = family; hints.ai_socktype = SOCK_STREAM; #ifdef HAVE_GAI_ADDRCONFIG if (family == APR_UNSPEC) { /* By default, only look up addresses using address types for * which a local interface is configured, i.e. no IPv6 if no * IPv6 interfaces configured. */ hints.ai_flags = AI_ADDRCONFIG; } #endif if(hostname == NULL) { #ifdef AI_PASSIVE /* If hostname is NULL, assume we are trying to bind to all * interfaces. */ hints.ai_flags |= AI_PASSIVE; #endif /* getaddrinfo according to RFC 2553 must have either hostname * or servname non-NULL. */ #ifdef OSF1 /* The Tru64 5.0 getaddrinfo() can only resolve services given * by the name listed in /etc/services; a numeric or unknown * servname gets an EAI_SERVICE error. So just resolve the * appropriate anyaddr and fill in the port later. */ hostname = family == AF_INET6 ? "::" : "0.0.0.0"; servname = NULL; #ifdef AI_NUMERICHOST hints.ai_flags |= AI_NUMERICHOST; #endif #else #ifdef _AIX /* But current AIX getaddrinfo() doesn't like servname = "0"; * the "1" won't hurt since we use the port parameter to fill * in the returned socket addresses later */ if (!port) { servname = "1"; } else #endif /* _AIX */ servname = apr_itoa(p, port); #endif /* OSF1 */ } error = getaddrinfo(hostname, servname, &hints, &ai_list); #ifdef HAVE_GAI_ADDRCONFIG if (error == EAI_BADFLAGS && family == APR_UNSPEC) { /* Retry with no flags if AI_ADDRCONFIG was rejected. */ hints.ai_flags = 0; error = getaddrinfo(hostname, servname, &hints, &ai_list); } #endif if (error) { #ifndef WIN32 if (error == EAI_SYSTEM) { return errno; } else #endif { /* issues with representing this with APR's error scheme: * glibc uses negative values for these numbers, perhaps so * they don't conflict with h_errno values... Tru64 uses * positive values which conflict with h_errno values */ #if defined(NEGATIVE_EAI) error = -error; #endif return error + APR_OS_START_EAIERR; } } prev_sa = NULL; ai = ai_list; while (ai) { /* while more addresses to report */ apr_sockaddr_t *new_sa; /* Ignore anything bogus: getaddrinfo in some old versions of * glibc will return AF_UNIX entries for APR_UNSPEC+AI_PASSIVE * lookups. */ if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) { ai = ai->ai_next; continue; } new_sa = apr_pcalloc(p, sizeof(apr_sockaddr_t)); new_sa->pool = p; memcpy(&new_sa->sa, ai->ai_addr, ai->ai_addrlen); apr_sockaddr_vars_set(new_sa, ai->ai_family, port); if (!prev_sa) { /* first element in new list */ if (hostname) { new_sa->hostname = apr_pstrdup(p, hostname); } *sa = new_sa; } else { new_sa->hostname = prev_sa->hostname; prev_sa->next = new_sa; } prev_sa = new_sa; ai = ai->ai_next; } freeaddrinfo(ai_list); return APR_SUCCESS; } static apr_status_t find_addresses(apr_sockaddr_t **sa, const char *hostname, apr_int32_t family, apr_port_t port, apr_int32_t flags, apr_pool_t *p) { if (flags & APR_IPV4_ADDR_OK) { apr_status_t error = call_resolver(sa, hostname, AF_INET, port, flags, p); #if APR_HAVE_IPV6 if (error) { family = AF_INET6; /* try again */ } else #endif return error; } #if APR_HAVE_IPV6 else if (flags & APR_IPV6_ADDR_OK) { apr_status_t error = call_resolver(sa, hostname, AF_INET6, port, flags, p); if (error) { family = AF_INET; /* try again */ } else { return APR_SUCCESS; } } #endif return call_resolver(sa, hostname, family, port, flags, p); } #else /* end of HAVE_GETADDRINFO code */ static apr_status_t find_addresses(apr_sockaddr_t **sa, const char *hostname, apr_int32_t family, apr_port_t port, apr_int32_t flags, apr_pool_t *p) { struct hostent *hp; apr_sockaddr_t *prev_sa; int curaddr; #if APR_HAS_THREADS && !defined(GETHOSTBYNAME_IS_THREAD_SAFE) && \ defined(HAVE_GETHOSTBYNAME_R) && !defined(BEOS) #ifdef GETHOSTBYNAME_R_HOSTENT_DATA struct hostent_data hd; #else /* If you see ERANGE, that means GETHOSBYNAME_BUFLEN needs to be * bumped. */ char tmp[GETHOSTBYNAME_BUFLEN]; #endif int hosterror; #endif struct hostent hs; struct in_addr ipaddr; char *addr_list[2]; const char *orig_hostname = hostname; if (hostname == NULL) { /* if we are given a NULL hostname, assume '0.0.0.0' */ hostname = "0.0.0.0"; } if (*hostname >= '0' && *hostname <= '9' && strspn(hostname, "0123456789.") == strlen(hostname)) { ipaddr.s_addr = inet_addr(hostname); addr_list[0] = (char *)&ipaddr; addr_list[1] = NULL; /* just one IP in list */ hs.h_addr_list = (char **)addr_list; hp = &hs; } else { #if APR_HAS_THREADS && !defined(GETHOSTBYNAME_IS_THREAD_SAFE) && \ defined(HAVE_GETHOSTBYNAME_R) && !defined(BEOS) #if defined(GETHOSTBYNAME_R_HOSTENT_DATA) /* AIX, HP/UX, D/UX et alia */ gethostbyname_r(hostname, &hs, &hd); hp = &hs; #else #if defined(GETHOSTBYNAME_R_GLIBC2) /* Linux glibc2+ */ gethostbyname_r(hostname, &hs, tmp, GETHOSTBYNAME_BUFLEN - 1, &hp, &hosterror); #else /* Solaris, Irix et alia */ hp = gethostbyname_r(hostname, &hs, tmp, GETHOSTBYNAME_BUFLEN - 1, &hosterror); #endif /* !defined(GETHOSTBYNAME_R_GLIBC2) */ if (!hp) { return (hosterror + APR_OS_START_SYSERR); } #endif /* !defined(GETHOSTBYNAME_R_HOSTENT_DATA) */ #else hp = gethostbyname(hostname); #endif if (!hp) { #ifdef WIN32 return apr_get_netos_error(); #else return (h_errno + APR_OS_START_SYSERR); #endif } } prev_sa = NULL; curaddr = 0; while (hp->h_addr_list[curaddr]) { apr_sockaddr_t *new_sa = apr_pcalloc(p, sizeof(apr_sockaddr_t)); new_sa->pool = p; new_sa->sa.sin.sin_addr = *(struct in_addr *)hp->h_addr_list[curaddr]; apr_sockaddr_vars_set(new_sa, AF_INET, port); if (!prev_sa) { /* first element in new list */ if (orig_hostname) { new_sa->hostname = apr_pstrdup(p, orig_hostname); } *sa = new_sa; } else { new_sa->hostname = prev_sa->hostname; prev_sa->next = new_sa; } prev_sa = new_sa; ++curaddr; } return APR_SUCCESS; } #endif /* end of !HAVE_GETADDRINFO code */ APR_DECLARE(apr_status_t) apr_sockaddr_info_get(apr_sockaddr_t **sa, const char *hostname, apr_int32_t family, apr_port_t port, apr_int32_t flags, apr_pool_t *p) { apr_int32_t masked; *sa = NULL; if ((masked = flags & (APR_IPV4_ADDR_OK | APR_IPV6_ADDR_OK))) { if (!hostname || family != APR_UNSPEC || masked == (APR_IPV4_ADDR_OK | APR_IPV6_ADDR_OK)) { return APR_EINVAL; } #if !APR_HAVE_IPV6 if (flags & APR_IPV6_ADDR_OK) { return APR_ENOTIMPL; } #endif } #if !APR_HAVE_IPV6 /* What may happen is that APR is not IPv6-enabled, but we're still * going to call getaddrinfo(), so we have to tell the OS we only * want IPv4 addresses back since we won't know what to do with * IPv6 addresses. */ if (family == APR_UNSPEC) { family = APR_INET; } #endif return find_addresses(sa, hostname, family, port, flags, p); } APR_DECLARE(apr_status_t) apr_getnameinfo(char **hostname, apr_sockaddr_t *sockaddr, apr_int32_t flags) { #if defined(HAVE_GETNAMEINFO) int rc; #if defined(NI_MAXHOST) char tmphostname[NI_MAXHOST]; #else char tmphostname[256]; #endif /* don't know if it is portable for getnameinfo() to set h_errno; * clear it then see if it was set */ SET_H_ERRNO(0); /* default flags are NI_NAMREQD; otherwise, getnameinfo() will return * a numeric address string if it fails to resolve the host name; * that is *not* what we want here * * For IPv4-mapped IPv6 addresses, drop down to IPv4 before calling * getnameinfo() to avoid getnameinfo bugs (MacOS X, glibc). */ #if APR_HAVE_IPV6 if (sockaddr->family == AF_INET6 && IN6_IS_ADDR_V4MAPPED(&sockaddr->sa.sin6.sin6_addr)) { struct sockaddr_in tmpsa; tmpsa.sin_family = AF_INET; tmpsa.sin_port = 0; tmpsa.sin_addr.s_addr = ((apr_uint32_t *)sockaddr->ipaddr_ptr)[3]; #ifdef SIN6_LEN tmpsa.sin_len = sizeof(tmpsa); #endif rc = getnameinfo((const struct sockaddr *)&tmpsa, sizeof(tmpsa), tmphostname, sizeof(tmphostname), NULL, 0, flags != 0 ? flags : NI_NAMEREQD); } else #endif rc = getnameinfo((const struct sockaddr *)&sockaddr->sa, sockaddr->salen, tmphostname, sizeof(tmphostname), NULL, 0, flags != 0 ? flags : NI_NAMEREQD); if (rc != 0) { *hostname = NULL; #ifndef WIN32 /* something went wrong. Look at the EAI_ error code */ if (rc == EAI_SYSTEM) { /* EAI_SYSTEM System error returned in errno. */ /* IMHO, Implementations that set h_errno a simply broken. */ if (h_errno) { /* for broken implementations which set h_errno */ return h_errno + APR_OS_START_SYSERR; } else { /* "normal" case */ return errno + APR_OS_START_SYSERR; } } else #endif { #if defined(NEGATIVE_EAI) if (rc < 0) rc = -rc; #endif return rc + APR_OS_START_EAIERR; /* return the EAI_ error */ } } *hostname = sockaddr->hostname = apr_pstrdup(sockaddr->pool, tmphostname); return APR_SUCCESS; #else #if APR_HAS_THREADS && !defined(GETHOSTBYADDR_IS_THREAD_SAFE) && \ defined(HAVE_GETHOSTBYADDR_R) && !defined(BEOS) #ifdef GETHOSTBYNAME_R_HOSTENT_DATA struct hostent_data hd; #else char tmp[GETHOSTBYNAME_BUFLEN]; #endif int hosterror; struct hostent hs, *hptr; #if defined(GETHOSTBYNAME_R_HOSTENT_DATA) /* AIX, HP/UX, D/UX et alia */ gethostbyaddr_r((char *)&sockaddr->sa.sin.sin_addr, sizeof(struct in_addr), AF_INET, &hs, &hd); hptr = &hs; #else #if defined(GETHOSTBYNAME_R_GLIBC2) /* Linux glibc2+ */ gethostbyaddr_r((char *)&sockaddr->sa.sin.sin_addr, sizeof(struct in_addr), AF_INET, &hs, tmp, GETHOSTBYNAME_BUFLEN - 1, &hptr, &hosterror); #else /* Solaris, Irix et alia */ hptr = gethostbyaddr_r((char *)&sockaddr->sa.sin.sin_addr, sizeof(struct in_addr), AF_INET, &hs, tmp, GETHOSTBYNAME_BUFLEN, &hosterror); #endif /* !defined(GETHOSTBYNAME_R_GLIBC2) */ if (!hptr) { *hostname = NULL; return hosterror + APR_OS_START_SYSERR; } #endif /* !defined(GETHOSTBYNAME_R_HOSTENT_DATA) */ #else struct hostent *hptr; hptr = gethostbyaddr((char *)&sockaddr->sa.sin.sin_addr, sizeof(struct in_addr), AF_INET); #endif if (hptr) { *hostname = sockaddr->hostname = apr_pstrdup(sockaddr->pool, hptr->h_name); return APR_SUCCESS; } *hostname = NULL; #if defined(WIN32) return apr_get_netos_error(); #elif defined(OS2) return h_errno; #else return h_errno + APR_OS_START_SYSERR; #endif #endif } APR_DECLARE(apr_status_t) apr_getservbyname(apr_sockaddr_t *sockaddr, const char *servname) { struct servent *se; if (servname == NULL) return APR_EINVAL; if ((se = getservbyname(servname, NULL)) != NULL){ sockaddr->port = htons(se->s_port); sockaddr->servname = apr_pstrdup(sockaddr->pool, servname); sockaddr->sa.sin.sin_port = se->s_port; return APR_SUCCESS; } return errno; } #define V4MAPPED_EQUAL(a,b) \ ((a)->sa.sin.sin_family == AF_INET && \ (b)->sa.sin.sin_family == AF_INET6 && \ IN6_IS_ADDR_V4MAPPED((struct in6_addr *)(b)->ipaddr_ptr) && \ !memcmp((a)->ipaddr_ptr, \ &((struct in6_addr *)(b)->ipaddr_ptr)->s6_addr[12], \ (a)->ipaddr_len)) APR_DECLARE(int) apr_sockaddr_equal(const apr_sockaddr_t *addr1, const apr_sockaddr_t *addr2) { if (addr1->ipaddr_len == addr2->ipaddr_len && !memcmp(addr1->ipaddr_ptr, addr2->ipaddr_ptr, addr1->ipaddr_len)) { return 1; } #if APR_HAVE_IPV6 if (V4MAPPED_EQUAL(addr1, addr2)) { return 1; } if (V4MAPPED_EQUAL(addr2, addr1)) { return 1; } #endif return 0; /* not equal */ } static apr_status_t parse_network(apr_ipsubnet_t *ipsub, const char *network) { /* legacy syntax for ip addrs: a.b.c. ==> a.b.c.0/24 for example */ int shift; char *s, *t; int octet; char buf[sizeof "255.255.255.255"]; if (strlen(network) < sizeof buf) { strcpy(buf, network); } else { return APR_EBADIP; } /* parse components */ s = buf; ipsub->sub[0] = 0; ipsub->mask[0] = 0; shift = 24; while (*s) { t = s; if (!apr_isdigit(*t)) { return APR_EBADIP; } while (apr_isdigit(*t)) { ++t; } if (*t == '.') { *t++ = 0; } else if (*t) { return APR_EBADIP; } if (shift < 0) { return APR_EBADIP; } octet = atoi(s); if (octet < 0 || octet > 255) { return APR_EBADIP; } ipsub->sub[0] |= octet << shift; ipsub->mask[0] |= 0xFFUL << shift; s = t; shift -= 8; } ipsub->sub[0] = ntohl(ipsub->sub[0]); ipsub->mask[0] = ntohl(ipsub->mask[0]); ipsub->family = AF_INET; return APR_SUCCESS; } /* return values: * APR_EINVAL not an IP address; caller should see if it is something else * APR_BADIP IP address portion is is not valid * APR_BADMASK mask portion is not valid */ static apr_status_t parse_ip(apr_ipsubnet_t *ipsub, const char *ipstr, int network_allowed) { /* supported flavors of IP: * * . IPv6 numeric address string (e.g., "fe80::1") * * IMPORTANT: Don't store IPv4-mapped IPv6 address as an IPv6 address. * * . IPv4 numeric address string (e.g., "127.0.0.1") * * . IPv4 network string (e.g., "9.67") * * IMPORTANT: This network form is only allowed if network_allowed is on. */ int rc; #if APR_HAVE_IPV6 rc = apr_inet_pton(AF_INET6, ipstr, ipsub->sub); if (rc == 1) { if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ipsub->sub)) { /* apr_ipsubnet_test() assumes that we don't create IPv4-mapped IPv6 * addresses; this of course forces the user to specify IPv4 addresses * in a.b.c.d style instead of ::ffff:a.b.c.d style. */ return APR_EBADIP; } ipsub->family = AF_INET6; } else #endif { rc = apr_inet_pton(AF_INET, ipstr, ipsub->sub); if (rc == 1) { ipsub->family = AF_INET; } } if (rc != 1) { if (network_allowed) { return parse_network(ipsub, ipstr); } else { return APR_EBADIP; } } return APR_SUCCESS; } static int looks_like_ip(const char *ipstr) { if (strchr(ipstr, ':')) { /* definitely not a hostname; assume it is intended to be an IPv6 address */ return 1; } /* simple IPv4 address string check */ while ((*ipstr == '.') || apr_isdigit(*ipstr)) ipstr++; return (*ipstr == '\0'); } static void fix_subnet(apr_ipsubnet_t *ipsub) { /* in case caller specified more bits in network address than are * valid according to the mask, turn off the extra bits */ int i; for (i = 0; i < sizeof ipsub->mask / sizeof(apr_int32_t); i++) { ipsub->sub[i] &= ipsub->mask[i]; } } /* be sure not to store any IPv4 address as a v4-mapped IPv6 address */ APR_DECLARE(apr_status_t) apr_ipsubnet_create(apr_ipsubnet_t **ipsub, const char *ipstr, const char *mask_or_numbits, apr_pool_t *p) { apr_status_t rv; char *endptr; long bits, maxbits = 32; /* filter out stuff which doesn't look remotely like an IP address; this helps * callers like mod_access which have a syntax allowing hostname or IP address; * APR_EINVAL tells the caller that it was probably not intended to be an IP * address */ if (!looks_like_ip(ipstr)) { return APR_EINVAL; } *ipsub = apr_pcalloc(p, sizeof(apr_ipsubnet_t)); /* assume ipstr is an individual IP address, not a subnet */ memset((*ipsub)->mask, 0xFF, sizeof (*ipsub)->mask); rv = parse_ip(*ipsub, ipstr, mask_or_numbits == NULL); if (rv != APR_SUCCESS) { return rv; } if (mask_or_numbits) { #if APR_HAVE_IPV6 if ((*ipsub)->family == AF_INET6) { maxbits = 128; } #endif bits = strtol(mask_or_numbits, &endptr, 10); if (*endptr == '\0' && bits > 0 && bits <= maxbits) { /* valid num-bits string; fill in mask appropriately */ int cur_entry = 0; apr_int32_t cur_bit_value; memset((*ipsub)->mask, 0, sizeof (*ipsub)->mask); while (bits > 32) { (*ipsub)->mask[cur_entry] = 0xFFFFFFFF; /* all 32 bits */ bits -= 32; ++cur_entry; } cur_bit_value = 0x80000000; while (bits) { (*ipsub)->mask[cur_entry] |= cur_bit_value; --bits; cur_bit_value /= 2; } (*ipsub)->mask[cur_entry] = htonl((*ipsub)->mask[cur_entry]); } else if (apr_inet_pton(AF_INET, mask_or_numbits, (*ipsub)->mask) == 1 && (*ipsub)->family == AF_INET) { /* valid IPv4 netmask */ } else { return APR_EBADMASK; } } fix_subnet(*ipsub); return APR_SUCCESS; } APR_DECLARE(int) apr_ipsubnet_test(apr_ipsubnet_t *ipsub, apr_sockaddr_t *sa) { #if APR_HAVE_IPV6 /* XXX This line will segv on Win32 build with APR_HAVE_IPV6, * but without the IPV6 drivers installed. */ if (sa->sa.sin.sin_family == AF_INET) { if (ipsub->family == AF_INET && ((sa->sa.sin.sin_addr.s_addr & ipsub->mask[0]) == ipsub->sub[0])) { return 1; } } else if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)sa->ipaddr_ptr)) { if (ipsub->family == AF_INET && (((apr_uint32_t *)sa->ipaddr_ptr)[3] & ipsub->mask[0]) == ipsub->sub[0]) { return 1; } } else { apr_uint32_t *addr = (apr_uint32_t *)sa->ipaddr_ptr; if ((addr[0] & ipsub->mask[0]) == ipsub->sub[0] && (addr[1] & ipsub->mask[1]) == ipsub->sub[1] && (addr[2] & ipsub->mask[2]) == ipsub->sub[2] && (addr[3] & ipsub->mask[3]) == ipsub->sub[3]) { return 1; } } #else if ((sa->sa.sin.sin_addr.s_addr & ipsub->mask[0]) == ipsub->sub[0]) { return 1; } #endif /* APR_HAVE_IPV6 */ return 0; /* no match */ }
001-log4cxx
trunk/src/apr/network_io/unix/sockaddr.c
C
asf20
29,655
/* Copyright (c) 1996 by Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ #include "apr_private.h" #include "apr_arch_networkio.h" #include "apr_strings.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_NETINET_IN_H #include <netinet/in.h> #endif #if APR_HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #include <string.h> #if APR_HAVE_ERRNO_H #include <errno.h> #endif #include <stdio.h> #ifndef IN6ADDRSZ #define IN6ADDRSZ 16 #endif #ifndef INT16SZ #define INT16SZ sizeof(apr_int16_t) #endif #ifndef __P #define __P(x) x #endif #if !defined(EAFNOSUPPORT) && defined(WSAEAFNOSUPPORT) #define EAFNOSUPPORT WSAEAFNOSUPPORT #endif /* * WARNING: Don't even consider trying to compile this on a system where * sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX. */ static const char *inet_ntop4 __P((const unsigned char *src, char *dst, apr_size_t size)); #if APR_HAVE_IPV6 static const char *inet_ntop6 __P((const unsigned char *src, char *dst, apr_size_t size)); #endif /* char * * inet_ntop(af, src, dst, size) * convert a network format address to presentation format. * return: * pointer to presentation format address (`dst'), or NULL (see errno). * author: * Paul Vixie, 1996. */ const char * apr_inet_ntop(int af, const void *src, char *dst, apr_size_t size) { switch (af) { case AF_INET: return (inet_ntop4(src, dst, size)); #if APR_HAVE_IPV6 case AF_INET6: return (inet_ntop6(src, dst, size)); #endif default: errno = EAFNOSUPPORT; return (NULL); } /* NOTREACHED */ } /* const char * * inet_ntop4(src, dst, size) * format an IPv4 address, more or less like inet_ntoa() * return: * `dst' (as a const) * notes: * (1) uses no statics * (2) takes a u_char* not an in_addr as input * author: * Paul Vixie, 1996. */ static const char * inet_ntop4(const unsigned char *src, char *dst, apr_size_t size) { const apr_size_t MIN_SIZE = 16; /* space for 255.255.255.255\0 */ int n = 0; char *next = dst; if (size < MIN_SIZE) { errno = ENOSPC; return NULL; } do { unsigned char u = *src++; if (u > 99) { *next++ = '0' + u/100; u %= 100; *next++ = '0' + u/10; u %= 10; } else if (u > 9) { *next++ = '0' + u/10; u %= 10; } *next++ = '0' + u; *next++ = '.'; n++; } while (n < 4); *--next = 0; return dst; } #if APR_HAVE_IPV6 /* const char * * inet_ntop6(src, dst, size) * convert IPv6 binary address into presentation (printable) format * author: * Paul Vixie, 1996. */ static const char * inet_ntop6(const unsigned char *src, char *dst, apr_size_t size) { /* * Note that int32_t and int16_t need only be "at least" large enough * to contain a value of the specified size. On some systems, like * Crays, there is no such thing as an integer variable with 16 bits. * Keep this in mind if you think this function should have been coded * to use pointer overlays. All the world's not a VAX. */ char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"], *tp; struct { int base, len; } best, cur; unsigned int words[IN6ADDRSZ / INT16SZ]; int i; const unsigned char *next_src, *src_end; unsigned int *next_dest; /* * Preprocess: * Copy the input (bytewise) array into a wordwise array. * Find the longest run of 0x00's in src[] for :: shorthanding. */ next_src = src; src_end = src + IN6ADDRSZ; next_dest = words; best.base = -1; cur.base = -1; cur.len = best.len = 0; /* silence gcc4 warning */ i = 0; do { unsigned int next_word = (unsigned int)*next_src++; next_word <<= 8; next_word |= (unsigned int)*next_src++; *next_dest++ = next_word; if (next_word == 0) { if (cur.base == -1) { cur.base = i; cur.len = 1; } else { cur.len++; } } else { if (cur.base != -1) { if (best.base == -1 || cur.len > best.len) { best = cur; } cur.base = -1; } } i++; } while (next_src < src_end); if (cur.base != -1) { if (best.base == -1 || cur.len > best.len) { best = cur; } } if (best.base != -1 && best.len < 2) { best.base = -1; } /* * Format the result. */ tp = tmp; for (i = 0; i < (IN6ADDRSZ / INT16SZ);) { /* Are we inside the best run of 0x00's? */ if (i == best.base) { *tp++ = ':'; i += best.len; continue; } /* Are we following an initial run of 0x00s or any real hex? */ if (i != 0) { *tp++ = ':'; } /* Is this address an encapsulated IPv4? */ if (i == 6 && best.base == 0 && (best.len == 6 || (best.len == 5 && words[5] == 0xffff))) { if (!inet_ntop4(src+12, tp, sizeof tmp - (tp - tmp))) { return (NULL); } tp += strlen(tp); break; } tp += apr_snprintf(tp, sizeof tmp - (tp - tmp), "%x", words[i]); i++; } /* Was it a trailing run of 0x00's? */ if (best.base != -1 && (best.base + best.len) == (IN6ADDRSZ / INT16SZ)) { *tp++ = ':'; } *tp++ = '\0'; /* * Check for overflow, copy, and we're done. */ if ((apr_size_t)(tp - tmp) > size) { errno = ENOSPC; return (NULL); } strcpy(dst, tmp); return (dst); } #endif
001-log4cxx
trunk/src/apr/network_io/unix/inet_ntop.c
C
asf20
6,410
/* 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_support.h" #include "apr_portable.h" #include "apr_arch_inherit.h" #ifdef HAVE_GETIFADDRS #include <net/if.h> #include <ifaddrs.h> #endif #ifdef HAVE_STRUCT_IPMREQ /* Only UDP and Raw Sockets can be used for Multicast */ static apr_status_t mcast_check_type(apr_socket_t *sock) { int type; apr_status_t rv; rv = apr_socket_type_get(sock, &type); if (rv != APR_SUCCESS) { return rv; } else if (type == SOCK_DGRAM || type == SOCK_RAW) { return APR_SUCCESS; } else { return APR_ENOTIMPL; } } static void fill_mip_v4(struct ip_mreq *mip, apr_sockaddr_t *mcast, apr_sockaddr_t *iface) { mip->imr_multiaddr = mcast->sa.sin.sin_addr; if (iface == NULL) { mip->imr_interface.s_addr = INADDR_ANY; } else { mip->imr_interface = iface->sa.sin.sin_addr; } } #if APR_HAVE_IPV6 static unsigned int find_if_index(const apr_sockaddr_t *iface) { unsigned int index = 0; #ifdef HAVE_GETIFADDRS struct ifaddrs *ifp, *ifs; /** * TODO: getifaddrs is only portable to *BSD and OS X. Using ioctl * and SIOCGIFCONF is needed for Linux/Solaris support. * * There is a wrapper that takes the messy ioctl interface into * getifaddrs. The license is acceptable, but, It is a fairly large * chunk of code. */ if (getifaddrs(&ifs) != 0) { return 0; } for (ifp = ifs; ifp; ifp = ifp->ifa_next) { if (ifp->ifa_addr != NULL && ifp->ifa_addr->sa_family == AF_INET6) { if (memcmp(&iface->sa.sin6.sin6_addr, &ifp->ifa_addr->sa_data[0], sizeof(iface->sa.sin6.sin6_addr)) == 0) { index = if_nametoindex(ifp->ifa_name); break; } } } freeifaddrs(ifs); #endif return index; } static void fill_mip_v6(struct ipv6_mreq *mip, const apr_sockaddr_t *mcast, const apr_sockaddr_t *iface) { memcpy(&mip->ipv6mr_multiaddr, mcast->ipaddr_ptr, sizeof(mip->ipv6mr_multiaddr)); if (iface == NULL) { mip->ipv6mr_interface = 0; } else { mip->ipv6mr_interface = find_if_index(iface); } } #endif static int sock_is_ipv4(apr_socket_t *sock) { if (sock->local_addr->family == APR_INET) return 1; return 0; } #if APR_HAVE_IPV6 static int sock_is_ipv6(apr_socket_t *sock) { if (sock->local_addr->family == APR_INET6) return 1; return 0; } #endif static apr_status_t do_mcast(int type, apr_socket_t *sock, apr_sockaddr_t *mcast, apr_sockaddr_t *iface, apr_sockaddr_t *source) { struct ip_mreq mip4; apr_status_t rv = APR_SUCCESS; #if APR_HAVE_IPV6 struct ipv6_mreq mip6; #endif #if MCAST_JOIN_SOURCE_GROUP struct group_source_req mip; int ip_proto; #endif rv = mcast_check_type(sock); if (rv != APR_SUCCESS) { return rv; } if (source != NULL) { #if MCAST_JOIN_SOURCE_GROUP if (sock_is_ipv4(sock)) { ip_proto = IPPROTO_IP; } #if APR_HAVE_IPV6 else if (sock_is_ipv6(sock)) { ip_proto = IPPROTO_IPV6; } #endif else { return APR_ENOTIMPL; } if (type == IP_ADD_MEMBERSHIP) type = MCAST_JOIN_SOURCE_GROUP; else if (type == IP_DROP_MEMBERSHIP) type = MCAST_LEAVE_SOURCE_GROUP; else return APR_ENOTIMPL; mip.gsr_interface = find_if_index(iface); memcpy(&mip.gsr_group, mcast->ipaddr_ptr, sizeof(mip.gsr_group)); memcpy(&mip.gsr_source, source->ipaddr_ptr, sizeof(mip.gsr_source)); if (setsockopt(sock->socketdes, ip_proto, type, (const void *) &mip, sizeof(mip)) == -1) { rv = errno; } #else /* We do not support Source-Specific Multicast. */ return APR_ENOTIMPL; #endif } else { if (sock_is_ipv4(sock)) { fill_mip_v4(&mip4, mcast, iface); if (setsockopt(sock->socketdes, IPPROTO_IP, type, (const void *) &mip4, sizeof(mip4)) == -1) { rv = errno; } } #if APR_HAVE_IPV6 && defined(IPV6_JOIN_GROUP) && defined(IPV6_LEAVE_GROUP) else if (sock_is_ipv6(sock)) { if (type == IP_ADD_MEMBERSHIP) { type = IPV6_JOIN_GROUP; } else if (type == IP_DROP_MEMBERSHIP) { type = IPV6_LEAVE_GROUP; } else { return APR_ENOTIMPL; } fill_mip_v6(&mip6, mcast, iface); if (setsockopt(sock->socketdes, IPPROTO_IPV6, type, &mip6, sizeof(mip6)) == -1) { rv = errno; } } #endif else { rv = APR_ENOTIMPL; } } return rv; } static apr_status_t do_mcast_opt(int type, apr_socket_t *sock, apr_byte_t value) { apr_status_t rv = APR_SUCCESS; rv = mcast_check_type(sock); if (rv != APR_SUCCESS) { return rv; } if (sock_is_ipv4(sock)) { if (setsockopt(sock->socketdes, IPPROTO_IP, type, (const void *) &value, sizeof(value)) == -1) { rv = errno; } } #if APR_HAVE_IPV6 else if (sock_is_ipv6(sock) && type == IP_MULTICAST_LOOP) { unsigned int loopopt = value; type = IPV6_MULTICAST_LOOP; if (setsockopt(sock->socketdes, IPPROTO_IPV6, type, &loopopt, sizeof(loopopt)) == -1) { rv = errno; } } else if (sock_is_ipv6(sock)) { if (type == IP_MULTICAST_TTL) { type = IPV6_MULTICAST_HOPS; } else { return APR_ENOTIMPL; } if (setsockopt(sock->socketdes, IPPROTO_IPV6, type, &value, sizeof(value)) == -1) { rv = errno; } } #endif else { rv = APR_ENOTIMPL; } return rv; } #endif APR_DECLARE(apr_status_t) apr_mcast_join(apr_socket_t *sock, apr_sockaddr_t *join, apr_sockaddr_t *iface, apr_sockaddr_t *source) { #if defined(IP_ADD_MEMBERSHIP) && defined(HAVE_STRUCT_IPMREQ) return do_mcast(IP_ADD_MEMBERSHIP, sock, join, iface, source); #else return APR_ENOTIMPL; #endif } APR_DECLARE(apr_status_t) apr_mcast_leave(apr_socket_t *sock, apr_sockaddr_t *addr, apr_sockaddr_t *iface, apr_sockaddr_t *source) { #if defined(IP_DROP_MEMBERSHIP) && defined(HAVE_STRUCT_IPMREQ) return do_mcast(IP_DROP_MEMBERSHIP, sock, addr, iface, source); #else return APR_ENOTIMPL; #endif } APR_DECLARE(apr_status_t) apr_mcast_hops(apr_socket_t *sock, apr_byte_t ttl) { #if defined(IP_MULTICAST_TTL) && defined(HAVE_STRUCT_IPMREQ) return do_mcast_opt(IP_MULTICAST_TTL, sock, ttl); #else return APR_ENOTIMPL; #endif } APR_DECLARE(apr_status_t) apr_mcast_loopback(apr_socket_t *sock, apr_byte_t opt) { #if defined(IP_MULTICAST_LOOP) && defined(HAVE_STRUCT_IPMREQ) return do_mcast_opt(IP_MULTICAST_LOOP, sock, opt); #else return APR_ENOTIMPL; #endif } APR_DECLARE(apr_status_t) apr_mcast_interface(apr_socket_t *sock, apr_sockaddr_t *iface) { #if defined(IP_MULTICAST_IF) && defined(HAVE_STRUCT_IPMREQ) apr_status_t rv = APR_SUCCESS; if (sock_is_ipv4(sock)) { if (setsockopt(sock->socketdes, IPPROTO_IP, IP_MULTICAST_IF, (const void *) &iface->sa.sin.sin_addr, sizeof(iface->sa.sin.sin_addr)) == -1) { rv = errno; } } #if APR_HAVE_IPV6 else if (sock_is_ipv6(sock)) { unsigned int idx = find_if_index(iface); if (setsockopt(sock->socketdes, IPPROTO_IPV6, IPV6_MULTICAST_IF, &idx, sizeof(idx)) == -1) { rv = errno; } } #endif else { rv = APR_ENOTIMPL; } return rv; #else return APR_ENOTIMPL; #endif }
001-log4cxx
trunk/src/apr/network_io/unix/multicast.c
C
asf20
9,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_arch_networkio.h" #include "apr_support.h" #if APR_HAS_SENDFILE /* This file is needed to allow us access to the apr_file_t internals. */ #include "apr_arch_file_io.h" #endif /* APR_HAS_SENDFILE */ /* osreldate.h is only needed on FreeBSD for sendfile detection */ #if defined(__FreeBSD__) #include <osreldate.h> #endif apr_status_t apr_socket_send(apr_socket_t *sock, const char *buf, apr_size_t *len) { apr_ssize_t rv; if (sock->options & APR_INCOMPLETE_WRITE) { sock->options &= ~APR_INCOMPLETE_WRITE; goto do_select; } do { rv = write(sock->socketdes, buf, (*len)); } while (rv == -1 && errno == EINTR); while (rv == -1 && (errno == EAGAIN || errno == EWOULDBLOCK) && (sock->timeout > 0)) { apr_status_t arv; do_select: arv = apr_wait_for_io_or_timeout(NULL, sock, 0); if (arv != APR_SUCCESS) { *len = 0; return arv; } else { do { rv = write(sock->socketdes, buf, (*len)); } while (rv == -1 && errno == EINTR); } } if (rv == -1) { *len = 0; return errno; } if ((sock->timeout > 0) && (rv < *len)) { sock->options |= APR_INCOMPLETE_WRITE; } (*len) = rv; return APR_SUCCESS; } apr_status_t apr_socket_recv(apr_socket_t *sock, char *buf, apr_size_t *len) { apr_ssize_t rv; apr_status_t arv; if (sock->options & APR_INCOMPLETE_READ) { sock->options &= ~APR_INCOMPLETE_READ; goto do_select; } do { rv = read(sock->socketdes, buf, (*len)); } while (rv == -1 && errno == EINTR); while ((rv == -1) && (errno == EAGAIN || errno == EWOULDBLOCK) && (sock->timeout > 0)) { do_select: arv = apr_wait_for_io_or_timeout(NULL, sock, 1); if (arv != APR_SUCCESS) { *len = 0; return arv; } else { do { rv = read(sock->socketdes, buf, (*len)); } while (rv == -1 && errno == EINTR); } } if (rv == -1) { (*len) = 0; return errno; } if ((sock->timeout > 0) && (rv < *len)) { sock->options |= APR_INCOMPLETE_READ; } (*len) = rv; if (rv == 0) { return APR_EOF; } return APR_SUCCESS; } 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; do { rv = sendto(sock->socketdes, buf, (*len), flags, (const struct sockaddr*)&where->sa, where->salen); } while (rv == -1 && errno == EINTR); while ((rv == -1) && (errno == EAGAIN || errno == EWOULDBLOCK) && (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 && errno == EINTR); } } if (rv == -1) { *len = 0; return errno; } *len = rv; return APR_SUCCESS; } 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; do { rv = recvfrom(sock->socketdes, buf, (*len), flags, (struct sockaddr*)&from->sa, &from->salen); } while (rv == -1 && errno == EINTR); while ((rv == -1) && (errno == EAGAIN || errno == EWOULDBLOCK) && (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 && errno == EINTR); } } if (rv == -1) { (*len) = 0; return errno; } (*len) = rv; if (rv == 0 && sock->type == SOCK_STREAM) { return APR_EOF; } return APR_SUCCESS; } apr_status_t apr_socket_sendv(apr_socket_t * sock, const struct iovec *vec, apr_int32_t nvec, apr_size_t *len) { #ifdef HAVE_WRITEV apr_ssize_t rv; apr_size_t requested_len = 0; apr_int32_t i; for (i = 0; i < nvec; i++) { requested_len += vec[i].iov_len; } if (sock->options & APR_INCOMPLETE_WRITE) { sock->options &= ~APR_INCOMPLETE_WRITE; goto do_select; } do { rv = writev(sock->socketdes, vec, nvec); } while (rv == -1 && errno == EINTR); while ((rv == -1) && (errno == EAGAIN || errno == EWOULDBLOCK) && (sock->timeout > 0)) { apr_status_t arv; do_select: arv = apr_wait_for_io_or_timeout(NULL, sock, 0); if (arv != APR_SUCCESS) { *len = 0; return arv; } else { do { rv = writev(sock->socketdes, vec, nvec); } while (rv == -1 && errno == EINTR); } } if (rv == -1) { *len = 0; return errno; } if ((sock->timeout > 0) && (rv < requested_len)) { sock->options |= APR_INCOMPLETE_WRITE; } (*len) = rv; return APR_SUCCESS; #else *len = vec[0].iov_len; return apr_socket_send(sock, vec[0].iov_base, len); #endif } #if APR_HAS_SENDFILE /* TODO: Verify that all platforms handle the fd the same way, * i.e. that they don't move the file pointer. */ /* TODO: what should flags be? int_32? */ /* Define a structure to pass in when we have a NULL header value */ static apr_hdtr_t no_hdtr; #if defined(__linux__) && defined(HAVE_WRITEV) apr_status_t apr_socket_sendfile(apr_socket_t *sock, apr_file_t *file, apr_hdtr_t *hdtr, apr_off_t *offset, apr_size_t *len, apr_int32_t flags) { int rv, nbytes = 0, total_hdrbytes, i; apr_status_t arv; #if APR_HAS_LARGE_FILES && defined(HAVE_SENDFILE64) apr_off_t off = *offset; #define sendfile sendfile64 #elif APR_HAS_LARGE_FILES && SIZEOF_OFF_T == 4 /* 64-bit apr_off_t but no sendfile64(): fail if trying to send * past the 2Gb limit. */ off_t off; if ((apr_int64_t)*offset + *len > INT_MAX) { return EINVAL; } off = *offset; #else off_t off = *offset; /* Multiple reports have shown sendfile failing with EINVAL if * passed a >=2Gb count value on some 64-bit kernels. It won't * noticably hurt performance to limit each call to <2Gb at a * time, so avoid that issue here: */ if (sizeof(off_t) == 8 && *len > INT_MAX) { *len = INT_MAX; } #endif if (!hdtr) { hdtr = &no_hdtr; } /* Ignore flags for now. */ flags = 0; if (hdtr->numheaders > 0) { apr_size_t hdrbytes; /* cork before writing headers */ rv = apr_socket_opt_set(sock, APR_TCP_NOPUSH, 1); if (rv != APR_SUCCESS) { return rv; } /* Now write the headers */ arv = apr_socket_sendv(sock, hdtr->headers, hdtr->numheaders, &hdrbytes); if (arv != APR_SUCCESS) { *len = 0; return errno; } nbytes += hdrbytes; /* If this was a partial write and we aren't doing timeouts, * return now with the partial byte count; this is a non-blocking * socket. */ total_hdrbytes = 0; for (i = 0; i < hdtr->numheaders; i++) { total_hdrbytes += hdtr->headers[i].iov_len; } if (hdrbytes < total_hdrbytes) { *len = hdrbytes; return apr_socket_opt_set(sock, APR_TCP_NOPUSH, 0); } } if (sock->options & APR_INCOMPLETE_WRITE) { sock->options &= ~APR_INCOMPLETE_WRITE; goto do_select; } do { rv = sendfile(sock->socketdes, /* socket */ file->filedes, /* open file descriptor of the file to be sent */ &off, /* where in the file to start */ *len); /* number of bytes to send */ } while (rv == -1 && errno == EINTR); while ((rv == -1) && (errno == EAGAIN || errno == EWOULDBLOCK) && (sock->timeout > 0)) { do_select: arv = apr_wait_for_io_or_timeout(NULL, sock, 0); if (arv != APR_SUCCESS) { *len = 0; return arv; } else { do { rv = sendfile(sock->socketdes, /* socket */ file->filedes, /* open file descriptor of the file to be sent */ &off, /* where in the file to start */ *len); /* number of bytes to send */ } while (rv == -1 && errno == EINTR); } } if (rv == -1) { *len = nbytes; rv = errno; apr_socket_opt_set(sock, APR_TCP_NOPUSH, 0); return rv; } nbytes += rv; if (rv < *len) { *len = nbytes; arv = apr_socket_opt_set(sock, APR_TCP_NOPUSH, 0); if (rv > 0) { /* If this was a partial write, return now with the * partial byte count; this is a non-blocking socket. */ if (sock->timeout > 0) { sock->options |= APR_INCOMPLETE_WRITE; } return arv; } else { /* If the file got smaller mid-request, eventually the offset * becomes equal to the new file size and the kernel returns 0. * Make this an error so the caller knows to log something and * exit. */ return APR_EOF; } } /* Now write the footers */ if (hdtr->numtrailers > 0) { apr_size_t trbytes; arv = apr_socket_sendv(sock, hdtr->trailers, hdtr->numtrailers, &trbytes); nbytes += trbytes; if (arv != APR_SUCCESS) { *len = nbytes; rv = errno; apr_socket_opt_set(sock, APR_TCP_NOPUSH, 0); return rv; } } apr_socket_opt_set(sock, APR_TCP_NOPUSH, 0); (*len) = nbytes; return rv < 0 ? errno : APR_SUCCESS; } #elif defined(__FreeBSD__) || defined(__DragonFly__) /* Release 3.1 or greater */ apr_status_t apr_socket_sendfile(apr_socket_t * sock, apr_file_t * file, apr_hdtr_t * hdtr, apr_off_t * offset, apr_size_t * len, apr_int32_t flags) { off_t nbytes = 0; int rv, i; struct sf_hdtr headerstruct; apr_size_t bytes_to_send = *len; /* Ignore flags for now. */ flags = 0; if (!hdtr) { hdtr = &no_hdtr; } #if defined(__FreeBSD_version) && __FreeBSD_version < 460001 else if (hdtr->numheaders) { /* On early versions of FreeBSD sendfile, the number of bytes to send * must include the length of the headers. Don't look at the man page * for this :( Instead, look at the the logic in * src/sys/kern/uipc_syscalls::sendfile(). * * This was fixed in the middle of 4.6-STABLE */ for (i = 0; i < hdtr->numheaders; i++) { bytes_to_send += hdtr->headers[i].iov_len; } } #endif headerstruct.headers = hdtr->headers; headerstruct.hdr_cnt = hdtr->numheaders; headerstruct.trailers = hdtr->trailers; headerstruct.trl_cnt = hdtr->numtrailers; /* FreeBSD can send the headers/footers as part of the system call */ do { if (sock->options & APR_INCOMPLETE_WRITE) { apr_status_t arv; sock->options &= ~APR_INCOMPLETE_WRITE; arv = apr_wait_for_io_or_timeout(NULL, sock, 0); if (arv != APR_SUCCESS) { *len = 0; return arv; } } if (bytes_to_send) { /* We won't dare call sendfile() if we don't have * header or file bytes to send because bytes_to_send == 0 * means send the whole file. */ rv = sendfile(file->filedes, /* file to be sent */ sock->socketdes, /* socket */ *offset, /* where in the file to start */ bytes_to_send, /* number of bytes to send */ &headerstruct, /* Headers/footers */ &nbytes, /* number of bytes written */ flags); /* undefined, set to 0 */ if (rv == -1) { if (errno == EAGAIN) { if (sock->timeout > 0) { sock->options |= APR_INCOMPLETE_WRITE; } /* FreeBSD's sendfile can return -1/EAGAIN even if it * sent bytes. Sanitize the result so we get normal EAGAIN * semantics w.r.t. bytes sent. */ if (nbytes) { /* normal exit for a big file & non-blocking io */ (*len) = nbytes; return APR_SUCCESS; } } } else { /* rv == 0 (or the kernel is broken) */ if (nbytes == 0) { /* Most likely the file got smaller after the stat. * Return an error so the caller can do the Right Thing. */ (*len) = nbytes; return APR_EOF; } } } else { /* just trailer bytes... use writev() */ rv = writev(sock->socketdes, hdtr->trailers, hdtr->numtrailers); if (rv > 0) { nbytes = rv; rv = 0; } else { nbytes = 0; } } if ((rv == -1) && (errno == EAGAIN) && (sock->timeout > 0)) { apr_status_t arv = apr_wait_for_io_or_timeout(NULL, sock, 0); if (arv != APR_SUCCESS) { *len = 0; return arv; } } } while (rv == -1 && (errno == EINTR || errno == EAGAIN)); (*len) = nbytes; if (rv == -1) { return errno; } return APR_SUCCESS; } #elif defined(__hpux) || defined(__hpux__) /* HP cc in ANSI mode defines __hpux; gcc defines __hpux__ */ /* HP-UX Version 10.30 or greater * (no worries, because we only get here if autoconfiguration found sendfile) */ /* ssize_t sendfile(int s, int fd, off_t offset, size_t nbytes, * const struct iovec *hdtrl, int flags); * * nbytes is the number of bytes to send just from the file; as with FreeBSD, * if nbytes == 0, the rest of the file (from offset) is sent */ apr_status_t apr_socket_sendfile(apr_socket_t *sock, apr_file_t *file, apr_hdtr_t *hdtr, apr_off_t *offset, apr_size_t *len, apr_int32_t flags) { int i; apr_ssize_t rc; apr_size_t nbytes = *len, headerlen, trailerlen; struct iovec hdtrarray[2]; char *headerbuf, *trailerbuf; #if APR_HAS_LARGE_FILES && defined(HAVE_SENDFILE64) /* later HP-UXes have a sendfile64() */ #define sendfile sendfile64 apr_off_t off = *offset; #elif APR_HAS_LARGE_FILES && SIZEOF_OFF_T == 4 /* HP-UX 11.00 doesn't have a sendfile64(): fail if trying to send * past the 2Gb limit */ off_t off; if ((apr_int64_t)*offset + *len > INT_MAX) { return EINVAL; } off = *offset; #else apr_off_t off = *offset; #endif if (!hdtr) { hdtr = &no_hdtr; } /* Ignore flags for now. */ flags = 0; /* HP-UX can only send one header iovec and one footer iovec; try to * only allocate storage to combine input iovecs when we really have to */ switch(hdtr->numheaders) { case 0: hdtrarray[0].iov_base = NULL; hdtrarray[0].iov_len = 0; break; case 1: hdtrarray[0] = hdtr->headers[0]; break; default: headerlen = 0; for (i = 0; i < hdtr->numheaders; i++) { headerlen += hdtr->headers[i].iov_len; } /* XXX: BUHHH? wow, what a memory leak! */ headerbuf = hdtrarray[0].iov_base = apr_palloc(sock->pool, headerlen); hdtrarray[0].iov_len = headerlen; for (i = 0; i < hdtr->numheaders; i++) { memcpy(headerbuf, hdtr->headers[i].iov_base, hdtr->headers[i].iov_len); headerbuf += hdtr->headers[i].iov_len; } } switch(hdtr->numtrailers) { case 0: hdtrarray[1].iov_base = NULL; hdtrarray[1].iov_len = 0; break; case 1: hdtrarray[1] = hdtr->trailers[0]; break; default: trailerlen = 0; for (i = 0; i < hdtr->numtrailers; i++) { trailerlen += hdtr->trailers[i].iov_len; } /* XXX: BUHHH? wow, what a memory leak! */ trailerbuf = hdtrarray[1].iov_base = apr_palloc(sock->pool, trailerlen); hdtrarray[1].iov_len = trailerlen; for (i = 0; i < hdtr->numtrailers; i++) { memcpy(trailerbuf, hdtr->trailers[i].iov_base, hdtr->trailers[i].iov_len); trailerbuf += hdtr->trailers[i].iov_len; } } do { if (nbytes) { /* any bytes to send from the file? */ rc = sendfile(sock->socketdes, /* socket */ file->filedes, /* file descriptor to send */ off, /* where in the file to start */ nbytes, /* number of bytes to send from file */ hdtrarray, /* Headers/footers */ flags); /* undefined, set to 0 */ } else { /* we can't call sendfile() with no bytes to send from the file */ rc = writev(sock->socketdes, hdtrarray, 2); } } while (rc == -1 && errno == EINTR); while ((rc == -1) && (errno == EAGAIN || errno == EWOULDBLOCK) && (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 { if (nbytes) { rc = sendfile(sock->socketdes, /* socket */ file->filedes, /* file descriptor to send */ off, /* where in the file to start */ nbytes, /* number of bytes to send from file */ hdtrarray, /* Headers/footers */ flags); /* undefined, set to 0 */ } else { /* we can't call sendfile() with no bytes to send from the file */ rc = writev(sock->socketdes, hdtrarray, 2); } } while (rc == -1 && errno == EINTR); } } if (rc == -1) { *len = 0; return errno; } /* Set len to the number of bytes written */ *len = rc; return APR_SUCCESS; } #elif defined(_AIX) || defined(__MVS__) /* AIX and OS/390 have the same send_file() interface. * * subtle differences: * AIX doesn't update the file ptr but OS/390 does * * availability (correctly determined by autoconf): * * AIX - version 4.3.2 with APAR IX85388, or version 4.3.3 and above * OS/390 - V2R7 and above */ apr_status_t apr_socket_sendfile(apr_socket_t * sock, apr_file_t * file, apr_hdtr_t * hdtr, apr_off_t * offset, apr_size_t * len, apr_int32_t flags) { int i, ptr, rv = 0; void * hbuf=NULL, * tbuf=NULL; apr_status_t arv; struct sf_parms parms; if (!hdtr) { hdtr = &no_hdtr; } /* Ignore flags for now. */ flags = 0; /* word to the wise: by default, AIX stores files sent by send_file() * in the network buffer cache... there are supposedly scenarios * where the most recent copy of the file won't be sent, but I can't * recreate the potential problem, perhaps because of the way we * use send_file()... if you suspect such a problem, try turning * on the SF_SYNC_CACHE flag */ /* AIX can also send the headers/footers as part of the system call */ parms.header_length = 0; if (hdtr && hdtr->numheaders) { if (hdtr->numheaders == 1) { parms.header_data = hdtr->headers[0].iov_base; parms.header_length = hdtr->headers[0].iov_len; } else { for (i = 0; i < hdtr->numheaders; i++) { parms.header_length += hdtr->headers[i].iov_len; } #if 0 /* Keepalives make apr_palloc a bad idea */ hbuf = malloc(parms.header_length); #else /* but headers are small, so maybe we can hold on to the * memory for the life of the socket... */ hbuf = apr_palloc(sock->pool, parms.header_length); #endif ptr = 0; for (i = 0; i < hdtr->numheaders; i++) { memcpy((char *)hbuf + ptr, hdtr->headers[i].iov_base, hdtr->headers[i].iov_len); ptr += hdtr->headers[i].iov_len; } parms.header_data = hbuf; } } else parms.header_data = NULL; parms.trailer_length = 0; if (hdtr && hdtr->numtrailers) { if (hdtr->numtrailers == 1) { parms.trailer_data = hdtr->trailers[0].iov_base; parms.trailer_length = hdtr->trailers[0].iov_len; } else { for (i = 0; i < hdtr->numtrailers; i++) { parms.trailer_length += hdtr->trailers[i].iov_len; } #if 0 /* Keepalives make apr_palloc a bad idea */ tbuf = malloc(parms.trailer_length); #else tbuf = apr_palloc(sock->pool, parms.trailer_length); #endif ptr = 0; for (i = 0; i < hdtr->numtrailers; i++) { memcpy((char *)tbuf + ptr, hdtr->trailers[i].iov_base, hdtr->trailers[i].iov_len); ptr += hdtr->trailers[i].iov_len; } parms.trailer_data = tbuf; } } else { parms.trailer_data = NULL; } /* Whew! Headers and trailers set up. Now for the file data */ parms.file_descriptor = file->filedes; parms.file_offset = *offset; parms.file_bytes = *len; /* O.K. All set up now. Let's go to town */ if (sock->options & APR_INCOMPLETE_WRITE) { sock->options &= ~APR_INCOMPLETE_WRITE; goto do_select; } do { rv = send_file(&(sock->socketdes), /* socket */ &(parms), /* all data */ flags); /* flags */ } while (rv == -1 && errno == EINTR); while ((rv == -1) && (errno == EAGAIN || errno == EWOULDBLOCK) && (sock->timeout > 0)) { do_select: arv = apr_wait_for_io_or_timeout(NULL, sock, 0); if (arv != APR_SUCCESS) { *len = 0; return arv; } else { do { rv = send_file(&(sock->socketdes), /* socket */ &(parms), /* all data */ flags); /* flags */ } while (rv == -1 && errno == EINTR); } } (*len) = parms.bytes_sent; #if 0 /* Clean up after ourselves */ if(hbuf) free(hbuf); if(tbuf) free(tbuf); #endif if (rv == -1) { return errno; } if ((sock->timeout > 0) && (parms.bytes_sent < (parms.file_bytes + parms.header_length + parms.trailer_length))) { sock->options |= APR_INCOMPLETE_WRITE; } return APR_SUCCESS; } #elif defined(__osf__) && defined (__alpha) /* Tru64's sendfile implementation doesn't work, and we need to make sure that * we don't use it until it is fixed. If it is used as it is now, it will * hang the machine and the only way to fix it is a reboot. */ #elif defined(HAVE_SENDFILEV) /* Solaris 8's sendfilev() interface * * SFV_FD_SELF refers to our memory space. * * Required Sparc patches (or newer): * 111297-01, 108528-09, 109472-06, 109234-03, 108995-02, 111295-01, 109025-03, * 108991-13 * Required x86 patches (or newer): * 111298-01, 108529-09, 109473-06, 109235-04, 108996-02, 111296-01, 109026-04, * 108992-13 */ #if APR_HAS_LARGE_FILES && defined(HAVE_SENDFILEV64) #define sendfilevec_t sendfilevec64_t #define sendfilev sendfilev64 #endif apr_status_t apr_socket_sendfile(apr_socket_t *sock, apr_file_t *file, apr_hdtr_t *hdtr, apr_off_t *offset, apr_size_t *len, apr_int32_t flags) { apr_status_t rv, arv; apr_size_t nbytes; sendfilevec_t *sfv; int vecs, curvec, i, repeat; apr_size_t requested_len = 0; if (!hdtr) { hdtr = &no_hdtr; } /* Ignore flags for now. */ flags = 0; /* Calculate how much space we need. */ vecs = hdtr->numheaders + hdtr->numtrailers + 1; sfv = apr_palloc(sock->pool, sizeof(sendfilevec_t) * vecs); curvec = 0; /* Add the headers */ for (i = 0; i < hdtr->numheaders; i++, curvec++) { sfv[curvec].sfv_fd = SFV_FD_SELF; sfv[curvec].sfv_flag = 0; sfv[curvec].sfv_off = (apr_off_t)hdtr->headers[i].iov_base; sfv[curvec].sfv_len = hdtr->headers[i].iov_len; requested_len += sfv[curvec].sfv_len; } /* If the len is 0, we skip the file. */ if (*len) { sfv[curvec].sfv_fd = file->filedes; sfv[curvec].sfv_flag = 0; sfv[curvec].sfv_off = *offset; sfv[curvec].sfv_len = *len; requested_len += sfv[curvec].sfv_len; curvec++; } else { vecs--; } /* Add the footers */ for (i = 0; i < hdtr->numtrailers; i++, curvec++) { sfv[curvec].sfv_fd = SFV_FD_SELF; sfv[curvec].sfv_flag = 0; sfv[curvec].sfv_off = (apr_off_t)hdtr->trailers[i].iov_base; sfv[curvec].sfv_len = hdtr->trailers[i].iov_len; requested_len += sfv[curvec].sfv_len; } /* If the last write couldn't send all the requested data, * wait for the socket to become writable before proceeding */ if (sock->options & APR_INCOMPLETE_WRITE) { sock->options &= ~APR_INCOMPLETE_WRITE; arv = apr_wait_for_io_or_timeout(NULL, sock, 0); if (arv != APR_SUCCESS) { *len = 0; return arv; } } /* Actually do the sendfilev * * Solaris may return -1/EAGAIN even if it sent bytes on a non-block sock. * * If no bytes were originally sent (nbytes == 0) and we are on a TIMEOUT * socket (which as far as the OS is concerned is a non-blocking socket), * we want to retry after waiting for the other side to read the data (as * determined by poll). Once it is clear to send, we want to retry * sending the sendfilevec_t once more. */ arv = 0; do { /* Clear out the repeat */ repeat = 0; /* socket, vecs, number of vecs, bytes written */ rv = sendfilev(sock->socketdes, sfv, vecs, &nbytes); if (rv == -1 && errno == EAGAIN) { if (nbytes) { rv = 0; } else if (!arv && (sock->timeout > 0)) { apr_status_t t = apr_wait_for_io_or_timeout(NULL, sock, 0); if (t != APR_SUCCESS) { *len = 0; return t; } arv = 1; repeat = 1; } } } while ((rv == -1 && errno == EINTR) || repeat); if (rv == -1) { *len = 0; return errno; } /* Update how much we sent */ *len = nbytes; if ((sock->timeout > 0) && (*len < requested_len)) { sock->options |= APR_INCOMPLETE_WRITE; } return APR_SUCCESS; } #else #error APR has detected sendfile on your system, but nobody has written a #error version of it for APR yet. To get past this, either write #error apr_socket_sendfile or change APR_HAS_SENDFILE in apr.h to 0. #endif /* __linux__, __FreeBSD__, __DragonFly__, __HPUX__, _AIX, __MVS__, Tru64/OSF1 */ #endif /* APR_HAS_SENDFILE */
001-log4cxx
trunk/src/apr/network_io/unix/sendrecv.c
C
asf20
30,226
/* 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_arch_inherit.h" #include "apr_network_io.h" #include "apr_general.h" #include "apr_portable.h" #include "apr_lib.h" #include "apr_strings.h" #include <errno.h> #include <string.h> #include <sys/socket.h> #include <netinet/tcp.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include "apr_arch_os2calls.h" static apr_status_t socket_cleanup(void *sock) { apr_socket_t *thesocket = sock; if (thesocket->socketdes < 0) { return APR_EINVALSOCK; } if (soclose(thesocket->socketdes) == 0) { thesocket->socketdes = -1; return APR_SUCCESS; } else { return APR_OS2_STATUS(sock_errno()); } } static void set_socket_vars(apr_socket_t *sock, int family, int type, int protocol) { sock->type = type; sock->protocol = protocol; apr_sockaddr_vars_set(sock->local_addr, family, 0); apr_sockaddr_vars_set(sock->remote_addr, family, 0); } static void alloc_socket(apr_socket_t **new, apr_pool_t *p) { *new = (apr_socket_t *)apr_pcalloc(p, sizeof(apr_socket_t)); (*new)->pool = p; (*new)->local_addr = (apr_sockaddr_t *)apr_pcalloc((*new)->pool, sizeof(apr_sockaddr_t)); (*new)->local_addr->pool = p; (*new)->remote_addr = (apr_sockaddr_t *)apr_pcalloc((*new)->pool, sizeof(apr_sockaddr_t)); (*new)->remote_addr->pool = p; (*new)->remote_addr_unknown = 1; /* Create a pollset with room for one descriptor. */ /* ### check return codes */ (void) apr_pollset_create(&(*new)->pollset, 1, p, 0); } APR_DECLARE(apr_status_t) apr_socket_protocol_get(apr_socket_t *sock, int *protocol) { *protocol = sock->protocol; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_create(apr_socket_t **new, int family, int type, int protocol, apr_pool_t *cont) { int downgrade = (family == AF_UNSPEC); apr_pollfd_t pfd; if (family == AF_UNSPEC) { #if APR_HAVE_IPV6 family = AF_INET6; #else family = AF_INET; #endif } alloc_socket(new, cont); (*new)->socketdes = socket(family, type, protocol); #if APR_HAVE_IPV6 if ((*new)->socketdes < 0 && downgrade) { family = AF_INET; (*new)->socketdes = socket(family, type, protocol); } #endif if ((*new)->socketdes < 0) { return APR_OS2_STATUS(sock_errno()); } set_socket_vars(*new, family, type, protocol); (*new)->timeout = -1; (*new)->nonblock = FALSE; apr_pool_cleanup_register((*new)->pool, (void *)(*new), socket_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_shutdown(apr_socket_t *thesocket, apr_shutdown_how_e how) { if (shutdown(thesocket->socketdes, how) == 0) { return APR_SUCCESS; } else { return APR_OS2_STATUS(sock_errno()); } } APR_DECLARE(apr_status_t) apr_socket_close(apr_socket_t *thesocket) { apr_pool_cleanup_kill(thesocket->pool, thesocket, socket_cleanup); return socket_cleanup(thesocket); } APR_DECLARE(apr_status_t) apr_socket_bind(apr_socket_t *sock, apr_sockaddr_t *sa) { if (bind(sock->socketdes, (struct sockaddr *)&sa->sa, sa->salen) == -1) return APR_OS2_STATUS(sock_errno()); else { sock->local_addr = sa; /* XXX IPv6 - this assumes sin_port and sin6_port at same offset */ if (sock->local_addr->sa.sin.sin_port == 0) { /* no need for ntohs() when comparing w/ 0 */ sock->local_port_unknown = 1; /* kernel got us an ephemeral port */ } return APR_SUCCESS; } } APR_DECLARE(apr_status_t) apr_socket_listen(apr_socket_t *sock, apr_int32_t backlog) { if (listen(sock->socketdes, backlog) == -1) return APR_OS2_STATUS(sock_errno()); else return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_accept(apr_socket_t **new, apr_socket_t *sock, apr_pool_t *connection_context) { alloc_socket(new, connection_context); set_socket_vars(*new, sock->local_addr->sa.sin.sin_family, SOCK_STREAM, sock->protocol); (*new)->timeout = -1; (*new)->nonblock = FALSE; (*new)->socketdes = accept(sock->socketdes, (struct sockaddr *)&(*new)->remote_addr->sa, &(*new)->remote_addr->salen); if ((*new)->socketdes < 0) { return APR_OS2_STATUS(sock_errno()); } *(*new)->local_addr = *sock->local_addr; (*new)->local_addr->pool = connection_context; (*new)->remote_addr->port = ntohs((*new)->remote_addr->sa.sin.sin_port); /* fix up any pointers which are no longer valid */ if (sock->local_addr->sa.sin.sin_family == AF_INET) { (*new)->local_addr->ipaddr_ptr = &(*new)->local_addr->sa.sin.sin_addr; } apr_pool_cleanup_register((*new)->pool, (void *)(*new), socket_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_connect(apr_socket_t *sock, apr_sockaddr_t *sa) { if ((connect(sock->socketdes, (struct sockaddr *)&sa->sa.sin, sa->salen) < 0) && (sock_errno() != SOCEINPROGRESS)) { return APR_OS2_STATUS(sock_errno()); } else { int namelen = sizeof(sock->local_addr->sa.sin); getsockname(sock->socketdes, (struct sockaddr *)&sock->local_addr->sa.sin, &namelen); sock->remote_addr = sa; return APR_SUCCESS; } } APR_DECLARE(apr_status_t) apr_socket_type_get(apr_socket_t *sock, int *type) { *type = sock->type; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_data_get(void **data, const char *key, apr_socket_t *sock) { sock_userdata_t *cur = sock->userdata; *data = NULL; while (cur) { if (!strcmp(cur->key, key)) { *data = cur->data; break; } cur = cur->next; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_data_set(apr_socket_t *sock, void *data, const char *key, apr_status_t (*cleanup) (void *)) { sock_userdata_t *new = apr_palloc(sock->pool, sizeof(sock_userdata_t)); new->key = apr_pstrdup(sock->pool, key); new->data = data; new->next = sock->userdata; sock->userdata = new; if (cleanup) { apr_pool_cleanup_register(sock->pool, data, cleanup, cleanup); } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_sock_get(apr_os_sock_t *thesock, apr_socket_t *sock) { *thesock = sock->socketdes; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_sock_make(apr_socket_t **apr_sock, apr_os_sock_info_t *os_sock_info, apr_pool_t *cont) { alloc_socket(apr_sock, cont); set_socket_vars(*apr_sock, os_sock_info->family, os_sock_info->type, os_sock_info->protocol); (*apr_sock)->timeout = -1; (*apr_sock)->socketdes = *os_sock_info->os_sock; if (os_sock_info->local) { memcpy(&(*apr_sock)->local_addr->sa.sin, os_sock_info->local, (*apr_sock)->local_addr->salen); /* XXX IPv6 - this assumes sin_port and sin6_port at same offset */ (*apr_sock)->local_addr->port = ntohs((*apr_sock)->local_addr->sa.sin.sin_port); } else { (*apr_sock)->local_port_unknown = (*apr_sock)->local_interface_unknown = 1; } if (os_sock_info->remote) { memcpy(&(*apr_sock)->remote_addr->sa.sin, os_sock_info->remote, (*apr_sock)->remote_addr->salen); /* XXX IPv6 - this assumes sin_port and sin6_port at same offset */ (*apr_sock)->remote_addr->port = ntohs((*apr_sock)->remote_addr->sa.sin.sin_port); } else { (*apr_sock)->remote_addr_unknown = 1; } apr_pool_cleanup_register((*apr_sock)->pool, (void *)(*apr_sock), socket_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_os_sock_put(apr_socket_t **sock, apr_os_sock_t *thesock, apr_pool_t *cont) { if (cont == NULL) { return APR_ENOPOOL; } if ((*sock) == NULL) { alloc_socket(sock, cont); set_socket_vars(*sock, AF_INET, SOCK_STREAM, 0); (*sock)->timeout = -1; } (*sock)->local_port_unknown = (*sock)->local_interface_unknown = 1; (*sock)->remote_addr_unknown = 1; (*sock)->socketdes = *thesock; return APR_SUCCESS; } APR_POOL_IMPLEMENT_ACCESSOR(socket); APR_IMPLEMENT_INHERIT_SET(socket, inherit, pool, socket_cleanup) APR_IMPLEMENT_INHERIT_UNSET(socket, inherit, pool, socket_cleanup)
001-log4cxx
trunk/src/apr/network_io/os2/sockets.c
C
asf20
9,965
#include "../unix/inet_pton.c"
001-log4cxx
trunk/src/apr/network_io/os2/inet_pton.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_general.h" #include "apr_lib.h" #include "apr_strings.h" #include <errno.h> #include <string.h> #include <sys/socket.h> #include <netinet/tcp.h> #include <netinet/in.h> #include <unistd.h> #include <netdb.h> #include <sys/so_ioctl.h> APR_DECLARE(apr_status_t) apr_socket_timeout_set(apr_socket_t *sock, apr_interval_time_t t) { sock->timeout = t; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_opt_set(apr_socket_t *sock, apr_int32_t opt, apr_int32_t on) { int one; struct linger li; if (on) one = 1; else one = 0; if (opt & APR_SO_KEEPALIVE) { if (setsockopt(sock->socketdes, SOL_SOCKET, SO_KEEPALIVE, (void *)&one, sizeof(int)) == -1) { return APR_OS2_STATUS(sock_errno()); } } if (opt & APR_SO_DEBUG) { if (setsockopt(sock->socketdes, SOL_SOCKET, SO_DEBUG, (void *)&one, sizeof(int)) == -1) { return APR_OS2_STATUS(sock_errno()); } } if (opt & APR_SO_REUSEADDR) { if (setsockopt(sock->socketdes, SOL_SOCKET, SO_REUSEADDR, (void *)&one, sizeof(int)) == -1) { return APR_OS2_STATUS(sock_errno()); } } if (opt & APR_SO_SNDBUF) { if (setsockopt(sock->socketdes, SOL_SOCKET, SO_SNDBUF, (void *)&on, sizeof(int)) == -1) { return APR_OS2_STATUS(sock_errno()); } } if (opt & APR_SO_NONBLOCK) { if (ioctl(sock->socketdes, FIONBIO, (caddr_t)&one, sizeof(one)) == -1) { return APR_OS2_STATUS(sock_errno()); } else { sock->nonblock = one; } } if (opt & APR_SO_LINGER) { li.l_onoff = on; li.l_linger = APR_MAX_SECS_TO_LINGER; if (setsockopt(sock->socketdes, SOL_SOCKET, SO_LINGER, (char *) &li, sizeof(struct linger)) == -1) { return APR_OS2_STATUS(sock_errno()); } } if (opt & APR_TCP_NODELAY) { if (setsockopt(sock->socketdes, IPPROTO_TCP, TCP_NODELAY, (void *)&on, sizeof(int)) == -1) { return APR_OS2_STATUS(sock_errno()); } } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_timeout_get(apr_socket_t *sock, apr_interval_time_t *t) { *t = sock->timeout; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_opt_get(apr_socket_t *sock, apr_int32_t opt, apr_int32_t *on) { switch(opt) { default: return APR_EINVAL; } return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_socket_atmark(apr_socket_t *sock, int *atmark) { int oobmark; if (ioctl(sock->socketdes, SIOCATMARK, (void*)&oobmark, sizeof(oobmark)) < 0) { return APR_OS2_STATUS(sock_errno()); } *atmark = (oobmark != 0); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_gethostname(char *buf, apr_int32_t len, apr_pool_t *cont) { if (gethostname(buf, len) == -1) { buf[0] = '\0'; return APR_OS2_STATUS(sock_errno()); } else if (!memchr(buf, '\0', len)) { /* buffer too small */ buf[0] = '\0'; return APR_ENAMETOOLONG; } return APR_SUCCESS; }
001-log4cxx
trunk/src/apr/network_io/os2/sockopt.c
C
asf20
4,190